37227. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 1/17/2019 10:54:17 AM Central 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.

37227.1 Files compared

# Location File Last Modified
1 v1_iter_1_VIP_Build_4_Dec_2018_CG.zip\v1_iter_1_VIP_Build_4\portlets\caret-portlet\docroot\WEB-INF\src\gov\va\caret\portlet\action CaretActionCommand.java Wed Jan 16 16:07:32 2019 UTC
2 v1_iter_1_VIP_Build_4_Dec_2018_CG.zip\v1_iter_1_VIP_Build_4\portlets\caret-portlet\docroot\WEB-INF\src\gov\va\caret\portlet\action CaretActionCommand.java Thu Jan 17 14:37:50 2019 UTC

37227.2 Comparison summary

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

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

37227.4 Active regular expressions

No regular expressions were active.

37227.5 Comparison detail

  1   package go v.va.caret .portlet.a ction;
  2  
  3   import jav a.io.File;
  4   import jav a.io.FileI nputStream ;
  5   import jav a.io.FileN otFoundExc eption;
  6   import jav a.io.IOExc eption;
  7   import jav a.io.Input Stream;
  8   import jav a.io.Seria lizable;
  9   import jav a.text.Dat eFormat;
  10   import jav a.text.Mes sageFormat ;
  11   import jav a.text.Num berFormat;
  12   import jav a.text.Par seExceptio n;
  13   import jav a.text.Sim pleDateFor mat;
  14   import jav a.util.Arr ayList;
  15   import jav a.util.Arr ays;
  16   import jav a.util.Cal endar;
  17   import jav a.util.Col lection;
  18   import jav a.util.Col lections;
  19   import jav a.util.Com parator;
  20   import jav a.util.Dat e;
  21   import jav a.util.Has hMap;
  22   import jav a.util.Has hSet;
  23   import jav a.util.Ite rator;
  24   import jav a.util.Lis t;
  25   import jav a.util.Loc ale;
  26   import jav a.util.Map ;
  27   import jav a.util.Set ;
  28   import jav a.util.Tre eMap;
  29  
  30   import jav ax.portlet .ActionReq uest;
  31   import jav ax.portlet .ActionRes ponse;
  32   import jav ax.portlet .PortletRe quest;
  33   import jav ax.portlet .ProcessAc tion;
  34  
  35   import org .apache.co mmons.coll ections.Co llectionUt ils;
  36  
  37   import com .liferay.c ounter.ser vice.Count erLocalSer viceUtil;
  38   import com .liferay.p ortal.NoSu chClassNam eException ;
  39   import com .liferay.p ortal.kern el.dao.jdb c.OutputBl ob;
  40   import com .liferay.p ortal.kern el.excepti on.PortalE xception;
  41   import com .liferay.p ortal.kern el.excepti on.SystemE xception;
  42   import com .liferay.p ortal.kern el.languag e.Language Util;
  43   import com .liferay.p ortal.kern el.log.Log ;
  44   import com .liferay.p ortal.kern el.log.Log FactoryUti l;
  45   import com .liferay.p ortal.kern el.upload. UploadPort letRequest ;
  46   import com .liferay.p ortal.kern el.util.Ar rayUtil;
  47   import com .liferay.p ortal.kern el.util.Fi leUtil;
  48   import com .liferay.p ortal.kern el.util.Li stUtil;
  49   import com .liferay.p ortal.kern el.util.Pa ramUtil;
  50   import com .liferay.p ortal.kern el.util.Pr efsPropsUt il;
  51   import com .liferay.p ortal.kern el.util.Pr opsKeys;
  52   import com .liferay.p ortal.kern el.util.Pr opsUtil;
  53   import com .liferay.p ortal.kern el.util.St ringPool;
  54   import com .liferay.p ortal.kern el.util.St ringUtil;
  55   import com .liferay.p ortal.kern el.util.Va lidator;
  56   import com .liferay.p ortal.kern el.util.We bKeys;
  57   import com .liferay.p ortal.mode l.BaseMode l;
  58   import com .liferay.p ortal.mode l.CountryC onstants;
  59   import com .liferay.p ortal.mode l.Dummy;
  60   import com .liferay.p ortal.mode l.Organiza tion;
  61   import com .liferay.p ortal.mode l.Role;
  62   import com .liferay.p ortal.serv ice.ClassN ameLocalSe rviceUtil;
  63   import com .liferay.p ortal.serv ice.Organi zationLoca lServiceUt il;
  64   import com .liferay.p ortal.serv ice.Region ServiceUti l;
  65   import com .liferay.p ortal.serv ice.RoleLo calService Util;
  66   import com .liferay.p ortal.serv ice.Servic eContext;
  67   import com .liferay.p ortal.serv ice.UserLo calService Util;
  68   import com .liferay.p ortal.them e.ThemeDis play;
  69   import com .liferay.p ortal.util .PortalUti l;
  70   import com .liferay.u til.portle t.PortletP rops;
  71  
  72   import gov .va.caret. Applicatio nWorkFlowE xception;
  73   import gov .va.caret. bean.Assmt Bean;
  74   import gov .va.caret. bean.Attac hmentBean;
  75   import gov .va.caret. bean.CespB ean;
  76   import gov .va.caret. controller .CaretView Controller ;
  77   import gov .va.caret. controller .dashboard .config.Cb opcDashboa rdConfig;
  78   import gov .va.caret. controller .dashboard .config.Cb opcFmDashb oardConfig ;
  79   import gov .va.caret. controller .dashboard .config.Cs cDashboard Config;
  80   import gov .va.caret. controller .dashboard .config.Cs lDashboard Config;
  81   import gov .va.caret. controller .dashboard .config.Da shboardCon fig;
  82   import gov .va.caret. controller .dashboard .config.Da shboardCon figFactory ;
  83   import gov .va.caret. controller .dashboard .config.Fa cilityDash boardConfi g;
  84   import gov .va.caret. letters.Cs cLetterTyp e;
  85   import gov .va.caret. letters.Oc cLetterTyp e;
  86   import gov .va.caret. letters.Po pulateLett ersImpl;
  87   import gov .va.caret. model.Apea l;
  88   import gov .va.caret. model.Assm t;
  89   import gov .va.caret. model.BgAs n;
  90   import gov .va.caret. model.BgLa e;
  91   import gov .va.caret. model.BgNu m;
  92   import gov .va.caret. model.BlsR e;
  93   import gov .va.caret. model.BoxG p;
  94   import gov .va.caret. model.CalE t;
  95   import gov .va.caret. model.Call ;
  96   import gov .va.caret. model.Cesp ;
  97   import gov .va.caret. model.ClSo c;
  98   import gov .va.caret. model.Docu m;
  99   import gov .va.caret. model.Faci l;
  100   import gov .va.caret. model.Lett er;
  101   import gov .va.caret. model.Note ;
  102   import gov .va.caret. model.PayL g;
  103   import gov .va.caret. model.Pers n;
  104   import gov .va.caret. model.StiP t;
  105   import gov .va.caret. model.Vcg;
  106   import gov .va.caret. model.VcgA n;
  107   import gov .va.caret. model.Vend r;
  108   import gov .va.caret. model.Waiv r;
  109   import gov .va.caret. model.WorI m;
  110   import gov .va.caret. model.WorS e;
  111   import gov .va.caret. model.impl .ApealImpl ;
  112   import gov .va.caret. model.impl .AssmtImpl ;
  113   import gov .va.caret. model.impl .BgAsnImpl ;
  114   import gov .va.caret. model.impl .CalEtImpl ;
  115   import gov .va.caret. model.impl .CallImpl;
  116   import gov .va.caret. model.impl .PersnImpl ;
  117   import gov .va.caret. model.impl .StiPtImpl ;
  118   import gov .va.caret. model.impl .VcgAnImpl ;
  119   import gov .va.caret. model.impl .WaivrImpl ;
  120   import gov .va.caret. model.impl .WorImImpl ;
  121   import gov .va.caret. model.impl .WorSeImpl ;
  122   import gov .va.caret. model.supp ort.Applic ationStatu s;
  123   import gov .va.caret. model.supp ort.AssmtS upport;
  124   import gov .va.caret. model.supp ort.BoxNum berSupport ;
  125   import gov .va.caret. model.supp ort.BoxedG roupAssoci ation;
  126   import gov .va.caret. model.supp ort.CallSu pport;
  127   import gov .va.caret. model.supp ort.Genera l;
  128   import gov .va.caret. model.supp ort.NoteSu pport;
  129   import gov .va.caret. model.supp ort.NoteSu pport.Note Group;
  130   import gov .va.caret. model.supp ort.Paymen tLog;
  131   import gov .va.caret. model.supp ort.Person ;
  132   import gov .va.caret. model.supp ort.Primar y;
  133   import gov .va.caret. model.supp ort.Second ary;
  134   import gov .va.caret. model.supp ort.Second aryTwo;
  135   import gov .va.caret. model.supp ort.VcgAnS upport;
  136   import gov .va.caret. model.supp ort.VcgApp lication;
  137   import gov .va.caret. model.supp ort.VcgSup port;
  138   import gov .va.caret. model.supp ort.Vetera n;
  139   import gov .va.caret. model.supp ort.WorkIt emSupport;
  140   import gov .va.caret. model.supp ort.WorkSt atus;
  141   import gov .va.caret. model.supp ort.WorkTy pe;
  142   import gov .va.caret. model.supp ort.occ.An nualRateIn crease;
  143   import gov .va.caret. model.supp ort.occ.Re coupmentVi ew;
  144   import gov .va.caret. model.supp ort.occ.St ipendConfi g;
  145   import gov .va.caret. pdf.FileTy pe;
  146   import gov .va.caret. pm.portlet .PMPortlet ;
  147   import gov .va.caret. security.C Action;
  148   import gov .va.caret. security.C Action.Car etCan;
  149   import gov .va.caret. security.C odifiedRol e;
  150   import gov .va.caret. service.Ap ealLocalSe rviceUtil;
  151   import gov .va.caret. service.As smtLocalSe rviceUtil;
  152   import gov .va.caret. service.Bg LaeLocalSe rviceUtil;
  153   import gov .va.caret. service.Bl sReLocalSe rviceUtil;
  154   import gov .va.caret. service.Bo xGpLocalSe rviceUtil;
  155   import gov .va.caret. service.Ca llLocalSer viceUtil;
  156   import gov .va.caret. service.Ca retLocalSe rviceUtil;
  157   import gov .va.caret. service.Ce spLocalSer viceUtil;
  158   import gov .va.caret. service.Cl SocLocalSe rviceUtil;
  159   import gov .va.caret. service.Do cumLocalSe rviceUtil;
  160   import gov .va.caret. service.Fa cilLocalSe rviceUtil;
  161   import gov .va.caret. service.Le tterLocalS erviceUtil ;
  162   import gov .va.caret. service.No teLocalSer viceUtil;
  163   import gov .va.caret. service.Pa yLgLocalSe rviceUtil;
  164   import gov .va.caret. service.Pe rsnLocalSe rviceUtil;
  165   import gov .va.caret. service.St iPtLocalSe rviceUtil;
  166   import gov .va.caret. service.Vc gAnLocalSe rviceUtil;
  167   import gov .va.caret. service.Vc gLocalServ iceUtil;
  168   import gov .va.caret. service.Ve ndrLocalSe rviceUtil;
  169   import gov .va.caret. service.Wa ivrLocalSe rviceUtil;
  170   import gov .va.caret. service.Wo rImLocalSe rviceUtil;
  171   import gov .va.caret. service.Wo rSeLocalSe rviceUtil;
  172   import gov .va.caret. service.im pl.FmsOgSu pport;
  173   import gov .va.caret. service.th read.NonCl usteredMon itor;
  174   import gov .va.caret. service.ti u.TiuServi ce;
  175   import gov .va.caret. soc.SocCac hedReportU til;
  176   import gov .va.caret. util.Caret Map;
  177   import gov .va.caret. util.Caret StrPool;
  178   import gov .va.caret. util.Caret Util;
  179   import gov .va.caret. util.CslHe cIdentityP aram;
  180   import gov .va.caret. util.Perso nSearches;
  181   import gov .va.caret. util.Toolb ox;
  182   import gov .va.caret. view.Cache dReport;
  183   import gov .va.caret. view.Caret Param;
  184   import gov .va.caret. view.Resul tMap;
  185   import gov .va.caret. workflow.O wnerQueue;
  186   import gov .va.caret. workflow.Q ueAction;
  187   import gov .va.caret. workflow.W orkName;
  188   import gov .va.med.vi a.service. TextTO;
  189   import gov .via.sts.s ervice.Sts Service;
  190  
  191  
  192   public cla ss CaretAc tionComman d extends  ActionComm and implem ents Seria lizable {
  193           
  194   private st atic final  long seri alVersionU ID = 22515 0078003840 9153L;
  195           
  196   @ProcessAc tion (name ="loadVcgM anagement" )
  197   public voi d loadVcgM anagement(  ActionReq uest reque st, Action Response r esponse )  {
  198  
  199           if  ( !CActio n.canDoCar et(request , CaretCan .MANAGE_VC G.name() )  ) {
  200                    _log .error("Pe rmissions  error");
  201                    retu rn;
  202           }
  203           
  204           Se t<Long> ca regivers =  new HashS et<Long>() ;
  205           Ma p<Long,Str ing> careg iversByLev el = new H ashMap<Lon g,String>( );
  206           lo ng worImId  = ParamUt il.getLong (request,  CaretStrPo ol.WORK_ID );
  207           lo ng vcgId =  ParamUtil .getLong(  request, C aretStrPoo l.VCGID );
  208           if  ( vcgId = = 0 ){
  209                    vcgI d = (Long)  request.g etAttribut e(CaretStr Pool.VCGID );
  210           }
  211           
  212           Ma p<String,  Object> fo rm = Resul tMap.getFo rm(request );
  213           fo rm.put(Car etStrPool. WORK_ID, w orImId);
  214           tr y {
  215                    VcgS upport vcg  = null;
  216                    VcgA n app = nu ll;
  217                    if (  vcgId !=  0 ){
  218                             vcg =  VcgSupport .getVcgSup port(vcgId );
  219                             vcg.se tViewable(  request ) ;
  220                             if (!  vcg.isView Member() )  {
  221                                      _log.err or("Facili ty members hip group  missing");
  222                                      return;
  223                             }
  224                             long a ssociate =  ParamUtil .getLong(r equest, "a ssociate") ;
  225                             if ( a ssociate >  0 ) {
  226                                      associat eWorkItem  ( associat e, vcgId,  request );
  227                             }
  228                             
  229                             //StsS ervice.get EmrSvcInte rface(vcg,  request);
  230                             app =   VcgAnLoca lServiceUt il.getRece nt(vcgId);
  231                             if ( a pp == null  ){
  232                                      app = ne w VcgAnImp l();
  233                             }
  234                             List<D ocum> supp ortDocs =  new ArrayL ist<Docum> ();
  235  
  236                             
  237                             Dashbo ardConfig  dashConfig  = ( Dashb oardConfig  ) request .getPortle tSession() .getAttrib ute( Caret StrPool.DA SHBOARD_CO NFIG );
  238                             if ( d ashConfig  instanceof  CbopcDash boardConfi g ){
  239                                      form.put ("queueIds ", ((Cbopc DashboardC onfig)dash Config).ge tQueueIds( ));
  240                             } else  {
  241                                      form.put ("queueIds ", "-1");
  242                                      if ( das hConfig in stanceof F acilityDas hboardConf ig ) {
  243                                               ResultMap. getCaretMa p(request) .put( Care tStrPool.V HA_MEMBER,  CaretUtil .getVhaOrg List( requ est ) );
  244                                      }
  245                             }
  246                             
  247                             form.p ut("suppor tDocs", su pportDocs  );
  248                             
  249   //                        String [] reasons  = new Str ing[] {"ti er", "appe aled-disap proved-",  "appealed- revoked-"} ;
  250                             if ( v cg.getPrim aryId() >  0 ) {
  251                                      int tier s = ApealL ocalServic eUtil.coun tByOwner2( vcg.getPri maryVcgAnI d(), vcg.g etPrimaryI d(), new S tring[] {" tier"});
  252                                      int revo kes = Apea lLocalServ iceUtil.co untByOwner 2(vcg.getP rimaryVcgA nId(), vcg .getPrimar yId(), new  String[]  {"appealed -revoked-" });
  253                                      int disa pproves =  ApealLocal ServiceUti l.countByO wner2(vcg. getPrimary VcgAnId(),  vcg.getPr imaryId(),  new Strin g[] {"appe aled-disap proved-"}) ;
  254                                      form.put ("primaryT ierAppeals ", ApealLo calService Util.getBy Owner2(vcg .getPrimar yVcgAnId() , vcg.getP rimaryId() , new Stri ng[] {"tie r"}) );
  255                                      form.put ("primaryR evocationA ppeals", A pealLocalS erviceUtil .getByOwne r2(vcg.get PrimaryVcg AnId(), vc g.getPrima ryId(), ne w String[]  {"appeale d-revoked- "}) );
  256                                      form.put ("primaryD isapproval Appeals",  ApealLocal ServiceUti l.getByOwn er2(vcg.ge tPrimaryVc gAnId(), v cg.getPrim aryId(), n ew String[ ] {"appeal ed-disappr oved-"}) ) ;
  257                                      form.put ("primaryA ppeals", t iers+revok es+disappr oves);
  258                             }
  259                             if ( v cg.getSeco ndaryId()  > 0 ) {
  260                                      int revo kes = Apea lLocalServ iceUtil.co untByOwner 2(vcg.getS econdaryVc gAnId(), v cg.getSeco ndaryId(),  new Strin g[] {"appe aled-revok ed-"});
  261                                      int disa pproves =  ApealLocal ServiceUti l.countByO wner2(vcg. getSeconda ryVcgAnId( ), vcg.get SecondaryI d(), new S tring[] {" appealed-d isapproved -"});
  262                                      form.put ("secondar yRevocatio nAppeals",  ApealLoca lServiceUt il.getByOw ner2(vcg.g etSecondar yVcgAnId() , vcg.getS econdaryId (), new St ring[] {"a ppealed-re voked-"})  );
  263                                      form.put ("secondar yDisapprov alAppeals" , ApealLoc alServiceU til.getByO wner2(vcg. getSeconda ryVcgAnId( ), vcg.get SecondaryI d(), new S tring[] {" appealed-d isapproved -"}) );
  264                                      form.put ("secondar yAppeals",  revokes+d isapproves );
  265                             }
  266                             if ( v cg.getSeco ndaryTwoId () > 0 ) {
  267                                      int revo kes = Apea lLocalServ iceUtil.co untByOwner 2(vcg.getS econdaryTw oVcgAnId() , vcg.getS econdaryTw oId(), new  String[]  {"appealed -revoked-" });
  268                                      int disa pproves =  ApealLocal ServiceUti l.countByO wner2(vcg. getSeconda ryTwoVcgAn Id(), vcg. getSeconda ryTwoId(),  new Strin g[] {"appe aled-disap proved-"}) ;
  269                                      form.put ("secondar yTwoRevoca tionAppeal s", ApealL ocalServic eUtil.getB yOwner2(vc g.getSecon daryTwoVcg AnId(), vc g.getSecon daryTwoId( ), new Str ing[] {"ap pealed-rev oked-"}) ) ;
  270                                      form.put ("secondar yDisapprov alAppeals" , ApealLoc alServiceU til.getByO wner2(vcg. getSeconda ryTwoVcgAn Id(), vcg. getSeconda ryTwoId(),  new Strin g[] {"appe aled-disap proved-"})  );
  271                                      form.put ("secondar yTwoAppeal s", revoke s+disappro ves);
  272                             }
  273                             Result Map.getCar etMap(requ est).put(  CaretStrPo ol.VCG_UPL OAD_FILE_T YPES, Arra ys.asList( FileType.v alues()) ) ;
  274                             form.p ut(CaretSt rPool.VCG_ UPLOAD_FIL E_TYPES, A rrays.asLi st(FileTyp e.values() ));
  275                             
  276                             //_log .info("num ber of sup porting do cs is : "+ supportDoc s.size());
  277                             
  278                    }
  279                    
  280                    form .put(Caret StrPool.VC GAN, app);
  281                    vcg. loadPermis sionState(  request ) ;
  282                    form .put("vcg" , vcg);
  283                    
  284                                                       
  285                    
  286                    //** *Start of  Supporting  Doc Code  ****           
  287                    VcgS upport vcg Support =  new VcgSup port(vcg);
  288                    vcgS upport.get Supporting DocData();
  289                                      
  290                    form .put("vcgD ocsCurrent ", vcgSupp ort.getVcg DocsCurren t());
  291                    form .put("vcgD ocsCurrent Size", vcg Support.ge tVcgDocsCu rrent().si ze());
  292  
  293                    bool ean hasDel eteAccess  = false;
  294                    if ( CAction.ca nDoCaret(r equest, Ca retCan.UPL OAD_VCG_FI LE.name()) ){
  295                             hasDel eteAccess  = true;
  296                    }
  297                    form .put("hasD eleteAcces s", hasDel eteAccess) ;
  298  
  299                    // P eriodic As sessments  code 
  300                    Stri ng section  = ParamUt il.getStri ng(request , "section ", "");
  301                    form .put("sect ion", sect ion);
  302                    
  303                    form .put("EaE" , CaretUti l.isMviEna bled());
  304                    
  305                    //** *Start of  Assessment s Code***                 
  306                    form .put(Caret StrPool.VE TERAN_ID,  app.getVet eranId() ) ;
  307                    if (  vcgId > 0  ){
  308                             //get  all applic ations for  the vcg r ecord (vcg id) - then  check for  IN_PROCES S apps
  309                             List<V cgAn> vcgA nList= Vcg AnLocalSer viceUtil.g etByVcg(vc gId);                              
  310                             
  311                             for(Vc gAn vcgAn: vcgAnList)
  312                             {
  313                                      String d ateStr = T oolbox.for matDateCpr s(vcgAn.ge tReceivedD ate());
  314                                      if(vcg.g etPrimaryV cgAnId()== vcgAn.getV cgAnId()){
  315                                               caregivers .add(vcgAn .getPrimar yId());
  316                                               caregivers ByLevel.pu t(vcgAn.ge tPrimaryId (),"primar y");                                     
  317                                               form.put(" primaryVal idAppDate" , dateStr) ;
  318                                               List<Assmt > training s = AssmtL ocalServic eUtil.find ByCaregive rTypes(vcg .getPrimar yId(), new  String[]  { "primary Training", "secondary Training", "secondary TwoTrainin g" } );
  319                                               form.put(" cgTraining Date" + vc g.getPrima ryId(), tr ainings.is Empty()? n ull: Toolb ox.formatD ateCprs( t rainings.g et(0).getC ompletionD ate() ) );                               }
  320                                      if(vcg.g etSecondar yVcgAnId() ==vcgAn.ge tVcgAnId() ){
  321                                               caregivers .add(vcgAn .getSecond aryId());
  322                                               caregivers ByLevel.pu t(vcgAn.ge tSecondary Id(),"seco ndary");                                          
  323                                               form.put(" secondaryV alidAppDat e", dateSt r);
  324                                               List<Assmt > training s = AssmtL ocalServic eUtil.find ByCaregive rTypes(vcg .getSecond aryId(), n ew String[ ] { "prima ryTraining ","seconda ryTraining ","seconda ryTwoTrain ing" } );
  325                                               form.put(" cgTraining Date" + vc g.getSecon daryId(),  trainings. isEmpty()?  null: Too lbox.forma tDateCprs(  trainings .get(0).ge tCompletio nDate() )  );
  326                                      }                                   
  327                                      if(vcg.g etSecondar yTwoVcgAnI d()==vcgAn .getVcgAnI d()){
  328                                               caregivers .add(vcgAn .getSecond aryTwoId() );
  329                                               caregivers ByLevel.pu t(vcgAn.ge tSecondary TwoId(),"s econdaryTw o");                                            
  330                                               form.put(" secondaryT woValidApp Date", dat eStr);
  331                                               List<Assmt > training s = AssmtL ocalServic eUtil.find ByCaregive rTypes(vcg .getSecond aryTwoId() , new Stri ng[] { "pr imaryTrain ing","seco ndaryTrain ing","seco ndaryTwoTr aining" }  );
  332                                               form.put(" cgTraining Date" + vc g.getSecon daryTwoId( ), trainin gs.isEmpty ()? null:  Toolbox.fo rmatDateCp rs( traini ngs.get(0) .getComple tionDate()  ) );                                  
  333                                      }
  334                             }
  335                             
  336                             //for  periodic a ssessments
  337                             if(vcg .getPrimar yDispReaso n()!=null  && (vcg.is Approved(v cg.getPrim aryDispRea son())||(v cg.isReins tated(vcg. getPrimary DispReason ())))){
  338                                      String d ateStr = T oolbox.for matDateCpr s(vcg.getP rimaryDisp ositionDat e());
  339                                      form.put ("primaryA pprovalDat e", dateSt r);                                  
  340                             }
  341                    
  342                             loadAs sessments( request, f orm, vcg);
  343                             
  344                             String  showSecti on = Param Util.getSt ring(reque st, CaretS trPool.SHO W_SECTION,  "");
  345                             reques t.setAttri bute("show Section",  showSectio n);
  346                             if(sho wSection!= null && !s howSection .equals("" )){
  347                                      request. setAttribu te("showAs sessments" , true);                     
  348                             }
  349                    }
  350                    //** *End of As sessments  Code***
  351  
  352                    Dash boardConfi g dashboar dConfig =  (Dashboard Config)req uest.getPo rtletSessi on().getAt tribute(Ca retStrPool .DASHBOARD _CONFIG);
  353                    if (  dashboard Config ins tanceof Fa cilityDash boardConfi g ){
  354                             try {
  355                                      Map<Stri ng,Long> g roupIds =  new TreeMa p<String,L ong>();
  356                                      for( Org anization  org: Organ izationLoc alServiceU til.getUse rOrganizat ions( Port alUtil.get UserId(req uest) ) ){
  357                                               if ( org.g etName().t oLowerCase ().startsW ith("visn" ) ){
  358                                                       fo r ( Organi zation des cendant :  org.getDes cendants()  ){
  359                                                                Faci l facil =  FacilLocal ServiceUti l.getByOrg Id(descend ant.getPri maryKey()) ;
  360                                                                grou pIds.put(  facil.getF acilityNum ber() + St ringPool.D ASH + desc endant.get Name(), de scendant.g etOrganiza tionId() ) ;
  361                                                       }
  362                                               } else {
  363                                                       Fa cil facil  = FacilLoc alServiceU til.getByO rgId(org.g etPrimaryK ey());
  364                                                       gr oupIds.put ( facil.ge tFacilityN umber() +  StringPool .DASH + or g.getName( ), org.get Organizati onId() );
  365                                               }
  366                                      }
  367                                      ResultMa p.getCaret Map(reques t).put( Ca retStrPool .WORKITEM_ GROUPS, gr oupIds);
  368                             } catc h (SystemE xception e ) {
  369                                      e.printS tackTrace( );
  370                             }
  371                             Result Map.getCar etMap(requ est).put(  CaretStrPo ol.VHA_SYS TEM, Caret Util.getVh aOrgTreeNo District(  PortalUtil .getCompan yId( reque st ), true  ) );
  372                    }
  373                    requ est.setAtt ribute( Ca retStrPool .TRACKER,  CaretParam .trackNdx(  request )  );
  374                    Resu ltMap.getC aretMap(re quest).put ("groupId" , Collecti ons.single ton( vcg.g etGroupId( ) ) );
  375                    Resu ltMap.getC aretMap(re quest).put ("noteCont ext", "vcg ");
  376                    Resu ltMap.getC aretMap(re quest).put ("context" , "manageV cg");
  377                    
  378                    //** * Training  Validatio n ***//
  379                    Map< Long,List< Persn>> cg Map = Pers onSearches .getExisti ngPersonsM apByLastNa mePhoneNum berBirthDa te(caregiv ers);
  380                    //Ma p<Long,Lis t<Persn>>  cgMap = Pe rsonSearch es.getExis tingPerson sMapByLast NameSSNBir thDateGend er(PortalU til.getUse r(request) , caregive rs);
  381                    //
  382                    Long  classPk =  ParamUtil .getLong(r equest, Ca retStrPool .CLASS_PK  );
  383                    Assm t assmt =  AssmtLocal ServiceUti l.fetchAss mt( classP k );
  384                    Assm tSupport a ssmtSuppor t = new As smtSupport (assmt);
  385                    Map< Long,Strin g> earlies tTrainingC ompletionD ateByCareg iverId = a ssmtSuppor t.getEarli estTrainin gCompletio nDateByCar egiver(car egivers,cg Map);
  386                    for( Iterator<L ong> i = e arliestTra iningCompl etionDateB yCaregiver Id.keySet( ).iterator (); i.hasN ext();) {
  387                             Long k ey = i.nex t();
  388                             String  value = e arliestTra iningCompl etionDateB yCaregiver Id.get(key );
  389                             String  caregiver Level = ca regiversBy Level.get( key);
  390                             String  labelByLe vel = care giverLevel  + "Earlie stTraining Date";
  391                             form.p ut(labelBy Level, val ue);
  392                    }
  393                    VcgA n vcgAn =  VcgAnLocal ServiceUti l.fetchVcg An( classP k );
  394                    VcgA nSupport v cgAnSuppor t = new Vc gAnSupport (vcgAn);
  395                    Map< Long,Strin g> earlies tApplicati onReceiveD ateByCareg iverId = v cgAnSuppor t.getEarli estApplica tionReceiv eDateByCar egiver(car egivers, c gMap);
  396                    for( Iterator<L ong> i = e arliestApp licationRe ceiveDateB yCaregiver Id.keySet( ).iterator (); i.hasN ext();) {
  397                             Long k ey = i.nex t();
  398                             String  value = e arliestApp licationRe ceiveDateB yCaregiver Id.get(key );
  399                             String  caregiver Level = ca regiversBy Level.get( key);
  400                             String  labelByLe vel = care giverLevel  + "Earlie stApplicat ionDate"; 
  401                             form.p ut(labelBy Level, val ue);
  402                    }                 
  403                    requ est.setAtt ribute(Car etStrPool. ROLE, ((Da shboardCon fig)reques t.getPortl etSession( ).getAttri bute(Caret StrPool.DA SHBOARD_CO NFIG)).get Role() );
  404                    if (  Toolbox.i sEmpty( vc g.getBlsRa teHourly()  ) && vcgS upport.get H75()!= nu ll ) {// S et the VCG  BLS
  405                             CaretL ocalServic eUtil.save (vcg);
  406                    }
  407                    
  408           }  catch (Ill egalArgume ntExceptio n e) {
  409                    Appl icationWor kFlowExcep tion.handl eException (e);
  410           }  catch (Por talExcepti on e) {
  411                    Appl icationWor kFlowExcep tion.handl eException (e);
  412           }  catch (Sys temExcepti on e) {
  413                    Appl icationWor kFlowExcep tion.handl eException (e);                 
  414           }
  415   }
  416  
  417  
  418           @P rocessActi on (name=" loadBlsRat es")
  419           pu blic void  loadBlsRat es ( Actio nRequest r equest, Ac tionRespon se respons e ) {
  420                    
  421                    if (  !CAction. canDoCaret (request,  CaretCan.V IEW_BLS_RA TES.name()  ) ) {
  422                             _log.e rror("Perm issions er ror");
  423                             return ;
  424                    }
  425                    
  426                    requ est.setAtt ribute( Ca retStrPool .TRACKER,  CaretParam .trackNdx(  request )  );
  427                             if ( _ log.isDebu gEnabled()  ){ 
  428                                      _log.inf o(" Action  loadBLSRa tes...");
  429                             }
  430                             reques t.setAttri bute( Care tStrPool.T RACKER, Ca retParam.t rackNdx( r equest ) ) ;
  431                             respon se.setRend erParamete r(CaretStr Pool.MVC_P ATH, Caret StrPool.BL S_RATES_PA GE);
  432                             try {
  433                                      request. setAttribu te(CaretSt rPool.STAT ES, Region ServiceUti l.getRegio ns( Countr yConstants .DEFAULT_C OUNTRY_ID  ) );
  434                             } catc h (SystemE xception e ) {
  435                                      e.printS tackTrace( );
  436                             }
  437           }
  438           /*
  439           @P rocessActi on (name=" newBlsEntr y")
  440           pu blic void  newBlsEntr y ( Action Request re quest, Act ionRespons e response  ) {
  441                    requ est.setAtt ribute( Ca retStrPool .TRACKER,  CaretParam .trackNdx(  request )  );
  442                    long  zip = Par amUtil.get Long(reque st, "form_ userName") ;
  443                    long  userId =  ParamUtil. getLong(re quest, "fo rm_userNam e");
  444                    
  445                             if ( _ log.isDebu gEnabled()  ){ 
  446                                      _log.inf o(" Action  loadBLSRa tes...");
  447                             }
  448                             reques t.setAttri bute( Care tStrPool.T RACKER, Ca retParam.t rackNdx( r equest ) ) ;
  449                             respon se.setRend erParamete r(CaretStr Pool.MVC_P ATH, Caret StrPool.BL S_RATES_PA GE);
  450           }
  451           */
  452  
  453           @P rocessActi on (name=" loadProces sApplicati on")
  454           pu blic void  loadProces sApplicati on ( Actio nRequest r equest, Ac tionRespon se respons e ) {
  455                    
  456                    if (  !CAction. canDoCaret (request,  CaretCan.P ROCESS_APP LICATIONS. name() ) )  {
  457                             _log.e rror("Perm issions er ror");
  458                             return ;
  459                    }
  460                    
  461                    Map< String, Ob ject> form  = ResultM ap.getForm (request);
  462                    requ est.setAtt ribute( Ca retStrPool .TRACKER,  CaretParam .trackNdx(  request )  );
  463                    long  worImId =  ParamUtil .getLong(r equest, Ca retStrPool .WORK_ID);
  464                    form .put(Caret StrPool.WO RK_ID, wor ImId);
  465                    try  {
  466                             if ( w orImId > 0  ){
  467                                      
  468                                      long vcg AnId = Par amUtil.get Long(reque st, CaretS trPool.PRI MARY_KEY);
  469                                      _log.inf o("primary  key is :  "+vcgAnId) ;
  470                                      VcgAn ap p = VcgAnL ocalServic eUtil.getV cgAn( vcgA nId );
  471                                      Veteran  veteran =  new Vetera n( PersnLo calService Util.getPe rsn( app.g etVeteranI d() ) );
  472                                      
  473                                      form.put ( CaretStr Pool.VETER AN_PERSN,  veteran );
  474                                      Boolean  verifiedVe teranOnly  = true; //  || String Pool.TRUE. equals( Po rtletProps .get("proc ess-app-ve teran.regi stered") ) ;
  475                                      form.put ( CaretStr Pool.REGIS TERED_ONLY , verified VeteranOnl y );
  476                                      
  477                                      if ( app .getPrimar yId() > 0  ){
  478                                               form.put(C aretStrPoo l.PRIMARY_ PERSN, new  Primary ( PersnLocal ServiceUti l.getPersn ( app.getP rimaryId()  ) ) );
  479                                      }
  480                                      if ( app .getSecond aryId() >  0 ){
  481                                               form.put(C aretStrPoo l.SECONDAR Y_PERSN, n ew Seconda ry (PersnL ocalServic eUtil.getP ersn( app. getSeconda ryId() ) )  );
  482                                      }
  483                                      if ( app .getSecond aryTwoId()  > 0 ){
  484                                               form.put(C aretStrPoo l.SECONDAR Y_TWO_PERS N, new Sec ondaryTwo  (PersnLoca lServiceUt il.getPers n( app.get SecondaryT woId() ) )  );
  485                                      }
  486                                      String a ctives = A rrays.deep ToString(  veteran.ge tVcgActive s() );
  487                                      form.put (CaretStrP ool.ACTIVE _VCG, acti ves.substr ing(1,acti ves.length ()-2) );
  488                                      form.put ("workType ", WorImLo calService Util.getWo rIm(worImI d).getType () );
  489                                      form.put (CaretStrP ool.VCGAN,  app);
  490                                      
  491                                      List<Doc um> suppor tDocs = Do cumLocalSe rviceUtil. getByPrima ryKey( vcg AnId );
  492                                      form.put ("supportD ocs", supp ortDocs );
  493                                      _log.inf o("number  of support ing docs i s : "+supp ortDocs.si ze());
  494                                      form.put ("veteranI d", app.ge tVeteranId () );
  495                                      ResultMa p.getCaret Map(reques t).put("ge nderTypes" , PortletP rops.get(" persn.gend er.types") .split(Str ingPool.CO MMA) ) ;
  496                                      response .setRender Parameter( CaretStrPo ol.MVC_PAT H, CaretSt rPool.VCG_ DISPOSITIO N_PAGE);
  497                             }
  498                    } ca tch (Illeg alArgument Exception  e) {
  499                             Applic ationWorkF lowExcepti on.handleE xception(e );
  500                    } ca tch (Porta lException  e) {
  501                             Applic ationWorkF lowExcepti on.handleE xception(e );
  502                    } ca tch (Syste mException  e) {
  503                             Applic ationWorkF lowExcepti on.handleE xception(e );
  504                    }
  505                    
  506           }
  507           
  508           pu blic void  loadAssess ments( Act ionRequest  request,  Map<String ,Object> f orm, Vcg v cg) 
  509           {
  510                    try 
  511                    {                         
  512                             AssmtB ean primar yClinical  = new Assm tBean(new  AssmtImpl( ), CaretSt rPool.PRIM ARY_CLINIC AL);                                 
  513                             AssmtB ean primar yAssessmen t = new As smtBean(ne w AssmtImp l(), Caret StrPool.PR IMARY_ASSE SSMENT);                    
  514                             AssmtB ean primar yTraining  = new Assm tBean(new  AssmtImpl( ), CaretSt rPool.PRIM ARY_TRAINI NG);                                 
  515                             AssmtB ean primar yInHome =  new AssmtB ean(new As smtImpl(),  CaretStrP ool.PRIMAR Y_IN_HOME) ;                                    
  516                             AssmtB ean second aryClinica l = new As smtBean(ne w AssmtImp l(), Caret StrPool.SE CONDARY_CL INICAL); 
  517                             AssmtB ean second aryAssessm ent = new  AssmtBean( new AssmtI mpl(), Car etStrPool. SECONDARY_ ASSESSMENT ); 
  518                             AssmtB ean second aryTrainin g = new As smtBean(ne w AssmtImp l(), Caret StrPool.SE CONDARY_TR AINING); 
  519                             AssmtB ean second aryTwoClin ical = new  AssmtBean (new Assmt Impl(), Ca retStrPool .SECONDARY _TWO_CLINI CAL); 
  520                             AssmtB ean second aryTwoAsse ssment = n ew AssmtBe an(new Ass mtImpl(),  CaretStrPo ol.SECONDA RY_TWO_ASS ESSMENT); 
  521                             AssmtB ean second aryTwoTrai ning = new  AssmtBean (new Assmt Impl(), Ca retStrPool .SECONDARY _TWO_TRAIN ING); 
  522                             
  523                             List<A ssmt> comp letedAsses smentList  = AssmtLoc alServiceU til.findBy VcgId(vcg. getVcgId() );
  524                             
  525                             long y ear=0;
  526                             for(As smt assess ment:compl etedAssess mentList)
  527                             {
  528                                      //get ac tive asses sments for  the careg iver
  529                                      if(asses sment.isAc tive())
  530                                      {
  531                                               String dat eStr = Too lbox.forma tDateCprs( assessment .getComple tionDate() );                                   
  532                                               if(assessm ent.getTyp e().equals (CaretStrP ool.PRIMAR Y_CLINICAL ) && asses sment.getC aregiverId ()==vcg.ge tPrimaryId ()){
  533                                                       pr imaryClini cal.setAss essment(as sessment);
  534                                                       pr imaryClini cal.setFor mattedcomp letionDate (dateStr);                                        
  535                                               }else if(a ssessment. getType(). equals(Car etStrPool. PRIMARY_AS SESSMENT)  && assessm ent.getCar egiverId() ==vcg.getP rimaryId() ){
  536                                                       pr imaryAsses sment.setA ssessment( assessment );
  537                                                       pr imaryAsses sment.setF ormattedco mpletionDa te(dateStr );
  538                                               }else if(a ssessment. getType(). equals(Car etStrPool. PRIMARY_TR AINING) &&  assessmen t.getCareg iverId()== vcg.getPri maryId()){
  539                                                       pr imaryTrain ing.setAss essment(as sessment);
  540                                                       pr imaryTrain ing.setFor mattedcomp letionDate (dateStr);
  541                                               }else if(a ssessment. getType(). equals(Car etStrPool. PRIMARY_IN _HOME) &&  assessment .getCaregi verId()==v cg.getPrim aryId()){
  542                                                       pr imaryInHom e.setAsses sment(asse ssment);
  543                                                       pr imaryInHom e.setForma ttedcomple tionDate(d ateStr);
  544                                               }else if(a ssessment. getType(). equals(Car etStrPool. SECONDARY_ CLINICAL)  && assessm ent.getCar egiverId() ==vcg.getS econdaryId ()){
  545                                                       se condaryCli nical.setA ssessment( assessment );
  546                                                       se condaryCli nical.setF ormattedco mpletionDa te(dateStr );
  547                                               }else if(a ssessment. getType(). equals(Car etStrPool. SECONDARY_ ASSESSMENT ) && asses sment.getC aregiverId ()==vcg.ge tSecondary Id()){
  548                                                       se condaryAss essment.se tAssessmen t(assessme nt);
  549                                                       se condaryAss essment.se tFormatted completion Date(dateS tr);
  550                                               }else if(a ssessment. getType(). equals(Car etStrPool. SECONDARY_ TRAINING)  && assessm ent.getCar egiverId() ==vcg.getS econdaryId ()){
  551                                                       se condaryTra ining.setA ssessment( assessment );
  552                                                       se condaryTra ining.setF ormattedco mpletionDa te(dateStr );
  553                                               }else if(a ssessment. getType(). equals(Car etStrPool. SECONDARY_ TWO_CLINIC AL) && ass essment.ge tCaregiver Id()==vcg. getSeconda ryTwoId()) {
  554                                                       se condaryTwo Clinical.s etAssessme nt(assessm ent);
  555                                                       se condaryTwo Clinical.s etFormatte dcompletio nDate(date Str);
  556                                               }else if(a ssessment. getType(). equals(Car etStrPool. SECONDARY_ TWO_ASSESS MENT) && a ssessment. getCaregiv erId()==vc g.getSecon daryTwoId( )){
  557                                                       se condaryTwo Assessment .setAssess ment(asses sment);
  558                                                       se condaryTwo Assessment .setFormat tedcomplet ionDate(da teStr);
  559                                               }else if(a ssessment. getType(). equals(Car etStrPool. SECONDARY_ TWO_TRAINI NG) && ass essment.ge tCaregiver Id()==vcg. getSeconda ryTwoId()) {
  560                                                       se condaryTwo Training.s etAssessme nt(assessm ent);
  561                                                       se condaryTwo Training.s etFormatte dcompletio nDate(date Str);
  562                                               }
  563                                              
  564                                               if(assessm ent.getYea r()>year){
  565                                                       ye ar = asses sment.getY ear();
  566                                               }
  567                                      }
  568                             }
  569                                              
  570                             
  571                             List<A ssmtBean>  primaryAss essmentLis t = new Ar rayList<As smtBean>() ;
  572                             primar yAssessmen tList.add( primaryCli nical);
  573                             primar yAssessmen tList.add( primaryAss essment);
  574                             primar yAssessmen tList.add( primaryTra ining);
  575                             primar yAssessmen tList.add( primaryInH ome);
  576                             
  577                             List<A ssmtBean>  secondaryA ssessmentL ist = new  ArrayList< AssmtBean> ();
  578                             second aryAssessm entList.ad d(secondar yClinical) ;
  579                             second aryAssessm entList.ad d(secondar yAssessmen t);
  580                             second aryAssessm entList.ad d(secondar yTraining) ;
  581  
  582                             List<A ssmtBean>  secondaryT woAssessme ntList = n ew ArrayLi st<AssmtBe an>();
  583                             second aryTwoAsse ssmentList .add(secon daryTwoCli nical);
  584                             second aryTwoAsse ssmentList .add(secon daryTwoAss essment);
  585                             second aryTwoAsse ssmentList .add(secon daryTwoTra ining);
  586  
  587                             form.p ut("primar yAssessmen tList", pr imaryAsses smentList) ;
  588                             form.p ut("second aryAssessm entList",  secondaryA ssessmentL ist);
  589                             form.p ut("second aryTwoAsse ssmentList ", seconda ryTwoAsses smentList) ;                               
  590                             
  591                             
  592                             //**** Start for  Periodic A ssessments *****
  593                             
  594                             //get  current se t of perio dic assess ments
  595                             List<A ssmtBean>  periodicAs sessmentLi st = new A rrayList<A ssmtBean>( );
  596                             for(As smt assess ment:compl etedAssess mentList)
  597                             {
  598                                      AssmtBea n assmtBea n = new As smtBean(ne w AssmtImp l(), "");
  599                                      //String  completio nDateStr =  Toolbox.f ormatDateC prs(assess ment.getCo mpletionDa te());
  600                                      String c ompletionD ateStr = " ";
  601                                      if(asses sment.isAc tive() &&  assessment .getYear() >0 && (yea r==assessm ent.getYea r() || (ye ar-1)==ass essment.ge tYear()))
  602                                      {
  603                                               String sch eduleDateS tr = Toolb ox.formatD ateCprs(as sessment.g etSchedule Date());
  604                                               if(assessm ent.getMod e().equals (CaretStrP ool.NOT_CO MPLETED) & & assessme nt.getComp letionDate ()==null){
  605                                                       co mpletionDa teStr = "" ;
  606                                               }else{
  607                                                       co mpletionDa teStr = To olbox.form atDateCprs (assessmen t.getCompl etionDate( ));
  608                                               }
  609                                                                                          
  610                                               assmtBean. setAssessm ent(assess ment);
  611                                               assmtBean. setFormatt edSchedule Date(sched uleDateStr );                                       
  612                                               assmtBean. setFormatt edcompleti onDate(com pletionDat eStr);                                            
  613                                               periodicAs sessmentLi st.add(ass mtBean);
  614                                      }
  615                                      //_log.i nfo("asses sment id i s : "+asse ssment.get AssmtId()) ;
  616                             }        
  617                             
  618                             //_log .info("per iodic assm t number i s : "+peri odicAssess mentList.s ize());
  619  
  620                             form.p ut("period icAssessme ntList", p eriodicAss essmentLis t);
  621                             form.p ut("period icAssessme ntSize", p eriodicAss essmentLis t.size());
  622                             
  623                    } ca tch (Appli cationWork FlowExcept ion e) {
  624                             Applic ationWorkF lowExcepti on.handleE xception(e );
  625                    }
  626           }
  627  
  628           
  629           @P rocessActi on (name=" workClose" )
  630           pu blic void  workClose  ( ActionRe quest requ est, Actio nResponse  response )  {
  631                    _log .info("wor kClose");
  632                    if (  !( CActio n.canDoCar et(request , CaretCan .ASSOCIATE _REFERRAL. name() ) | | CAction. canDoCaret (request,  CaretCan.C BOPC_HELD_ PAYMENT_Q)  ) ) {
  633                             _log.e rror("Perm issions er ror");
  634                             return ;
  635                    }
  636                    Serv iceContext  sc = Care tParam.set CaretServi ceContext( request);
  637                    Stri ng workTyp e = reques t.getParam eter("work Type");
  638                    if (  "rejected Payments". equals(wor kType ) ||  "returned Payments". equals(wor kType ) ||  "heldPaym ents".equa ls(workTyp e ) ) {
  639                             
  640                             String  tracker =  ParamUtil .getString (request,  CaretStrPo ol.TRACKER , StringPo ol.BLANK ) ;
  641                             if ( !  CaretPara m.isTracke d( request , tracker,  true ) ){
  642                                      _log.war n("TRACKER  BLOCKING  action...  ");
  643                                      request. setAttribu te(CaretSt rPool.INVA LID_REQUES T, true);
  644                                      return;
  645                             }
  646                             
  647                             if ( !  CAction.c anDoCaret( request, C aretCan.CB OPC_HELD_P AYMENT_Q)  ) {
  648                                      _log.war n("Access  missing to  release.. .");
  649                                      return;
  650                             }
  651                             Set<Lo ng> workId s = new Ha shSet<Long >();
  652                             for (  String id:  request.g etParamete r( workTyp e +"_rowCh eckerIds") .split(Str ingPool.CO MMA ) ) {
  653                                      
  654                                      if ( "on ".equals(i d)) {
  655                                               continue;
  656                                      }
  657                                      
  658                                      workIds. add( Long. valueOf(id ) );
  659                             }
  660                             if ( ! workIds.is Empty() )  {
  661                                      try {
  662                                               FmsOgSuppo rt.removeH old( sc, w orkIds );
  663                                      } catch  (SystemExc eption | P ortalExcep tion e) {
  664                                               e.printSta ckTrace();
  665                                      }
  666                             }
  667                             return ;
  668                    }
  669                    long  worImId =  ParamUtil .getLong(r equest, Ca retStrPool .WORK_ID);
  670                    try  {
  671                             WorkIt emSupport  workItem =  new WorkI temSupport (WorImLoca lServiceUt il.getWorI m(worImId)  );
  672                             switch  ( WorkTyp e.valueOf(  workItem. getType()  ) ){
  673                             case C ALL_REFERR AL:
  674                             case R EFERRAL:
  675                             case H EC_REFERRA L:
  676                             case H RC_REFERRA L:
  677                             case C SL_REFERRA L:
  678                             case D ELAY_REVIE WED:
  679                                      
  680                                      workItem .setStatus ( WorkStat us.COMPLET E.name() ) ;
  681                                      workItem .setComple tionBy( sc .getUserId () );
  682                                      workItem .setComple tionDate(  sc.getCrea teDate() ) ;
  683                                      
  684                                      CaretLoc alServiceU til.save(w orkItem);
  685                                      _log.inf o("adding  note " + L anguageUti l.get( Loc ale.getDef ault(), Pa ramUtil.ge t(request,  CaretStrP ool.WORK_C OMMENT, St ringPool.B LANK) ) );
  686                                      CaretLoc alServiceU til.addNot e(CaretUti l.createNo te(sc.getC reateDate( ),
  687                                                       wo rImId,
  688                                                       No teSupport. NoteGroup. CLOSE_NOTE .groupId() ,
  689                                                       sc .getUserId (),
  690                                                       Pa ramUtil.ge t(request,  CaretStrP ool.WORK_C OMMENT, St ringPool.B LANK)));
  691                                      break;
  692                             case F AILED_TIU_ NOTE:
  693                                      if ( wor ImId > 0 & & CAction. canDoCaret (request,  CAction.Ca retCan.APP ROVE_TIU_R EWRITE ) ) {
  694                                               if ( workI tem.getCom pletionDat e() == nul l ){
  695                                                       Vc gSupport v cg = new V cgSupport(  VcgLocalS erviceUtil .getVcg( w orkItem.ge tVcgId() )  );
  696                                                       Ba seModel<?>  bm = vcg. getPersonV cgAn( work Item.getCa regiverId( ) );
  697                                                       if  ( bm == n ull ){
  698                                                                bm =  vcg;
  699                                                       }
  700                                                       Wo rkItemSupp ort cscWor k = new Wo rkItemSupp ort( 
  701                                                                         CaretU til.create WorkItem(  sc, vcg.ge tGroupId() , bm, Work Type.TIU_N OTE_REWRIT E, vcg.get VeteranId( ), workIte m.getCareg iverId() )  );
  702                                                       cs cWork.setV cgId( work Item.getVc gId() );
  703                                                       St ring note  = ParamUti l.get(requ est, Caret StrPool.WO RK_COMMENT , StringPo ol.BLANK);
  704                                                       if  ( !Toolbo x.isEmpty( note) ){
  705                                                                Note  noteObj =  CaretUtil .createNot e(sc.getCr eateDate() , worImId,  NoteSuppo rt.NoteGro up.CLOSE_N OTE.groupI d(), sc.ge tUserId(),  note);
  706                                                                Care tLocalServ iceUtil.ad dNote(note Obj);
  707                                                                Care tLocalServ iceUtil.sa ve( cscWor k );
  708                                                                cscW ork.useNot e("tiuRewr iteNote",  noteObj);
  709                                                                work Item.useNo te("tiuRew riteNote",  noteObj);
  710                                                       }
  711                                                       Ca retLocalSe rviceUtil. save( cscW ork );
  712                                                       wo rkItem.set Completion By( sc.get UserId() ) ;
  713                                                       wo rkItem.set Status( Wo rkStatus.C OMPLETE.na me() );
  714                                                       wo rkItem.set Completion Date( sc.g etCreateDa te() );
  715                                                       Ca retLocalSe rviceUtil. save( work Item );
  716                                               }
  717                                      }
  718                             defaul t:
  719                                      break;
  720                             }
  721                    } ca tch (Porta lException  e) {
  722                             Applic ationWorkF lowExcepti on.handleE xception(e );
  723                    } ca tch (Syste mException  e) {
  724                             Applic ationWorkF lowExcepti on.handleE xception(e );
  725                    }
  726           }
  727  
  728           @P rocessActi on (name=" openReferr al")
  729           pu blic void  openReferr al ( Actio nRequest r equest, Ac tionRespon se respons e ) {
  730                    
  731                    if (  !( CActio n.canDoCar et(request , CaretCan .MANAGE_VC G) ) ) {
  732                             _log.e rror("Perm issions er ror");
  733                             return ;
  734                    }
  735                    
  736                    try  {
  737                             WorkTy pe type =  WorkType.v alueOf( Pa ramUtil.ge tString(re quest, "ty pe", Strin gPool.BLAN K) );  
  738                             reques t.setAttri bute(Caret StrPool.WO RK_ID, Par amUtil.get Long(reque st, CaretS trPool.WOR K_ID ) );
  739                             switch  ( type ){
  740                             case C ALL_REFERR AL:
  741                                      loadExis tingCall ( request);
  742                                      request. setAttribu te("enable Soc", fals e);
  743                                      request. setAttribu te("isDisa bled", tru e);
  744                                      request. setAttribu te("dispos itionCall" , false);
  745                                      response .setRender Parameter( CaretStrPo ol.MVC_PAT H, CaretSt rPool.EDIT _CALL_PAGE );
  746                                      break;                             
  747                             case C SL_REFERRA L:
  748                                      loadCall (request);
  749                                      response .setRender Parameter( CaretStrPo ol.MVC_PAT H, CaretSt rPool.EDIT _CALL_PAGE );
  750                                      break;
  751                             case R EFERRAL:
  752                             case H EC_REFERRA L:
  753                             case H RC_REFERRA L:
  754                                      loadRefe rral(reque st);
  755                                      response .setRender Parameter( CaretStrPo ol.MVC_PAT H, CaretSt rPool.EDIT _REFERRAL_ PAGE);
  756                                      break;
  757                             defaul t:
  758                                      break;
  759                             }
  760                             if ( " VCG_MANAGE MENT_PAGE" .equals( P aramUtil.g etString(r equest, "o nPageCompl ete", Stri ngPool.BLA NK) ) ){
  761                                      ResultMa p.getForm( request).p ut("onPage Complete",  "VCG_MANA GEMENT_PAG E" );
  762   //                                 response .setRender Parameter( CaretStrPo ol.MVC_PAT H, CaretSt rPool.VCG_ MANAGEMENT _PAGE);
  763                             }
  764                    } ca tch (Porta lException  e) {
  765                             Applic ationWorkF lowExcepti on.handleE xception(e );
  766                    } ca tch (Illeg alArgument Exception  e) {
  767                             Applic ationWorkF lowExcepti on.handleE xception(e );
  768                    } 
  769                    
  770           }
  771           
  772           @P rocessActi on (name=" loadTen10A pp")
  773           pu blic void  loadVcgAnA pp ( Actio nRequest a ctionReque st, Action Response a ctionRespo nse ) {
  774                    if (  !( CActio n.canDoCar et( action Request, C aretCan.CR EATE_APPLI CATIONS) )  ) {
  775                             _log.e rror("Perm issions er ror");
  776                             return ;
  777                    }
  778                    _log .info("loa dTen10App. .." );
  779                    acti onResponse .setRender Parameter( CaretStrPo ol.MVC_PAT H, "/jsp/i nternal/cr eateTen10. jsp" );
  780                    load StatesAndF acilities(  actionReq uest );
  781           }
  782           
  783           pu blic void  loadStates AndFacilit ies ( Port letRequest  request )  {
  784                    try  {
  785                             Map<St ring,Objec t> caret =  ResultMap .getCaretM ap(request );
  786                             caret. put( Caret StrPool.VH A_SYSTEM,  CaretUtil. getVhaOrgT reeNoDistr ict( Porta lUtil.getC ompanyId(  request ),  true ) );
  787                             try {
  788                                      caret.pu t(CaretStr Pool.STATE S, RegionS erviceUtil .getRegion s( Country Constants. DEFAULT_CO UNTRY_ID )  );
  789                                      caret.pu t(CaretStr Pool.COUNT RIES, Care tUtil.getC ountryMap( ) );
  790                             } catc h (SystemE xception e ) {
  791                                      Applicat ionWorkFlo wException .handleExc eption(e);
  792                             }
  793                             
  794                             
  795                    } ca tch (Porta lException  e) {
  796                             Applic ationWorkF lowExcepti on.handleE xception(e );
  797                    }
  798           }
  799           
  800           pr ivate void  saveBoxGr oups ( Por tletReques t request,  long prim aryKey ){
  801                    try  {
  802                             List<L ong> fmChe cks = Care tParam.loa dSelectedB oxModel(re quest, Car etStrPool. BOX_GROUP) ;
  803  
  804                             String [] radioNa mes = new  String[]{
  805                                               "boxRadioG rp_heardFr omUs", "bo xRadioGrp_ enrolledVa Health", 
  806                                               "boxRadioG rp_dischar gedAfter91 1", "boxRa dioGrp_vet eranScCond ition",
  807                                               "boxRadioG rp_prescre enPcafc"
  808                             };
  809                             for (  String rad io: radioN ames ){
  810                                      Long rad ioId = Par amUtil.get Long(reque st, radio,  0);
  811                                      if ( rad ioId > 0 ) {
  812                                               fmChecks.a dd(radioId );
  813                                      }
  814                             }
  815                             
  816                             if ( p rimaryKey  > 0 ){
  817                                      List<Lon g> updated  = new Arr ayList<Lon g>();
  818                                      List<BgA sn> bgAsnL ist = BoxG pLocalServ iceUtil.ge tBoxGroupA ssociation s( primary Key );
  819                                      for ( Bg Asn bgAsn:  bgAsnList  ){
  820                                               if ( fmChe cks.contai ns( bgAsn. getBoxGpId () ) ){
  821                                                       if  ( !bgAsn. isSelected () ){
  822                                                                bgAs n.setSelec ted( true  );
  823                                                                Care tLocalServ iceUtil.sa ve( new Bo xedGroupAs sociation( bgAsn) );
  824                                                                upda ted.add( b gAsn.getBo xGpId() );
  825                                                       }
  826                                                       fm Checks.rem ove( bgAsn .getBoxGpI d() );
  827                                               } else {
  828                                                       if  ( bgAsn.i sSelected( ) ){
  829                                                                bgAs n.setSelec ted( false  );
  830                                                                Care tLocalServ iceUtil.sa ve( new Bo xedGroupAs sociation( bgAsn) );
  831                                                       }
  832                                               }
  833                                      }
  834                                      for ( Lo ng boxGpId : fmChecks ){
  835                                               if ( ! upd ated.conta ins( boxGp Id ) ){
  836                                                       Bg Asn bgAsn  = new BgAs nImpl();
  837                                                       bg Asn.setBox GpId( boxG pId );
  838                                                       bg Asn.setOwn erId( prim aryKey );
  839                                                       bg Asn.setSel ected( tru e );
  840                                                       Ca retLocalSe rviceUtil. save( new  BoxedGroup Associatio n(bgAsn) ) ;
  841                                               }
  842                                      }
  843                             } else  {
  844                                      for ( Lo ng boxGpId : fmChecks  ){
  845                                               BgAsn bgAs n = new Bg AsnImpl();
  846                                               bgAsn.setB oxGpId(box GpId);
  847                                               bgAsn.setO wnerId( pr imaryKey ) ;
  848                                               bgAsn.setS elected( t rue );
  849                                               CaretLocal ServiceUti l.save( ne w BoxedGro upAssociat ion(bgAsn)  );
  850                                      }
  851                             }
  852                             
  853                             _log.i nfo(fmChec ks);
  854                    } ca tch (Appli cationWork FlowExcept ion e) {
  855                             Applic ationWorkF lowExcepti on.handleE xception(e );
  856                    }
  857           }
  858           
  859           pr ivate void  saveCall  ( ActionRe quest requ est ) thro ws Applica tionWorkFl owExceptio n{
  860                    _log .info("sav eCall..."  );
  861                    //Ca ll call =  null;
  862                    Call Support ca ll = null;
  863                    Pers on caller  = null;
  864                    Vete ran vetera n = null;
  865                    
  866                    getO utput(requ est);
  867                    Long  callId =  ParamUtil. getLong(re quest, "ca ll_primary Key");
  868                    Long  veteranId  = ParamUt il.getLong (request,  "veteranPe rsn_primar yKey");
  869                    
  870                    Serv iceContext  sc = Care tParam.set CaretServi ceContext( request);
  871                    if (  callId >  0 ){
  872                             try {
  873                                      //call =  CallLocal ServiceUti l.getCall( callId);
  874                                      call = n ew CallSup port(CallL ocalServic eUtil.getC all(callId ));
  875                             } catc h (PortalE xception e ) {
  876                                      Applicat ionWorkFlo wException .handleExc eption(e);
  877                             } catc h (SystemE xception e ) {
  878                                      Applicat ionWorkFlo wException .handleExc eption(e);
  879                             }
  880                    }
  881                    
  882                    if (  call == n ull) {
  883                             //call  = new Cal lImpl();
  884                             call =  new CallS upport(new  CallImpl( ));
  885                    }
  886                             
  887                    Long  callerId  = ParamUti l.getLong( request, " callerPers n_primaryK ey");
  888                    
  889                    Map< Long,Perso n> cachedM VI = (Map< Long,Perso n>) reques t.getPortl etSession( ).getAttri bute(Caret StrPool.CA CHED_MVI);
  890                    if (  cachedMVI  == null ) {
  891                             cached MVI = new  HashMap<>( );
  892                    }
  893                    
  894                    if (  callerId  > 0 ){
  895                             try {
  896                                      if ( cac hedMVI.con tainsKey(c allerId) ) {
  897                                               Persn pers on = null;
  898                                               if ( !Tool box.isEmpt y( cachedM VI.get(cal lerId).get ICN() ) ){
  899                                                       pe rson = Per snLocalSer viceUtil.g etByIcn( c achedMVI.g et(callerI d).getICN( ) );
  900                                               }
  901                                               if ( perso n != null  ){
  902                                                       ca ller = new  Person (  person );
  903                                               } else {
  904                                                       ca ller = new  Person( c achedMVI.g et(callerI d) );
  905                                                       Ca retLocalSe rviceUtil. save(calle r);
  906                                               }
  907                                               callerId =  caller.ge tPrimaryKe y();
  908                                      }
  909                                      
  910                                      caller =  new Perso n( PersnLo calService Util.getPe rsn( calle rId ) );
  911                             } catc h (Excepti on e) {
  912                                      Applicat ionWorkFlo wException .handleExc eption(e);
  913                             }
  914                    }
  915                    bool ean checkF orExisting CallerIden tity = fal se;
  916                    if (  caller ==  null ){
  917                             caller  = new Per son ( new  PersnImpl( ) );
  918                             CaretP aram.loadM odel(reque st, caller , caller.g etModelAtt ributes(). keySet(),  "callerPer sn_");
  919                             checkF orExisting CallerIden tity = tru e;
  920                    }
  921                    else  {
  922                             CaretP aram.loadM odel(reque st, caller , caller.g etModelAtt ributes(). keySet(),  "callerPer sn_");
  923                             if (!C slHecIdent ityParam.c allIdentit yIsVerifie dPerson(ca ller, fals e)) {
  924                                      caller =  new Perso n ( new Pe rsnImpl()  );
  925                                      CaretPar am.loadMod el(request , caller,  CslHecIden tityParam. getIdentit yPropertie s(CslHecId entityPara m.CALL_CAL LER), "cal lerPersn_" );
  926                                      checkFor ExistingCa llerIdenti ty = true;
  927                             }
  928                    }
  929                    if ( checkForEx istingCall erIdentity  || caller .getPersnI d() == 0)  {
  930                             Person  alreadyEx istingCall erPerson =  CslHecIde ntityParam .checkForE xistingIde ntity(CslH ecIdentity Param.CALL _CALLER, c aller);
  931                             if (al readyExist ingCallerP erson != n ull) {
  932                                      _log.inf o("USE EXI STING CALL ER: " + al readyExist ingCallerP erson.getP ersnId());
  933                                      caller =  alreadyEx istingCall erPerson;
  934                             }
  935                    }
  936                    //TO DO: pass l ist of par ameter nam es 
  937                    //// ////////// ////////// ////////// ////////
  938                    Stri ng s_callb ackPref =  request.ge tParameter ("call_cal lbackPref" );
  939                    //ca ll.setCall backPref(s _callbackP ref);
  940                    //_l og.info("M Action deb ug....Care tActionCom mand.saveC all...call _callbackP ref: " + s _callbackP ref);
  941                    Stri ng v5_call backPref =  SocCached ReportUtil .getCallba ckPref_24H ourFormat( s_callback Pref);
  942                    //_l og.info("M Action deb ug....Care tActionCom mand.saveC all...v5_c allbackPre f: " + v5_ callbackPr ef);
  943                    //// ////////// ////////// ////////// ////////                
  944                    call .setCompou ndValue(re quest,"tra nsferRemar ks","call_ ");
  945                    call .setCompou ndValue(re quest,"sum mary","cal l_");                
  946                    Care tParam.loa dModel( re quest, cal l, call.ge tModelAttr ibutes().k eySet(), " call_");
  947                    if ( call.isHan gUp() || c all.isWron gNumber()  || call.is WithoutCon tact()) {
  948                             call.s etCallStat e("complet e");
  949                    }                 
  950                    Care tParam.loa dModelSing leElement( request, c all, "call backPref",  v5_callba ckPref, "c all_");
  951  
  952                    //TO DO: pass l ist of par ameter nam es 
  953                    //mo ved up hig her//Caret Param.load Model(requ est, calle r, caller. getModelAt tributes() .keySet(),  "callerPe rsn_");
  954                    
  955                    bool ean unknow n = ParamU til.getBoo lean(reque st,  "call erPersn_st atusLabel" );
  956                    if (  unknown ) {
  957                             caller .setStatus (CaretStrP ool.UNKNOW N_IDENTITY );
  958                             caller .setFirstN ame(String Pool.BLANK );
  959                             caller .setLastNa me(StringP ool.BLANK) ;
  960                    } el se if ( !T oolbox.isE mpty( call er.getFirs tName() )  ){
  961                             caller .setStatus (StringPoo l.BLANK);
  962                    } 
  963                    
  964                    if (  veteranId  > 0 ){
  965                             try {
  966                                      if ( cac hedMVI.con tainsKey(v eteranId)  ){
  967                                               Persn pers on = null;
  968                                               if ( !Tool box.isEmpt y( cachedM VI.get(vet eranId).ge tICN() ) ) {
  969                                                       pe rson = Per snLocalSer viceUtil.g etByIcn( c achedMVI.g et(veteran Id).getICN () );
  970                                               }
  971                                               if ( perso n != null  ){
  972                                                       ve teran = ne w Veteran  ( person ) ;
  973                                               } else {
  974                                                       ve teran = ne w Veteran(  cachedMVI .get(veter anId) );
  975                                                       Ca retLocalSe rviceUtil. save(veter an);
  976                                               }
  977                                               veteranId  = veteran. getPrimary Key();
  978                                      }
  979                                      veteran  = new Vete ran ( Pers nLocalServ iceUtil.ge tPersn( ve teranId )  );
  980                             } catc h (Excepti on e) {
  981                                      throw ne w Applicat ionWorkFlo wException (e);
  982                             }
  983                    }
  984                    bool ean checkF orExisting VeteranIde ntity = fa lse;
  985                    if (  veteran = = null ){
  986                             vetera n = new Ve teran ( ne w PersnImp l() );
  987                             CaretP aram.loadM odel(reque st, vetera n, veteran .getModelA ttributes( ).keySet() , "veteran Persn_");
  988                             checkF orExisting VeteranIde ntity = tr ue;
  989                    }
  990                    else  {
  991                             CaretP aram.loadM odel(reque st, vetera n, veteran .getModelA ttributes( ).keySet() , "veteran Persn_");
  992                             if (!C slHecIdent ityParam.c allIdentit yIsVerifie dPerson(ve teran, tru e)) {
  993                                      veteran  = new Vete ran ( new  PersnImpl( ) );
  994                                      CaretPar am.loadMod el(request , veteran,  CslHecIde ntityParam .getIdenti tyProperti es(CslHecI dentityPar am.CALL_VE TERAN), "v eteranPers n_");
  995                                      checkFor ExistingVe teranIdent ity = true ;
  996                             }
  997                    }
  998                    if ( checkForEx istingVete ranIdentit y || veter an.getPers nId() == 0 ) {
  999                             Person  alreadyEx istingVete ranPerson  = CslHecId entityPara m.checkFor ExistingId entity(Csl HecIdentit yParam.CAL L_VETERAN,  veteran);
  1000                             if (al readyExist ingVeteran Person !=  null) {
  1001                                      _log.inf o("USE EXI STING VETE RAN: " + a lreadyExis tingVetera nPerson.ge tPersnId() );
  1002                                      veteran  = new Vete ran(alread yExistingV eteranPers on);
  1003                             }
  1004                    }                 
  1005                    //TO DO: pass l ist of par ameter nam es 
  1006                    
  1007                    //mo ved up hig her//Caret Param.load Model(requ est, veter an, vetera n.getModel Attributes ().keySet( ), "vetera nPersn_");
  1008                    
  1009                    if (  veteran.i sForeigner () ){
  1010                             CaretP aram.loadM odel( requ est, veter an, Toolbo x.getAddre ssCollecti on(), Care tStrPool.V ETERAN_PER SN + Caret StrPool.G_ UNDERLINE  );
  1011                    } el se {
  1012                             CaretP aram.loadM odel( requ est, veter an, Toolbo x.getAddre ssCollecti on(), Care tStrPool.V ETERAN_PER SN + Caret StrPool.U_ UNDERLINE  );
  1013                    }
  1014                    
  1015                    if (  call.isSa meAddress( ) ){
  1016                             caller .setAddres s(veteran. getAddress ());
  1017                             caller .setAddres s2(veteran .getAddres s2());
  1018                             caller .setZip(ve teran.getZ ip());
  1019                             caller .setState( veteran.ge tState());
  1020                             caller .setCity(v eteran.get City());
  1021                             caller .setValidA ddress(vet eran.getVa lidAddress ());
  1022                    } el se {
  1023                             if ( c aller.isFo reigner()  ){
  1024                                      CaretPar am.loadMod el( reques t, caller,  Toolbox.g etAddressC ollection( ), CaretSt rPool.CALL ER_PERSN +  CaretStrP ool.G_UNDE RLINE );
  1025                             } else  {
  1026                                      CaretPar am.loadMod el( reques t, caller,  Toolbox.g etAddressC ollection( ), CaretSt rPool.CALL ER_PERSN +  CaretStrP ool.U_UNDE RLINE );
  1027                             }
  1028                    }
  1029                    _log .info("[be fore save]  caller is  " + calle r);
  1030                    _log .info("[be fore save]  veteran i s " + vete ran);                
  1031                    Care tLocalServ iceUtil.sa ve( caller  );
  1032                    Care tLocalServ iceUtil.sa ve( vetera n );
  1033                    _log .info("[af ter save]  caller is  " + caller );
  1034                    _log .info("[af ter save]  veteran is  " + veter an);
  1035                    
  1036                    long  roleId =  (Long)sc.g etAttribut e( CaretSt rPool.ROLE _ID );
  1037                    Them eDisplay t hemeDispla y = (Theme Display) r equest.get Attribute(  WebKeys.T HEME_DISPL AY );
  1038  
  1039                    Stri ng message  = null;
  1040                    if (  call.getP rimaryKey( ) == 0 ){
  1041                             call.s etCreateGr oupId( rol eId );
  1042                             call.s etUserId(  (Long) sc. getAttribu te( CaretS trPool.USE R_ID ) );
  1043                             try {
  1044                                      message  = PortalUt il.getUser (request). getFullNam e() + " cr eated " +
  1045                                                                Lang uageUtil.g et(themeDi splay.getL ocale(), c all.getCal lType()) +  " as " +
  1046                                                                Lang uageUtil.g et(themeDi splay.getL ocale(), c all.getCal lState() )  ; 
  1047                             } catc h (Excepti on e) {
  1048                                      throw ne w Applicat ionWorkFlo wException (e);
  1049                             }
  1050                    }
  1051                    call .setVetera nPersnId(  veteran.ge tPersnId()  );
  1052                    call .setCaller PersnId( c aller.getP ersnId() ) ;
  1053                    if (  call.getC allId() >  0 ){
  1054                             call.s etModifica tionDate(  sc.getCrea teDate() ) ;
  1055                    }
  1056                    if (  call.getC allState()  != null & &
  1057                                      call.get CallState( ).toLowerC ase().cont ains(Caret StrPool.CA LL_STATE_C OMPLETE)
  1058                                      && call. getComplet ionDate()  == null ){
  1059                             call.s etCompleti onDate(sc. getCreateD ate());
  1060                    }
  1061                    //
  1062                    bool ean update CreationDa teAfterSav e = false;
  1063                    Date  newStartD ate = null ;
  1064                    if (  call.getC allId() ==  0 ){
  1065                             //turn Call.Start DateOn//if  (!CallSup port.USE_C REATIONDAT E_FOR_STAR T_DATE) {
  1066                             //turn Call.Start DateOn//         call .setStartD ate( sc.ge tCreateDat e() );
  1067                             //turn Call.Start DateOn//}                          
  1068                             String  callStart DateDispla y = reques t.getParam eter("call StartDateD isplay");
  1069                             String  callStart DateZone =  request.g etParamete r("callSta rtDateZone ");
  1070                             String  callStart DateTimest amp = requ est.getPar ameter("ca llStartDat eTimestamp ");
  1071                             String  callStart DateTime =  request.g etParamete r("callSta rtDateTime ");
  1072  
  1073                             DateFo rmat df =  new Simple DateFormat (Toolbox.C ARET_DATET IME_FORMAT _UI_FULL);
  1074                             //
  1075                             try {n ewStartDat e = df.par se(callSta rtDateTime stamp + "  " + callSt artDateZon e);}
  1076                             catch( Exception  e) {
  1077                                      Applicat ionWorkFlo wException .handleExc eption(e);
  1078                             }
  1079                             _log.i nfo("newSt artDate: "  + newStar tDate);
  1080                             if (To olbox.isSa meDay(newS tartDate,  new Date() )) {
  1081                                      updateCr eationDate AfterSave  = false;
  1082                             }
  1083                             else {
  1084                                      updateCr eationDate AfterSave  = true;                                         
  1085                             }
  1086                    } 
  1087                    
  1088                    //ca ll = (Call )CaretLoca lServiceUt il.save( c all );
  1089                    call  = (CallSu pport) Car etLocalSer viceUtil.s ave( call  );
  1090                    
  1091                    if ( updateCrea tionDateAf terSave &&  newStartD ate != nul l) {
  1092                             try {
  1093                                      Call cal lCopy = Ca llLocalSer viceUtil.g etCall(cal l.getCallI d());
  1094                                      if (Call Support.US E_CREATION DATE_FOR_S TART_DATE)  {
  1095                                               callCopy.s etCreation Date(newSt artDate);
  1096                                      }
  1097                                      CaretLoc alServiceU til.save(c allCopy);
  1098                             }
  1099                             catch( Exception  e) {
  1100                                      Applicat ionWorkFlo wException .handleExc eption(e);
  1101                             }                         
  1102                    }
  1103    
  1104                    if (  CaretStrP ool.CALL_S TATE_REFER RAL.equals ( call.get CallState( ) ) ){
  1105                             WorIm  workItem =  null;
  1106                             
  1107                             if ( v eteran.get GroupId()  > 0  ){//t ype, persn Id
  1108                                      if ( cal l.getWorkP rimaryKey( ) > 0 ){
  1109                                               try {
  1110                                                       wo rkItem = W orImLocalS erviceUtil .getWorIm(  call.getW orkPrimary Key() );
  1111                                                       if  ( workIte m != null  ){
  1112                                                                work Item.setGr oupId( vet eran.getGr oupId() );
  1113                                                                Care tLocalServ iceUtil.sa ve( workIt em );
  1114                                                       }
  1115                                               } catch (P ortalExcep tion e) {
  1116                                                       Ap plicationW orkFlowExc eption.han dleExcepti on(e);
  1117                                               } catch (S ystemExcep tion e) {
  1118                                                       Ap plicationW orkFlowExc eption.han dleExcepti on(e);
  1119                                               }
  1120                                      }
  1121                                      if ( wor kItem == n ull ){
  1122                                               call.setCa llState(Ca retStrPool .CALL_STAT E_COMPLETE );
  1123                                               DashboardC onfig dash Config = (  Dashboard Config ) r equest.get PortletSes sion().get Attribute(  CaretStrP ool.DASHBO ARD_CONFIG  );
  1124                                               call.setCr eateGroupI d( dashCon fig.getRol eId() );
  1125                                               call.setUs erId( (Lon g) sc.getA ttribute(  CaretStrPo ol.USER_ID  ) );
  1126                                               CaretLocal ServiceUti l.save( ca ll );
  1127                                              
  1128                                               WorkType w orkType;
  1129                                               if ( dashC onfig inst anceof Csl DashboardC onfig ){
  1130                                                       wo rkType = W orkType.CS L_REFERRAL ;
  1131                                               } else {
  1132                                                       tr y{
  1133                                                                work Type = Wor kType.valu eOf( dashC onfig.getR ole() + "_ REFERRAL") ;
  1134                                                       }  catch(Exce ption e){
  1135                                                                work Type = Wor kType.REFE RRAL;
  1136                                                       }
  1137                                               }
  1138                                              
  1139                                               workItem =  CaretUtil .createWor kItem(sc,  veteran.ge tGroupId() , call, wo rkType, ve teran.getP ersnId(),  call.getCa llerPersnI d() );
  1140                                              
  1141   //                                          workItem.s etQueId(Ca retStrPool .REFERRAL_ QUE);
  1142                                               CaretLocal ServiceUti l.save( wo rkItem );
  1143                                               //transfer  remarks g o here ? c ompare wit h saveRefe rral() ?
  1144                                               call.setWo rkPrimaryK ey(workIte m.getPrima ryKey());
  1145                                               CaretLocal ServiceUti l.save( ca ll );
  1146                                      }
  1147                                      workItem  = new Wor kItemSuppo rt(workIte m);
  1148                                      if ( !To olbox.isEm pty( call. getTransfe rRemarks()  ) ){
  1149                                               ((WorkItem Support)wo rkItem).us eNote("ref erralRemar k", CaretU til.create Note(sc.ge tCreateDat e(), workI tem.getWor ImId(), No teSupport. NoteGroup. REFERRAL.g roupId(),  sc.getUser Id(), call .getTransf erRemarks( )));
  1150                                      }
  1151                                      if ( !To olbox.isEm pty( call. getSummary () ) ){
  1152                                               ((WorkItem Support)wo rkItem).us eNote("ref erralSumma ry", Caret Util.creat eNote(sc.g etCreateDa te(), work Item.getWo rImId(), N oteSupport .NoteGroup .REFERRAL. groupId(),  sc.getUse rId(), cal l.getSumma ry()));
  1153                                      }
  1154                                      if ( !To olbox.isEm pty( call. getTransfe rredTo() )  ){
  1155                                               ((WorkItem Support)wo rkItem).us eNote("ref erralWarmT ransferTo" , CaretUti l.createNo te(sc.getC reateDate( ), workIte m.getWorIm Id(), Note Support.No teGroup.RE FERRAL.gro upId(), sc .getUserId (), call.g etTransfer redTo()));
  1156                                      }
  1157                                      CaretLoc alServiceU til.save(  workItem ) ;
  1158                             } else  {
  1159                                      throw ne w Applicat ionWorkFlo wException ( "NEED GR OUP ID" );
  1160                             }
  1161                             
  1162                    } el se if ( !C aretStrPoo l.CALL_STA TE_COMPLET E.equals(   call.getC allState()  ) ){
  1163                             CalEt  callEvent  = new CalE tImpl();
  1164                             callEv ent.setCal lId(call.g etCallId() );
  1165                             String Builder sb  = new Str ingBuilder ( call.get CallType()  );
  1166                             sb.app end(CaretS trPool.COL ON_SPACE);
  1167                             if ( c all.isHang Up() ){
  1168                                      sb.appen d("Hang-up , ");
  1169                             }
  1170                             if ( c all.isWith outContact () ){
  1171                                      sb.appen d("Without -contact,  ");
  1172                             }
  1173                             if ( c all.isWron gNumber()  ){
  1174                                      sb.appen d("Wrong-n umber, ");
  1175                             }
  1176                             callEv ent.setCom ment( sb.s ubstring(0 ,sb.length ()-1) );
  1177                             callEv ent.setEve nt( call.g etCallStat e() );
  1178                             callEv ent.setCre ationDate(  sc.getCre ateDate()  );
  1179                             CaretL ocalServic eUtil.save (callEvent );
  1180                    }
  1181                    
  1182                    
  1183                    save BoxGroups( request, c all.getPri maryKey()) ;
  1184                    _log .info("add ing note "  + Languag eUtil.get(  Locale.ge tDefault() , message         ) ) ;
  1185                    Care tLocalServ iceUtil.ad dNote( Car etUtil.cre ateNote(sc .getCreate Date(), ca ll.getCall Id(), Note Support.No teGroup.CA LL_NOTE.gr oupId(), s c.getUserI d(), messa ge) );
  1186                    _log .info("cal l is " + c all);
  1187           }
  1188           
  1189           pr ivate void  saveCall_ callbackDa te ( Actio nRequest r equest, bo olean setC allStatusT oCallBack)  throws Ap plicationW orkFlowExc eption {
  1190                    //_l og.info("M Action deb ug....Care tActionCom mand.saveC all_callba ckDate...s tart");
  1191                    Stri ng soc_cal lbackPref  = request. getParamet er("soc_ca llbackPref ");
  1192                    //_l og.info("M Action deb ug....Care tActionCom mand.saveS oc...soc_c allbackPre f: " + soc _callbackP ref);
  1193                    if ( SocCachedR eportUtil. isCallback PrefEmpty( soc_callba ckPref) &&  !setCallS tatusToCal lBack) {re turn;}
  1194                    //
  1195                    Call  call = nu ll;
  1196  
  1197                    getO utput(requ est);
  1198                    Long  callId =  ParamUtil. getLong(re quest, "so c_callId") ;
  1199                     
  1200                    //_l og.info("M Action deb ug....Care tActionCom mand.saveC all_callba ckDate...c allId: " +  callId);
  1201                    Serv iceContext  sc = Care tParam.set CaretServi ceContext( request);
  1202                    if (  callId >  0 ){
  1203                    try  {
  1204                    call  = CallLoc alServiceU til.getCal l(callId);
  1205                    } ca tch (Porta lException  e) {
  1206                    Appl icationWor kFlowExcep tion.handl eException (e);
  1207                    } ca tch (Syste mException  e) {
  1208                    Appl icationWor kFlowExcep tion.handl eException (e);
  1209                    }
  1210                    }
  1211                    if (  call == n ull) {
  1212                    call  = new Cal lImpl();
  1213                    }
  1214                    //// ////////// ////////// ////////// ////////
  1215                    Stri ng v5_call backPref =  SocCached ReportUtil .getCallba ckPref_24H ourFormat( soc_callba ckPref);
  1216                    //_l og.info("M Action deb ug....Care tActionCom mand.saveC all...v5_c allbackPre f: " + v5_ callbackPr ef);
  1217                    if ( !SocCached ReportUtil .isCallbac kPrefEmpty (v5_callba ckPref)) {
  1218                    call .setCallba ckPref(soc _callbackP ref);
  1219                     
  1220                    }
  1221                    if ( (!SocCache dReportUti l.isCallba ckPrefEmpt y(soc_call backPref))  || setCal lStatusToC allBack) {
  1222                    call .setCallSt ate("csl-c all-back") ;
  1223                    }
  1224                    //// ////////// ////////// ////////// ////////
  1225                    //TO DO: pass l ist of par ameter nam es 
  1226                    Care tParam.loa dModel( re quest, cal l, call.ge tModelAttr ibutes().k eySet(), " call_");
  1227                    //Ca retParam.l oadModelSi ngleElemen t(request,  call, "ca llbackPref ", v5_call backPref,  "call_");
  1228                    Care tLocalServ iceUtil.sa ve(call);
  1229           } 
  1230                    
  1231           pu blic void  saveSoc (  ActionRequ est reques t ){
  1232                    _log .info("sav eSoc()");
  1233                    Date  now = new  Date();
  1234                    Stri ng callIdS  = ParamUt il.get(req uest, "cal lId", Stri ngPool.BLA NK);
  1235                    List <ClSoc> so cList = nu ll;
  1236                    Call  call = nu ll;
  1237                    //
  1238                    long  callId =  Toolbox.is Empty(call IdS) ? 0 :  Long.pars eLong(call IdS);
  1239                    try  {
  1240                             socLis t = ClSocL ocalServic eUtil.find ByCallId(c allId);
  1241                             call =  CallLocal ServiceUti l.getCall(  Long.pars eLong(Para mUtil.get( request, " soc_callId ", StringP ool.BLANK) ) );
  1242                    }
  1243                    catc h(Exceptio n e) {
  1244                             Applic ationWorkF lowExcepti on.handleE xception(e );
  1245                    }
  1246                    bool ean isNew  = Collecti onUtils.is Empty(socL ist);
  1247                    ClSo c oneSoc =  isNew ? n ull : socL ist.get(so cList.size () - 1);           
  1248                    Stri ng attempt Num = oneS oc == null  ? "1" : ( (Integer.p arseInt(on eSoc.getAt temptNum() )) + 1) +  "";
  1249                    try  {                    
  1250                             getOut put(reques t);
  1251                             Servic eContext s c = CaretP aram.setCa retService Context(re quest);
  1252                             String  threshold Met = Para mUtil.get( request, " soc_tresho ldMet", St ringPool.B LANK);                                                   
  1253                             long s ocId = isN ew ? Count erLocalSer viceUtil.i ncrement(  ClSoc.clas s.getName( )) : oneSo c.getClSoc Id();
  1254                             ClSoc  soc = isNe w ? ClSocL ocalServic eUtil.crea teClSoc(so cId) : one Soc;
  1255                             CaretP aram.loadM odel_reset (request,  soc, soc.g etModelAtt ributes(). keySet(),  "soc_");
  1256                             soc.se tClSocId(s ocId);
  1257                             soc.se tPrimaryKe y(socId);
  1258                             soc.se tCreationD ate(now);
  1259                             soc.se tAttemptNu m(attemptN um + "");
  1260                             //
  1261                             boolea n setCallS tatusToCal lBack = fa lse;
  1262                             if(thr esholdMet. equals("No ")){
  1263                                      //String  followupC allTime =  ParamUtil. get(reques t, "soc_fo llowupCall Time_q14",  StringPoo l.BLANK);
  1264                                      String f ollowupCal l = ParamU til.get(re quest, "so c_followup Call_q14",  StringPoo l.BLANK);
  1265                                      //soc.se tFollowupC allTime(fo llowupCall Time);
  1266                                      soc.setF ollowupCal l(followup Call);
  1267                             }
  1268                             else i f (thresho ldMet.equa ls("Yes"))  {
  1269                                      if (!soc .getFollow upCall().e quals("No" )) {
  1270                                               setCallSta tusToCallB ack = true ;
  1271                                      }
  1272                             }
  1273                             ClSocL ocalServic eUtil.upda teClSoc(so c);
  1274                             saveCa ll_callbac kDate(requ est, setCa llStatusTo CallBack);                  
  1275                             //crea te work it em for fol low up cal l                    
  1276                             if(soc .getFollow upCall() ! = null &&  soc.getFol lowupCall( ).equals(" Yes")){
  1277                                      //Call c all = Call LocalServi ceUtil.get Call( Long .parseLong (ParamUtil .get(reque st, "soc_c allId", St ringPool.B LANK)) );
  1278                                      long vet eranId = c all.getVet eranPersnI d();
  1279                                      Person v eteran = n ew Person  ( PersnLoc alServiceU til.getPer sn( vetera nId ) );
  1280                                      CaretLoc alServiceU til.save(  CaretUtil. createWork Item( sc,  veteran.ge tGroupId() , soc, Wor kType.SOC_ FOLLOWUP,  veteranId,  call.getC allerPersn Id() ));
  1281                             }
  1282                             //
  1283                             call.s etModifica tionDate(  now );
  1284                             CaretL ocalServic eUtil.save ( call );                       
  1285                             //
  1286                             CaretL ocalServic eUtil.addN ote( Caret Util.creat eNote(sc.g etCreateDa te(), soc. getCallId( ), (Long)s c.getAttri bute( Care tStrPool.R OLE_ID ),  sc.getUser Id(), "Com pleted SOC  Call Atte mpt - "+so c.getAttem ptNum()) ) ;                  
  1287                    } ca tch (Excep tion e) {
  1288                             Applic ationWorkF lowExcepti on.handleE xception(e );
  1289                    }
  1290           }
  1291           
  1292  
  1293           pu blic void  saveCesp (  ActionReq uest reque st ){
  1294                    _log .info("sav eCesp..."  );
  1295  
  1296                    try  {
  1297                             getOut put(reques t);
  1298                             
  1299                             Servic eContext s c = CaretP aram.setCa retService Context(re quest);
  1300  
  1301                             int nu mOfCesp =  ParamUtil. getInteger (request,  "cesp_numO fCesp");
  1302                             String  cespClose d = ParamU til.get(re quest, "ce sp_cespClo sed", Stri ngPool.BLA NK);
  1303  
  1304                             long c espId = Co unterLocal ServiceUti l.incremen t( Cesp.cl ass.getNam e() );
  1305                             Cesp c esp = Cesp LocalServi ceUtil.cre ateCesp(ce spId);
  1306                             CaretP aram.loadM odel(reque st, cesp,  cesp.getMo delAttribu tes().keyS et(), "ces p_");
  1307                             
  1308                             cesp.s etCespId(c espId);
  1309                             cesp.s etCreation Date(new D ate());
  1310  
  1311                             String  notificat ion = "";
  1312                             if(num OfCesp ==  0){
  1313                                      cesp.set Status(Car etStrPool. CESP_STATU S_INITIAL) ;//initial       
  1314                                      notifica tion = "CE SP - Initi al - Compl eted";
  1315                             }else  if(cespClo sed.equals ("No")){
  1316                                      cesp.set Status(Car etStrPool. CESP_STATU S_COMPLETE );//comple te - in st ep 2                                                                      
  1317                                      notifica tion = "CE SP - Compl eted";
  1318                             }else  if(cespClo sed.equals ("Yes")){
  1319                                      cesp.set Status(Car etStrPool. CESP_STATU S_CLOSED); //complete  - cesp cl osed                                                                                        
  1320                                      notifica tion = "CE SP - Close d";
  1321                             }
  1322  
  1323                             CespLo calService Util.addCe sp(cesp);
  1324                             //NOTE : TODO use  save() to  save cesp
  1325                             //Care tLocalServ iceUtil.sa ve( cesp ) ;
  1326  
  1327                             
  1328                             //crea te work it em for CSC                         
  1329                             if(nul l!=cesp.ge tCespClose dReason() 
  1330                                      && (cesp .getCespCl osedReason ().equals( "Goals Rea ched") ||  cesp.getCe spClosedRe ason().equ als("Parti cipation D iscontinue d - refer  to CSC"))) {
  1331                                      Call cal l = CallLo calService Util.getCa ll( Long.p arseLong(P aramUtil.g et(request , "cesp_ca llId", Str ingPool.BL ANK)) );
  1332                                      long vet eranId = c all.getVet eranPersnI d();
  1333                                      Person v eteran = n ew Person  ( PersnLoc alServiceU til.getPer sn( vetera nId ) );
  1334                                      CaretLoc alServiceU til.save(  CaretUtil. createWork Item( sc,  veteran.ge tGroupId() , cesp, Wo rkType.CES P_CSC, vet eranId, ca ll.getCall erPersnId( ) ));
  1335                             }
  1336  
  1337                             CaretL ocalServic eUtil.addN ote( Caret Util.creat eNote(sc.g etCreateDa te(), cesp .getCallId (), (Long) sc.getAttr ibute( Car etStrPool. ROLE_ID ),  sc.getUse rId(), not ification)  );                         
  1338                    } ca tch (Excep tion e) {
  1339                             Applic ationWorkF lowExcepti on.handleE xception(e );
  1340                    }
  1341           }
  1342  
  1343           pr ivate void  saveRefer ral ( Acti onRequest  request )  throws App licationWo rkFlowExce ption{
  1344                    //Ca ll call =  null;
  1345                    Call Support ca ll = null;
  1346                    Pers on caller  = null;
  1347                    WorI m workItem  = null;
  1348  
  1349                    getO utput(requ est);
  1350                    Long  callId =  ParamUtil. getLong(re quest, "ca ll_primary Key");
  1351  
  1352                    Pers on veteran  = null;
  1353                    Long  veteranId  = ParamUt il.getLong (request,  "veteranPe rsn_primar yKey");
  1354                    if (  veteranId  > 0 ){
  1355                             try {
  1356                                      veteran  = new Pers on ( Persn LocalServi ceUtil.get Persn( vet eranId ) ) ;
  1357                             } catc h (PortalE xception e ) {
  1358                                      Applicat ionWorkFlo wException .handleExc eption(e);
  1359                             } catc h (SystemE xception e ) {
  1360                                      Applicat ionWorkFlo wException .handleExc eption(e);
  1361                             }
  1362                    }
  1363                    if (  veteran = = null ){
  1364                             vetera n = new Pe rson ( new  PersnImpl () );
  1365                    }
  1366                    
  1367                    Care tParam.set CaretServi ceContext( request);
  1368                    bool ean create WorkItem =  false;
  1369                    if (  callId >  0 ){
  1370                             try {
  1371                                      //call =  CallLocal ServiceUti l.getCall( callId);
  1372                                      call = n ew CallSup port(CallL ocalServic eUtil.getC all(callId ));   
  1373                                      if ( cal l.getWorkP rimaryKey( ) > 0 ){
  1374                                               workItem =  WorImLoca lServiceUt il.getWorI m( call.ge tWorkPrima ryKey() );
  1375                                      } else {
  1376                                               createWork Item = tru e;
  1377                                               workItem =  new WorIm Impl();
  1378                                      }
  1379                             } catc h (Excepti on e) {
  1380                                      throw ne w Applicat ionWorkFlo wException (e);
  1381                             }
  1382                             if ( w orkItem.ge tStatus(). equals( St ringPool.B LANK ) ){
  1383                                      workItem .setStatus ( WorkStat us.NEW.nam e() );
  1384                             }
  1385                             
  1386                             if ( ! workItem.g etStatus() .equals( W orkStatus. NEW.name()  ) ){
  1387                                      throw ne w Applicat ionWorkFlo wException ( "WORK IT EM ALREADY  STARTED"  );
  1388                             }
  1389                    }
  1390                    
  1391                    
  1392                             
  1393                    Long  callerId  = ParamUti l.getLong( request, " callerPers n_primaryK ey");
  1394                    if (  callerId  > 0 ){
  1395                             try {
  1396                                      caller =  new Perso n ( PersnL ocalServic eUtil.getP ersn( call erId ) );
  1397                             } catc h (Excepti on e) {
  1398                                      throw ne w Applicat ionWorkFlo wException (e);
  1399                             }
  1400                    }
  1401                    if (  caller ==  null ){
  1402                             caller  = new Per son ( new  PersnImpl( ) );
  1403                    }
  1404                    
  1405                    //TO DO: pass l ist of par ameter nam es
  1406                    Care tParam.loa dModel(req uest, call er, caller .getModelA ttributes( ).keySet() , "callerP ersn_");
  1407                    
  1408                    bool ean unknow n = ParamU til.getBoo lean(reque st,  "call erPersn_st atusLabel" );
  1409                    if (  unknown ) {
  1410                             caller .setStatus (CaretStrP ool.UNKNOW N_IDENTITY );
  1411                             caller .setFirstN ame(String Pool.BLANK );
  1412                             caller .setLastNa me(StringP ool.BLANK) ;
  1413                    } el se if ( !T oolbox.isE mpty( call er.getFirs tName() )  ){
  1414                             caller .setStatus (StringPoo l.BLANK);
  1415                    }
  1416                    Care tLocalServ iceUtil.sa ve( caller  );
  1417                    _log .info("cal ler is " +  caller);
  1418                    
  1419  
  1420                    //TO DO: pass l ist of par ameter nam es 
  1421                    Care tParam.loa dModel(req uest, vete ran, veter an.getMode lAttribute s().keySet (), "veter anPersn_") ;
  1422                    _log .info("vet eran is "  + veteran) ;
  1423                    if (  veteran.i sForeigner () ){
  1424                             CaretP aram.loadM odel( requ est, veter an, Toolbo x.getAddre ssCollecti on(), Care tStrPool.V ETERAN_PER SN + Caret StrPool.G_ UNDERLINE  );
  1425                    } el se {
  1426                             CaretP aram.loadM odel( requ est, veter an, Toolbo x.getAddre ssCollecti on(), Care tStrPool.V ETERAN_PER SN + Caret StrPool.U_ UNDERLINE  );
  1427                    }
  1428                    
  1429                    if (  call == n ull) {
  1430                             //call  = new Cal lImpl();
  1431                             call =  new CallS upport(new  CallImpl( ));
  1432                    }
  1433                    Stri ng s_callb ackPref =  request.ge tParameter ("call_cal lbackPref" );
  1434                    Stri ng v5_call backPref =  SocCached ReportUtil .getCallba ckPref_24H ourFormat( s_callback Pref);
  1435                    call .setCompou ndValue(re quest,"tra nsferRemar ks","call_ ");
  1436                    call .setCompou ndValue(re quest,"mes sage","cal l_");                
  1437                    Care tParam.loa dModel( re quest, cal l, call.ge tModelAttr ibutes().k eySet(), " call_");
  1438                    Care tParam.loa dModelSing leElement( request, c all, "call backPref",  v5_callba ckPref, "c all_");
  1439  
  1440                    if (  call.isSa meAddress( ) ){
  1441                             caller .setAddres s( veteran .getAddres s() );
  1442                             caller .setAddres s2( vetera n.getAddre ss2() );
  1443                             caller .setZip( v eteran.get Zip() );
  1444                             caller .setState(  veteran.g etState()  );
  1445                             caller .setCity(  veteran.ge tCity() );
  1446                             caller .setValidA ddress( ve teran.getV alidAddres s() );
  1447                    }
  1448                    Care tLocalServ iceUtil.sa ve( vetera n );
  1449                    
  1450                    if (  ! CaretVi ewControll er.getView Controller ().validat eRequired( CaretStrPo ol.CALL, r equest) ){
  1451                             throw  new Applic ationWorkF lowExcepti on( "VALID ATION" );
  1452                    }
  1453                    
  1454  
  1455                    Serv iceContext  sc = Care tParam.set CaretServi ceContext(  request ) ;
  1456                    
  1457                    call .setVetera nPersnId(  veteran.ge tPersnId()  );
  1458                    call .setCaller PersnId( c aller.getP ersnId() ) ;
  1459  
  1460                    if (  call.getC allId() ==  0 || crea teWorkItem  ){
  1461                             call.s etCallStat e(CaretStr Pool.CALL_ STATE_COMP LETE);
  1462                             Dashbo ardConfig  dashConfig  = ( Dashb oardConfig  ) request .getPortle tSession() .getAttrib ute( Caret StrPool.DA SHBOARD_CO NFIG );
  1463                             call.s etCreateGr oupId( das hConfig.ge tRoleId()  );
  1464                             call.s etUserId(  (Long) sc. getAttribu te( CaretS trPool.USE R_ID ) );
  1465                             CaretL ocalServic eUtil.save ( call );
  1466                             
  1467                             WorkTy pe workTyp e;
  1468                             if ( d ashConfig  instanceof  CslDashbo ardConfig  ){
  1469                                      workType  = WorkTyp e.CSL_REFE RRAL;
  1470                             } else  {
  1471                                      try{
  1472                                               workType =  WorkType. valueOf( d ashConfig. getRole()  + "_REFERR AL");
  1473                                      } catch( Exception  e){
  1474                                               workType =  WorkType. REFERRAL;
  1475                                      }
  1476                             }
  1477                             
  1478                             workIt em = Caret Util.creat eWorkItem( sc, vetera n.getGroup Id(), call , workType , veteran. getPersnId (), call.g etCallerPe rsnId() );
  1479                    } el se {
  1480                             workIt em.setGrou pId( veter an.getGrou pId() );
  1481                    }
  1482                    Care tLocalServ iceUtil.sa ve( workIt em );
  1483                    work Item = new  WorkItemS upport(wor kItem);
  1484                    Stri ng s_trans ferRemarks  = call.ge tTransferR emarks_asS tring();
  1485                    Stri ng transfe rRemarksNo te = 
  1486                                      Toolbox. isEmpty(s_ transferRe marks) ? " " :
  1487                                      s_transf erRemarks. substring( 0,  (s_tra nsferRemar ks.length( ) >= 400 ?  400 : s_t ransferRem arks.lengt h()));                  
  1488                    
  1489                    //if  ( !Toolbo x.isEmpty(  call.getM essage() )  ){
  1490                    //(( WorkItemSu pport)work Item).useN ote("refer ralNote",  CaretUtil. createNote (sc.getCre ateDate(),  workItem. getWorImId (), NoteSu pport.Note Group.REFE RRAL.group Id(), sc.g etUserId() , call.get Message()) );
  1491                    if (  !Toolbox. isEmpty( t ransferRem arksNote )  ){
  1492                             ((Work ItemSuppor t)workItem ).useNote( "referralN ote", Care tUtil.crea teNote(sc. getCreateD ate(), wor kItem.getW orImId(),  NoteSuppor t.NoteGrou p.REFERRAL .groupId() , sc.getUs erId(), tr ansferRema rksNote));
  1493                    }
  1494                    Care tLocalServ iceUtil.sa ve( workIt em );
  1495                    
  1496                    call .setWorkPr imaryKey(  workItem.g etPrimaryK ey() );
  1497                    if (  call.getC allState()  != null & &
  1498                                      call.get CallState( ).toLowerC ase().cont ains(Caret StrPool.CA LL_STATE_C OMPLETE)
  1499                                      && call. getComplet ionDate()  == null ){
  1500                             call.s etCompleti onDate(sc. getCreateD ate());
  1501                    }
  1502                    //ca ll = (Call )CaretLoca lServiceUt il.save( c all );
  1503                    call  = (CallSu pport) Car etLocalSer viceUtil.s ave( call  );
  1504                    _log .info("cal l is" + ca ll);
  1505                    
  1506                    save ReferralQu estionaire  ( call.ge tCallId(),  request ) ;
  1507                             
  1508                    
  1509                    //Su pporting D ocs attach ment code
  1510   //               try  {            
  1511                             String  tracker =  ParamUtil .getString (request,  CaretStrPo ol.TRACKER , StringPo ol.BLANK ) ;
  1512                             List<D ocum> docu ments = Do cumLocalSe rviceUtil. getByTrack erNote( tr acker );
  1513                             for (  Docum docu m : docume nts ){
  1514                                      if ( doc um.getClas sPk() == 0  ){
  1515                                               docum.setC lassPk( ca ll.getCall Id() );
  1516                                               docum.setC lassId( Po rtalUtil.g etClassNam eId(Call.c lass) );
  1517                                               docum.setN ote(String Pool.BLANK );
  1518                                               try {
  1519                                                       Do cumLocalSe rviceUtil. updateDocu m(docum);
  1520                                               } catch (S ystemExcep tion e) {
  1521                                                       e. printStack Trace();
  1522                                               }
  1523                                      }
  1524                             }
  1525                             
  1526   //                        if ( r equest.get PortletSes sion().get Attribute( CaretStrPo ol.FILE_PA TH) != nul l ){
  1527   //                                 for ( Do cum docume nt : Docum LocalServi ceUtil.get ByPrimaryK ey( call.g etCallId()  ) ){
  1528   //                                          DocumLocal ServiceUti l.deleteDo cument( do cument );
  1529   //                                 }
  1530   //                                 String p ath = (Str ing) reque st.getPort letSession ().getAttr ibute(Care tStrPool.F ILE_PATH);
  1531   //                                 String n ame = (Str ing) reque st.getPort letSession ().getAttr ibute(Care tStrPool.F ILE_NAME);
  1532   //                                 Attachme ntBean att achment =  new Attach mentBean() ;
  1533   //                                 attachme nt.setClas sId(Portal Util.getCl assNameId( Call.class ));
  1534   //                                 attachme nt.setClas sPk(call.g etCallId() );
  1535   //                                 attachme nt.setPath (path);
  1536   //                                 attachme nt.setName (name);
  1537   //                                 attachme nt.setType (FileType. REFERRAL_1 010.name() );
  1538   //                                 handleAp plicationD ocument( r equest, at tachment);
  1539   //                                 request. getPortlet Session(). removeAttr ibute(Care tStrPool.F ILE_PATH);
  1540   //                                 request. getPortlet Session(). removeAttr ibute(Care tStrPool.F ILE_NAME);
  1541   //                        }
  1542   //                        if ( r equest.get PortletSes sion().get Attribute( CaretStrPo ol.POA_FIL E_PATH) !=  null ){
  1543   //                                 String p ath = (Str ing) reque st.getPort letSession ().getAttr ibute(Care tStrPool.P OA_FILE_PA TH);
  1544   //                                 String n ame = (Str ing) reque st.getPort letSession ().getAttr ibute(Care tStrPool.P OA_FILE_NA ME);
  1545   //                                 Attachme ntBean att achment =  new Attach mentBean() ;
  1546   //                                 attachme nt.setClas sId(Portal Util.getCl assNameId( Call.class ));
  1547   //                                 attachme nt.setClas sPk(call.g etCallId() );
  1548   //                                 attachme nt.setPath (path);
  1549   //                                 attachme nt.setName (name);
  1550   //                                 attachme nt.setType (FileType. REFERRAL_P OA.name()) ;
  1551   //                                 handleAp plicationD ocument( r equest, at tachment);
  1552   //                                 request. getPortlet Session(). removeAttr ibute(Care tStrPool.P OA_FILE_PA TH);
  1553   //                                 request. getPortlet Session(). removeAttr ibute(Care tStrPool.P OA_FILE_NA ME);
  1554   //                        }
  1555   //               } ca tch (FileN otFoundExc eption e)  {
  1556   //                        Applic ationWorkF lowExcepti on.handleE xception(e );
  1557   //               } ca tch (Syste mException  e) {
  1558   //                        Applic ationWorkF lowExcepti on.handleE xception(e );
  1559   //               }
  1560                    
  1561                    
  1562                    _log .info("sav eReferral. .." );
  1563           }
  1564           
  1565           pr ivate void  saveRefer ralQuestio naire(long  persnId,  PortletReq uest reque st) throws  Applicati onWorkFlow Exception  {
  1566                    
  1567                    List <Long> fmC hecks = Ca retParam.l oadSelecte dBoxModel( request, C aretStrPoo l.BOX_GROU P);
  1568  
  1569                    Stri ng[] radio Names = ne w String[] {
  1570                                      "boxRadi oGrp_enrol ledVaHealt h", "boxRa dioGrp_dis chargedAft er911", 
  1571                                      "boxRadi oGrp_veter anScCondit ion", "box RadioGrp_p rescreenPc afc"
  1572                    };
  1573                    for  ( String r adio: radi oNames ){
  1574                             Long r adioId = P aramUtil.g etLong(req uest, radi o, 0);
  1575                             if ( r adioId > 0  ){
  1576                                      fmChecks .add(radio Id);
  1577                             }
  1578                    }
  1579                    
  1580                    List <Long> upd ated = new  ArrayList <Long>();
  1581  
  1582                    Set< Long> priv ateSet = n ew HashSet <Long>();
  1583                    for  ( BoxGp it em: BoxGpL ocalServic eUtil.getB oxGroups(C aretStrPoo l.REFERRAL _QUESTIONA IRE_YN) ){
  1584                             privat eSet.add(  item.getBo xGpId() );
  1585                    }
  1586                    bool ean lodQa  = CAction. canDoCaret (request,  CaretCan.L OD_QA.name () );
  1587                    
  1588                    List <BgAsn> bg AsnList =  BoxGpLocal ServiceUti l.getBoxGr oupAssocia tions( per snId );
  1589                    
  1590                    for  ( BgAsn bg Asn: bgAsn List ){
  1591                             if ( ! lodQa && p rivateSet. contains(  bgAsn.getB oxGpId() )  ){
  1592                                      fmChecks .remove( b gAsn.getBo xGpId() );
  1593                                      continue ;
  1594                             }
  1595                             if ( f mChecks.co ntains( bg Asn.getBox GpId() ) ) {
  1596                                      if ( !bg Asn.isSele cted() ){
  1597                                               bgAsn.setS elected( t rue );
  1598                                               CaretLocal ServiceUti l.save( ne w BoxedGro upAssociat ion(bgAsn)  );
  1599                                               updated.ad d( bgAsn.g etBoxGpId( ) );
  1600                                      }
  1601                                      fmChecks .remove( b gAsn.getBo xGpId() );
  1602                             } else  {
  1603                                      if ( bgA sn.isSelec ted() ){
  1604                                               bgAsn.setS elected( f alse );
  1605                                               CaretLocal ServiceUti l.save( ne w BoxedGro upAssociat ion(bgAsn)  );
  1606                                      }
  1607                             }
  1608                    }
  1609                    for  ( Long box GpId: fmCh ecks){
  1610                             if ( !  updated.c ontains( b oxGpId ) ) {
  1611                                      BgAsn bg Asn = new  BgAsnImpl( );
  1612                                      bgAsn.se tBoxGpId(  boxGpId );
  1613                                      bgAsn.se tOwnerId(  persnId );
  1614                                      bgAsn.se tSelected(  true );
  1615                                      CaretLoc alServiceU til.save(  new BoxedG roupAssoci ation(bgAs n) );
  1616                             }
  1617                    }
  1618           }
  1619  
  1620           
  1621           pu blic void  getOutput(  PortletRe quest requ est ){
  1622                    Care tViewContr oller.getV iewControl ler().getO utput(requ est);
  1623           }
  1624           
  1625           pu blic void  writeTiuNo te ( Actio nRequest r equest, St ring noteB ody, Strin g noteTitl e, VcgSupp ort vcg, P erson.Role  caregiver Role, long  userId )  throws App licationWo rkFlowExce ption{
  1626                    _log .info("wri te TIU Not e..." );
  1627                    try{
  1628                             /*bool ean except ion = fals e;
  1629                             except ion = "tru e".equals(  PortletPr ops.get("t iu.pending ") );
  1630                             if ( e xception ) {
  1631                                      throw ne w Exceptio n("WriteTI UNote serv ice impl.  PENDING");
  1632                             }*/
  1633                             
  1634                             String  dispositi onChoice =  vcg.careg iverDispRe ason(careg iverRole);
  1635                             Servic eContext s c = CaretP aram.setCa retService Context(re quest);
  1636                             StsSer vice.getEm rSvcInterf ace(vcg, r equest);
  1637                             TextTO  textTO =  TiuService .WriteTIUN ote(vcg, r equest,
  1638                                               getNoteTit le(vcg, di spositionC hoice, car egiverRole ),
  1639                                               getNoteBod y(vcg, dis positionCh oice, care giverRole,  sc),
  1640                                               vcg.getVet eran().get Icn());
  1641                             
  1642                             if (te xtTO == nu ll || text TO.getFaul t() != nul l) {
  1643                                               throw new  Exception( "WriteTIUN ote servic e impl. PE NDING");
  1644                             }
  1645                             
  1646                    } ca tch ( Exce ption e ){
  1647                             String  msg = req uest.getPa rameter("m sg");
  1648                             Applic ationWorkF lowExcepti on.handleE xception(e , msg);
  1649                             Servic eContext s c = CaretP aram.setCa retService Context(re quest);
  1650                             WorkIt emSupport  work = new  WorkItemS upport( Ca retUtil.cr eateWorkIt em( sc, vc g.getGroup Id(), vcg. getPersonV cgAn( vcg. getPerson( caregiverR ole).getPe rsnId() ),  WorkType. FAILED_TIU _NOTE, vcg .getVetera nId(), vcg .getPerson Id(caregiv erRole) )  );
  1651                             work.s etStatus(" research-r equired");
  1652   //                        work.s etQueId( s c.getUserI d() );
  1653                             work.s etVcgId( v cg.getVcgI d() );
  1654                             work.s etLeaAttr( "FAILURE_D ESC", "ERR  CODE: Exc eption, ER R DESC: "  + e.getMes sage() );
  1655                             CaretL ocalServic eUtil.save ( work );
  1656                             
  1657                             WorSe  workItemSt ep = new W orSeImpl() ;
  1658                             workIt emStep.set WorImId( w ork.getWor ImId() );
  1659                             workIt emStep.set CreationDa te( sc.get CreateDate () );
  1660                             workIt emStep.set UserId( us erId == 0?  sc.getUse rId() : us erId );
  1661                             int co unt = WorS eLocalServ iceUtil.ge tCount ( w ork.getWor ImId() );
  1662                             workIt emStep.set Step( (cou nt < 10? " 0":StringP ool.BLANK)  + count +  StringPoo l.COLON +  work.getTy pe() + Str ingPool.CO LON + work .getStatus () );
  1663                             workIt emStep.set StepNumber (count+1);
  1664                             CaretL ocalServic eUtil.save ( workItem Step );
  1665                             
  1666                    }
  1667           }
  1668  
  1669           pu blic void  newWorkNot e ( Action Request re quest, Act ionRespons e response  ) throws  Applicatio nWorkFlowE xception {
  1670                    if (  !( CActio n.canDoCar et( reques t, CaretCa n.ADD_GENE RIC_NOTE )  || CActio n.canDoCar et( reques t, CaretCa n.ALTER_CA LL_NOTES )  || CActio n.canDoCar et( reques t, CaretCa n.OCC_REVI EW_1) ) )  {
  1671                             _log.e rror("Perm issions er ror");
  1672                             return ;
  1673                    }
  1674                    Stri ng note =  request.ge tParameter (CaretStrP ool.WORK_C OMMENT);
  1675                    try{
  1676                             long w orImId = P aramUtil.g etLong(req uest, Care tStrPool.W ORK_ID);
  1677                             WorkIt emSupport  work = new  WorkItemS upport( Wo rImLocalSe rviceUtil. getWorIm(w orImId) );
  1678                             
  1679                             Servic eContext s c = CaretP aram.setCa retService Context(re quest);
  1680  
  1681                             String  applicati onStatus =  request.g etParamete r("applica tionStatus ");
  1682                             if ( ! Toolbox.is Empty( app licationSt atus ) &&  ( CaretStr Pool.IN_PR OCESS.equa ls( work.g etStatus()  ) || Care tStrPool.N EW.equals(  work.getS tatus() )  ) ){
  1683                                      VcgAppli cation vcg An = new V cgApplicat ion ( VcgA nLocalServ iceUtil.ge tVcgAn( wo rk.getClas sPk() ) );
  1684                                      if ( Car etStrPool. IN_PROCESS .equals( a pplication Status ) ) {
  1685                                               applicatio nStatus =  LanguageUt il.get( Lo cale.getDe fault(), " awaiting-v a-healthca re-enrollm ent");
  1686                                               work.setNo te("newWor kNote", ap plicationS tatus + ": " + note,  sc.getUser Id(), sc.g etCreateDa te(), Note Support.No teGroup.CU STOM_NOTE. groupId()  );
  1687                                               vcgAn.setS tatus( App licationSt atus.IN_RE VIEW.name( ) );
  1688                                      } else i f ( CActio n.canDoCar et( reques t, CAction .CaretCan. DISPOSITIO N_VCG.name () ) ) {
  1689                                               VcgSupport  vcgSuppor t = ( work .getVcgId( ) == 0? Vc gSupport.g etVeteranV cg( work.g etPersnId( ) ) : new  VcgSupport ( VcgLocal ServiceUti l.getVcg(  work.getVc gId() ) )  );
  1690                                               if ( Caret StrPool.DU PLICATE.eq uals(appli cationStat us) ){
  1691                                                       vc gAn.setSta tus( Caret StrPool.DU PLICATE );
  1692                                                       vc gAn.setSta tus( Appli cationStat us.DECISIO N_MADE.nam e() );
  1693                                                       if  ( vcgSupp ort.getVcg Id() > 0 ) {
  1694                                                                vcgS upport.set DuplicateA pplication (vcgAn.get VcgAnId(),  request.g etParamete r(CaretStr Pool.DISPO SITION_NOT E) );
  1695                                                                Care tLocalServ iceUtil.sa ve(vcgSupp ort);
  1696                                                       }
  1697                                               } else if  ( CaretStr Pool.INVAL ID.equals( applicatio nStatus) ) {
  1698                                                       vc gAn.setSta tus( Caret StrPool.IN VALID );
  1699                                                       vc gAn.setSta tus( Appli cationStat us.DECISIO N_MADE.nam e() );
  1700                                                       if  ( vcgSupp ort.getVcg Id() > 0 ) {
  1701                                                                vcgS upport.set InvalidApp lication(  work.getCl assPk(), n ote);
  1702                                                                Care tLocalServ iceUtil.sa ve(vcgSupp ort);
  1703                                                       }
  1704                                               }
  1705                                               work.setSt atus(Caret StrPool.CO MPLETE);
  1706                                               work.setCo mpletionDa te( sc.get CreateDate () );
  1707                                               work.setCo mpletionBy ( sc.getUs erId() );
  1708                                               work.setNo te("newWor kNote", ap plicationS tatus + ": " + note,  sc.getUser Id(), sc.g etCreateDa te(), Note Support.No teGroup.CU STOM_NOTE. groupId()   );
  1709                                               if ( Appli cationStat us.DECISIO N_MADE.nam e().equals (vcgAn.get Status() )  && WorkTy pe.ONLINE_ APP.equals ( work.get Type() ) )  {
  1710                                                       Se t<Long> us erSet = ne w HashSet< Long>();
  1711                                                       us erSet.add(  CaretStrP ool.ALL_PO S );
  1712                                                       se tOnlineNot es(userSet , vcgAn, v cgSupport. getVeteran (), sc);
  1713                                               }
  1714                                      }
  1715                                      CaretLoc alServiceU til.save(v cgAn);
  1716                             } else  if ( !Too lbox.isEmp ty(note) ) {
  1717                                      work.set Note("newW orkNote",  note, sc.g etUserId() , sc.getCr eateDate() , NoteSupp ort.NoteGr oup.CUSTOM _NOTE.grou pId() );
  1718                             }
  1719                             
  1720                             CaretL ocalServic eUtil.save (work);
  1721                             checkC ontext( re quest, res ponse, wor k.getVcgId () );
  1722                    } ca tch (Porta lException  e) {
  1723                             Applic ationWorkF lowExcepti on.handleE xception(e );
  1724                    } ca tch (Syste mException  e) {
  1725                             Applic ationWorkF lowExcepti on.handleE xception(e );
  1726                    }
  1727           }
  1728           
  1729           
  1730           pu blic void  submitTiuN ote ( Acti onRequest  request, A ctionRespo nse respon se ) throw s Applicat ionWorkFlo wException  {
  1731                    
  1732                    if (  CAction.c anDoCaret( request, C Action.Car etCan.PERF ORM_TIU_RE WRITE) ) t ry {
  1733                             
  1734                             long w orImId = P aramUtil.g etLong(req uest, Care tStrPool.W ORK_ID);
  1735                             WorkIt emSupport  work = new  WorkItemS upport( Wo rImLocalSe rviceUtil. getWorIm(w orImId) );
  1736                             VcgSup port vcg =  new VcgSu pport( Vcg LocalServi ceUtil.get Vcg( work. getVcgId()  ) );
  1737                             Person  person =  vcg.getPer sonRole( w ork.getCar egiverId()  );
  1738                             String  dispositi onChoice =  vcg.careg iverDispRe ason( pers on.getRole () );
  1739                             Servic eContext s c = CaretP aram.setCa retService Context(re quest);
  1740                             
  1741                             writeT iuNote(req uest, getN oteBody(vc g, disposi tionChoice , person.g etRole(),  sc),
  1742                                               getNoteTit le(vcg, di spositionC hoice, per son.getRol e()), vcg,  person.ge tRole(), w ork.getUse rId() );
  1743                             work.s etStatus(W orkStatus. COMPLETE.n ame());
  1744                             work.s etCompleti onDate( sc .getCreate Date() );
  1745                             CaretL ocalServic eUtil.save (work);
  1746   /*
  1747                             String  body = re quest.getP arameter(C aretStrPoo l.WORK_COM MENT);
  1748                             String  header =  request.ge tParameter ("tiu_head er");
  1749                             
  1750                             Servic eFacade.Wr iteTIUNote (PersnLoca lServiceUt il.getPers n( CaretPa ram.getPer snId(reque st) ),
  1751                                               getNoteTit le(vcg, di spositionC hoice, per son.getRol e()),
  1752                                               getNoteBod y(vcg, dis positionCh oice, pers on.getRole (), sc),
  1753                                               vcg.getVet eran().get Icn());
  1754                             
  1755                             boolea n exceptio n = false;
  1756                             except ion = "tru e".equals(  PortletPr ops.get("t iu.pending ") );
  1757                             //TODO : comment  out when S erviceFaca de.WriteTI UNote() is  completed
  1758                             if ( e xception ) {
  1759                                      Applicat ionWorkFlo wException .handleExc eption("Co uld not no t save TIU  Note");
  1760                                      if ( ! T oolbox.isE mpty(heade r) ){
  1761                                               work.setNo te("errorT iuRewrite" , header,  sc.getUser Id(), sc.g etCreateDa te() );
  1762                                      }
  1763   //                                 work.set Note("tiuW riteAttemp tBody", bo dy, sc.get UserId(),  sc.getCrea teDate() ) ;
  1764                                      CaretLoc alServiceU til.save(  work );
  1765                             } else  {
  1766                                      work.set Status(Wor kStatus.CO MPLETE.nam e());
  1767                                      work.set Completion Date( sc.g etCreateDa te() );
  1768                                      CaretLoc alServiceU til.save(w ork);
  1769                             }
  1770                    */       
  1771                             
  1772                             
  1773                    } ca tch (Porta lException  e) {
  1774                             Applic ationWorkF lowExcepti on.handleE xception(e );
  1775                    } ca tch (Syste mException  e) {
  1776                             Applic ationWorkF lowExcepti on.handleE xception(e );
  1777                    } ca tch (Excep tion e) {
  1778                             Applic ationWorkF lowExcepti on.handleE xception(e );
  1779                    }
  1780                    
  1781                    
  1782           }
  1783           
  1784           pu blic void  saveVcgTie r ( Action Request re quest, Act ionRespons e response  ) throws  Applicatio nWorkFlowE xception{
  1785                    // s ee saveVcg Entry
  1786                    _log .info("sav eVcgTier") ;
  1787           }
  1788           
  1789           pu blic void  createVcg(  ActionReq uest reque st, Action Response r esponse )  throws App licationWo rkFlowExce ption {
  1790                    Stri ng tracker  = ParamUt il.getStri ng(request , CaretStr Pool.TRACK ER, String Pool.BLANK  );
  1791                    if (  ! CaretPa ram.isTrac ked( reque st, tracke r, true )  ){
  1792                             _log.w arn("TRACK ER BLOCKIN G action.. . ");
  1793                             reques t.setAttri bute(Caret StrPool.IN VALID_REQU EST, true) ;
  1794                             return ;
  1795                    }
  1796                    if ( CAction.ca nDoCaret(r equest, CA ction.Care tCan.CREAT E_VCG.name ())) {
  1797                             _log.i nfo("creat eVcg... ") ;
  1798                             getOut put(reques t);
  1799                             long v eteranId =  ParamUtil .getLong(r equest, "v cg_veteran Id", 0);
  1800                             long v cgAnId = P aramUtil.g etLong(req uest, Care tStrPool.V CGANID);
  1801                             long w orImId = P aramUtil.g etLong(req uest, Care tStrPool.W ORK_ID);
  1802  
  1803                             Servic eContext s c = CaretP aram.setCa retService Context(re quest);
  1804                             String  applicati onStatus =  request.g etParamete r("applica tionStatus ");
  1805  
  1806                             VcgApp lication v cgAn = nul l;
  1807                             WorIm  worIm = nu ll;
  1808                             VcgSup port vcgSu pport = nu ll;
  1809                             Vetera n vcgVeter an = null;
  1810                             Map<Lo ng,Person>  cachedMVI  = (Map<Lo ng,Person> ) request. getPortlet Session(). getAttribu te(CaretSt rPool.CACH ED_MVI);
  1811                             if ( c achedMVI = = null ){
  1812                                      cachedMV I = new Ha shMap<>();
  1813                             }
  1814                             try {
  1815                                      worIm =  WorImLocal ServiceUti l.getWorIm (worImId);
  1816                                      vcgAn =  new VcgApp lication(V cgAnLocalS erviceUtil .getVcgAn( vcgAnId));
  1817                                      vcgAn.se tStatus(ap plicationS tatus);
  1818                                      if ( cac hedMVI.con tainsKey(v eteranId)  ){
  1819                                               Persn pers on = null;
  1820                                               if ( !Tool box.isEmpt y( cachedM VI.get(vet eranId).ge tICN() ) ) {
  1821                                                       pe rson = Per snLocalSer viceUtil.g etByIcn( c achedMVI.g et(veteran Id).getICN () );
  1822                                               }
  1823                                               if ( perso n != null  ){
  1824                                                       vc gVeteran =  new Veter an ( perso n );
  1825                                               } else {
  1826                                                       vc gVeteran =  new Veter an( cached MVI.get(ve teranId) ) ;
  1827                                                       Ca retLocalSe rviceUtil. save(vcgVe teran);
  1828                                               }
  1829                                               vcgVeteran .setGroupI d( vcgAn.g etGroupId( ) );
  1830                                               veteranId  = vcgVeter an.getPrim aryKey();
  1831                                      }
  1832  
  1833                                      if (Care tStrPool.I NVALID.equ als(applic ationStatu s)) {
  1834                                               if (vetera nId > 0) {
  1835                                                       vc gVeteran =  new Veter an(PersnLo calService Util.getPe rsn(vetera nId));
  1836                                                       vc gVeteran.s etStatus(C aretStrPoo l.ACTIVE_V CG);
  1837                                                       
  1838                                                       vc gSupport =  VcgSuppor t.getVeter anVcg(vete ranId);
  1839                                                       vc gSupport.s etGroupId( vcgVeteran .getGroupI d());
  1840                                                       St ring noteS tr = reque st.getPara meter(Care tStrPool.D ISPOSITION _NOTE);
  1841                                                       vc gSupport.s etInvalidA pplication (vcgAnId,  noteStr);
  1842  
  1843                                                       Ca retLocalSe rviceUtil. save(vcgVe teran);
  1844                                                       No te note =  CaretLocal ServiceUti l.addNote( CaretUtil. createNote (sc.getCre ateDate(),  worImId,
  1845                                                                         NoteSu pport.Note Group.CORR ECTIVE_RES PONSE.grou pId(), sc. getUserId( ), noteStr ));
  1846                                                       no te.setVcgI d( vcgSupp ort.getVcg Id() );
  1847                                                       vc gSupport.u seNote("In valid", no te);
  1848                                                       Ca retLocalSe rviceUtil. save(vcgSu pport);
  1849                                                       vc gAn.setVcg Id(vcgSupp ort.getVcg Id());
  1850                                                       
  1851                                                       wo rIm.setVcg Id(vcgSupp ort.getVcg Id());
  1852                                               }
  1853                                               vcgAn.setI nvalidPers on(1, requ est.getPar ameter(Car etStrPool. DISPOSITIO N_NOTE) );
  1854                                               vcgAn.setS tatus(appl icationSta tus);
  1855                                               CaretLocal ServiceUti l.save(vcg An);
  1856  
  1857                                               worIm.setS tatus(Work Status.COM PLETE.name ());
  1858                                               worIm.setC ompletionD ate( sc.ge tCreateDat e() );
  1859                                               worIm.setC ompletionB y( sc.getU serId() );
  1860                                               CaretLocal ServiceUti l.save(wor Im);
  1861                                              
  1862                                               //Note for  Online us ers
  1863   //                                          _log.info( "adding no te " + Lan guageUtil. get( Local e.getDefau lt(), Care tStrPool.D ISPOSITION ED_ONLINE_ MESSAGE) ) ;
  1864                                               if ( worIm .getType() .equals( W orkType.ON LINE_APP.n ame() ) ){
  1865                                                       Ca retLocalSe rviceUtil. addNote(Ca retUtil.cr eateNote(s c.getCreat eDate(), v cgAn.getVc gAnId(),
  1866                                                                         NoteSu pport.Note Group.CORR ECTIVE_RES PONSE.grou pId(), vcg An.getVete ranId(), L anguageUti l.get( Loc ale.getDef ault(), Ca retStrPool .DISPOSITI ONED_ONLIN E_MESSAGE)  ) );
  1867                                               }
  1868                                               return;
  1869                                      } else i f (veteran Id == 0) {
  1870                                               Applicatio nWorkFlowE xception.h andleExcep tion("VCG  requires V eteranId") ;
  1871                                               return;
  1872                                      } 
  1873  
  1874                                      vcgVeter an = new V eteran(Per snLocalSer viceUtil.g etPersn(ve teranId));
  1875                                      String o ldVeteranA ddress = n ew StringB uilder(vcg Veteran.ge tAddress() ).append(S tringPool. COMMA_AND_ SPACE).app end(vcgVet eran.getCi ty()).appe nd(StringP ool.SPACE) .append(vc gVeteran.g etState()) .append(St ringPool.S PACE).appe nd(vcgVete ran.getZip ()).toStri ng();
  1876                                      String o ldZip = vc gVeteran.g etZip();
  1877                                      vcgVeter an.setStat us(CaretSt rPool.ACTI VE_VCG);
  1878                                      vcgSuppo rt = VcgSu pport.getV eteranVcg( veteranId) ;
  1879                                      boolean  isNewVcg =  vcgSuppor t.getVcgId () == 0;
  1880   //                                 BlsRe ne wRate = Bl sReLocalSe rviceUtil. findLatest BlsByZip(  oldZip );
  1881   //                                 if ( isN ewVcg && n ewRate !=  null ) {
  1882   //                                          vcgSupport .setBlsRat eHourly( S tring.valu eOf( newRa te.getH75( ) ) );
  1883   //                                 }
  1884                                      // group Id defect. ..
  1885   //                                 _log.inf o( "****** ********** ********** ********** ");
  1886   //                                 _log.inf o( "****** ********** ********** ********** ");
  1887                                      _log.inf o( "VCG=Ve teran=Appl ication...  groupId="  + vcgAn.g etGroupId( ) );
  1888   //                                 _log.inf o( "****** ********** ********** ********** ");
  1889   //                                 _log.inf o( "****** ********** ********** ********** ");
  1890                                      vcgSuppo rt.setGrou pId(vcgAn. getGroupId ());
  1891                                      vcgVeter an.setGrou pId(vcgAn. getGroupId ());
  1892  
  1893   //                                 String c omment = S tringPool. BLANK;
  1894  
  1895                                      Map<Pers on,boolean []> change Map = new  HashMap<Pe rson,boole an[]>();
  1896                                      List<Str ing> error s = new Ar rayList<St ring>();
  1897                                      
  1898                                      int inva lids = 0;
  1899                                      int care givers = 0 ;
  1900                                      int coun t = 0;
  1901                                      Set<Long > userSet  = new Hash Set<Long>( );
  1902                                      
  1903                                      if (Care tStrPool.D UPLICATE.e quals(appl icationSta tus)) {
  1904                                               worIm.setS tatus( Wor kStatus.CO MPLETE.nam e() );
  1905                                               worIm.setC ompletionD ate( sc.ge tCreateDat e() );
  1906                                               worIm.setC ompletionB y( sc.getU serId() );
  1907                                               vcgAn.setS tatus( Car etStrPool. DUPLICATE  );
  1908                                               vcgSupport .setDuplic ateApplica tion(vcgAn .getVcgAnI d(), reque st.getPara meter(Care tStrPool.D ISPOSITION _NOTE) );
  1909                                              
  1910                                               userSet.ad d(CaretStr Pool.ALL_P OS);
  1911                                      } else {
  1912                                               worIm.setS tatus(Work Status.IN_ PROCESS.na me());
  1913  
  1914                                               long prima ryId = Par amUtil.get Long(reque st, "vcg_p rimaryId",  0);
  1915                                               long secon daryId = P aramUtil.g etLong(req uest, "vcg _secondary Id", 0);
  1916                                               long secon daryTwoId  = ParamUti l.getLong( request, " vcg_second aryTwoId",  0);
  1917  
  1918                                               Person vcg Primary =  null, vcgS econdary =  null, vcg SecondaryT wo = null;
  1919  
  1920                                               if (vcgAn. getVeteran Id() != ve teranId) {
  1921                                                       bo olean[] ch anges = ne w boolean[ Person.Cha nges.value s().length ];
  1922                                                       Pe rsn merged  = PersnLo calService Util.getPe rsn(vcgAn. getVeteran Id());
  1923                                                       er rors.addAl l( CaretVi ewControll er.getView Controller ().setVcgP erson(requ est, new V eteran(mer ged), vcgV eteran, ch anges) );
  1924  
  1925                                                       if  ( errors. isEmpty()  ){
  1926                                                                merg ed.setStat us(CaretSt rPool.REVI SION_MERGE D);
  1927                                                                Care tLocalServ iceUtil.sa ve(merged) ;
  1928                                                       }
  1929                                                       if  ( vcgSupp ort != nul l && ( vcg Support.is PrimaryApp roved() )  && changes [Person.Ch anges.ADDR ESS_CHANGE .ordinal() ]  ){
  1930                                                                chan geMap.put( vcgVeteran , changes) ;
  1931                                                       }
  1932                                               }
  1933   //                                          vcgAn.setV eteranId(  veteranId  );
  1934                                               //init VCG  
  1935                                               CaretLocal ServiceUti l.save(vcg Support);
  1936                                              
  1937                                               if (vcgAn. getPrimary Id() > 0)  {
  1938                                                       Pr imary appP rimary = n ew Primary (PersnLoca lServiceUt il.getPers n(vcgAn.ge tPrimaryId ()));
  1939                                                       St ring prima ryStatus =  ParamUtil .get(reque st, "prima ryStatus",  StringPoo l.BLANK);
  1940                                                       ca regivers++ ;
  1941                                                       if  (CaretStr Pool.INVAL ID.equals( primarySta tus)) { // Decision M ade
  1942                                                                vcgA n.setInval idPerson(v cgAn.getPr imaryId(),  ParamUtil .get(reque st, "prima ryNote", " Missing IN VALID-App  reason"));
  1943                                                                
  1944                                                                inva lids++;
  1945                                                                if (  appPrimar y.getRootU serId() >  0 ){
  1946                                                                         userSe t.add( app Primary.ge tRootUserI d() ); //D ecision Ma de
  1947                                                                }
  1948                                                       }  else if (p rimaryId >  0) {
  1949                                                                
  1950                                                                if (  cachedMVI .containsK ey( primar yId ) ){
  1951                                                                         Persn  person = n ull;
  1952                                                                         if ( ! Toolbox.is Empty( cac hedMVI.get ( primaryI d ).getICN () ) ){
  1953                                                                                  person =  PersnLoca lServiceUt il.getByIc n( cachedM VI.get( pr imaryId ). getICN() ) ;
  1954                                                                         }
  1955                                                                         if ( p erson != n ull ){
  1956                                                                                  vcgPrima ry = new P rimary ( p erson );
  1957                                                                         } else  {
  1958                                                                                  vcgPrima ry = new P rimary( ca chedMVI.ge t( primary Id ) );
  1959                                                                                  CaretLoc alServiceU til.save(  vcgPrimary  );
  1960                                                                         }
  1961                                                                         primar yId = vcgP rimary.get PrimaryKey ();
  1962                                                                } el se {
  1963                                                                         vcgPri mary = new  Primary(P ersnLocalS erviceUtil .getPersn( primaryId) );
  1964                                                                }
  1965                                                                
  1966                                                                if ( CaretStrPo ol.IN_PROC ESS.equals (primarySt atus)) {
  1967                                                                         if ( v eteranId = = vcgPrima ry.getPers nId() || v cgSupport. getPrimary DispReason () != null  && VcgSup port.isAct ive( vcgSu pport.getP rimaryDisp Reason() )  ) {
  1968                                                                                  throw ne w Applicat ionWorkFlo wException ("VCG - Pr imary Slot  already r eserved!") ;
  1969                                                                         } else  {
  1970                                                                                  if (vcgA n.getPrima ryId() ==  primaryId)  {
  1971                                                                                           if ( !Cach edReport.s earchPerso n(null, nu ll, null,  vcgPrimary .getSsn(),  null, nul l, null, n ull, null,  null, nul l, null, t rue).isEmp ty() ) {
  1972                                                                                                   th row new Ap plicationW orkFlowExc eption("VC G - Primar y SSN alre ady reserv ed!");
  1973                                                                                           }
  1974                                                                                  }
  1975                                                                                  boolean[ ] changes  = new bool ean[Person .Changes.v alues().le ngth];
  1976                                                                                  CaretVie wControlle r.getViewC ontroller( ).setVcgPe rson(reque st, appPri mary, vcgP rimary, ch anges);
  1977                                                                                  
  1978                                                                                  vcgPrima ry.setStat us(CaretSt rPool.ACTI VE_VCG);
  1979                                                                                  if ( isV endorCandi date(vcgPr imary, vcg Support.ge tVcgId() )  ){
  1980                                                                                           changeMap. put(vcgPri mary, chan ges);
  1981   //                                                                             } else i f ( ArrayU til.contai ns(changes , true) ){
  1982                                                                                  }
  1983                                                                                  CaretLoc alServiceU til.save(  vcgPrimary  );
  1984                                                                                  
  1985                                                                         }
  1986                                                                         Date r ecievedDat e = vcgAn. getReceive dDate();
  1987                                                                         if ( v cgSupport. getVcgId()  > 0 ){
  1988                                                                                  recieved Date =  Ca retUtil.is ValidRecie vedDate(vc gSupport,  vcgAn, app Primary, v cgSupport. getPrimary (), null);
  1989                                                                                  vcgAn.se tReceivedD ate( recie vedDate );
  1990                                                                         }
  1991                                                                         vcgSup port.setNe wPrimary(  primaryId,  vcgAn.get PrimaryRel ationship( ), vcgAnId , recieved Date );
  1992                                                                         count+ +;
  1993                                                                }
  1994                                                       }
  1995                                               }
  1996                                               if (vcgAn. getSeconda ryId() > 0 ) {
  1997                                                       Se condary ap pSecondary  = new Sec ondary(Per snLocalSer viceUtil.g etPersn(vc gAn.getSec ondaryId() ));
  1998                                                       St ring secon daryStatus  = ParamUt il.get(req uest, "sec ondaryStat us", Strin gPool.BLAN K);
  1999                                                       ca regivers++ ;
  2000                                                       if  (CaretStr Pool.INVAL ID.equals( secondaryS tatus)) {
  2001                                                                vcgA n.setInval idPerson(v cgAn.getSe condaryId( ),
  2002                                                                                  ParamUti l.get(requ est, "seco ndaryNote" , "Missing  INVALID-A pp reason" ));
  2003                                                                inva lids++;
  2004                                                                user Set.add( a ppSecondar y.getRootU serId() );
  2005                                                       }  else if (s econdaryId  > 0) {
  2006                                                                
  2007                                                                if (  cachedMVI .containsK ey( second aryId ) ){
  2008                                                                         Persn  person = n ull;
  2009                                                                         if ( ! Toolbox.is Empty( cac hedMVI.get ( secondar yId ).getI CN() ) ){
  2010                                                                                  person =  PersnLoca lServiceUt il.getByIc n( cachedM VI.get( se condaryId  ).getICN()  );
  2011                                                                         }
  2012                                                                         if ( p erson != n ull ){
  2013                                                                                  vcgSecon dary = new  Secondary  ( person  );
  2014                                                                         } else  {
  2015                                                                                  vcgSecon dary = new  Secondary ( cachedMV I.get( sec ondaryId )  );
  2016                                                                                  CaretLoc alServiceU til.save(  vcgSeconda ry );
  2017                                                                         }
  2018                                                                         second aryId = vc gSecondary .getPrimar yKey();
  2019                                                                } el se {
  2020                                                                         vcgSec ondary = n ew Seconda ry(PersnLo calService Util.getPe rsn(second aryId));
  2021                                                                }
  2022                                                                
  2023                                                                if ( CaretStrPo ol.IN_PROC ESS.equals (secondary Status)) {
  2024                                                                         if ( v eteranId = = vcgSecon dary.getPe rsnId() ||  vcgSuppor t.getSecon daryDispRe ason() !=  null && Vc gSupport.i sActive( v cgSupport. getSeconda ryDispReas on() ) ) {
  2025                                                                                  throw ne w Applicat ionWorkFlo wException ("VCG - Se condary Sl ot already  reserved! ");
  2026                                                                         } else  {
  2027                                                                                  if (vcgA n.getSecon daryId() = = secondar yId) {
  2028                                                                                           if ( !Cach edReport.s earchPerso n(null, nu ll, null,  vcgSeconda ry.getSsn( ), null, n ull, null,  null, nul l, null, n ull, null,  true).isE mpty() ) {
  2029                                                                                                   th row new Ap plicationW orkFlowExc eption("VC G - Second ary SSN al ready rese rved!");
  2030                                                                                           }
  2031                                                                                  }
  2032                                                                                  
  2033                                                                                  boolean[ ] changes  = new bool ean[Person .Changes.v alues().le ngth];
  2034                                                                                  CaretVie wControlle r.getViewC ontroller( ).setVcgPe rson(reque st, appSec ondary,
  2035                                                                                                   vc gSecondary , changes) ;
  2036                                                                                  
  2037                                                                                  if ( isV endorCandi date( vcgS econdary,  vcgSupport .getVcgId( ) ) ){
  2038                                                                                           changeMap. put(vcgSec ondary, ch anges);
  2039   //                                                                             } else i f ( ArrayU til.contai ns(changes , true) ){
  2040                                                                                  }
  2041                                                                         }
  2042                                                                         vcgSec ondary.set Status(Car etStrPool. ACTIVE_VCG );
  2043                                                                         CaretL ocalServic eUtil.save ( vcgSecon dary );
  2044                                                                         vcgSup port.setNe wSecondary ( secondar yId, vcgAn .getSecond aryRelatio nship(), v cgAnId );
  2045                                                                         count+ +;
  2046                                                                }
  2047                                                       }
  2048                                               }
  2049                                               if (vcgAn. getSeconda ryTwoId()  > 0) {
  2050                                                       Se condaryTwo  appSecond aryTwo = n ew Seconda ryTwo(Pers nLocalServ iceUtil.ge tPersn(vcg An.getSeco ndaryTwoId ()));
  2051                                                       St ring secon daryTwoSta tus = Para mUtil.get( request, " secondaryT woStatus",  StringPoo l.BLANK);
  2052                                                       ca regivers++ ;
  2053                                                       
  2054                                                       if  (CaretStr Pool.INVAL ID.equals( secondaryT woStatus))  {
  2055                                                                vcgA n.setInval idPerson(v cgAn.getSe condaryTwo Id(),
  2056                                                                                  ParamUti l.get(requ est, "seco ndaryTwoNo te", "Miss ing INVALI D-App reas on"));
  2057                                                                inva lids++;
  2058                                                                user Set.add( a ppSecondar yTwo.getRo otUserId()  );
  2059                                                       }  else if (s econdaryTw oId > 0) {
  2060                                                                
  2061                                                                if (  cachedMVI .containsK ey( second aryTwoId )  ){
  2062                                                                         Persn  person = n ull;
  2063                                                                         if ( ! Toolbox.is Empty( cac hedMVI.get ( secondar yTwoId ).g etICN() )  ){
  2064                                                                                  person =  PersnLoca lServiceUt il.getByIc n( cachedM VI.get( se condaryTwo Id ).getIC N() );
  2065                                                                         }
  2066                                                                         if ( p erson != n ull ){
  2067                                                                                  vcgSecon daryTwo =  new Second aryTwo ( p erson );
  2068                                                                         } else  {
  2069                                                                                  vcgSecon daryTwo =  new Second aryTwo( ca chedMVI.ge t( seconda ryTwoId )  );
  2070                                                                                  CaretLoc alServiceU til.save(  vcgSeconda ryTwo );
  2071                                                                         }
  2072                                                                         second aryTwoId =  vcgSecond aryTwo.get PrimaryKey ();
  2073                                                                } el se {
  2074                                                                         vcgSec ondaryTwo  = new Seco ndaryTwo(P ersnLocalS erviceUtil .getPersn( secondaryT woId));
  2075                                                                }
  2076                                                                if ( CaretStrPo ol.IN_PROC ESS.equals (secondary TwoStatus) ) {
  2077                                                                         if ( v eteranId = = vcgSecon daryTwo.ge tPersnId()  || vcgSup port.getSe condaryTwo DispReason () != null  && VcgSup port.isAct ive( vcgSu pport.getS econdaryTw oDispReaso n() ) ) {
  2078                                                                                  throw ne w Applicat ionWorkFlo wException ("VCG - Se condary II  Slot alre ady reserv ed!");
  2079                                                                         } else  {
  2080                                                                                  if (vcgA n.getSecon daryTwoId( ) == secon daryTwoId)  {
  2081                                                                                           if ( !Cach edReport.s earchPerso n(null, nu ll, null,  vcgSeconda ryTwo.getS sn(), null , null, nu ll, null,  null, null , null, nu ll, true). isEmpty()  ) {
  2082                                                                                                   th row new Ap plicationW orkFlowExc eption("VC G - Second ary Two SS N already  reserved!" );
  2083                                                                                           }
  2084                                                                                  }
  2085                                                                                  
  2086                                                                                  boolean[ ] changes  = new bool ean[Person .Changes.v alues().le ngth];
  2087                                                                                  CaretVie wControlle r.getViewC ontroller( ).setVcgPe rson(reque st, appSec ondaryTwo,
  2088                                                                                                   vc gSecondary Two, chang es);
  2089                                                                                  if ( isV endorCandi date( vcgS econdaryTw o, vcgSupp ort.getVcg Id() ) ){
  2090                                                                                           changeMap. put(vcgSec ondaryTwo,  changes);
  2091   //                                                                             } else i f ( ArrayU til.contai ns(changes , true) ){
  2092                                                                                  }
  2093                                                                         }
  2094                                                                         vcgSec ondaryTwo. setStatus( CaretStrPo ol.ACTIVE_ VCG);
  2095                                                                         CaretL ocalServic eUtil.save ( vcgSecon daryTwo );
  2096                                                                         vcgSup port.setNe wSecondary Two( secon daryTwoId,  vcgAn.get SecondaryT woRelation ship(), vc gAnId );
  2097                                                                         count+ +;
  2098                                                                }
  2099                                                       }
  2100                                               }
  2101                                      }
  2102                                      setOnlin eNotes(use rSet, vcgA n, vcgVete ran, sc);
  2103                                      
  2104                                      CaretLoc alServiceU til.save(v cgSupport) ;
  2105                                      CaretLoc alServiceU til.save(v cgVeteran) ;
  2106                                      
  2107                                      if ( inv alids == c aregivers  || count = = 0 ){
  2108                                               worIm.setS tatus(Work Status.COM PLETE.name ());
  2109                                               vcgAn.setS tatus( App licationSt atus.DECIS ION_MADE.n ame() );
  2110                                      } else {
  2111                                               vcgAn.setS tatus( App licationSt atus.IN_RE VIEW.name( ) );
  2112                                      }
  2113                                      vcgAn.se tVcgId( vc gSupport.g etVcgId()  );
  2114                                      CaretLoc alServiceU til.save(v cgAn);
  2115  
  2116                                      worIm.se tVcgId( vc gSupport.g etVcgId()  );
  2117                                      CaretLoc alServiceU til.save(w orIm);
  2118                                      
  2119                                      String c omment = i sNewVcg?
  2120                                                       "U pdated VCG  record wi th " + cou nt + " new  Caregiver  selection (s)"
  2121                                                       :  "Created n ew VCG rec ord with "  + count +  " Caregiv er selecti on(s)";
  2122                                      Note not e = CaretU til.create Note(sc.ge tCreateDat e(), worIm .getWorImI d(),
  2123                                                       No teSupport. NoteGroup. CREATE_VCG .groupId() , sc.getUs erId(), co mment);
  2124                                      note.set VcgId( vcg Support.ge tVcgId() ) ;
  2125                                      CaretLoc alServiceU til.addNot e( note );
  2126                                      
  2127                                      if ( Too lbox.isEmp ty( vcgSup port.getBl sRateHourl y() ) ) {
  2128                                               vcgSupport .getH75();  // Sets t he VCG BLS
  2129                                               CaretLocal ServiceUti l.save(vcg Support);
  2130                                      }
  2131                                      BlsRe ne wRate = Bl sReLocalSe rviceUtil. findByLess Year( vcgV eteran.get Zip(), Cal endar.getI nstance(). get(Calend ar.YEAR) ) ;
  2132                                      
  2133                                      for ( Pe rson perso n: changeM ap.keySet( ) ){
  2134                                               if ( perso n.isVetera nRole() ){
  2135                                                       if  ( changeM ap.get(per son)[Perso n.Changes. ADDRESS_CH ANGE.ordin al()] ){
  2136                                                                WorI m workItem  = CaretUt il.createW orkItem(sc , vcgSuppo rt.getGrou pId(), vcg An, WorkTy pe.ADDRESS _CHANGE, 
  2137                                                                                  person.g etPersnId( ), vcgSupp ort.getPri maryId() ) ;
  2138   //                                                           work Item.setQu eId( sc.ge tUserId()  );
  2139                                                                work Item.setSt atus(Caret StrPool.AD DRESS_CHAN GE_REVIEW_ PENDING);
  2140                                                                work Item.setQu eueId( Own erQueue.VC G_INFO_MOD _Q.queueId  );
  2141                                                                work Item.setVc gId(vcgSup port.getVc gId());
  2142                                                                Care tLocalServ iceUtil.sa ve( workIt em );
  2143                                                                
  2144                                                                Stri ng newAddr ess = new  StringBuil der(person .getAddres s()).appen d(StringPo ol.COMMA_A ND_SPACE). append(per son.getCit y()).appen d(StringPo ol.SPACE). append(per son.getSta te()).appe nd(StringP ool.SPACE) .append(pe rson.getZi p()).toStr ing();
  2145                                                                
  2146                                                                BlsR e oldRate  = BlsReLoc alServiceU til.findBy LessYear(  oldZip, Ca lendar.get Instance() .get(Calen dar.YEAR)  );
  2147                                                                if (  newRate = = null ||  oldRate ==  null ) {
  2148                                                                         _log.e rror("BLS  Rate no lo nger found  for the s elected ad dress");
  2149                                                                } el se if ( !n ewRate.get H75().equa ls( oldRat e.getH75()  ) ) {
  2150                                                                         Stipen dConfig co nfig = new  StipendCo nfig( new  StiPtImpl( ) );
  2151                                                                         config .setFields (sc.getCre ateDate(),  vcgSuppor t, new Wor kItemSuppo rt( workIt em ), sc,  oldVeteran Address, n ewAddress  );
  2152                                                                         Vendr  vendor = V endrLocalS erviceUtil .findByPer snId( vcgS upport.get PrimaryId( ) );
  2153                                                                         if ( v endor != n ull ){
  2154                                                                                  config.s etVendrId(  vendor.ge tVendrId()  ) ;
  2155                                                                         }
  2156                                                                         CaretL ocalServic eUtil.save (config);
  2157                                                                } el se {
  2158                                                                         _log.i nfo("Creat ed an addr ess Change  work item  without C alculation s - same B LS Rate.") ;
  2159                                                                }
  2160                                                       }  else {
  2161                                                                Care tViewContr oller.getV iewControl ler().appl yWorkItem(  request,  changeMap. get(person ), person,  vcgSuppor t, person. getRole()  );
  2162                                                       }
  2163                                               } else {
  2164                                                       Ca retViewCon troller.ge tViewContr oller().ap plyWorkIte m( request , changeMa p.get(pers on), perso n, vcgSupp ort, perso n.getRole( ) );
  2165                                                       Ca retLocalSe rviceUtil. save(perso n);
  2166                                               }
  2167                                      }
  2168                                      
  2169                                      if ( CAc tion.canDo Caret(requ est, CActi on.CaretCa n.MANAGE_V CG.name())  ) {
  2170                                               request.se tAttribute ( CaretStr Pool.VCGID , vcgSuppo rt.getVcgI d() );
  2171                                               loadVcgMan agement(re quest, res ponse);
  2172                                               response.s etRenderPa rameter(Ca retStrPool .MVC_PATH,  CaretStrP ool.VCG_MA NAGEMENT_P AGE);
  2173                                      }
  2174                             } catc h (PortalE xception e ) {
  2175                                      Applicat ionWorkFlo wException .handleExc eption(e);
  2176                             } catc h (SystemE xception e ) {
  2177                                      Applicat ionWorkFlo wException .handleExc eption(e);
  2178                             }
  2179                    }
  2180           }
  2181  
  2182           pr ivate bool ean isVend orCandidat e (Person  vcgPrimary , long exc ludeVcgId  ) throws A pplication WorkFlowEx ception {
  2183                    retu rn VendrLo calService Util.findB yPersnId(  vcgPrimary .getPersnU serId() )  != null;
  2184           }
  2185  
  2186  
  2187           pr ivate void  setOnline Notes( Set <Long> use rSet, VcgA pplication  vcgAn, Ve teran vcgV eteran, Se rviceConte xt sc ) th rows Appli cationWork FlowExcept ion, Porta lException , SystemEx ception {
  2188                    if (  userSet.c ontains( C aretStrPoo l.ALL_POS  ) ){
  2189                             userSe t.remove(  CaretStrPo ol.ALL_POS  );
  2190                             if ( v cgAn.getPr imaryId()  > 0 ){
  2191                                      userSet. add(new Pr imary(Pers nLocalServ iceUtil.ge tPersn(vcg An.getPrim aryId())). getRootUse rId());
  2192                             }
  2193                             if ( v cgAn.getSe condaryId( ) > 0 ){
  2194                                      userSet. add(new Se condary(Pe rsnLocalSe rviceUtil. getPersn(v cgAn.getSe condaryId( ))).getRoo tUserId()) ;
  2195                             }
  2196                             if ( v cgAn.getSe condaryTwo Id() > 0 ) {
  2197                                      userSet. add(new Se condaryTwo (PersnLoca lServiceUt il.getPers n(vcgAn.ge tSecondary TwoId())). getRootUse rId());
  2198                             }
  2199                    }
  2200                    Stri ng onlineM essage = L anguageUti l.get( Loc ale.getDef ault(), Ca retStrPool .DISPOSITI ONED_ONLIN E_MESSAGE)  ;
  2201                    if (  !userSet. isEmpty()  ){
  2202                             userSe t.add(vcgV eteran.get RootUserId ());
  2203                    }
  2204                    for  ( Long id  : userSet  ){
  2205                             CaretL ocalServic eUtil.addN ote(CaretU til.create Note(sc.ge tCreateDat e(), vcgAn .getVcgAnI d(), NoteS upport.Not eGroup.DIS POSITION.g roupId(),  id, online Message )  );
  2206                    }
  2207           }
  2208  
  2209  
  2210           pu blic void  saveVcgDis position (  ActionReq uest reque st, VcgSup port vcg,  Person per son ) thro ws Applica tionWorkFl owExceptio n{
  2211                             String  ndx = req uest.getPa rameter("v cg_ndx") +  StringPoo l.UNDERLIN E;
  2212                             Date d isposition Date = Too lbox.parse Date(reque st.getPara meter(ndx  + "disposi tionDate") );
  2213                             String  dispositi onChoice =  request.g etParamete r(ndx + "d isposition Choice");
  2214                             String  dispositi onReason =  Toolbox.n ullSafe( r equest.get Parameter( ndx + "dis positionRe ason") );
  2215                             
  2216                             String  tracker =  ParamUtil .getString (request,  CaretStrPo ol.TRACKER , StringPo ol.BLANK ) ;
  2217                                                       
  2218                             String  oldDispos itionState  = null;
  2219                             long v cgAnId = 0 ;
  2220                             int[]  extensionD ays = new  int[1];
  2221                             Servic eContext s c = CaretP aram.setCa retService Context( r equest );
  2222                             String  outComeAp peal = Str ingPool.BL ANK;
  2223                             Set<Lo ng> userId s = new Ha shSet<Long >();
  2224   //                        VcgApp lication v cgApp = nu ll;
  2225                             
  2226                             if ( p erson.getR ole() == P erson.Role .PRIMARY & & !vcg.get PrimaryDis pReason(). equals( di spositionC hoice )){
  2227                                      oldDispo sitionStat e = vcg.ge tPrimaryDi spReason() ;
  2228                                      _log.inf o("updated ...");
  2229                                      String e xtDays = C aretUtil.e xtDays(dis positionCh oice, exte nsionDays) ;
  2230                                      if ( vcg .isGeneral Approved()  && ( vcg. isApproved ( extDays  + disposit ionReason  ) || vcg.i sReinstate d( extDays  + disposi tionReason  ) ) ) {
  2231                                               throw new  Applicatio nWorkFlowE xception(" Cannot app rove CG wh ile Genera l is in Ap proved sta te");
  2232                                      }
  2233                                      vcg.setP rimaryDisp Reason( ex tDays + di spositionR eason  );
  2234                                      userIds. add( vcg.g etPrimary( ).getRootU serId() );  
  2235                                      vcgAnId  = vcg.getP rimaryVcgA nId();
  2236                                      
  2237  
  2238                                      StipendC onfig conf ig = new S tipendConf ig ( new S tiPtImpl()  ); 
  2239                                      Vendr ve ndor = Ven drLocalSer viceUtil.f indByPersn Id( vcg.ge tPrimaryId () );
  2240                                      _log.inf o("Vendr w as..." + v endor);
  2241                                      if ( ven dor != nul l ){
  2242                                               config.set VendrId( v endor.getV endrId() ) ;
  2243   //                                 } else {  //TODO: t emporary  
  2244   //                                          for (StiPt  nextConfi g: StiPtLo calService Util.findB yVcg(vcg.g etVcgId(),  -1, -1, n ull) ) {
  2245   //                                                  co nfig.setVe ndrId( nex tConfig.ge tVendrId()  );
  2246   //                                          }
  2247                                      }
  2248  
  2249                                      if ( vcg .isPrimary Revoked()  ){
  2250                                               vcg.setPri maryRevoca tionDate(d isposition Date);
  2251                                               CaretUtil. extDays(di spositionR eason, ext ensionDays );
  2252                                               config.set EntitledDa ys( extens ionDays[0]  );
  2253                                               config.set StipendSta rtDate(dis positionDa te);
  2254                                      } else {
  2255                                               if ( vcg.i sTierEditE nabled() ) {
  2256                                                       Da te tierEff ectiveDate  = Toolbox .parseDate (request.g etParamete r(ndx + "t ierEffecti veDate"));
  2257                                                       vc g.setTierE ffectiveDa te(tierEff ectiveDate  );
  2258                                                       St ring tierL evelStr =  request.ge tParameter ( ndx + "t ier");
  2259                                                       if  ( !"appea l-tier".eq uals(tierL evelStr) )  {
  2260                                                                int  tierLevel  = Integer. valueOf(ti erLevelStr );
  2261                                                                vcg. setTierLev el( tierLe vel );
  2262                                                       }
  2263  
  2264                                                       if  ( ( vcg.i sDisapprov ed(disposi tionChoice ) || vcg.i sApproved( dispositio nChoice) )  && vcg.ge tPrimaryIn itDispDate () == null  ){
  2265                                                                if (  VcgSuppor t.WaiverCo de.APPROVE D.name().e quals( vcg .getPrimar yWaiverCod e() ) || 
  2266                                                                                  VcgSuppo rt.WaiverC ode.DENIED .name().eq uals( vcg. getPrimary WaiverCode () ) ){
  2267                                                                         WorkIt emSupport  workAppDel ay = new W orkItemSup port ( clo seDelayWor k ( reques t, person,  sc, vcg )  );
  2268                                                                         saveWa iverNotes( vcg, workA ppDelay, N oteSupport .NoteGroup .APP_DELAY .groupId() , ndx, new  String[]{ "waiverRea son", "wai verNote"},  sc, reque st);
  2269                                                                } el se if ( vc g.isWaiver Primary()  ) {
  2270                                                                         saveCs cWaiver( r equest, pe rson, sc,  ndx, vcg.g etPrimaryV cgAnId(),  CaretStrPo ol.ACCEPTE D );
  2271                                                                         saveWa iverNotes( vcg, null,  NoteSuppo rt.NoteGro up.APP_DEL AY.groupId (), ndx, n ew String[ ]{"waiverR eason", "w aiverNote" }, sc, req uest);
  2272                                                                } 
  2273                                                       }
  2274                                                       
  2275                                               }
  2276                                               vcg.setPri maryDispos itionDate( dispositio nDate, sc. getCreateD ate());
  2277                                      }
  2278  
  2279                                      if ( dis positionCh oice.endsW ith("-vete ran-") ){
  2280                                               outComeApp eal = disp ositionCho ice.substr ing(0, dis positionCh oice.index Of("-veter an-") + 1) ;
  2281                                               CaretLocal ServiceUti l.save(vcg );
  2282                                               if ( dispo sitionChoi ce.contain s("revoked ") ){
  2283                                                       di spositionC hoice = Ca retStrPool .REINSTATE D;
  2284                                               } else {
  2285                                                       di spositionC hoice = Ca retStrPool .IN_PROCES S;
  2286                                               }
  2287                                               vcg.setPri maryDispRe ason( disp ositionCho ice );
  2288                                      }
  2289  
  2290                                      WorkType  cbopcWork  = vcg.get Dispositio nWork(disp ositionCho ice);
  2291                                      
  2292                                      if ( cbo pcWork  !=  null ){
  2293                                               WorIm work Item = Car etUtil.cre ateWorkIte m(sc, vcg. getGroupId (), vcg.ge tPrimaryVc gAn(), cbo pcWork, vc g.getVeter anId(), pe rson.getPe rsnId() );
  2294                                               workItem.s etVcgId( v cg.getVcgI d() );
  2295                                               if ( cbopc Work == Wo rkType.APP ROVED_DISP OSITION )  {
  2296                                                       wo rkItem.set Status( Qu eAction.TR IAGE_PENDI NG.name()  );
  2297                                               } else if  ( cbopcWor k == WorkT ype.REINST ATED_DISPO SITION )   {
  2298                                                       wo rkItem.set Status( Qu eAction.RE INSTATE_PE NDING.name () );
  2299                                               } else if  ( cbopcWor k == WorkT ype.REVOKE D_DISPOSIT ION )  {
  2300                                                       wo rkItem.set Status( Ca retStrPool .REVOKE_PE NDING );
  2301                                               } else {
  2302                                                       wo rkItem.set Status( Ca retStrPool .PENDING ) ;
  2303                                               }
  2304   //                                          workItem.s etQueId( s c.getUserI d() );
  2305                                               workItem.s etQueueId(  cbopcWork .workName. getQueueId () );
  2306                                               CaretLocal ServiceUti l.save(wor kItem);
  2307                                               if ( cbopc Work == Wo rkType.REI NSTATED_DI SPOSITION  ){
  2308                                                       Ca lendar cal  = Calenda r.getInsta nce();
  2309                                                       ca l.setTime( vcg.getPri maryRevoca tionDate(  ));
  2310                                                       ex tensionDay s = new in t[1];
  2311                                                       Ca retUtil.ex tDays(oldD isposition State, ext ensionDays );
  2312                                                       if  ( extensi onDays[0]  > 0 ) {
  2313                                                                cal. add(Calend ar.DATE, e xtensionDa ys[0] + 1) ;
  2314                                                       }  else {
  2315                                                                cal. add(Calend ar.DATE, 1 );
  2316                                                       }
  2317                                                       co nfig.setFi elds( cal. getTime(),  vcg, new  WorkItemSu pport( wor kItem ), s c, String. valueOf(vc g.getTierL evelPrevio usly()), S tring.valu eOf(vcg.ge tTierLevel ()) );
  2318                                               } else if  ( cbopcWor k == WorkT ype.REVOKE D_DISPOSIT ION ) {
  2319                                                       co nfig.setFi elds( vcg. getPrimary Revocation Date(), vc g, new Wor kItemSuppo rt( workIt em ), sc,  StringPool .BLANK, Ca retUtil.ex tDays(disp ositionRea son, exten sionDays)   );
  2320                                                       co nfig.setSt ipendType( StipendCon fig.ONE_TI ME);
  2321                                               } else {
  2322                                                       Da te effecti veDate;
  2323                                                       if  ( WorkTyp e.APPROVED _DISPOSITI ON.name(). equals( wo rkItem.get Type() ) ) {
  2324                                                                effe ctiveDate  = vcg.getP rimaryVcgA n().getRec eivedDate( );
  2325                                                       }  else {
  2326                                                                effe ctiveDate  = vcg.getT ierEffecti veDate();
  2327                                                       }
  2328                                                       co nfig.setFi elds( effe ctiveDate,  vcg, new  WorkItemSu pport( wor kItem ), s c, StringP ool.BLANK,  StringPoo l.BLANK  ) ;
  2329                                               }
  2330                                               CaretLocal ServiceUti l.save( co nfig );
  2331  
  2332                                      }
  2333                                      
  2334                                      boolean  deactivate Again = tr ue;
  2335                                      if ( dis positionCh oice.endsW ith("-va-" ) ){
  2336                                               outComeApp eal = disp ositionCho ice.substr ing(0, dis positionCh oice.index Of("-va-")  +1 );
  2337                                               deactivate Again = fa lse;
  2338                                               CaretLocal ServiceUti l.save(vcg );
  2339                                               if ( dispo sitionChoi ce.contain s("revoked ") ){
  2340                                                       fo r ( gov.va .caret.mod el.AudLg l g : CaretL ocalServic eUtil.find ByClassPk( vcg.getVcg Id(), "pri maryDispRe ason") ){
  2341                                                                if (  lg.getNew Value().to LowerCase( ).startsWi th("revoke ") ){
  2342                                                                         dispos itionChoic e = lg.get NewValue() ;
  2343                                                                         break;
  2344                                                                }
  2345                                                       }
  2346                                               } else {
  2347                                                       di spositionC hoice = Ca retStrPool .DISAPPROV ED;
  2348                                               }
  2349                                               vcg.setPri maryDispRe ason( disp ositionCho ice );
  2350                                      }
  2351  
  2352                                      long wor kUserId =  updateActi veWork(vcg AnId, vcg,  userIds,  sc);
  2353                                      
  2354                                      if ( vcg .isRevoked ( disposit ionChoice  ) || vcg.i sApproved( dispositio nChoice) | | vcg.isRe instated(d isposition Choice) ||  vcg.isApp ealed(disp ositionCho ice) ){
  2355                                               if ( Caret Util.isTiu Enabled()  ) {
  2356                                                       wr iteTiuNote (request,  getNoteBod y(vcg, dis positionCh oice, pers on.getRole (), sc), g etNoteTitl e(vcg, dis positionCh oice, pers on.getRole ()), vcg,  person.get Role(), wo rkUserId);
  2357                                               }
  2358                                      }
  2359                                      
  2360                                      //**** P eriodic As sessments
  2361                                      //if dis p == appro ved -> cre ate 4 peri odic asses sments sch eduled 90  days apart
  2362                                      if(vcg.i sApproved( dispositio nChoice)){
  2363                                               saveFirstP eriodicAss essments(r equest, vc g, person,  dispositi onDate);                               
  2364                                      }
  2365                                      //if pri mary was r evoked; in activate a ll periodi c assessme nts
  2366                                      if(vcg.i sRevoked(d isposition Choice) &&  deactivat eAgain){
  2367                                               _log.info( "primary s tatus chan ged from a pproved... inactivati ng periodi c assmts.. .");
  2368                                               inactivate Assessment s(vcg.getV cgId(), vc g.getPrima ryId(), Ca retStrPool .ASSMT_PER IODIC);
  2369                                      }
  2370                                      
  2371                                      //if pri mary was r einstated;  activate  all period ic assessm ents
  2372                                      if(vcg.i sReinstate d(disposit ionChoice) ){
  2373                                               _log.info( "primary s tatus chan ged to rei nstated... activating  periodic  assmts..." );
  2374                                               activateAs sessments( vcg.getVcg Id(), vcg. getPrimary Id(), Care tStrPool.A SSMT_PERIO DIC);
  2375                                      }
  2376                                      
  2377                             } else  if ( pers on.getRole () == Pers on.Role.SE CONDARY &&  !vcg.getS econdaryDi spReason() .equals( d isposition Choice ) ) {
  2378   //                                 oldDispo sitionStat e = vcg.ge tSecondary DispReason ();
  2379                                      String e xtDays = C aretUtil.e xtDays(dis positionCh oice, exte nsionDays) ;
  2380                                      if ( vcg .isGeneral Approved()  && vcg.is Approved(  extDays +  dispositio nReason )  || vcg.isR einstated(  extDays +  dispositi onReason )  ) {
  2381                                               throw new  Applicatio nWorkFlowE xception(" Cannot app rove CG wh ile Genera l is in Ap proved sta te");
  2382                                      }
  2383                                      vcg.setS econdaryDi spReason(  extDays +  dispositio nReason  ) ;
  2384                                      vcgAnId  = vcg.getS econdaryVc gAnId();
  2385                                      userIds. add( vcg.g etSecondar y().getRoo tUserId()  );
  2386                                      if ( vcg .isRevoked ( vcg.getS econdaryDi spReason()  ) ){
  2387                                               vcg.setSec ondaryRevo cationDate (dispositi onDate);
  2388                                      } else {
  2389                                               if ( ( vcg .isDisappr oved(dispo sitionChoi ce) || vcg .isApprove d(disposit ionChoice)  )  && vcg .getSecond aryInitDis pDate()==  null ){
  2390                                                       if  ( VcgSupp ort.Waiver Code.APPRO VED.name() .equals( v cg.getSeco ndaryWaive rCode() )  || 
  2391                                                                         VcgSup port.Waive rCode.DENI ED.name(). equals( vc g.getSecon daryWaiver Code() ) ) {
  2392                                                                Work ItemSuppor t workAppD elay = new  WorkItemS upport ( c loseDelayW ork ( requ est, perso n, sc, vcg  ) );
  2393                                                                save WaiverNote s(vcg, wor kAppDelay,  NoteSuppo rt.NoteGro up.APP_DEL AY.groupId (), ndx, n ew String[ ]{"waiverR eason", "w aiverNote" }, sc, req uest);
  2394                                                       }  else if (  vcg.isWaiv erSecondar y() ) {
  2395                                                                save CscWaiver(  request,  person, sc , ndx, vcg .getSecond aryVcgAnId (), CaretS trPool.ACC EPTED);
  2396                                                                save WaiverNote s(vcg, nul l, NoteSup port.NoteG roup.APP_D ELAY.group Id(), ndx,  new Strin g[]{"waive rReason",  "waiverNot e"}, sc, r equest);
  2397                                                       }
  2398                                               }
  2399                                               vcg.setSec ondaryDisp ositionDat e(disposit ionDate, s c.getCreat eDate());
  2400                                      }
  2401                                      if ( dis positionCh oice.endsW ith("-vete ran-") ){
  2402                                               outComeApp eal = disp ositionCho ice.substr ing(0, dis positionCh oice.index Of("-veter an-") + 1) ;
  2403                                               CaretLocal ServiceUti l.save(vcg );
  2404                                               if ( dispo sitionChoi ce.contain s("revoked ") ){
  2405                                                       di spositionC hoice = Ca retStrPool .REINSTATE D;
  2406                                               } else {
  2407                                                       di spositionC hoice = Ca retStrPool .IN_PROCES S;
  2408                                               }
  2409                                               vcg.setSec ondaryDisp Reason( di spositionC hoice );
  2410                                      } else i f ( dispos itionChoic e.endsWith ("-va-") ) {
  2411                                               outComeApp eal = disp ositionCho ice.substr ing(0, dis positionCh oice.index Of("-va-")  +1 );
  2412                                               CaretLocal ServiceUti l.save(vcg );
  2413                                               if ( dispo sitionChoi ce.contain s("revoked ") ){
  2414                                                       fo r ( gov.va .caret.mod el.AudLg l g : CaretL ocalServic eUtil.find ByClassPk( vcg.getVcg Id(), "sec ondaryDisp Reason") ) {
  2415                                                                if (  lg.getNew Value().to LowerCase( ).startsWi th("revoke ") ){
  2416                                                                         dispos itionChoic e = lg.get NewValue() ;
  2417                                                                         break;
  2418                                                                }
  2419                                                       }
  2420                                               } else {
  2421                                                       di spositionC hoice = Ca retStrPool .DISAPPROV ED;
  2422                                               }
  2423                                               vcg.setSec ondaryDisp Reason( di spositionC hoice );
  2424                                      }
  2425                                      long wor kUserId =  updateActi veWork(vcg AnId, vcg,  userIds,  sc);
  2426                                      
  2427                                      if ( vcg .isRevoked ( disposit ionChoice  ) || vcg.i sApproved( dispositio nChoice) | | vcg.isRe instated(d isposition Choice) ||  vcg.isApp ealed(disp ositionCho ice) ){
  2428                                               if ( Caret Util.isTiu Enabled()  ) {
  2429                                                       wr iteTiuNote (request,  getNoteBod y(vcg, dis positionCh oice, pers on.getRole (), sc), g etNoteTitl e(vcg, dis positionCh oice, pers on.getRole ()), vcg,  person.get Role(), wo rkUserId);
  2430                                               }
  2431                                      }
  2432                             } else  if ( pers on.getRole () == Pers on.Role.SE CONDARYTWO  && !vcg.g etSecondar yTwoDispRe ason().equ als( dispo sitionChoi ce )  ){
  2433   //                                 oldDispo sitionStat e = vcg.ge tSecondary TwoDispRea son();
  2434                                      String e xtDays = C aretUtil.e xtDays(dis positionCh oice, exte nsionDays) ;
  2435                                      if ( vcg .isGeneral Approved()  && vcg.is Approved(  extDays +  dispositio nReason )  || vcg.isR einstated(  extDays +  dispositi onReason )  ) {
  2436                                               throw new  Applicatio nWorkFlowE xception(" Cannot app rove CG wh ile Genera l is in Ap proved sta te");
  2437                                      }
  2438                                      vcg.setS econdaryTw oDispReaso n( extDays  + disposi tionReason   );
  2439                                      vcgAnId  = vcg.getS econdaryTw oVcgAnId() ;
  2440                                      userIds. add( vcg.g etSecondar yTwo().get RootUserId () );
  2441                                      if ( vcg .isRevoked ( vcg.getS econdaryTw oDispReaso n() ) ){
  2442                                               vcg.setSec ondaryTwoR evocationD ate(dispos itionDate) ;
  2443                                      } else {
  2444                                               if ( ( vcg .isDisappr oved(dispo sitionChoi ce) || vcg .isApprove d(disposit ionChoice)  ) && vcg. getSeconda ryInitDisp Date() ==  null ){
  2445                                                       if  ( VcgSupp ort.Waiver Code.APPRO VED.name() .equals( v cg.getSeco ndaryTwoWa iverCode()  ) || 
  2446                                                                         VcgSup port.Waive rCode.DENI ED.name(). equals( vc g.getSecon daryTwoWai verCode()  ) ){
  2447                                                                Work ItemSuppor t workAppD elay = new  WorkItemS upport ( c loseDelayW ork ( requ est, perso n, sc, vcg  ) );
  2448                                                                save WaiverNote s(vcg, wor kAppDelay,  NoteSuppo rt.NoteGro up.APP_DEL AY.groupId (), ndx, n ew String[ ]{"waiverR eason", "w aiverNote" }, sc, req uest);
  2449                                                       }  else if (  vcg.isWaiv erSecondar yTwo() ){
  2450                                                                save CscWaiver(  request,  person, sc , ndx, vcg .getSecond aryTwoVcgA nId(), Car etStrPool. ACCEPTED);
  2451                                                                save WaiverNote s(vcg, nul l, NoteSup port.NoteG roup.APP_D ELAY.group Id(), ndx,  new Strin g[]{"waive rReason",  "waiverNot e"}, sc, r equest);
  2452                                                       }
  2453                                               }
  2454                                               vcg.setSec ondaryTwoD isposition Date(dispo sitionDate , sc.getCr eateDate() );
  2455                                      }
  2456                                      if ( dis positionCh oice.endsW ith("-vete ran-") ){
  2457                                               outComeApp eal = disp ositionCho ice.substr ing(0, dis positionCh oice.index Of("-veter an-") + 1) ;
  2458                                               CaretLocal ServiceUti l.save(vcg );
  2459                                               if ( dispo sitionChoi ce.contain s("revoked ") ){
  2460                                                       di spositionC hoice = Ca retStrPool .REINSTATE D;
  2461                                               } else {
  2462                                                       di spositionC hoice = Ca retStrPool .IN_PROCES S;
  2463                                               }
  2464                                               vcg.setSec ondaryTwoD ispReason(  dispositi onChoice ) ;
  2465                                      } else i f ( dispos itionChoic e.endsWith ("-va-") ) {
  2466                                               outComeApp eal = disp ositionCho ice.substr ing(0, dis positionCh oice.index Of("-va-")  +1 );
  2467                                               CaretLocal ServiceUti l.save(vcg );
  2468                                               if ( dispo sitionChoi ce.contain s("revoked ") ){
  2469                                                       fo r ( gov.va .caret.mod el.AudLg l g : CaretL ocalServic eUtil.find ByClassPk( vcg.getVcg Id(), "sec ondaryTwoD ispReason" ) ){
  2470                                                                if (  lg.getNew Value().to LowerCase( ).startsWi th("revoke ") ){
  2471                                                                         dispos itionChoic e = lg.get NewValue() ;
  2472                                                                         break;
  2473                                                                }
  2474                                                       }
  2475                                               } else {
  2476                                                       di spositionC hoice = Ca retStrPool .DISAPPROV ED;
  2477                                               }
  2478                                               vcg.setSec ondaryTwoD ispReason(  dispositi onChoice ) ;
  2479                                      }
  2480                                      if ( ext ensionDays [0] > 0 ){
  2481                                               _log.info( "Benefits  extended "  + extensi onDays[0]  + " days f rom revoca tion date" );
  2482                                      }
  2483                                      long wor kUserId =  updateActi veWork(vcg AnId, vcg,  userIds,  sc);
  2484                                      
  2485                                      if ( vcg .isRevoked ( disposit ionChoice  ) || vcg.i sApproved( dispositio nChoice) | | vcg.isRe instated(d isposition Choice) ||  vcg.isApp ealed(disp ositionCho ice) ){
  2486                                               if ( Caret Util.isTiu Enabled()  ) {
  2487                                                       wr iteTiuNote (request,  getNoteBod y(vcg, dis positionCh oice, pers on.getRole (), sc), g etNoteTitl e(vcg, dis positionCh oice, pers on.getRole ()), vcg,  person.get Role(), wo rkUserId);
  2488                                               }
  2489                                      }
  2490                             } else  if ( pers on.getRole () == Pers on.Role.GE NERAL && ! vcg.getGen eralDispRe ason().equ als( dispo sitionChoi ce )  ){ / / General  Caregiver
  2491                                      _log.inf o( "Genera l Caregive r... updat e profile. .." );
  2492   //                                 generalU pdate = tr ue;
  2493                                      String e xtDays = C aretUtil.e xtDays(dis positionCh oice, exte nsionDays) ;
  2494                                      if ( ( v cg.isPrima ryApproved () || vcg. isSecondar yApproved( ) || vcg.i sSecondary TwoApprove d() 
  2495   //                                                  ||  vcg.isApp ealed(Pers on.Role.PR IMARY) ||  vcg.isAppe aled(Perso n.Role.SEC ONDARY) ||  vcg.isApp ealed(Pers on.Role.SE CONDARYTWO
  2496                                                       )  && vcg.isA pproved( e xtDays + d isposition Reason ) | | vcg.isRe instated(  extDays +  dispositio nReason )  ) {
  2497                                               throw new  Applicatio nWorkFlowE xception(" Cannot app rove Gener al CG whil e 10-10CG  CG is in A pproved/Ap pealled st ate");
  2498                                      }
  2499                                      vcg.setG eneralDisp Reason( ex tDays + di spositionR eason  );
  2500   //                                 oldDispo sitionStat e = vcg.ge tGeneralDi spReason() ;
  2501                                      if ( vcg .isRevoked ( vcg.getG eneralDisp Reason() )  ){
  2502                                               vcg.setGen eralRevoca tionDate(d isposition Date);
  2503                                      } else {
  2504                                               vcg.setGen eralDispos itionDate( dispositio nDate);
  2505                                      }
  2506                             } else  {
  2507                                      _log.err or("Invali d state: "  + person  + " with r ole " + pe rson.getRo le() );
  2508                             }
  2509                             
  2510                             if ( v cgAnId > 0  && ( vcg. isAppealed (dispositi onChoice)  || !Toolbo x.isEmpty( outComeApp eal) )  ){
  2511                                      try {
  2512                                               Apeal appe al;
  2513                                               if ( !Tool box.isEmpt y(outComeA ppeal) ){
  2514                                                       ap peal = Ape alLocalSer viceUtil.g etByOwner( vcgAnId, p erson.getP ersnId(),  outComeApp eal);
  2515                                                       St ring adjud ication =  LanguageUt il.get( Lo cale.getDe fault(), d isposition Choice ) +  ":" + req uest.getPa rameter(nd x + "note" );
  2516                                                       ap peal.setAd judication ( adjudica tion.subst ring(0, Ma th.min( ad judication .length(),  75 ) ) );
  2517                                                       ap peal.setCo mpletionDa te( Toolbo x.parseDat e( request .getParame ter(ndx +  "appealDat e") ) );
  2518                                                       ap peal.setCo ntact( req uest.getPa rameter(nd x + "appea lContact")  );
  2519                                               } else {
  2520                                                       ap peal = new  ApealImpl ();
  2521                                                       ap peal.setCl assPk( vcg AnId );
  2522                                                       ap peal.setOw nerId( per son.getPer snId() );
  2523                                                       ap peal.setRe ason(dispo sitionChoi ce);
  2524                                                       ap peal.setCr eationDate ( Toolbox. parseDate(  request.g etParamete r(ndx + "a ppealDate" ) ) );
  2525                                                       ap peal.setCo ntact( req uest.getPa rameter(nd x + "appea lContact")  );
  2526                                                       St ring note  = request. getParamet er(ndx + " note");
  2527                                                       ap peal.setNo te( note.s ubstring(0 , Math.min ( note.len gth(), 75  ) ) );
  2528                                               }
  2529                                               CaretLocal ServiceUti l.save( ap peal );
  2530                                              
  2531                                               List<Docum > document s = DocumL ocalServic eUtil.getB yTrackerNo te( tracke r );
  2532                                               for ( Docu m docum :  documents  ){
  2533                                                       if  ( docum.g etClassPk( ) == 0 ){
  2534                                                                docu m.setClass Pk(appeal. getApealId ());
  2535                                                                docu m.setClass Id(PortalU til.getCla ssNameId(A peal.class ));
  2536                                                                docu m.setNote( StringPool .BLANK);
  2537                                                                try  {
  2538                                                                         DocumL ocalServic eUtil.upda teDocum(do cum);
  2539                                                                } ca tch (Syste mException  e) {
  2540                                                                         e.prin tStackTrac e();
  2541                                                                }
  2542                                                       }
  2543                                               }
  2544                                               if ( Caret StrPool.IN _PROCESS.e quals( dis positionCh oice )) {
  2545                                                       No te note =  CaretUtil. createNote (sc.getCre ateDate(),  appeal.ge tApealId() , NoteGrou p.APPEAL.g roupId(),  sc.getUser Id(), requ est.getPar ameter(ndx  + "note") );
  2546                                                       no te.setVcgI d(vcg.getV cgId());
  2547                                                       No teLocalSer viceUtil.a ddNote(not e);
  2548                                               }
  2549                                              
  2550                                      } catch  (Applicati onWorkFlow Exception  e) {
  2551                                               Applicatio nWorkFlowE xception.h andleExcep tion(e);
  2552                                      } catch  (SystemExc eption e)  {
  2553                                               e.printSta ckTrace();
  2554                                      } 
  2555                             }
  2556                             
  2557                             if ( C Action.can DoCaret(re quest, Car etCan.TECH _DISPOSITI ON ) ){
  2558                                      String t icketNumbe r = Toolbo x.nullSafe ( request. getParamet er(ndx + " ticketNumb er") );
  2559                                      _log.inf o("ticket"  + vcgAnId  + ":" + t icketNumbe r );
  2560                                      vcg.setT icketNumbe r(vcgAnId,  ticketNum ber);
  2561                                      vcg.setN ote( "Tick etNumber",  ticketNum ber, sc.ge tUserId(),  sc.getCre ateDate(),  NoteSuppo rt.NoteGro up.DISPOSI TION.group Id() );
  2562                             }
  2563                             
  2564                             String  note = re quest.getP arameter(n dx + "note ");
  2565                             if ( ! CaretStrPo ol.IN_PROC ESS.equals ( disposit ionChoice  )){
  2566                                      vcg.setN ote("dispo sitionNote ", note, s c.getUserI d(), sc.ge tCreateDat e(), NoteS upport.Not eGroup.DIS POSITION.g roupId() ) ;
  2567                             }
  2568                             
  2569                             CaretL ocalServic eUtil.save (vcg);
  2570                    }
  2571           
  2572           
  2573           pu blic long  updateActi veWork( lo ng vcgAnId , VcgSuppo rt vcg, Co llection<L ong> userI ds, Servic eContext s c ) throws  Applicati onWorkFlow Exception{
  2574                             //Upda te active  Work Item
  2575                             try {
  2576                                      long wor kUserId =  0;
  2577                                      VcgAppli cation vcg App = new  VcgApplica tion( VcgA nLocalServ iceUtil.ge tVcgAn( vc gAnId ) );
  2578                                      if ( vcg App != nul l ){
  2579                                               Applicatio nStatus ap pStatus =  null;
  2580                                               List<WorIm > works =  WorImLocal ServiceUti l.findByCl assId( vcg .getVcgId( ), vcgAnId ); //worIm Id=630644,  type=CSC_ APP, US251 7B, CGU2
  2581                                               if ( !work s.isEmpty( ) ){
  2582                                                       Wo rkItemSupp ort vcgApp Work = new  WorkItemS upport( wo rks.get(0)  );
  2583                                                       if  ( vcgAppW ork.isComp letable( v cg ) ){
  2584                                                                if (  !WorkStat us.COMPLET E.name().e quals( vcg AppWork.ge tStatus()  ) ){
  2585                                                                         vcgApp Work.setSt atus( Care tStrPool.C OMPLETE );
  2586                                                                         vcgApp Work.setCo mpletionBy (sc.getUse rId());
  2587                                                                         vcgApp Work.setCo mpletionDa te(sc.getC reateDate( ));
  2588                                                                         workUs erId = vcg AppWork.ge tUserId();
  2589                                                                         CaretL ocalServic eUtil.save (vcgAppWor k);
  2590                                                                         appSta tus = Appl icationSta tus.DECISI ON_MADE;
  2591                                                                } el se if ( !A pplication Status.DEC ISION_MADE .name().eq uals( vcgA pp.getStat us() ) ){
  2592                                                                         appSta tus = Appl icationSta tus.IN_REV IEW;
  2593                                                                }
  2594                                                       }  else if (  !Applicati onStatus.D ECISION_MA DE.name(). equals( vc gApp.getSt atus() ) ) {
  2595                                                                appS tatus = Ap plicationS tatus.IN_R EVIEW;
  2596                                                       }
  2597                                               }
  2598                                               if ( appSt atus != nu ll ){
  2599                                                       vc gApp.setSt atus( appS tatus.name () );
  2600                                                       Ca retLocalSe rviceUtil. save( vcgA pp );
  2601                                               }
  2602                                      }
  2603                                      
  2604                                      
  2605                                      if ( ! u serIds.isE mpty() &&  vcgApp !=  null ) {
  2606                                               String mes sage = Lan guageUtil. get( Local e.getDefau lt(), Care tStrPool.D ISPOSITION ED_ONLINE_ MESSAGE);
  2607                                               userIds.ad d( vcg.get Veteran(). getRootUse rId() );
  2608                                               for ( long  userId :  userIds ){
  2609                                                       if  ( userId  > 0 ){
  2610                                                                Care tLocalServ iceUtil.ad dNote( Car etUtil.cre ateNote( s c.getCreat eDate(), v cgApp.getV cgAnId(),  NoteSuppor t.NoteGrou p.DISPOSIT ION.groupI d(), userI d, message  ) );
  2611                                                       }
  2612                                               }
  2613                                      }
  2614                                      
  2615                                      return w orkUserId   == 0? sc. getUserId( ): workUse rId;
  2616                                      
  2617                             } catc h (NoSuchC lassNameEx ception e)  {
  2618                                      throw ne w Applicat ionWorkFlo wException (e);
  2619                             } catc h (SystemE xception e ) {
  2620                                      throw ne w Applicat ionWorkFlo wException (e);
  2621                             } catc h (PortalE xception e ) {
  2622                                      throw ne w Applicat ionWorkFlo wException (e);
  2623                             }
  2624           }
  2625           
  2626           pu blic Strin g getNoteB ody(VcgSup port vcg,  String dis positionCh oice, Pers on.Role ro le, Servic eContext s c ) {
  2627                    Stri ngBuilder  sb = new S tringBuild er();
  2628                    sb.a ppend("Vet eran's Nam e - ").app end(vcg.ge tVeteranNa me()).appe nd("\n");
  2629                    sb.a ppend("Vet eran's SSN  - ").appe nd(vcg.get Veteran(). getSsn()). append("\n ");
  2630                    
  2631                    VcgA n app = vc g.getPerso nVcgAn(rol e);
  2632                    if ( app != nul l){
  2633                             sb.app end("Form  10-10CG Va lid Date -  ").append ( Toolbox. formatDate Cprs(app.g etReceived Date() ) ) .append("\ n");
  2634                             
  2635                    }
  2636                    //sb .append("F orm 10-10C G Valid Da te - ").ap pend( Tool box.format DateCprs(a pp.getRece ivedDate()  ) ).appen d("\n");
  2637                    
  2638                    try  {
  2639                             sb.app end("Veter an Assessm ent Comple ted - ").a ppend( Too lbox.forma tDateCprs( vcg.geVete ranAssessm entComplet ionDate()  ) ).append ("\n");
  2640                             sb.app end("Careg iver Asses sment Comp leted - ") .append( T oolbox.for matDateCpr s(vcg.getC aregiverAs sessmentCo mpletionDa te(role) )  ).append( "\n");
  2641                             sb.app end("Careg iver Train ing Verifi ed - ").ap pend( Tool box.format DateCprs(v cg.getCare giverTrain ingComplet ionDate(ro le) ) ).ap pend("\n") ;
  2642                             sb.app end("In-Ho me Visit C ompleted -  ").append ( Toolbox. formatDate Cprs(vcg.g etInHomeCo mpletionDa te(role) )  ).append( "\n");
  2643                    } ca tch (Appli cationWork FlowExcept ion e) {
  2644                             e.prin tStackTrac e();
  2645                    }
  2646                    
  2647                    sb.a ppend("App roval Date  - ").appe nd( Toolbo x.formatDa teCprs(sc. getCreateD ate()) ).a ppend("\n" );
  2648                    sb.a ppend("App roved Prim ary Family  Caregiver  Name - ") .append(vc g.getPrima ryName()). append("\n ");
  2649   //               (If  there is a  Secondary )
  2650                    if (  vcg.isSec ondaryAppr oved() ){
  2651                             sb.app end("Appro ved Second ary Family  Caregiver  Name - ") .append(vc g.getSecon daryName() ). append( "\n");
  2652                    }
  2653                    
  2654                    
  2655                    retu rn sb.toSt ring();
  2656           }
  2657  
  2658  
  2659           pu blic Strin g getNoteT itle(VcgSu pport vcg,  String di spositionC hoice, Per son.Role r ole ) {
  2660                    
  2661                    Stri ng title =  MessageFo rmat.forma t( Languag eUtil.get(  Locale.ge tDefault() , "nationa l-note-tit le-" + dis positionCh oice ), ro le.name()  );
  2662                    
  2663                    retu rn title;
  2664           }
  2665  
  2666  
  2667           pr ivate WorI m closeDel ayWork(Act ionRequest  request,  Person per son, Servi ceContext  sc, VcgSup port vcg)  throws App licationWo rkFlowExce ption {
  2668                    
  2669                    WorI m workItem  = WorImLo calService Util.findB yCgWorkLas t( vcg.get VcgId(), p erson.getP ersnId(),  WorkType.A PP_DELAY.n ame() );
  2670                    
  2671                    if (  Toolbox.i sEmpty( wo rkItem.get Status() )  || CaretS trPool.IN_ PROCESS.eq uals( work Item.getSt atus() ) ) {
  2672                             throw  new Applic ationWorkF lowExcepti on( "INVAL ID WORK IT EM STATUS"  );
  2673                    } el se {
  2674                             workIt em = WorIm LocalServi ceUtil.fin dByCgWorkL ast( vcg.g etVcgId(),  person.ge tPersnId() , WorkType .DELAY_REV IEWED.name () );
  2675                             workIt em.setComp letionBy(P ortalUtil. getUserId( request) ) ;
  2676                             workIt em.setComp letionDate ( sc.getCr eateDate()  );
  2677                             workIt em.setStat us( WorkSt atus.COMPL ETE.name()  );
  2678                             
  2679   //                        workIt em.useNote (noteAtt,  vcg.getNot e(noteAtt) );
  2680                             CaretL ocalServic eUtil.save (workItem) ;
  2681                    }
  2682                    retu rn workIte m;
  2683           }
  2684  
  2685  
  2686           pr ivate Waiv r saveCscW aiver(Acti onRequest  request, P erson pers on, Servic eContext s c, String  ndx, long  classPk, S tring adju dication)  throws App licationWo rkFlowExce ption {
  2687                    Waiv r waiver =  new Waivr Impl();
  2688                    waiv er.setReas on( reques t.getParam eter(ndx +  "waiverRe ason") );
  2689                    waiv er.setNote ( request. getParamet er(ndx + " waiverNote ") );
  2690                    waiv er.setUser Id( Portal Util.getUs erId( requ est ) );
  2691                    waiv er.setOwne rId( perso n.getPersn Id() );
  2692                    waiv er.setCrea tionDate(  sc.getCrea teDate() ) ;
  2693                    waiv er.setClas sPk( class Pk );
  2694                    waiv er.setAdju dication(  adjudicati on );
  2695                    Care tLocalServ iceUtil.sa ve(waiver) ;
  2696                    retu rn waiver;
  2697           }
  2698           
  2699           pr ivate void  saveWaive rNotes ( V cgSupport  vcg, WorkI temSupport  workItem,  long note GroupId, S tring ndx,  String[]  params, Se rviceConte xt sc, Por tletReques t request  ) throws A pplication WorkFlowEx ception {
  2700                    for  ( String p aram: para ms ) {
  2701                             String  note = re quest.getP arameter(n dx + param );
  2702                             if ( T oolbox.isE mpty( note  ) ) conti nue;
  2703                             if ( " waiverReas on".equals ( param )  ){
  2704                                      note = " App Delay  Reason:" +  LanguageU til.get( L ocale.getD efault(),  note );
  2705                             }
  2706                             vcg.se tNote(para m,  note,  sc.getUser Id(), sc.g etCreateDa te(), note GroupId );
  2707                    }
  2708                    Care tLocalServ iceUtil.sa ve(vcg);
  2709                    
  2710                    if (  workItem  != null )  {
  2711                             for (  String par am: params  ) {
  2712                                      workItem .useNote(p aram, vcg. getNote(pa ram));
  2713                             }
  2714                             CaretL ocalServic eUtil.save (workItem) ;
  2715                    }
  2716           }
  2717  
  2718  
  2719           pr ivate void  saveFirst PeriodicAs sessments( ActionRequ est reques t, VcgSupp ort vcgSup port, Pers on person,  Date disp ositionDat e){
  2720                    
  2721                    Map< String, Ob ject> form  = ResultM ap.getForm (request);
  2722                    Serv iceContext  sc = Care tParam.set CaretServi ceContext( request);
  2723                    
  2724                    //As smtBean pe riodicAssm tOne = new  AssmtBean (new Assmt Impl(), Ca retStrPool .QUARTER1) ;                             
  2725                    //As smtBean pe riodicAssm tTwo = new  AssmtBean (new Assmt Impl(), Ca retStrPool .QUARTER2) ;                    
  2726                    //As smtBean pe riodicAssm tThree = n ew AssmtBe an(new Ass mtImpl(),  CaretStrPo ol.QUARTER 3);                                    
  2727                    //As smtBean pe riodicAssm tAnnual =  new AssmtB ean(new As smtImpl(),  CaretStrP ool.ANNUAL ); 
  2728  
  2729                    List <AssmtBean > periodic Assessment List = new  ArrayList <AssmtBean >();
  2730                    //pe riodicAsse ssmentList .add(perio dicAssmtOn e);
  2731                    //pe riodicAsse ssmentList .add(perio dicAssmtTw o);
  2732                    //pe riodicAsse ssmentList .add(perio dicAssmtTh ree);
  2733                    //pe riodicAsse ssmentList .add(perio dicAssmtAn nual);
  2734                    peri odicAssess mentList.a dd(new Ass mtBean(new  AssmtImpl (), CaretS trPool.QUA RTER1));
  2735                    peri odicAssess mentList.a dd(new Ass mtBean(new  AssmtImpl (), CaretS trPool.QUA RTER2));
  2736                    peri odicAssess mentList.a dd(new Ass mtBean(new  AssmtImpl (), CaretS trPool.QUA RTER3));
  2737                    peri odicAssess mentList.a dd(new Ass mtBean(new  AssmtImpl (), CaretS trPool.ANN UAL));
  2738  
  2739                    try  {
  2740                             Calend ar c = Cal endar.getI nstance();  
  2741                             c.setT ime(dispos itionDate) ;
  2742                             for(As smtBean on eAssmt:per iodicAsses smentList) {
  2743                                      oneAssmt .getAssess ment().set Year(1);
  2744                                      oneAssmt .getAssess ment().set VcgId(vcgS upport.get VcgId());
  2745                                      oneAssmt .getAssess ment().set Active(tru e);
  2746                                      oneAssmt .getAssess ment().set CaregiverI d(person.g etPersnId( ));
  2747                                      oneAssmt .getAssess ment().set UserId(sc. getUserId( ));
  2748                                      
  2749                                      c.add(Ca lendar.DAT E, 90);
  2750                                      oneAssmt .getAssess ment().set ScheduleDa te(c.getTi me());  
  2751                                      
  2752                                      CaretLoc alServiceU til.save(o neAssmt.ge tAssessmen t());
  2753                             }
  2754                    } ca tch (Appli cationWork FlowExcept ion e) {
  2755                             Applic ationWorkF lowExcepti on.handleE xception(e );
  2756                    }
  2757  
  2758                    form .put("peri odicAssess mentList",  periodicA ssessmentL ist);
  2759           }
  2760  
  2761           
  2762           pu blic void  inactivate Assessment s( long vc gId, long  caregiverI d, String  category) 
  2763           {
  2764                    Stri ng[] perio dicTypes =  {CaretStr Pool.QUART ER1, Caret StrPool.QU ARTER2, Ca retStrPool .QUARTER3,  CaretStrP ool.ANNUAL };
  2765                    Stri ng[] initi alTypes =  {CaretStrP ool.PRIMAR Y_ASSESSME NT, CaretS trPool.PRI MARY_CLINI CAL, Caret StrPool.PR IMARY_TRAI NING, Care tStrPool.P RIMARY_IN_ HOME, Care tStrPool.S ECONDARY_A SSESSMENT,  CaretStrP ool.SECOND ARY_CLINIC AL, CaretS trPool.SEC ONDARY_TRA INING, Car etStrPool. SECONDARY_ TWO_ASSESS MENT, Care tStrPool.S ECONDARY_T WO_CLINICA L, CaretSt rPool.SECO NDARY_TWO_ TRAINING};
  2766  
  2767                    try 
  2768                    {                                                    
  2769                             List<A ssmt> asse ssmentList ;
  2770                             if(cat egory.equa ls(CaretSt rPool.ASSM T_PERIODIC )){
  2771                                      assessme ntList = A ssmtLocalS erviceUtil .findByAss mtTypes(vc gId, perio dicTypes);
  2772                             }else  if(categor y.equals(C aretStrPoo l.ASSMT_IN ITIAL)){
  2773                                      assessme ntList = A ssmtLocalS erviceUtil .findByAss mtTypes(vc gId, initi alTypes);
  2774                             }else{
  2775                                      assessme ntList = A ssmtLocalS erviceUtil .findByVcg Id(vcgId);
  2776                             }
  2777                             
  2778                             for(As smt assess ment:asses smentList)
  2779                             {
  2780                                      if(asses sment.isAc tive() &&  assessment .getCaregi verId()==c aregiverId )
  2781                                      {
  2782                                               assessment .setActive (false);
  2783                                               CaretLocal ServiceUti l.save(ass essment);
  2784                                      }
  2785                             }                         
  2786                    } ca tch (Appli cationWork FlowExcept ion e) {
  2787                                      Applicat ionWorkFlo wException .handleExc eption(e);
  2788                    }
  2789           }
  2790  
  2791           
  2792           pu blic void  activateAs sessments(  long vcgI d, long ca regiverId,  String ca tegory) 
  2793           {
  2794                    Stri ng[] perio dicTypes =  {CaretStr Pool.QUART ER1, Caret StrPool.QU ARTER2, Ca retStrPool .QUARTER3,  CaretStrP ool.ANNUAL };
  2795                    Stri ng[] initi alTypes =  {CaretStrP ool.PRIMAR Y_ASSESSME NT, CaretS trPool.PRI MARY_CLINI CAL, Caret StrPool.PR IMARY_TRAI NING, Care tStrPool.P RIMARY_IN_ HOME, Care tStrPool.S ECONDARY_A SSESSMENT,  CaretStrP ool.SECOND ARY_CLINIC AL, CaretS trPool.SEC ONDARY_TRA INING, Car etStrPool. SECONDARY_ TWO_ASSESS MENT, Care tStrPool.S ECONDARY_T WO_CLINICA L, CaretSt rPool.SECO NDARY_TWO_ TRAINING};
  2796  
  2797                    try 
  2798                    {                                                    
  2799                             List<A ssmt> asse ssmentList ;
  2800                             if(cat egory.equa ls(CaretSt rPool.ASSM T_PERIODIC )){
  2801                                      assessme ntList = A ssmtLocalS erviceUtil .findByAss mtTypes(vc gId, perio dicTypes);
  2802                             }else  if(categor y.equals(C aretStrPoo l.ASSMT_IN ITIAL)){
  2803                                      assessme ntList = A ssmtLocalS erviceUtil .findByAss mtTypes(vc gId, initi alTypes);
  2804                             }else{
  2805                                      assessme ntList = A ssmtLocalS erviceUtil .findByVcg Id(vcgId);
  2806                             }
  2807                             
  2808                             for(As smt assess ment:asses smentList)
  2809                             {
  2810                                      if(!asse ssment.isA ctive() &&  assessmen t.getCareg iverId()== caregiverI d)
  2811                                      {
  2812                                               assessment .setActive (true);
  2813                                               CaretLocal ServiceUti l.save(ass essment);
  2814                                      }
  2815                             }                         
  2816                    } ca tch (Appli cationWork FlowExcept ion e) {
  2817                                      Applicat ionWorkFlo wException .handleExc eption(e);
  2818                    }
  2819           }
  2820  
  2821  
  2822           
  2823           pu blic void  saveVcgEnt ry ( Actio nRequest r equest, Ac tionRespon se respons e ) throws  Applicati onWorkFlow Exception{
  2824                    if (  !CAction. canDoCaret (request,  CaretCan.M ANAGE_VCG. name() ) )  {
  2825                             _log.e rror("perm issioning. .. ");
  2826                             return ;
  2827                    }
  2828                    getO utput(requ est);
  2829                    Stri ng ndx = T oolbox.nul lSafe(requ est.getPar ameter("nd x")) + Str ingPool.UN DERLINE;
  2830                    long  persnId =  ParamUtil .getLong(r equest, re quest.getP arameter(" vcg_ndx")  + "_primar yKey", Par amUtil.get Long(reque st, "_prim aryKey", P aramUtil.g etLong(req uest, ndx  + "primary Key") ) );
  2831                    long  vcgId = P aramUtil.g etLong(req uest, requ est.getPar ameter("nd x") + "vcg Id", Param Util.getLo ng(request , "vcgId")  );
  2832                    Stri ng icn = r equest.get Parameter( ndx + "iCN ");
  2833                    
  2834                    Serv iceContext  sc = Care tParam.set CaretServi ceContext(  request ) ;
  2835                    VcgS upport vcg  = null;
  2836                    if (  vcgId > 0  ){
  2837                             vcg =  VcgSupport .getVcgSup port( vcgI d );
  2838                             
  2839                             if ( C Action.can DoCaret( r equest, CA ction.Care tCan.MANAG E_VCG.name () ) ){
  2840                                      int mode  = ParamUt il.getInte ger(reques t, "MODE",  0);
  2841                                      
  2842                                      try {
  2843                                              
  2844                                               Person per son = null ;
  2845                                               Person for mPerson =  null;
  2846                                               boolean is Approved =  false;
  2847   //                                          boolean re lationship Empty = mo de == 1 ||  Toolbox.i sEmpty( re quest.getP arameter(  ndx + "rel ationship"  ) );
  2848                                               if ( persn Id > 0 ){
  2849                                                       if  ( persnId  == vcg.ge tVeteranId () ){
  2850                                                                if (  mode == 0  ){
  2851                                                                         formPe rson = (Ve teran) Car etParam.lo adModel( r equest, ne w Veteran(  new Persn Impl() ), 
  2852                                                                                  Toolbox. getCollect ion("first Name","las tName","mi ddleName",  "birthDat e", "gende r", "email ", "addres s", "addre ss2", "pho ne", "phon e2", "ssn" , "country ", "validA ddress",   "externalI d", "group Id" ),
  2853                                                                                  ndx );
  2854                                                                         ((Vete ran)formPe rson).setV aHealthEnr olled(Para mUtil.get( request, n dx + "vaHe althEnroll ed", false ));
  2855                                                                }
  2856                                                                pers on = new V eteran( Pe rsnLocalSe rviceUtil. getPersn(p ersnId) );
  2857                                                                isAp proved = v cg.isPrima ryApproved ();
  2858                                                       }  else if (  persnId ==  vcg.getPr imaryId()  ){
  2859                                                                pers on = new P rimary( Pe rsnLocalSe rviceUtil. getPersn(p ersnId) );
  2860                                                                if (  mode == 0  ) {
  2861                                                                         formPe rson = (Pr imary) Car etParam.lo adModel( r equest, ne w Primary(  new Persn Impl() ), 
  2862                                                                                           Toolbox.ge tCollectio n("firstNa me","lastN ame","midd leName", " birthDate" , "gender" , "email",  "address" , "address 2", "phone ", "phone2 ", "ssn",  "country",  "validAdd ress",  "e xternalId" , "otherHe althInsura nce"),
  2863                                                                                           ndx );
  2864                                                                         ((Prim ary)formPe rson).setI nsurance(  Primary.OT HER_INSURA NCE_ATTRIB UTE, reque st.getPara meter(ndx+ "otherInsC hecked") ) ;
  2865                                                                         ((Prim ary)formPe rson).setI nsurance(  Primary.ME DI_ENROLLE D_ATTRIBUT E, request .getParame ter(ndx+Pr imary.MEDI _ENROLLED_ ATTRIBUTE)  );
  2866                                                                         ((Prim ary)formPe rson).setI nsurance(  Primary.TR ICARE_ENRO LLED_ATTRI BUTE, requ est.getPar ameter(ndx +Primary.T RICARE_ENR OLLED_ATTR IBUTE) );
  2867                                                                         ((Prim ary)formPe rson).setI nsurance(  Primary.CH AMPVA_ENRO LLED_ATTRI BUTE, requ est.getPar ameter(ndx +Primary.C HAMPVA_ENR OLLED_ATTR IBUTE) );
  2868                                                                         vcg.se tPrimaryTy pe( reques t.getParam eter( ndx  + "relatio nship" ) ) ;
  2869                                                                }
  2870                                                                isAp proved = v cg.isPrima ryApproved ();
  2871                                                       }  else if (  persnId ==  vcg.getSe condaryId( ) ){
  2872                                                                pers on = new S econdary(  PersnLocal ServiceUti l.getPersn (persnId)  );
  2873                                                                if (  mode == 0  ) {
  2874                                                                         formPe rson = (Se condary) C aretParam. loadModel(  request,  new Second ary( new P ersnImpl()  ), 
  2875                                                                                           Toolbox.ge tCollectio n("firstNa me","lastN ame","midd leName", " birthDate" , "gender" , "email",  "address" , "address 2", "phone ", "phone2 ", "ssn",  "country",  "validAdd ress",  "e xternalId"  ),
  2876                                                                                           ndx );
  2877                                                                         vcg.se tSecondary Type( requ est.getPar ameter( nd x + "relat ionship" )  );
  2878                                                                }
  2879                                                                isAp proved = v cg.isSecon daryApprov ed();
  2880                                                       }  else if (  persnId ==  vcg.getSe condaryTwo Id() ){
  2881                                                                pers on = new S econdaryTw o( PersnLo calService Util.getPe rsn(persnI d) );
  2882                                                                if (  mode == 0  ) {
  2883                                                                         formPe rson = (Se condaryTwo ) CaretPar am.loadMod el( reques t, new Sec ondaryTwo(  new Persn Impl() ), 
  2884                                                                                           Toolbox.ge tCollectio n("firstNa me","lastN ame","midd leName", " birthDate" , "gender" , "email",  "address" , "address 2", "phone ", "phone2 ", "ssn",  "country",  "validAdd ress",  "e xternalId"  ),
  2885                                                                                           ndx );
  2886                                                                         vcg.se tSecondary TwoType( r equest.get Parameter(  ndx + "re lationship " ) );
  2887                                                                }
  2888                                                                isAp proved = v cg.isSecon daryTwoApp roved();
  2889                                                       }  else {
  2890                                                                pers on = new G eneral( Pe rsnLocalSe rviceUtil. getPersn(p ersnId) );
  2891                                                                if (  mode == 0   || mode  == 3 ) {
  2892                                                                         formPe rson = (Ge neral) Car etParam.lo adModel( r equest, ne w General(  new Persn Impl() ), 
  2893                                                                                           Toolbox.ge tCollectio n("firstNa me","lastN ame","midd leName", " birthDate" , "gender" , "email",  "address" , "address 2", "phone ", "phone2 ", "ssn",  "country",  "validAdd ress",  "e xternalId"  ),
  2894                                                                                           ndx );
  2895                                                                         vcg.se tGeneralTy pe( reques t.getParam eter( ndx  + "relatio nship" ) ) ;
  2896                                                                }
  2897                                                       }
  2898                                                       if  ( mode !=  2 && CAct ion.canDoC aret( requ est, CActi on.CaretCa n.CREATE_V CG.name()  ) ) {
  2899                                                                Care tLocalServ iceUtil.sa ve(vcg);
  2900                                                       }
  2901                                               } else if  ( mode ==  3 ) {
  2902                                                       pe rson = new  General(  new PersnI mpl() );
  2903                                                       if  ( mode ==  0  || mod e == 3 ) {
  2904                                                                form Person = ( General) C aretParam. loadModel(  request,  new Genera l( new Per snImpl() )
  2905                                                                                  Toolbox. getCollect ion("first Name","las tName","mi ddleName",  "birthDat e", "gende r", "email ", "addres s", "addre ss2", "pho ne", "phon e2", "ssn" , "country ", "validA ddress",   "externalI d" ),
  2906                                                                                  ndx );
  2907                                                       }
  2908                                               }
  2909                                              
  2910                                              
  2911                                               if ( mode  == 0 || mo de == 3 ){
  2912                                                       if  ( formPer son.isFore igner() ){
  2913                                                                Care tParam.loa dModel( re quest, for mPerson, T oolbox.get AddressCol lection(),  Toolbox.n ullSafe(re quest.getP arameter(" ndx")) + C aretStrPoo l.G_UNDERL INE );
  2914                                                       }  else {
  2915                                                                Care tParam.loa dModel( re quest, for mPerson, T oolbox.get AddressCol lection(),  Toolbox.n ullSafe(re quest.getP arameter(" ndx")) + C aretStrPoo l.U_UNDERL INE );
  2916                                                       }
  2917                                               }
  2918                                              
  2919                                               //writeTiu Note(reque st, getNot eBody(vcg,  "Approved ", person. getRole(),  sc), getN oteTitle(v cg, "Appro ved", pers on.getRole ()), vcg,  person.get Role(), 0) ;
  2920                                              
  2921                                               switch ( m ode ){
  2922                                                       ca se 1:
  2923                                                                if (  CAction.c anDoCaret(  request,  CAction.Ca retCan.DIS POSITION_V CG.name()  ) ){
  2924                                                                         saveVc gDispositi on ( reque st, vcg, p erson );
  2925                                                                }
  2926                                                                brea k;
  2927                                                       ca se 2:
  2928                                                                save VcgTier( r equest, re sponse );
  2929                                                                if (  CAction.c anDoCaret(  request,  CAction.Ca retCan.UPD ATE_TIER_L EVEL.name( ) ) ){
  2930                                                                         String  tierEffec tiveDate =  request.g etParamete r(ndx + "t ierEffecti veDate");
  2931                                                                         String  contact =  request.g etParamete r(ndx + "a ppealConta ct");
  2932                                                                         String  tierLevel Str = requ est.getPar ameter(ndx  + "tier") ;
  2933                                                                         boolea n appealTi er = Param Util.getBo olean(requ est, "appe alTier");
  2934                                                                         String  dispositi onDate = r equest.get Parameter( ndx + "dis positionDa te");
  2935                                                                         String  caretNote  = request .getParame ter("caret _note");
  2936                                                                         String  outComeAp peal  = re quest.getP arameter(" _appeal_ou tcome");
  2937                                                                         int ti erLevel =  ParamUtil. getInteger (request,  ndx + "tie r");
  2938                                                                         int ol dTier = vc g.getTierL evel();
  2939                                                                         boolea n tierChan ged = tier Level != o ldTier;
  2940                                                                         
  2941                                                                         String  tracker =  ParamUtil .getString (request,  CaretStrPo ol.TRACKER , StringPo ol.BLANK ) ;
  2942                                                                         vcg.se tTierLevel (tierLevel );
  2943                                                                         if ( ! Toolbox.is Empty(outC omeAppeal)  || appeal Tier )  {
  2944                                                                                  try {
  2945                                                                                           Apeal appe al;
  2946                                                                                           String aud itOnce = S tringPool. BLANK;
  2947                                                                                           boolean ap pealed = f alse;
  2948                                                                                           if ( !Tool box.isEmpt y(outComeA ppeal) ){
  2949                                                                                                   ap peal = Ape alLocalSer viceUtil.g etByOwner(  vcg.getPr imaryVcgAn Id(), pers on.getPers nId(), "ti er" );
  2950                                                                                                   ap peal.setAd judication ( Language Util.get(  Locale.get Default(),  outComeAp peal ) + " :" + caret Note );
  2951                                                                                                   ap peal.setCo mpletionDa te(Toolbox .parseDate ( request. getParamet er(ndx + " appealDate ") ) );
  2952   //                                                                                              if  ( outCome Appeal.end sWith( "ve teran-" )  ){
  2953   //                                                                                                       tier Level = In teger.valu eOf(String .valueOf(t ierLevelSt r));
  2954   //                                                                                              }
  2955                                                                                                   ap peal.setCo ntact(cont act);
  2956   //                                                                                              Ap ealLocalSe rviceUtil. countByOwn er( vcg.ge tPrimaryVc gAnId(), p erson.getP ersnId(),  "tier" + v cg.getTier Level() );
  2957                                                                                                   au ditOnce =  outComeApp eal;
  2958                                                                                                   ap pealed = f alse;
  2959                                                                                           } else {
  2960                                                                                                   au ditOnce =  tierLevelS tr;
  2961                                                                                                   ap pealed = t rue;
  2962                                                                                                   ap peal = new  ApealImpl ();
  2963                                                                                                   ap peal.setCl assPk( vcg .getPrimar yVcgAnId()  );
  2964                                                                                                   ap peal.setOw nerId( per son.getPer snId() );
  2965                                                                                                   ap peal.setRe ason( "tie r" );
  2966                                                                                                   ap peal.setTy pe( tierLe velStr );
  2967                                                                                                   ap peal.setCr eationDate ( Toolbox. parseDate(  request.g etParamete r(ndx + "a ppealDate" ) ) );
  2968                                                                                                   ap peal.setCo ntact(cont act);
  2969                                                                                                   ap peal.setNo te( caretN ote );
  2970                                                                                           }
  2971                                                                                          
  2972                                                                                           vcg.setTie rAppealed( appealed,  auditOnce) ;
  2973                                                                                           CaretLocal ServiceUti l.save(vcg );
  2974                                                                                           vcg.setTie rAppealed( appealed,  auditOnce) ;
  2975                                                                                          
  2976                                                                                           CaretLocal ServiceUti l.save( ap peal );
  2977                                                                                          
  2978                                                                                           List<Docum > document s = DocumL ocalServic eUtil.getB yTrackerNo te( tracke r );
  2979                                                                                           for ( Docu m docum :  documents  ){
  2980                                                                                                   if  ( docum.g etClassPk( ) == 0 ){
  2981                                                                                                            docu m.setClass Pk(appeal. getApealId ());
  2982                                                                                                            docu m.setClass Id(PortalU til.getCla ssNameId(A peal.class ));
  2983                                                                                                            docu m.setNote( StringPool .BLANK);
  2984                                                                                                            try  {
  2985                                                                                                                     DocumL ocalServic eUtil.upda teDocum(do cum);
  2986                                                                                                            } ca tch (Syste mException  e) {
  2987                                                                                                                     e.prin tStackTrac e();
  2988                                                                                                            }
  2989                                                                                                   }
  2990                                                                                           }
  2991                                                                                          
  2992                                                                                  } catch  (Applicati onWorkFlow Exception  e) {
  2993                                                                                           Applicatio nWorkFlowE xception.h andleExcep tion(e);
  2994                                                                                  } 
  2995                                                                         }
  2996                                                                         
  2997                                                                         
  2998   //                                                                    VcgSup port vcgSu pport = ne w VcgSuppo rt(vcg);
  2999                                                                         if ( t ierChanged  ){
  3000   //                                                                    if ( t ierEffecti veDate !=  null && !v cg.getTier EffectiveD ateStr().e quals( tie rEffective Date ) ||  tierChange d ){
  3001                                                                                  vcg.setT ierEffecti veDateStr(  tierEffec tiveDate ) ;
  3002                                                                                  if ( dis positionDa te!= null  && !String Pool.BLANK .equals( d isposition Date ) ){
  3003                                                                                           vcg.setPri maryDispos itionDate(  Toolbox.p arseDate(d isposition Date) );
  3004                                                                                  }
  3005                                                                                  vcg.setT ierLevel(  tierLevel   );
  3006                                              
  3007                                                                                  vcg.setN ote("tierU pdateNote" , caretNot e, sc.getU serId(), s c.getCreat eDate(), N oteSupport .NoteGroup .TIER_UPDA TE.groupId () );
  3008                                                                                  CaretLoc alServiceU til.save(v cg);
  3009                                                                                  
  3010                                                                                  if ( tie rChanged ) {
  3011                                                                                           String mes sage = Lan guageUtil. get( Local e.getDefau lt(), Care tStrPool.D ISPOSITION ED_ONLINE_ MESSAGE);
  3012                                                                                           CaretLocal ServiceUti l.addNote(  CaretUtil .createNot e(sc.getCr eateDate() , vcg.getP rimaryVcgA nId(), Not eSupport.N oteGroup.T IER_UPDATE .groupId() , person.g etRootUser Id(), mess age ) );
  3013                                                                                           CaretLocal ServiceUti l.addNote(  CaretUtil .createNot e(sc.getCr eateDate() , vcg.getP rimaryVcgA nId(), Not eSupport.N oteGroup.T IER_UPDATE .groupId() , vcg.getV eteran().g etRootUser Id(), mess age ) );
  3014                                                                                  }
  3015                                                                                  
  3016                                                                                  BaseMode l<?> bm =  vcg.getPer sonVcgAn(  persnId );
  3017                                                                                  if ( bm  == null ||  mode == 0  ){
  3018                                                                                           bm = vcg;
  3019                                                                                  }
  3020                                                                                  
  3021   //                                                                                     
  3022   //                                                                                      List<StiPt > list = S tiPtLocalS erviceUtil .findByVen dorId(vend r.getVendr Id(), -1,  -1);
  3023   //                                                                                      if ( !list .isEmpty()  ) {
  3024                                                                                                            
  3025                                                                                                   Wo rIm workIt em = Caret Util.creat eWorkItem( sc, vcg.ge tGroupId() , bm, Work Type.TIER_ UPDATE, 
  3026                                                                                                                     vcg.ge tVeteranId (), person .getPersnI d() == vcg .getVetera nId()? vcg .getPrimar yId(): per son.getPer snId() );
  3027                                                                                                   wo rkItem.set QueueId( O wnerQueue. TIER_MOD_Q .queueId ) ;
  3028                                                                                                   wo rkItem.set Status( Ca retStrPool .TIER_UPDA TE_REVIEW_ PENDING );
  3029                                                                                                   wo rkItem.set VcgId(vcgI d);
  3030                                                                                                   Ca retLocalSe rviceUtil. save( work Item );
  3031                                                                                                   
  3032                                                                                                   St ipendConfi g config =  new Stipe ndConfig (  new StiPt Impl() );
  3033                                                                                                   co nfig.setFi elds( vcg. getTierEff ectiveDate (), vcg, n ew WorkIte mSupport(  workItem ) , sc, Stri ng.valueOf (vcg.getTi erLevelPre viously()) , String.v alueOf(vcg .getTierLe vel())   ) ;
  3034                                                                                                   Ve ndr vendr  = VendrLoc alServiceU til.findBy PersnId( v cg.getPrim aryId() );
  3035                                                                                                   if  ( vendr ! = null ) {
  3036                                                                                                            conf ig.setVend rId( vendr .getVendrI d() );
  3037                                                                                                   }
  3038                                                                                                   Ca retLocalSe rviceUtil. save( conf ig );
  3039                                                                                                   Ca retLocalSe rviceUtil. addNote( C aretUtil.c reateNote(  sc.getCre ateDate(),  workItem. getWorImId (), NoteSu pport.Note Group.TIER _UPDATE.gr oupId(), s c.getUserI d(), reque st.getPara meter("car et_note")  ) );
  3040                                                                                  
  3041                                                                         } else  {
  3042                                                                                  Note nt  = CaretUti l.createNo te( sc.get CreateDate (), vcgId,  NoteSuppo rt.NoteGro up.TIER_UP DATE.group Id(), sc.g etUserId() , request. getParamet er("caret_ note") );
  3043                                                                                  nt.setVc gId( vcgId  );
  3044                                                                                  CaretLoc alServiceU til.addNot e( nt );
  3045                                                                         }
  3046                                                                }
  3047                                                                brea k;
  3048                                                       ca se 3: //as signing Ge neral CG
  3049                                                                
  3050                                                                if (  vcg.getGe neralId()  > 0 && ( v cg.isAppro ved( vcg.g etGeneralD ispReason( ) ) || vcg .isReinsta ted( vcg.g etGeneralD ispReason( ) ) ) ){
  3051                                                                         throw  new Applic ationWorkF lowExcepti on ( "Cann ot over-wr ite an app roved Gene ral Caregi ver for a  new Genera l Caregive r ");
  3052                                                                }
  3053                                                                
  3054                                                                if (  CaretView Controller .getViewCo ntroller() .setVcgPer son( reque st, formPe rson, pers on, new bo olean[5]). isEmpty()  ){
  3055                                                                         CaretL ocalServic eUtil.save (person);
  3056                                                                         vcg.se tNote("gen eralAssign mentNote",  ParamUtil .get(reque st, CaretS trPool.WOR K_COMMENT,  CaretStrP ool.ASSIGN ED_GENERAL _CG_MESSAG E ),
  3057                                                                                           sc.getUser Id(), sc.g etCreateDa te(), Note Support.No teGroup.AS SIGN_GENER AL.groupId () );
  3058                                                                         
  3059                                                                         vcg.se tNewGenera l(person.g etPersnId( ), request .getParame ter( ndx +  "relation ship" ) );
  3060                                                                         CaretL ocalServic eUtil.save (vcg);
  3061                                                                }
  3062                                                                
  3063                                                                brea k;
  3064                                                       ca se 4:
  3065   //                                                           Stri ng vcgNdx  = request. getParamet er("vcg_nd x") + Stri ngPool.UND ERLINE;
  3066   //                                                           VcgA n vcgAn =  vcg.getPer sonVcgAn(  persnId );
  3067                                                                Base Model<?> b m = vcg.ge tPersonVcg An( persnI d );
  3068                                                                if (  bm == nul l || mode  == 0 ){
  3069                                                                         bm = v cg;
  3070                                                                }
  3071                                                                Work ItemSuppor t workAppD elay =  ne w WorkItem Support(Ca retUtil.cr eateWorkIt em(sc, vcg .getGroupI d(), bm, W orkType.AP P_DELAY, v cg.getVete ranId(), p ersnId));
  3072                                                                work AppDelay.s etVcgId( v cg.getVcgI d() );
  3073   //                                                           work AppDelay.s etQueId( w aiver.getW aivrId() ) ;
  3074                                                                Care tLocalServ iceUtil.sa ve(workApp Delay);
  3075                                                                
  3076                                                                save CscWaiver(  request,  person, sc , ndx, wor kAppDelay. getApplica tionId(),  null );
  3077                                                                save WaiverNote s(vcg, wor kAppDelay,  NoteSuppo rt.NoteGro up.APP_DEL AY.groupId (), ndx, n ew String[ ]{"waiverR eason", "w aiverNote" }, sc, req uest);
  3078                                                                
  3079                                                                brea k;
  3080                                                       de fault:
  3081                                              
  3082                                                                
  3083                                                       
  3084                                                       bo olean[] ch ange = new  boolean[5 ];
  3085                                                       
  3086                                                       St ring oldAd dress = nu ll;
  3087                                                       St ring oldzi p = person .getZip();
  3088                                                       if  ( Person. Role.VETER AN == pers on.getRole () || Pers on.Role.PR IMARY == p erson.getR ole() ){
  3089                                                                oldA ddress = n ew StringB uilder(per son.getAdd ress()).ap pend(Strin gPool.COMM A_AND_SPAC E).append( person.get City()).ap pend(Strin gPool.SPAC E).append( person.get State()).a ppend(Stri ngPool.SPA CE).append (person.ge tZip()).to String();
  3090                                                       }
  3091                                                       
  3092                                                       Li st<String>  errors =  CaretViewC ontroller. getViewCon troller(). setVcgPers on( reques t, formPer son, perso n, change) ;
  3093                                                       
  3094                                                       if  ( ! error s.isEmpty( ) ){
  3095   //                                                           requ est.setAtt ribute("SA VE_FAILED" , errors.g et(0) );
  3096   //                                                           retu rn;
  3097                                                       }
  3098                                                       
  3099                                                       if  ( change[ Person.Cha nges.INSUR ANCE_CHANG E.ordinal( )] || 
  3100                                                                         change [Person.Ch anges.ADDR ESS_CHANGE .ordinal() ] || 
  3101                                                                         change [Person.Ch anges.PII_ CHANGE.ord inal()] ||  
  3102                                                                         change [Person.Ch anges.NAME _CHANGE.or dinal()] ) {
  3103                                                                if (  isApprove d ){
  3104                                                                         long c aregiverPe rsnId = pe rson.getPe rsnId() ==  vcg.getVe teranId()?  vcg.getPr imaryId():  person.ge tPersnId() ;
  3105                                                                         bm = v cg.getPers onVcgAn( c aregiverPe rsnId );
  3106                                                                         if ( b m == null  && mode ==  0 ){
  3107                                                                                  bm = vcg ;
  3108                                                                         }
  3109                                                                         boolea n addedIns urChange =  false;
  3110                                                                         boolea n addedInf oChange =  false;
  3111                                                                         Stipen dConfig co nfig = nul l;
  3112                                                                         List < WorIm> wor kItems =   CaretUtil. createWork Items(requ est, 0, bm , change, 
  3113                                                                                           vcg.getVet eranId(),  caregiverP ersnId ) ;
  3114                                                                         if ( p erson.getR ole() == P erson.Role .PRIMARY | | person.g etRole() = = Person.R ole.VETERA N ) {
  3115                                                                                  for ( Wo rIm workIt em : workI tems ){
  3116                                                                                           if ( WorkN ame.INSURA NCE_CHANGE .name().eq uals( work Item.getTy pe() ) ){
  3117                                                                                                   if  ( !addedI nsurChange  ){
  3118                                                                                                            work Item.setVc gId( vcg.g etVcgId()  );
  3119                                                                                                            work Item.setGr oupId( vcg .getGroupI d() );
  3120                                                                                                            work Item.setQu eueId( Own erQueue.PR IM_HEALTH_ INS_Q.queu eId );
  3121                                                                                                            Care tLocalServ iceUtil.sa ve(workIte m);
  3122                                                                                                            adde dInsurChan ge = true;
  3123                                                                                                   }
  3124                                                                                           } else if  ( !addedIn foChange ) {
  3125                                                                                                   St ring oldVa lue = Stri ngPool.BLA NK;
  3126                                                                                                   St ring newVa lue = Stri ngPool.BLA NK;
  3127                                                                                                   if  ( Person. Role.PRIMA RY == pers on.getRole () ){
  3128                                                                                                            work Item.setTy pe( WorkNa me.C_INFO_ CHANGE.nam e() );
  3129                                                                                                            if (  vcg.isPri maryApprov ed() && ch ange[Perso n.Changes. ADDRESS_CH ANGE.ordin al()] ){
  3130                                                                                                                     oldVal ue = oldAd dress;
  3131                                                                                                                     newVal ue = new S tringBuild er(person. getAddress ()).append (StringPoo l.COMMA_AN D_SPACE).a ppend(pers on.getCity ()).append (StringPoo l.SPACE).a ppend(pers on.getStat e()).appen d(StringPo ol.SPACE). append(per son.getZip ()).toStri ng();
  3132                                                                                                            }
  3133                                                                                                   }  else if (  Person.Rol e.VETERAN  == person. getRole()  && !oldzip .equals( p erson.getZ ip() ) ){
  3134                                                                                                            int  currentYea r = Calend ar.getInst ance().get (Calendar. YEAR);
  3135                                                                                                            work Item.setTy pe( WorkNa me.V_INFO_ CHANGE.nam e() );
  3136                                                                                                            if (  vcg.getPr imaryId()  > 0 ){
  3137                                                                                                                     if ( c onfig == n ull && vcg .isPrimary Approved()  && change [Person.Ch anges.ADDR ESS_CHANGE .ordinal() ] ){
  3138                                                                                                                              BlsRe ne wRate = Bl sReLocalSe rviceUtil. findByLess Year( pers on.getZip( ), current Year+1 );
  3139                                                                                                                              BlsRe ol dRate = Bl sReLocalSe rviceUtil. findByLess Year( oldz ip, curren tYear+1 );
  3140                                                                                                                              if ( new Rate == nu ll || oldR ate == nul l ) {
  3141                                                                                                                                       _log.error ("BLS Rate  no longer  found for  the selec ted addres s");
  3142                                                                                                                              } else {
  3143                                                                                                                                       if ( newRa te.getBlsA eId() != o ldRate.get BlsAeId()  ) {
  3144                                                                                                                                               co nfig = new  StipendCo nfig( new  StiPtImpl( ) );
  3145                                                                                                                                               co nfig.setBl sRateHourl y( newRate .getH75(). toString()  );
  3146                                                                                                                                       }
  3147                                                                                                                              }
  3148                                                                                                                              oldValue  = oldAddr ess;
  3149                                                                                                                              newValue  = new Str ingBuilder (person.ge tAddress() ).append(S tringPool. COMMA_AND_ SPACE).app end(person .getCity() ).append(S tringPool. SPACE).app end(person .getState( )).append( StringPool .SPACE).ap pend(perso n.getZip() ).toString ();
  3150                                                                                                                              workItem .setType(  WorkType.A DDRESS_CHA NGE.name()  );
  3151                                                                                                                     }
  3152                                                                                                            }
  3153                                                                                                   }
  3154                                                                                                   wo rkItem.set QueId( sc. getUserId( ) );
  3155                                                                                                   wo rkItem.set QueueId( O wnerQueue. VCG_INFO_M OD_Q.queue Id );
  3156                                                                                                   if  ( workIte m.getGroup Id() == 0  ) {
  3157                                                                                                            work Item.setGr oupId( vcg .getGroupI d() );
  3158                                                                                                   }
  3159                                                                                                   wo rkItem.set VcgId( vcg .getVcgId( ) );
  3160                                                                                                   Ca retLocalSe rviceUtil. save(workI tem);
  3161                                                                                                   if  ( config  != null &&  config.ge tPrimaryKe y() == 0 ) {
  3162                                                                                                            Care tLocalServ iceUtil.sa ve(person) ;
  3163                                                                                                            conf ig.setFiel ds( sc.get CreateDate (), vcg, n ew WorkIte mSupport(  workItem ) , sc, oldV alue, newV alue  );
  3164                                                                                                            Vend r vendr =  VendrLocal ServiceUti l.findByPe rsnId(care giverPersn Id);
  3165                                                                                                            if (  vendr !=  null ) {
  3166                                                                                                                     config .setVendrI d( vendr.g etVendrId( ) );
  3167                                                                                                            }
  3168                                                                                                            Care tLocalServ iceUtil.sa ve( config  );
  3169                                                                                                   }
  3170                                                                                                   ad dedInfoCha nge = true ;
  3171                                                                                          
  3172                                                                                  }
  3173                                                                         }
  3174                                                                }
  3175                                                                Stri ng comment  = request .getParame ter(CaretS trPool.WOR K_COMMENT) ;
  3176                                                                if (  !Toolbox. isEmpty(co mment) ){
  3177                                                                         vcg.se tNote(pers on.getRole ().getLabe l()+"Note" , request. getParamet er(CaretSt rPool.WORK _COMMENT),  sc.getUse rId(), sc. getCreateD ate(), Not eSupport.N oteGroup.P ROFILE_UPD ATE.groupI d() );
  3178                                                                         CaretL ocalServic eUtil.save (vcg);
  3179                                                                }
  3180                                                       }  else {
  3181                                                                Stri ng comment  = request .getParame ter(CaretS trPool.WOR K_COMMENT) ;
  3182                                                                if (  !Toolbox. isEmpty(co mment) ){
  3183                                                                         vcg.se tNote(pers on.getRole ().getLabe l()+"Note" , request. getParamet er(CaretSt rPool.WORK _COMMENT),  sc.getUse rId(), sc. getCreateD ate(), Not eSupport.N oteGroup.C AREGIVER_I NFO.groupI d() );
  3184                                                                         CaretL ocalServic eUtil.save (vcg);
  3185                                                                }
  3186                                                       }
  3187                                                       Ca retLocalSe rviceUtil. save(perso n);
  3188                                               }
  3189  
  3190                                      } catch  (PortalExc eption e)  {
  3191                                               Applicatio nWorkFlowE xception.h andleExcep tion(e);
  3192                                      } catch  (SystemExc eption e)  {
  3193                                               Applicatio nWorkFlowE xception.h andleExcep tion(e);
  3194                                      }
  3195                                      
  3196                                      loadVcgM anagement  (request,  response);
  3197                                      response .setRender Parameter( CaretStrPo ol.MVC_PAT H, CaretSt rPool.VCG_ MANAGEMENT _PAGE);
  3198                             }
  3199                    } el se if ( CA ction.canD oCaret( re quest, Car etCan.CREA TE_VCG ) )  {
  3200                             
  3201                             _log.i nfo("vcgId  == 0");
  3202                             Vetera n vcgVeter an;
  3203                             try {
  3204                                      
  3205                                      Map<Long ,Person> c achedMVI =  (Map<Long ,Person>)  request.ge tPortletSe ssion().ge tAttribute (CaretStrP ool.CACHED _MVI);
  3206                                      if ( cac hedMVI ==  null ){
  3207                                               cachedMVI  = new Hash Map<>();
  3208                                      }
  3209                                      if ( per snId > 0 ) {
  3210                                               if ( cache dMVI.conta insKey(per snId) ){
  3211                                                       Pe rsn person  = null;
  3212                                                       if  ( !Toolbo x.isEmpty(  cachedMVI .get(persn Id).getICN () ) ){
  3213                                                                pers on = Persn LocalServi ceUtil.get ByIcn( cac hedMVI.get (persnId). getICN() ) ;
  3214                                                       }
  3215                                                       if  ( person  != null ){
  3216                                                                vcgV eteran = n ew Veteran  ( person  );
  3217                                                       }  else {
  3218                                                                vcgV eteran = n ew Veteran ( cachedMV I.get(pers nId) );
  3219                                                                Care tLocalServ iceUtil.sa ve(vcgVete ran);
  3220                                                       }
  3221                                                       pe rsnId = vc gVeteran.g etPrimaryK ey();
  3222                                               }
  3223                                      }
  3224                                      
  3225                                      if ( per snId > 0 ) {
  3226                                               vcgVeteran  = new Vet eran(Persn LocalServi ceUtil.get Persn(pers nId));
  3227                                      } else i f ( !Toolb ox.isEmpty (icn) ){
  3228                                               vcgVeteran  = new Vet eran(new P ersnImpl() );
  3229                                               vcgVeteran .setICN(ic n);
  3230                                               vcgVeteran .setLastNa me(request .getParame ter("veter anPersonu_ lastName") );
  3231                                      } else {
  3232                                               throw new  Applicatio nWorkFlowE xception (  "NEED VER IFIED ID F OR VCG CRE ATION" );
  3233                                      }
  3234                                      CaretPar am.loadMod el(request , vcgVeter an, vcgVet eran.getMo delAttribu tes().keyS et(), ndx) ;
  3235                                      if ( vcg Veteran.is Foreigner( ) ){
  3236                                               CaretParam .loadModel ( request,  vcgVetera n, Toolbox .getAddres sCollectio n(), Caret StrPool.VE TERAN_PERS ON + Caret StrPool.G_ UNDERLINE  );
  3237                                      } else {
  3238                                               CaretParam .loadModel ( request,  vcgVetera n, Toolbox .getAddres sCollectio n(), Caret StrPool.VE TERAN_PERS ON + Caret StrPool.U_ UNDERLINE  );
  3239                                      }
  3240                             } catc h (PortalE xception e ) {
  3241                                      throw ne w Applicat ionWorkFlo wException (e);
  3242                             } catc h (SystemE xception e ) {
  3243                                      throw ne w Applicat ionWorkFlo wException (e);
  3244                             }
  3245                             vcgVet eran.setSt atus(Caret StrPool.AC TIVE_VCG);
  3246                             vcgVet eran.setVa HealthEnro lled(Param Util.get(r equest, nd x + "_vaHe althEnroll ed", false ));
  3247                             CaretL ocalServic eUtil.save (vcgVetera n);
  3248                             VcgSup port vcgSu pport = Vc gSupport.g etVeteranV cg( vcgVet eran.getPe rsnId() );
  3249                             vcgSup port.setGr oupId(vcgV eteran.get GroupId()) ;
  3250  
  3251                             CaretL ocalServic eUtil.save (vcgSuppor t);
  3252                             vcgSup port.setNo te("vcgCre ateNote",  ParamUtil. get(reques t, "vetera nPerson_co mments", " Created a  VCG Record "),
  3253                                               sc.getUser Id(), sc.g etCreateDa te(), Note Support.No teGroup.CR EATE_VCG.g roupId());
  3254                             CaretL ocalServic eUtil.save (vcgSuppor t);
  3255  
  3256                             Note n ote = vcgS upport.get Note("vcgC reateNote" );
  3257                             long w orImId = P aramUtil.g etLong(req uest, "wor ImId");
  3258                             if ( w orImId > 0  ){
  3259                                      try {
  3260                                               WorkItemSu pport work Item = new  WorkItemS upport ( W orImLocalS erviceUtil .getWorIm( worImId) ) ;
  3261                                               workItem.u seNote("vc gCreateNot e", note);
  3262                                               workItem.s etVcgId( v cgSupport. getVcgId()  );
  3263                                               CaretLocal ServiceUti l.save(wor kItem);
  3264                                      } catch  (PortalExc eption e)  {
  3265                                               throw new  Applicatio nWorkFlowE xception() ;
  3266                                      } catch  (SystemExc eption e)  {
  3267                                               throw new  Applicatio nWorkFlowE xception() ;
  3268                                      }
  3269                             }
  3270                             vcg =  vcgSupport ;
  3271                    }
  3272                    
  3273                    if (  vcg != nu ll ){
  3274                             reques t.setAttri bute(Caret StrPool.VC GID, vcg.g etVcgId()  );
  3275                    }
  3276                    load VcgManagem ent (reque st, respon se);
  3277                    requ est.setAtt ribute( Ca retStrPool .MVC_PATH,  CaretStrP ool.VCG_MA NAGEMENT_P AGE );
  3278           }
  3279           
  3280   //      pr ivate bool ean isVali d( Portlet Request re quest, Str ing addres s, String  city, Stri ng state,  String zip  ) {
  3281   //               Port letSession  session =  request.g etPortletS ession();
  3282   //               Stri ngBuilder  sb = new S tringBuild er().appen d(address) .append( c ity ).appe nd( state  ).append(  zip );
  3283   //               Bool ean valid  = (Boolean )session.g etAttribut e( sb.toSt ring() );
  3284   //               if (  valid ==  null ){
  3285   //                        valid  = CaretUti l.isValida teUspsAddr ess(addres s, city, s tate, zip  );
  3286   //                        sessio n.setAttri bute( sb.t oString()  , valid );
  3287   //               }
  3288   //               retu rn valid;
  3289   //      }
  3290  
  3291  
  3292           pu blic void  associateW orkItem (  long assoc iateId, lo ng vcgId,  PortletReq uest reque st ) throw s Applicat ionWorkFlo wException {
  3293                    if (  associate Id > 0 ){
  3294                             try {
  3295                                      ServiceC ontext sc  = CaretPar am.setCare tServiceCo ntext(requ est);
  3296                                      WorkItem Support as sociateWor Im = new W orkItemSup port ( Wor ImLocalSer viceUtil.g etWorIm(as sociateId)  );
  3297                                      String s ummary = n ull;
  3298                                      if ( Wor kType.CALL _REFERRAL. equals( as sociateWor Im.getWork Type() ) )  {
  3299                                               summary =  "<a href=\ "javascrip t:callview (this,'";
  3300                                               summary +=  CallLocal ServiceUti l.getCall(  associate WorIm.getC lassPk() ) .getCallId ();
  3301                                               summary +=  "');\">vi ew</a>";
  3302                                               summary +=  "&nbsp;";
  3303                                               summary =  summary +=  CallLocal ServiceUti l.getCall(  associate WorIm.getC lassPk() ) .getSummar y();
  3304                                               int len =  summary.le ngth() > 7 5 ? 75 : s ummary.len gth();
  3305                                               summary =  summary.su bstring(0, len);
  3306                                      }
  3307                                      //
  3308                                      associat eWorIm.set VcgId(vcgI d); 
  3309                                      String c omment = " Associated  " + assoc iateWorIm. getType()  + " to VCG . ";
  3310                                      if ( !To olbox.isEm pty(summar y) ){
  3311                                               associateW orIm.setNo te("callSu mmary", su mmary, sc. getUserId( ), sc.getC reateDate( ), NoteSup port.NoteG roup.CALL_ NOTE.group Id() );
  3312                                               associateW orIm.setNo te("associ atedNote",  comment,  sc.getUser Id(), sc.g etCreateDa te(), Note Support.No teGroup.AS SOCIATE_NO TE.groupId () );
  3313                                      } else {
  3314                                               associateW orIm.setNo te("associ atedNote",  comment,  sc.getUser Id(), sc.g etCreateDa te(), Note Support.No teGroup.AS SOCIATE_NO TE.groupId () );
  3315                                      }
  3316                                      if ( Car etStrPool. NEW.equals ( associat eWorIm.get Status() )  ){
  3317                                               associateW orIm.setSt atus( Care tStrPool.I N_PROCESS  );
  3318                                      }
  3319                                      CaretLoc alServiceU til.save(a ssociateWo rIm);
  3320                                      Note not e = associ ateWorIm.g etNote( "a ssociatedN ote" );
  3321                                      
  3322                                      VcgSuppo rt vcgSupp ort = VcgS upport.get VcgSupport (vcgId);
  3323                                      vcgSuppo rt.useNote ("workItem Associate" , note );
  3324                                      CaretLoc alServiceU til.save(  vcgSupport  );
  3325                                      
  3326                                      List<Lon g> noteIds  = new Arr ayList<Lon g>();
  3327                                      if (note  != null)  {
  3328                                               if (!noteI ds.contain s(note.get NoteId()))  {
  3329                                                       no teIds.add( note.getNo teId());
  3330                                               }
  3331                                      } else {
  3332                                               _log.info( "associate WorkItem.. ..current  note is nu ll ");
  3333                                      }
  3334                                      List<Not e> notes =  NoteLocal ServiceUti l.findByCh ainId(asso ciateWorIm .getClassP k());
  3335                                      for (Not e noteIter  : notes)  {
  3336                                               if (!noteI ds.contain s(noteIter .getNoteId ())) {
  3337                                                       no teIds.add( noteIter.g etNoteId() );
  3338                                               }
  3339                                      }
  3340                                      notes =  NoteLocalS erviceUtil .findByCha inId(vcgSu pport.getV cgId());
  3341                                      for (Not e noteIter  : notes)  {
  3342                                               if (!noteI ds.contain s(noteIter .getNoteId ())) {
  3343                                                       no teIds.add( noteIter.g etNoteId() );
  3344                                               }
  3345                                      }
  3346                                      for (Lon g longIter  : noteIds ) {
  3347                                               Note noteI ter = Note LocalServi ceUtil.fet chNote(lon gIter.long Value());
  3348                                               noteIter.s etVcgId(vc gId);
  3349                                               NoteLocalS erviceUtil .updateNot e(noteIter );
  3350                                      } 
  3351  
  3352                                      
  3353                             } catc h (PortalE xception e ) {
  3354                                      throw ne w Applicat ionWorkFlo wException ();
  3355                             } catc h (SystemE xception e ) {
  3356                                      throw ne w Applicat ionWorkFlo wException ();
  3357                             }
  3358                    }
  3359           }
  3360           
  3361           pu blic void  saveVcgAn  ( ActionRe quest acti onRequest  ){
  3362                    _log .info("sav eVcgAn..."  );
  3363                    getO utput(acti onRequest) ;
  3364                    
  3365                    try  {
  3366                             
  3367                             VcgApp lication v cgApplicat ion = new  VcgApplica tion( new  VcgAnImpl( ) );
  3368                             CaretP aram.loadM odel(actio nRequest,  vcgApplica tion, vcgA pplication .getModelA ttributes( ).keySet() , CaretStr Pool.VCGAN _UNDERLINE );
  3369                                                       
  3370                             //crea te new per son record s in db fo r veteran  and caregi vers
  3371                             Servic eContext s c = CaretP aram.setCa retService Context(ac tionReques t);
  3372                             vcgApp lication.s etCreation Date(sc.ge tCreateDat e());
  3373                             
  3374                             long c aregiverId  = 0;
  3375  
  3376                             String  veteranFi rstName =  ParamUtil. get(action Request, " veteranPer sn_firstNa me", "");
  3377                             if(!ve teranFirst Name.equal s("")){                         
  3378                                      Veteran  veteran =  new Vetera n( new Per snImpl() ) ;
  3379                                      CaretPar am.loadMod el(actionR equest, ve teran, vet eran.getMo delAttribu tes().keyS et(), Care tStrPool.V ETERAN_PER SN  + Stri ngPool.UND ERLINE);
  3380                                      if( "fal se".equals (veteran.g etCountry( )) || "USA ".equals(v eteran.get Country())  ){ //usa  address
  3381                                               CaretParam .loadModel (actionReq uest, vete ran, Toolb ox.getAddr essCollect ion(), Car etStrPool. VETERAN_PE RSN + "u_"  );
  3382                                               if ( Portl etProps.ge t("csc.req uired.vete ran.input" ).contains ("uspsVali dation") & & veteran. isComplete DomesticAd dress() &&  !veteran. isForeigne r() ){
  3383                                                       ve teran.setV alidAddres s(veteran. isValidUsp sAddress() );
  3384                                               }
  3385                                      }else if (!"false". equals(vet eran.getCo untry())){ //foreign  address
  3386                                               CaretParam .loadModel (actionReq uest, vete ran, Toolb ox.getAddr essCollect ion(), Car etStrPool. VETERAN_PE RSN + "g_"  );                                                                                       
  3387                                      }       
  3388                                      veteran. setVaHealt hEnrolled(  vcgApplic ation.getV aHealthEnr olled() );
  3389                                      CaretLoc alServiceU til.save(  veteran );
  3390                                      vcgAppli cation.set VeteranId( veteran.ge tPersnId() );
  3391                             }
  3392                             
  3393                             String  primaryFi rstName =  ParamUtil. get(action Request, " primaryPer sn_firstNa me", "");
  3394                             if(!pr imaryFirst Name.equal s("")){                         
  3395                                      Primary  primary =  new Primar y ( new Pe rsnImpl()  );
  3396                                      CaretPar am.loadMod el(actionR equest, pr imary, pri mary.getMo delAttribu tes().keyS et(), Care tStrPool.P RIMARY_PER SN  + Stri ngPool.UND ERLINE);
  3397                                      if( "fal se".equals (primary.g etCountry( )) || "USA ".equals(p rimary.get Country())  ){ //usa  address
  3398                                               CaretParam .loadModel (actionReq uest, prim ary, Toolb ox.getAddr essCollect ion(), Car etStrPool. PRIMARY_PE RSN + "u_"  );
  3399                                               if ( Portl etProps.ge t("csc.req uired.prim ary.input" ).contains ("uspsVali dation") & & primary. isComplete DomesticAd dress() &&  !primary. isForeigne r() ){
  3400                                                       pr imary.setV alidAddres s(primary. isValidUsp sAddress() );
  3401                                               }
  3402                                      } else i f (!"false ".equals(p rimary.get Country()) ){
  3403                                               CaretParam .loadModel (actionReq uest, prim ary, Toolb ox.getAddr essCollect ion(), Car etStrPool. PRIMARY_PE RSN + "g_"  );                                           
  3404                                      }
  3405                                      primary. setOtherIn sChecked(P aramUtil.g etBoolean( actionRequ est, "prim aryPersn_o therHealth InsuranceY esNo"));
  3406                                      primary. setMediEnr olled(vcgA pplication .getMediEn rolled());
  3407                                      CaretLoc alServiceU til.save(  primary );
  3408                                      vcgAppli cation.set PrimaryId( primary.ge tPersnId() );
  3409                                      caregive rId = prim ary.getPer snId();
  3410                             }
  3411                             
  3412                             String  secondary FirstName  = ParamUti l.get(acti onRequest,  "secondar yPersn_fir stName", " ");
  3413                             if(!se condaryFir stName.equ als("")){                       
  3414                                      Person s econdary =  new Perso n ( new Pe rsnImpl()  );
  3415                                      CaretPar am.loadMod el(actionR equest, se condary, s econdary.g etModelAtt ributes(). keySet(),  CaretStrPo ol.SECONDA RY_PERSN   + StringPo ol.UNDERLI NE);
  3416                                      if( "fal se".equals (secondary .getCountr y()) || "U SA".equals (secondary .getCountr y()) ){ // usa addres s
  3417                                               CaretParam .loadModel (actionReq uest, seco ndary, Too lbox.getAd dressColle ction(), C aretStrPoo l.SECONDAR Y_PERSN +  "u_" );
  3418                                               if ( Portl etProps.ge t("csc.req uired.seco ndary.inpu t").contai ns("uspsVa lidation")  && second ary.isComp leteDomest icAddress( ) && !seco ndary.isFo reigner()  ){
  3419                                                       se condary.se tValidAddr ess(second ary.isVali dUspsAddre ss());
  3420                                               }
  3421                                      }else if (!"false". equals(sec ondary.get Country())  ){
  3422                                               CaretParam .loadModel (actionReq uest, seco ndary, Too lbox.getAd dressColle ction(), C aretStrPoo l.SECONDAR Y_PERSN +  "g_" );                                       
  3423                                      }
  3424                                      CaretLoc alServiceU til.save(  secondary  );
  3425                                      vcgAppli cation.set SecondaryI d(secondar y.getPersn Id());
  3426                                      if ( car egiverId = = 0 ){
  3427                                               caregiverI d = second ary.getPer snId();
  3428                                      }
  3429                             }
  3430  
  3431                             String  secondary TwoFirstNa me = Param Util.get(a ctionReque st, "secon daryTwoPer sn_firstNa me", "");
  3432                             if(!se condaryTwo FirstName. equals("") ){                   
  3433                                      Person s econdaryTw o = new Pe rson ( new  PersnImpl () );
  3434                                      CaretPar am.loadMod el(actionR equest, se condaryTwo , secondar yTwo.getMo delAttribu tes().keyS et(), Care tStrPool.S ECONDARY_T WO_PERSN   + StringPo ol.UNDERLI NE);
  3435                                      if( "fal se".equals (secondary Two.getCou ntry())  | | "USA".eq uals(secon daryTwo.ge tCountry() ) ){ //usa  address
  3436                                               CaretParam .loadModel (actionReq uest, seco ndaryTwo,  Toolbox.ge tAddressCo llection() , CaretStr Pool.SECON DARY_TWO_P ERSN + "u_ " );
  3437                                               if ( Portl etProps.ge t("csc.req uired.seco ndaryTwo.i nput").con tains("usp sValidatio n") && sec ondaryTwo. isComplete DomesticAd dress() &&  !secondar yTwo.isFor eigner() ) {
  3438                                                       se condaryTwo .setValidA ddress(sec ondaryTwo. isValidUsp sAddress() );
  3439                                               }
  3440                                      }else if (!"false". equals(sec ondaryTwo. getCountry ()) ){
  3441                                               CaretParam .loadModel (actionReq uest, seco ndaryTwo,  Toolbox.ge tAddressCo llection() , CaretStr Pool.SECON DARY_TWO_P ERSN + "g_ " );
  3442                                      }
  3443                                      CaretLoc alServiceU til.save(  secondaryT wo );
  3444                                      vcgAppli cation.set SecondaryT woId(secon daryTwo.ge tPersnId() );
  3445                                      if ( car egiverId = = 0 ){
  3446                                               caregiverI d = second aryTwo.get PersnId();
  3447                                      }
  3448                             }
  3449  
  3450                             boolea n foreignC ountry = P aramUtil.g etBoolean( actionRequ est, "vete ranPersn_c ountry");
  3451                             String  groupId =  "";
  3452                             if(for eignCountr y){
  3453                                      groupId  = ParamUti l.get(acti onRequest,  "veteranP ersng_grou pId", "");
  3454                             }else{
  3455                                      groupId  = ParamUti l.get(acti onRequest,  "veteranP ersn_group Id", "");
  3456                             }
  3457                             if(!gr oupId.equa ls("")){vc gApplicati on.setGrou pId(Long.p arseLong(g roupId));}
  3458  
  3459                             CaretL ocalServic eUtil.save ( vcgAppli cation );
  3460                             
  3461                                                       
  3462                             long d ocumId = P aramUtil.g etLong(act ionRequest , "REFERRA L_1010");
  3463                             if ( d ocumId > 0  ){
  3464                                      try {
  3465                                               Docum docu m = DocumL ocalServic eUtil.getD ocum(docum Id);
  3466                                               Docum copy  = DocumLo calService Util.creat eDocum( Co unterLocal ServiceUti l.incremen t( Docum.c lass.getNa me() ) );
  3467                                               copy.setDo cument(doc um.getDocu ment());
  3468                                               copy.setCl assPk(vcgA pplication .getVcgAnI d());
  3469                                               copy.setCl assId(Port alUtil.get ClassNameI d(VcgAn.cl ass));
  3470                                               copy.setNo te("Loaded  from Refe ral");
  3471                                               copy.setNa me(docum.g etName());
  3472                                               copy.setTy pe(FileTyp e.CSC_1010 .name());
  3473                                               DocumLocal ServiceUti l.addDocum ( copy );
  3474                                      } catch  (PortalExc eption e)  {
  3475                                               e.printSta ckTrace();
  3476                                      }
  3477                             } else  {
  3478                                      String t racker = P aramUtil.g etString(a ctionReque st, CaretS trPool.TRA CKER, Stri ngPool.BLA NK );
  3479                                      List<Doc um> docume nts = Docu mLocalServ iceUtil.ge tByTracker Note( trac ker );
  3480                                      for ( Do cum docum  : document s ){
  3481                                               if ( docum .getClassP k() == 0 ) {
  3482                                                       do cum.setCla ssPk(vcgAp plication. getVcgAnId ());
  3483                                                       do cum.setCla ssId(Porta lUtil.getC lassNameId (VcgAn.cla ss));
  3484                                                       do cum.setNot e(StringPo ol.BLANK);
  3485                                                       Do cumLocalSe rviceUtil. updateDocu m(docum);
  3486                                               }
  3487                                      }
  3488                             }
  3489                             WorkIt emSupport  work = new  WorkItemS upport( Ca retUtil.cr eateWorkIt em( sc, vc gApplicati on.getGrou pId(), vcg Applicatio n, WorkTyp e.CSC_APP,  vcgApplic ation.getV eteranId() , caregive rId ) );
  3490                             CaretL ocalServic eUtil.save ( work );
  3491                             work.s etNote("cs cNewApp",  actionRequ est.getPar ameter("vc gAn_commen ts"), sc.g etUserId() , sc.getCr eateDate() , NoteSupp ort.NoteGr oup.CSC_AP P.groupId( )  );
  3492                             CaretL ocalServic eUtil.save ( work );
  3493                             
  3494                    } ca tch (Syste mException  e1) {
  3495                             Applic ationWorkF lowExcepti on.handleE xception(e 1);
  3496                    } ca tch (Appli cationWork FlowExcept ion e) {
  3497                             Applic ationWorkF lowExcepti on.handleE xception(e );
  3498                    } 
  3499           }
  3500           
  3501   //      pu blic void  handleAppl icationDoc ument ( Po rtletReque st request , Attachme ntBean att achment) t hrows File NotFoundEx ception, S ystemExcep tion {
  3502   //               
  3503   //               //Fi le uploadF ile = new  File(path) ;
  3504   //               File  uploadFil e = new Fi le(attachm ent.getPat h());
  3505   //               Inpu tStream in putStream  = new File InputStrea m( uploadF ile );
  3506   //               Outp utBlob out putBlob =  new Output Blob ( inp utStream,  uploadFile .length()  );
  3507   //               
  3508   //               long  documId =  CounterLo calService Util.incre ment( Docu m.class.ge tName() );
  3509   //               Docu m document  = DocumLo calService Util.creat eDocum(doc umId);
  3510   //               docu ment.setDo cument(out putBlob);
  3511   //               docu ment.setDe leted(fals e);
  3512   //               //do cument.set ClassPk( v cgApplicat ion.getVcg AnId() );
  3513   //               //do cument.set ClassId( P ortalUtil. getClassNa meId(VcgAn .class) );
  3514   //               docu ment.setCl assPk( att achment.ge tClassPk()  );
  3515   //               docu ment.setCl assId( att achment.ge tClassId()  );
  3516   //               docu ment.setTy pe(attachm ent.getTyp e());
  3517   //               docu ment.setNa me(attachm ent.getNam e());
  3518   //               try  {
  3519   //                        DocumL ocalServic eUtil.addD ocum( docu ment );
  3520   //                        reques t.getPortl etSession( ).removeAt tribute(Ca retStrPool .FILE_NAME );
  3521   //                        FileUt il.delete( uploadFile );
  3522   //               }
  3523   //               catc h (Excepti on e) {
  3524   //                        Applic ationWorkF lowExcepti on.handleE xception(e );
  3525   //               }
  3526   //      }
  3527           @P rocessActi on (name=" searchEntr y")
  3528           pu blic void  searchEntr y( ActionR equest act ionRequest , ActionRe sponse act ionRespons e ) {
  3529                    sear chEntry(ac tionReques t);
  3530           }
  3531  
  3532           pu blic void  loadCallTy pe(Portlet Request re quest) thr ows Applic ationWorkF lowExcepti on {
  3533                    
  3534                    Map< String,Obj ect> form  = ResultMa p.getForm  (request);
  3535                    
  3536                    Stri ng callTyp e = Portle tProps.get ("call.typ e");
  3537                    if (  !callType .isEmpty()  ){
  3538                             String [] array =  (callType  + StringP ool.COMMA  + "soc-cal l").split( StringPool .COMMA) ;
  3539                             List<S tring> c =  ListUtil. fromArray( array);
  3540                             Collec tions.sort (c);
  3541                             form.p ut( "stand ard-call-t ypes", c ) ;
  3542                    }
  3543                    form .put( Care tStrPool.C USTOM_CALL _TYPES, Bo xGpLocalSe rviceUtil. getBoxGrou ps(CaretSt rPool.CUST OM_CALL_TY PES) );
  3544                    Dash boardConfi gFactory.l oadInstanc e( request , null );
  3545           }
  3546           
  3547           pu blic void  loadCall(P ortletRequ est reques t) throws  Applicatio nWorkFlowE xception {
  3548                    requ est.setAtt ribute( Ca retStrPool .TRACKER,  CaretParam .trackNdx(  request )  );
  3549                    
  3550                    Stri ng service Status = P ortletProp s.get("vet eran.suppl emental.se rviceStatu ses");
  3551                    if (  !serviceS tatus.isEm pty() ){
  3552                             reques t.setAttri bute("serv iceStatus" , serviceS tatus.spli t(StringPo ol.COMMA)  );
  3553                    }
  3554  
  3555                    Map< String,Obj ect> form  = ResultMa p.getForm  (request);
  3556                    Map< String,Obj ect> caret  = ResultM ap.getCare tMap(reque st);
  3557                    
  3558                    Map< String,Int eger> tota l = Result Map.getRes ultTotalMa p( request  );
  3559                    Map< String,Lis t<?>> resu lts = Resu ltMap.getR esultListM ap( reques t );
  3560                    bool ean newIns tance = Ca retStrPool .NEW.equal s( request .getParame ter(CaretS trPool.STA TUS) ) ;
  3561                    
  3562                    long  veteranId  = 0;
  3563                    
  3564                    try  {
  3565                             long c allId = Pa ramUtil.ge tLong(requ est, Caret StrPool.CA LL_ID, 0 ) ;
  3566                             CaretV iewControl ler contro ller = Car etViewCont roller.get ViewContro ller();
  3567                             if ( c allId > 0  ){
  3568                                      //Call c all = Call LocalServi ceUtil.get Call( call Id );
  3569                                      CallSupp ort call =  new CallS upport(Cal lLocalServ iceUtil.ge tCall( cal lId ));
  3570                                      if ( new Instance )  {
  3571                                               call.setCa llId(0);
  3572                                               call.setWo rkPrimaryK ey(0);
  3573                                               call.setRe ferralAgre eable(fals e);
  3574                                               call.setCo ntactInfoP rovided(fa lse);
  3575                                      }
  3576                                      if (!Too lbox.isEmp ty(call.ge tCallbackP ref())) {
  3577                                               call.setCa llbackPref (
  3578                                                                SocC achedRepor tUtil.getC allbackPre f_12HourFo rmat(call. getCallbac kPref())
  3579                                               );
  3580                                      }
  3581                                      form.put ( "call",  call );
  3582                                      request. setAttribu te("transf erRemarks_ ", call.ge tTransferR emarks_asS tring());
  3583                                      request. setAttribu te("summar y_", call. getSummary _asString( ));   
  3584                                      request. setAttribu te("messag e_", call. getMessage _asString( ));                     
  3585                                      
  3586                                      Person c aller = ne w Person(P ersnLocalS erviceUtil .getPersn(  call.getC allerPersn Id() ));
  3587                                      form.put (CaretStrP ool.CALLER _PERSN, ca ller );
  3588                                      controll er.loadAdd ress( care t, caller,  CaretStrP ool.CALLER _PERSN );
  3589                                      
  3590                                      if ( !ne wInstance  ){
  3591                                               //Start SO C
  3592                                               String cal lerName =  caller.get FirstName( ) +" "+cal ler.getLas tName();
  3593                                               form.put(" callerName ", callerN ame);
  3594           
  3595                                               loadSocAsp ects(reque st, form,  call, call Id);
  3596                                               //End SOC
  3597                                              
  3598                                               //Start CE SP
  3599                                               loadCespAs pects(requ est, form,  call, cal lId);
  3600                                               //End CESP
  3601                                      }
  3602                                      
  3603                                      veteranI d = call.g etVeteranP ersnId();
  3604                                      Person p erson = ne w Person(  PersnLocal ServiceUti l.getPersn ( veteranI d ) );
  3605                                      form.put (CaretStrP ool.VETERA N_PERSN, p erson );
  3606                                      controll er.loadAdd ress( care t, person,  CaretStrP ool.VETERA N_PERSN );
  3607                             
  3608                                      //enable Soc is onl y set on r equests co ming from  SOCs Pendi ng Queue o r SOCs Pen ding Searc h
  3609                                      //boolea n enableSo c = !newIn stance &&  call.getCr eationDate ().before(  CaretPara m.getSocDu eDate() );
  3610                                      boolean  enableSoc  = false;
  3611                                      request. setAttribu te("enable Soc", enab leSoc );
  3612                                      //reques t.setAttri bute("expa nded", ena bleSoc? "c ollapsed":  "expanded " );
  3613                                      request. setAttribu te("expand ed", "expa nded");
  3614  
  3615                                      List<?>  l = CaretL ocalServic eUtil.getC allEvents(  callId );
  3616                                      results. put("callE vents", l) ;
  3617                                      total.pu t("callEve nts", l.si ze());
  3618  
  3619                                      request. setAttribu te("isDisa bled", cal l.getCallS tate() !=  null && ca ll.getCall State().to LowerCase( ).contains (CaretStrP ool.CALL_S TATE_COMPL ETE) );
  3620   //                                 request. setAttribu te("isDisa bled", cal l.getCallI d() > 0);
  3621                                      
  3622                                      if ( cal l.getWorkP rimaryKey( ) > 0 ){
  3623                                               WorIm work Item = Wor ImLocalSer viceUtil.g etWorIm( c all.getWor kPrimaryKe y() );
  3624                                               if (workIt em != null  && workIt em.getType ().equals( "CALL_REFE RRAL")) {
  3625                                                       re quest.setA ttribute(" worImId",  "");
  3626                                               }
  3627                                               else {
  3628                                                       fo rm.put("wo rkItem", w orkItem );
  3629                                                       if  ( workIte m != null  && ( workI tem.getUse rId() > 0  || workIte m.getCompl etionBy()  > 0 ) ){
  3630                                                                requ est.setAtt ribute("is Disabled",  true);
  3631                                                                if (  workItem. getStatus( ) != null  ){
  3632                                                                         if ( !  workItem. getStatus( ).toLowerC ase().cont ains("comp leted") ){
  3633                                                                                  request. setAttribu te("dispos itionCall" , CAction. canDoCaret (request,  CaretCan.D ISPOSITION _CALLS.nam e() ) );
  3634                                                                         }
  3635                                                                } el se {
  3636                                                                         reques t.setAttri bute("disp ositionCal l", CActio n.canDoCar et(request , CaretCan .DISPOSITI ON_CALLS.n ame() ) );
  3637                                                                }
  3638                                                       }
  3639                                               }
  3640                                      }
  3641                                      
  3642                                      if ( Str ingPool.TR UE.equals(  PortletPr ops.get("c sl-lead-on -open")) & & CAction. canDoCaret (request,  CaretCan.C SL_FUNCTIO N) ){
  3643                                               call.setUs erId( Care tParam.set CaretServi ceContext( request).g etUserId()  );
  3644                                               CaretLocal ServiceUti l.save(cal l);
  3645                                      }
  3646                                      //
  3647                    Date  d = null;
  3648                    if ( CallSuppor t.USE_CREA TIONDATE_F OR_START_D ATE) {
  3649                             d = ca ll.getCrea tionDate() ;
  3650                    }
  3651                    //tu rnCall.Sta rtDateOn// else {
  3652                    //tu rnCall.Sta rtDateOn//         d  = call.get StartDate( );
  3653                    //tu rnCall.Sta rtDateOn//   } 
  3654                    Date Format df  = new Simp leDateForm at(Toolbox .CARET_DAT ETIME_FORM AT_UI_FULL );
  3655                    Stri ng callSta rtDateDisp lay = df.f ormat(d);
  3656                    Stri ng[] parts  = callSta rtDateDisp lay.split( " ");
  3657                    Stri ng callSta rtDateZone  = parts[3 ];
  3658                    Stri ng callSta rtDateTime stamp = pa rts[0] + "  " + parts [1] + " "  + parts[2] ;
  3659                    requ est.setAtt ribute("ca llStartDat eDisplay",  callStart DateDispla y);
  3660                    requ est.setAtt ribute("ca llStartDat eZone", ca llStartDat eZone);
  3661                    requ est.setAtt ribute("ca llStartDat eTimestamp ", callSta rtDateTime stamp);
  3662                    Long  lng = cal l.getCallI d();
  3663                    requ est.setAtt ribute("ca llStartDat eCallId",  lng + "");
  3664                                      //                                 
  3665                             } else  {
  3666                                      request. setAttribu te("expand ed", "expa nded");
  3667                                      //reques t.setAttri bute("call StartDateC allId", nu ll);
  3668                    Date  d = new D ate();
  3669                    Date Format df  = new Simp leDateForm at(Toolbox .CARET_DAT ETIME_FORM AT_UI_FULL );
  3670                    Stri ng callSta rtDateDisp lay = df.f ormat(d);
  3671                    Stri ng[] parts  = callSta rtDateDisp lay.split( " ");
  3672                    Stri ng callSta rtDateZone  = parts[3 ];
  3673                    Stri ng callSta rtDateTime stamp = pa rts[0] + "  " + parts [1] + " "  + parts[2] ;
  3674                    requ est.setAtt ribute("ca llStartDat eDisplay",  callStart DateDispla y);
  3675                    requ est.setAtt ribute("ca llStartDat eZone", ca llStartDat eZone);
  3676                    requ est.setAtt ribute("ca llStartDat eTimestamp ", callSta rtDateTime stamp);
  3677                    Long  lng = new  Long(0l);
  3678                    requ est.setAtt ribute("ca llStartDat eCallId",  lng + "");
  3679                             }
  3680                             
  3681                             Result Map.getCar etMap(requ est).put(" noteContex t", CaretS trPool.CAL L);
  3682                             Result Map.getCar etMap(requ est).put(" genderType s", Portle tProps.get ("persn.ge nder.types ").split(S tringPool. COMMA) ) ;
  3683                             loadCa llSelects(  request ) ;
  3684                             loadMo reCallInfo  ( request  );
  3685   //                        loadMo reReferral Info ( req uest, vete ranId );
  3686                             loadSt atesAndFac ilities( r equest );
  3687                             contro ller.loadR equiredInp uts( Caret StrPool.CA LL, form ) ;
  3688                             
  3689                             reques t.setAttri bute(Caret StrPool.RO LE, ((Dash boardConfi g)request. getPortlet Session(). getAttribu te(CaretSt rPool.DASH BOARD_CONF IG)).getRo le() );
  3690                    } ca tch (Excep tion e) {
  3691                             Applic ationWorkF lowExcepti on.handleE xception(e );
  3692                    }
  3693                    
  3694           }
  3695           pu blic void  loadNewCal lUseExisti ngIdentiti es(Portlet Request re quest) thr ows Applic ationWorkF lowExcepti on {
  3696                    Map< String,Obj ect> form  = ResultMa p.getForm  (request);
  3697                    Call  callExist ingIdentit y = null;
  3698                    long  callIdExi stingIdent ity = 0;
  3699                    Obje ct callIdO 2 = null;
  3700                    try  {
  3701                             callId O2 = reque st.getPara meter("sel ectedExist ingCallId" );
  3702                             //
  3703                             if (ca llIdO2 !=  null && ca llIdO2 ins tanceof St ring) {cal lIdExistin gIdentity  = Long.par seLong((St ring) call IdO2);}
  3704                             else i f (callIdO 2 != null  && callIdO 2 instance of Integer ) {callIdE xistingIde ntity = ne w Long(cal lIdO2 + "" );}
  3705                             else i f (callIdO 2 != null  && callIdO 2 instance of Long) { callIdExis tingIdenti ty = ((Lon g) callIdO 2).longVal ue();}
  3706                             if ( c allIdExist ingIdentit y > 0 ){
  3707                                      callExis tingIdenti ty = CallL ocalServic eUtil.getC all( callI dExistingI dentity );
  3708                             }
  3709                    }
  3710                    catc h( Excepti on e) {
  3711                             Applic ationWorkF lowExcepti on.handleE xception(e );
  3712                    }  
  3713                    requ est.setAtt ribute( Ca retStrPool .TRACKER,  CaretParam .trackNdx(  request )  );
  3714                    Stri ng service Status = P ortletProp s.get("vet eran.suppl emental.se rviceStatu ses");
  3715                    if (  !serviceS tatus.isEm pty() ){
  3716                             reques t.setAttri bute("serv iceStatus" , serviceS tatus.spli t(StringPo ol.COMMA)  );
  3717                    }
  3718                    Map< String,Obj ect> caret  = ResultM ap.getCare tMap(reque st);
  3719                    
  3720                    Map< String,Int eger> tota l = Result Map.getRes ultTotalMa p( request  );
  3721                    Map< String,Lis t<?>> resu lts = Resu ltMap.getR esultListM ap( reques t );
  3722                    bool ean newIns tance = tr ue;
  3723                    
  3724                    long  veteranId  = 0;
  3725                    
  3726                    try  {
  3727                             long c allId = Pa ramUtil.ge tLong(requ est, Caret StrPool.CA LL_ID, 0 ) ;
  3728                             CaretV iewControl ler contro ller = Car etViewCont roller.get ViewContro ller();
  3729                             if ( c allIdExist ingIdentit y > 0){
  3730                                      Person c aller = ne w Person(P ersnLocalS erviceUtil .getPersn(  callExist ingIdentit y.getCalle rPersnId()  ));
  3731                                      form.put (CaretStrP ool.CALLER _PERSN, ca ller );
  3732                                      controll er.loadAdd ress( care t, caller,  CaretStrP ool.CALLER _PERSN );
  3733                                      String c allerName  = caller.g etFirstNam e() + " "  + caller.g etLastName ();
  3734                                      form.put ("callerNa me", calle rName);
  3735                                      veteranI d = callEx istingIden tity.getVe teranPersn Id();
  3736                                      Person p erson = ne w Person(  PersnLocal ServiceUti l.getPersn ( veteranI d ) );
  3737                                      form.put (CaretStrP ool.VETERA N_PERSN, p erson );
  3738                                      controll er.loadAdd ress( care t, person,  CaretStrP ool.VETERA N_PERSN );
  3739                                      //enable Soc is onl y set on r equests co ming from  SOCs Pendi ng Queue o r SOCs Pen ding Searc h
  3740                                      request. setAttribu te("enable Soc", fals e );
  3741                                      request. setAttribu te("expand ed", "expa nded");
  3742                                      request. setAttribu te("isDisa bled", tru e );
  3743                                      //if ( S tringPool. TRUE.equal s( Portlet Props.get( "csl-lead- on-open"))  && CActio n.canDoCar et(request , CaretCan .CSL_FUNCT ION) ){
  3744                                      //  call .setUserId ( CaretPar am.setCare tServiceCo ntext(requ est).getUs erId() );
  3745                                      //  Care tLocalServ iceUtil.sa ve(call);
  3746                                      //}
  3747                             } else  {
  3748                                      request. setAttribu te("expand ed", "expa nded");
  3749                             }
  3750                             Result Map.getCar etMap(requ est).put(" noteContex t", CaretS trPool.CAL L);
  3751                             Result Map.getCar etMap(requ est).put(" genderType s", Portle tProps.get ("persn.ge nder.types ").split(S tringPool. COMMA) ) ;
  3752                             loadCa llSelects(  request ) ;
  3753                             loadMo reCallInfo  ( request  );
  3754                             loadSt atesAndFac ilities( r equest );
  3755                             contro ller.loadR equiredInp uts( Caret StrPool.CA LL, form ) ;
  3756                             
  3757                             reques t.setAttri bute(Caret StrPool.RO LE, ((Dash boardConfi g)request. getPortlet Session(). getAttribu te(CaretSt rPool.DASH BOARD_CONF IG)).getRo le() );
  3758                    } ca tch (Excep tion e) {
  3759                             Applic ationWorkF lowExcepti on.handleE xception(e );
  3760                    }
  3761           }   
  3762           
  3763       public  void load ExistingCa ll(Portlet Request re quest) thr ows Applic ationWorkF lowExcepti on {
  3764           Ma p<String,O bject> for m = Result Map.getFor m (request );
  3765           Ca llSupport  call = nul l;
  3766           lo ng callId  = 0;
  3767           Ob ject callI dO = null;
  3768           tr y {
  3769                    call IdO = Tool box.getReg isteredVal ue(PortalU til.getUse rId(reques t) + "|" +  "selected CallId");
  3770                    
  3771                    if ( callIdO ==  null) {
  3772                             callId O = reques t.getParam eter("call Id");
  3773                    }
  3774                    _log .info(":::  caretActi onCommand. loadExisti ngCall 2.. ........ca llId0: " +  callIdO);
  3775                    
  3776                    if ( callIdO !=  null && c allIdO ins tanceof St ring) {cal lId = Long .parseLong ((String)  callIdO);}
  3777                    else  if (callI dO != null  && callId O instance of Integer ) {callId  = new Long (callIdO +  "");}
  3778                    else  if (callI dO != null  && callId O instance of Long) { callId = ( (Long) cal lIdO).long Value();}
  3779                    if (  callId >  0 ){
  3780                             call =  new CallS upport(Cal lLocalServ iceUtil.ge tCall( cal lId ));
  3781                    }
  3782           }
  3783           ca tch( Excep tion e) {
  3784                    Appl icationWor kFlowExcep tion.handl eException (e);
  3785           }   
  3786           re quest.setA ttribute(  CaretStrPo ol.TRACKER , CaretPar am.trackNd x( request  ) );
  3787           St ring servi ceStatus =  PortletPr ops.get("v eteran.sup plemental. serviceSta tuses");
  3788           if  ( !servic eStatus.is Empty() ){
  3789                    requ est.setAtt ribute("se rviceStatu s", servic eStatus.sp lit(String Pool.COMMA ) );
  3790           }
  3791           Ma p<String,O bject> car et = Resul tMap.getCa retMap(req uest);
  3792           Ma p<String,I nteger> to tal = Resu ltMap.getR esultTotal Map( reque st );
  3793           Ma p<String,L ist<?>> re sults = Re sultMap.ge tResultLis tMap( requ est );
  3794           bo olean newI nstance =  false;
  3795           lo ng veteran Id = 0;
  3796           tr y {
  3797                    Care tViewContr oller cont roller = C aretViewCo ntroller.g etViewCont roller();
  3798                    if (  callId >  0 ){
  3799                             form.p ut( "call" , call );
  3800                             reques t.setAttri bute("tran sferRemark s_", call. getTransfe rRemarks_a sString()) ;
  3801                             reques t.setAttri bute("summ ary_", cal l.getSumma ry_asStrin g());
  3802                             reques t.setAttri bute("mess age_", cal l.getMessa ge_asStrin g());
  3803  
  3804                             Person  caller =  new Person (PersnLoca lServiceUt il.getPers n( call.ge tCallerPer snId() ));
  3805                             form.p ut(CaretSt rPool.CALL ER_PERSN,  caller );
  3806                             contro ller.loadA ddress( ca ret, calle r, CaretSt rPool.CALL ER_PERSN ) ;
  3807                             if ( ! newInstanc e ){
  3808                                      //Start  SOC
  3809                                      String c allerName  = caller.g etFirstNam e() +" "+c aller.getL astName();
  3810                                      form.put ("callerNa me", calle rName);
  3811                                      loadSocA spects(req uest, form , call, ca llId);
  3812                                      //End SO C
  3813                                      
  3814                                      //Start  CESP
  3815                                      loadCesp Aspects(re quest, for m, call, c allId);
  3816                                      //End CE SP
  3817                             }
  3818                             vetera nId = call .getVetera nPersnId() ;
  3819                             Person  person =  new Person ( PersnLoc alServiceU til.getPer sn( vetera nId ) );
  3820                             form.p ut(CaretSt rPool.VETE RAN_PERSN,  person );
  3821                             contro ller.loadA ddress( ca ret, perso n, CaretSt rPool.VETE RAN_PERSN  );
  3822                             _log.i nfo("enabl eSoc: newI nstance =  " + newIns tance );
  3823                             //enab leSoc is o nly set on  requests  coming fro m SOCs Pen ding Queue  or SOCs P ending Sea rch
  3824                             //bool ean enable Soc = !new Instance & & call.get CreationDa te().befor e( CaretPa ram.getSoc DueDate()  );
  3825                             boolea n enableSo c = false;
  3826                             _log.i nfo("enabl eSoc = " +  enableSoc  );
  3827                             reques t.setAttri bute("enab leSoc", en ableSoc );
  3828                             reques t.setAttri bute("expa nded", "ex panded");
  3829                    
  3830                             List<? > l = Care tLocalServ iceUtil.ge tCallEvent s( callId  );
  3831                             result s.put("cal lEvents",  l);
  3832                             total. put("callE vents", l. size());
  3833                    
  3834                             reques t.setAttri bute("isDi sabled", c all.getCal lState() ! = null &&  call.getCa llState(). toLowerCas e().contai ns(CaretSt rPool.CALL _STATE_COM PLETE) );
  3835                             
  3836                             if ( c all.getWor kPrimaryKe y() > 0 ){
  3837                                      WorIm wo rkItem = W orImLocalS erviceUtil .getWorIm(  call.getW orkPrimary Key() );
  3838                                               if (workIt em != null  && workIt em.getType ().equals( "CALL_REFE RRAL")) {
  3839                                                       re quest.setA ttribute(" worImId",  "");
  3840                                               }
  3841                                               else {                             
  3842                                               form.put(" workItem",  workItem  );
  3843                                               if ( workI tem != nul l && ( wor kItem.getU serId() >  0 || workI tem.getCom pletionBy( ) > 0 ) ){
  3844                                                       re quest.setA ttribute(" isDisabled ", true);
  3845                                                       if  ( workIte m.getStatu s() != nul l ){
  3846                                                                if (  ! workIte m.getStatu s().toLowe rCase().co ntains("co mpleted")  ){
  3847                                                                         reques t.setAttri bute("disp ositionCal l", CActio n.canDoCar et(request , CaretCan .DISPOSITI ON_CALLS.n ame() ) );
  3848                                                                }
  3849                                                       }  else {
  3850                                                                requ est.setAtt ribute("di spositionC all", CAct ion.canDoC aret(reque st, CaretC an.DISPOSI TION_CALLS .name() )  );
  3851                                                       }
  3852                                               }
  3853                                               }
  3854                             }
  3855                             if ( S tringPool. TRUE.equal s( Portlet Props.get( "csl-lead- on-open"))  && CActio n.canDoCar et(request , CaretCan .CSL_FUNCT ION) ){
  3856                                      call.set UserId( Ca retParam.s etCaretSer viceContex t(request) .getUserId () );
  3857                                      CaretLoc alServiceU til.save(c all);
  3858                             }
  3859                    } el se {
  3860                             reques t.setAttri bute("expa nded", "ex panded");
  3861                    }
  3862                    
  3863                    Resu ltMap.getC aretMap(re quest).put ("noteCont ext", Care tStrPool.C ALL);
  3864                    Resu ltMap.getC aretMap(re quest).put ("genderTy pes", Port letProps.g et("persn. gender.typ es").split (StringPoo l.COMMA) )  ;
  3865                    load CallSelect s( request  );
  3866                    load MoreCallIn fo ( reque st );
  3867                    load StatesAndF acilities(  request ) ;
  3868                    cont roller.loa dRequiredI nputs( Car etStrPool. CALL, form  );
  3869                    
  3870                    requ est.setAtt ribute(Car etStrPool. ROLE, ((Da shboardCon fig)reques t.getPortl etSession( ).getAttri bute(Caret StrPool.DA SHBOARD_CO NFIG)).get Role() );
  3871           }  catch (Exc eption e)  {
  3872                    Appl icationWor kFlowExcep tion.handl eException (e);
  3873           }
  3874       }
  3875           pu blic void  loadCallFr omSocView( PortletReq uest reque st) throws  Applicati onWorkFlow Exception  {
  3876                    Map< String,Obj ect> form  = ResultMa p.getForm  (request);
  3877                    ClSo c clSoc =  null;
  3878                    Call Support ca ll = null;
  3879                    long  callId =  0;
  3880                    try  {
  3881                             String  viewSocRe turnUrl =  ParamUtil. getString( request, " viewSocRet urnUrl");
  3882                             long c lSocId = P aramUtil.g etLong(req uest, "soc Id", 0 );
  3883                             if ( c lSocId > 0  ){
  3884                                      clSoc =  ClSocLocal ServiceUti l.getClSoc (clSocId);
  3885                                      callId =  clSoc.get CallId();
  3886                                      if ( cal lId > 0 ){
  3887                                               call = new  CallSuppo rt(CallLoc alServiceU til.getCal l( callId  ));
  3888                                      };  
  3889                             }
  3890                    }
  3891                    catc h( Excepti on e) {
  3892                             Applic ationWorkF lowExcepti on.handleE xception(e );
  3893                    }  
  3894                    requ est.setAtt ribute( Ca retStrPool .TRACKER,  CaretParam .trackNdx(  request )  );
  3895                    Stri ng service Status = P ortletProp s.get("vet eran.suppl emental.se rviceStatu ses");
  3896                    if (  !serviceS tatus.isEm pty() ){
  3897                             reques t.setAttri bute("serv iceStatus" , serviceS tatus.spli t(StringPo ol.COMMA)  );
  3898                    }
  3899                    Map< String,Obj ect> caret  = ResultM ap.getCare tMap(reque st);
  3900                    Map< String,Int eger> tota l = Result Map.getRes ultTotalMa p( request  );
  3901                    Map< String,Lis t<?>> resu lts = Resu ltMap.getR esultListM ap( reques t );
  3902                    bool ean newIns tance = fa lse;
  3903                    long  veteranId  = 0;
  3904                    try  {
  3905                             CaretV iewControl ler contro ller = Car etViewCont roller.get ViewContro ller();
  3906                             if ( c allId > 0  ){
  3907                             form.p ut( "call" , call );
  3908                             reques t.setAttri bute("tran sferRemark s_", call. getTransfe rRemarks_a sString()) ;
  3909                             reques t.setAttri bute("summ ary_", cal l.getSumma ry_asStrin g());
  3910                             reques t.setAttri bute("mess age_", cal l.getMessa ge_asStrin g());
  3911  
  3912                             Person  caller =  new Person (PersnLoca lServiceUt il.getPers n( call.ge tCallerPer snId() ));
  3913                             form.p ut(CaretSt rPool.CALL ER_PERSN,  caller );
  3914                             contro ller.loadA ddress( ca ret, calle r, CaretSt rPool.CALL ER_PERSN ) ;
  3915                             if ( ! newInstanc e ){
  3916                                      //Start  SOC
  3917                                      String c allerName  = caller.g etFirstNam e() +" "+c aller.getL astName();
  3918                                      form.put ("callerNa me", calle rName);
  3919                                      loadSocA spects(req uest, form , call, ca llId);
  3920                                      //End SO C
  3921                                      //Start  CESP
  3922                                      loadCesp Aspects(re quest, for m, call, c allId);
  3923                                      //End CE SP
  3924                             }
  3925                             vetera nId = call .getVetera nPersnId() ;
  3926                             Person  person =  new Person ( PersnLoc alServiceU til.getPer sn( vetera nId ) );
  3927                             form.p ut(CaretSt rPool.VETE RAN_PERSN,  person );
  3928                             contro ller.loadA ddress( ca ret, perso n, CaretSt rPool.VETE RAN_PERSN  );
  3929                             _log.i nfo("enabl eSoc: newI nstance =  " + newIns tance );
  3930                             //enab leSoc is o nly set on  requests  coming fro m SOCs Pen ding Queue  or SOCs P ending Sea rch
  3931                             //bool ean enable Soc = !new Instance & & call.get CreationDa te().befor e( CaretPa ram.getSoc DueDate()  );
  3932                             boolea n enableSo c = false;
  3933                             _log.i nfo("enabl eSoc = " +  enableSoc  );
  3934                             reques t.setAttri bute("enab leSoc", en ableSoc );
  3935                             reques t.setAttri bute("expa nded", "ex panded");
  3936           
  3937                             List<? > l = Care tLocalServ iceUtil.ge tCallEvent s( callId  );
  3938                             result s.put("cal lEvents",  l);
  3939                             total. put("callE vents", l. size());
  3940           
  3941                             reques t.setAttri bute("isDi sabled", c all.getCal lState() ! = null &&  call.getCa llState(). toLowerCas e().contai ns(CaretSt rPool.CALL _STATE_COM PLETE) );
  3942                             if ( c all.getWor kPrimaryKe y() > 0 ){
  3943                                      WorIm wo rkItem = W orImLocalS erviceUtil .getWorIm(  call.getW orkPrimary Key() );
  3944                                      if (work Item != nu ll && work Item.getTy pe().equal s("CALL_RE FERRAL"))  {
  3945                                               request.se tAttribute ("worImId" , "");
  3946                                      }
  3947                                      else {                             
  3948                                               form.put(" workItem",  workItem  );
  3949                                               if ( workI tem != nul l && ( wor kItem.getU serId() >  0 || workI tem.getCom pletionBy( ) > 0 ) ){
  3950                                                       re quest.setA ttribute(" isDisabled ", true);
  3951                                                       if  ( workIte m.getStatu s() != nul l ){
  3952                                                                if (  ! workIte m.getStatu s().toLowe rCase().co ntains("co mpleted")  ){
  3953                                                                requ est.setAtt ribute("di spositionC all", CAct ion.canDoC aret(reque st, CaretC an.DISPOSI TION_CALLS .name() )  );
  3954                                                                }
  3955                                                       }  else {
  3956                                                       re quest.setA ttribute(" dispositio nCall", CA ction.canD oCaret(req uest, Care tCan.DISPO SITION_CAL LS.name()  ) );
  3957                                                       }
  3958                                               }
  3959                                      }
  3960                             }
  3961                             if ( S tringPool. TRUE.equal s( Portlet Props.get( "csl-lead- on-open"))  && CActio n.canDoCar et(request , CaretCan .CSL_FUNCT ION) ){
  3962                                      call.set UserId( Ca retParam.s etCaretSer viceContex t(request) .getUserId () );
  3963                                      CaretLoc alServiceU til.save(c all);
  3964                             }
  3965                             } else  {
  3966                                      request. setAttribu te("expand ed", "expa nded");
  3967                             }
  3968                             Result Map.getCar etMap(requ est).put(" noteContex t", CaretS trPool.CAL L);
  3969                             Result Map.getCar etMap(requ est).put(" genderType s", Portle tProps.get ("persn.ge nder.types ").split(S tringPool. COMMA) ) ;
  3970                             loadCa llSelects(  request ) ;
  3971                             loadMo reCallInfo  ( request  );
  3972                             loadSt atesAndFac ilities( r equest );
  3973                             contro ller.loadR equiredInp uts( Caret StrPool.CA LL, form ) ;
  3974                             reques t.setAttri bute(Caret StrPool.RO LE, ((Dash boardConfi g)request. getPortlet Session(). getAttribu te(CaretSt rPool.DASH BOARD_CONF IG)).getRo le() );
  3975                    } ca tch (Excep tion e) {
  3976                             Applic ationWorkF lowExcepti on.handleE xception(e );
  3977                    }
  3978           }   
  3979           pu blic void  loadCallAn dSoc(Portl etRequest  request) t hrows Appl icationWor kFlowExcep tion {
  3980                    Map< String,Obj ect> form  = ResultMa p.getForm  (request);
  3981                    ClSo c clSoc =  null;
  3982                    Call  call = nu ll;
  3983                    try  {
  3984                             String  viewSocRe turnUrl =  ParamUtil. getString( request, " viewSocRet urnUrl");
  3985                             long c lSocId = P aramUtil.g etLong(req uest, "soc Id", 0 );
  3986                             if ( c lSocId > 0  ){
  3987                                      clSoc =  ClSocLocal ServiceUti l.getClSoc (clSocId);
  3988                                      long cal lId = clSo c.getCallI d();
  3989                                      if ( cal lId > 0 ){
  3990                                               call = Cal lLocalServ iceUtil.ge tCall( cal lId );
  3991                                      }
  3992                                      loadSocV iewAspects (request,  form, call , clSoc);   
  3993                             }
  3994                    }
  3995                    catc h( Excepti on e) {
  3996                    Appl icationWor kFlowExcep tion.handl eException (e);
  3997                    }
  3998           }        
  3999           pu blic Strin g initiate Letter(Act ionRequest  request,  ActionResp onse respo nse) {
  4000                    
  4001                    if (  !CAction. canDoCaret (request,  CaretCan.I NITIATE_LE TTER.name( ) ) ) {
  4002                             _log.e rror("perm issioning. .. ");
  4003                             return  StringPoo l.BLANK;
  4004                    }
  4005                    
  4006                    Popu lateLetter sImpl popu lateLetter sImpl = ne w Populate LettersImp l();
  4007                    try  {
  4008                             Boolea n fromOcc  = ParamUti l.getBoole an(request , "fromOcc ");
  4009                             respon se.setRend erParamete r(CaretStr Pool.MVC_P ATH, Caret StrPool.LO AD_LETTER_ PAGE);
  4010                             long w orImId = P aramUtil.g etLong(req uest, Care tStrPool.W ORK_ID);
  4011                             long v cgId = Par amUtil.get Long( requ est, Caret StrPool.VC GID );
  4012                             if ( v cgId == 0  ) {
  4013                                      vcgId =  (Long) req uest.getAt tribute(Ca retStrPool .VCGID);
  4014                             }
  4015                             VcgAn  vcgAn =  V cgAnLocalS erviceUtil .getRecent (vcgId);
  4016                             Long v cgAnId = v cgAn.getVc gAnId();
  4017                             reques t.setAttri bute(Caret StrPool.WO RK_ID, wor ImId);
  4018                             reques t.setAttri bute(Caret StrPool.VC GID, vcgId );
  4019                             if (fr omOcc) {
  4020                                      OccLette rType[] oc cLetterTyp es = OccLe tterType.v alues();
  4021                                      Arrays.s ort(occLet terTypes,  new Compar ator<OccLe tterType>( ) {
  4022                                                public in t compare( OccLetterT ype s1, Oc cLetterTyp e s2) {
  4023                                                       re turn s1.to String().c ompareToIg noreCase(s 2.toString ());
  4024                                                   }
  4025                                      });
  4026                                      request. setAttribu te(CaretSt rPool.OCC_ LETTER_NAM ES, Arrays .asList(oc cLetterTyp es));
  4027                             } else  {
  4028                                      CscLette rType[] cs cLetterTyp es = CscLe tterType.v alues();
  4029                                      Arrays.s ort(cscLet terTypes,  new Compar ator<CscLe tterType>( ) {
  4030                                                public in t compare( CscLetterT ype s1, Cs cLetterTyp e s2) {
  4031                                                       re turn s1.to String().c ompareToIg noreCase(s 2.toString ());
  4032                                                   }
  4033                                      });
  4034                                      request. setAttribu te(CaretSt rPool.CSC_ LETTER_NAM ES, Arrays .asList(cs cLetterTyp es));
  4035                             }
  4036                             reques t.setAttri bute("reci pients", p opulateLet tersImpl.g etLetterRe cipients(r equest));
  4037                             reques t.setAttri bute("from Occ", from Occ);
  4038                    
  4039                             } catc h (Applica tionWorkFl owExceptio n e) {
  4040                             e.prin tStackTrac e();
  4041                    } ca tch (Porta lException  e) {
  4042                             // TOD O Auto-gen erated cat ch block
  4043                             e.prin tStackTrac e();
  4044                    } 
  4045                    
  4046                    retu rn StringP ool.BLANK;
  4047           }
  4048           
  4049           @P rocessActi on (name=" sendLetter ")
  4050           pu blic void  sendLetter ( ActionRe quest acti onRequest,  ActionRes ponse acti onResponse  ) throws  IOExceptio n {
  4051                    if (  !CAction. canDoCaret (actionReq uest, Care tCan.INITI ATE_LETTER .name() )  ) {
  4052                             _log.e rror("perm issioning. .. ");
  4053                             return ;
  4054                    }
  4055                String l etterName  = actionRe quest.getP arameter(C aretStrPoo l.SEND_LET TER_NAME);
  4056                Boolean  veteranRec ipient = P aramUtil.g etBoolean( actionRequ est, "vete ranRecipie nt");
  4057                    Bool ean primar yCGRecipie nt = Param Util.getBo olean(acti onRequest,  "primaryC GRecipient ");
  4058                Boolean  secondaryC GRecipient  = ParamUt il.getBool ean(action Request, " secondaryC GRecipient ");
  4059                Boolean  secondaryT woCGRecipi ent = Para mUtil.getB oolean(act ionRequest , "seconda ryTwoCGRec ipient");
  4060                Populate LettersImp l populate LettersImp l = new Po pulateLett ersImpl();
  4061                Boolean  fromOcc =  ParamUtil. getBoolean (actionReq uest, "fro mOcc");
  4062                    
  4063                populate LettersImp l.generate AndPopulat ePDFWithEd itedConten t(actionRe quest, let terName, f alse);
  4064                    //up date if ex isting pdf  or save i f new pdf
  4065                    if (  letterNam e != null  && !letter Name.isEmp ty() ) {
  4066                             try {
  4067                                      String t ype = from Occ?FileTy pe.OCC_Let ter.name() :FileType. CSC_Letter .name();
  4068                                      long vcg Id = Param Util.getLo ng( action Request, C aretStrPoo l.VCGID );
  4069                                      String r ecipients  = "";
  4070                                      VcgAn vc gAn;
  4071                                      vcgAn =  VcgAnLocal ServiceUti l.getRecen t(vcgId);
  4072                                      Long vcg AnId = vcg An.getVcgA nId();
  4073                                      
  4074                                      String n ote = "Let ter docume nt added";
  4075                                      Attachme ntBean att achment =  new Attach mentBean() ;
  4076                                      attachme nt.setClas sPk(vcgAnI d);
  4077                                      attachme nt.setClas sId(Portal Util.getCl assNameId( VcgAn.clas s));
  4078                                      attachme nt.setType (type);
  4079                                      attachme nt.setName (letterNam e);
  4080                                      Long doc umId = han dleLetters Document(  actionRequ est, attac hment, not e);
  4081                                      
  4082                                      Map<Stri ng, String > recepien tMap = pop ulateLette rsImpl.get LetterReci pients(act ionRequest );
  4083                                      Letter l etter = Le tterLocalS erviceUtil .createLet ter(Counte rLocalServ iceUtil.in crement(Le tter.class .getName() ));
  4084                                      letter.s etClassPk( vcgAnId);
  4085                                      letter.s etClassId( PortalUtil .getClassN ameId(VcgA n.class));
  4086                                      letter.s etName(let terName +  ".pdf");
  4087                                      letter.s etType(typ e);
  4088                                      letter.s etSentDate (new Date( ));
  4089                                      letter.s etDocumId( documId);
  4090                                      Boolean  first = tr ue;
  4091                                      if (vete ranRecipie nt) {
  4092                                               recipients  =  recepi entMap.get (CaretStrP ool.PERSON _CATEGORY_ VETERAN);
  4093                                               first = fa lse;
  4094                                      } if (pr imaryCGRec ipient) {
  4095                                               if (first  == false)  {
  4096                                                       re cipients =   recipien ts + ", ";
  4097                                               }
  4098                                               recipients  =  recipi ents + rec epientMap. get(CaretS trPool.PER SON_CATEGO RY_PRIMARY );
  4099                                               first = fa lse;
  4100                                      } if (se condaryCGR ecipient)  {
  4101                                               if (first  == false)  {
  4102                                                       re cipients =   recipien ts + ", ";
  4103                                               }
  4104                                               recipients  =  recipi ents + rec epientMap. get(CaretS trPool.PER SON_CATEGO RY_SECONDA RY);
  4105                                               first = fa lse;
  4106                                      } if (se condaryTwo CGRecipien t) {
  4107                                               if (first  == false)  {
  4108                                                       re cipients =   recipien ts + ", ";
  4109                                               }
  4110                                               recipients  =  recipi ents + rec epientMap. get(CaretS trPool.PER SON_CATEGO RY_SECONDA RYTWO);
  4111                                               first = fa lse;
  4112                                      } 
  4113                                      letter.s etRecepien ts(recipie nts);
  4114                                      LetterLo calService Util.addLe tter(lette r);
  4115                                      ServiceC ontext sc  = CaretPar am.setCare tServiceCo ntext(acti onRequest) ;
  4116                                      String c omment = " Letter sen t";
  4117                                      CaretLoc alServiceU til.addNot e(CaretUti l.createNo te(sc.getC reateDate( ), vcgId,
  4118                                                       No teSupport. NoteGroup. LETTER_NOT E.groupId( ), sc.getU serId(), c omment));
  4119                                      
  4120                                      
  4121                             } catc h (Applica tionWorkFl owExceptio n | System Exception  e) {
  4122                                      e.printS tackTrace( );
  4123                             }
  4124                    }
  4125                    init iateLetter (actionReq uest, acti onResponse );
  4126           }
  4127           
  4128           // Saves lett er documen t to DB
  4129           pu blic long  handleLett ersDocumen t( ActionR equest act ionRequest , Attachme ntBean att achment, S tring note ) {
  4130                    
  4131                    try  {
  4132                             Servic eContext s c = CaretP aram.setCa retService Context(ac tionReques t);
  4133                             String  name = (S tring) act ionRequest .getAttrib ute(CaretS trPool.LET TER_FILE);
  4134                             File u ploadFile  = new File ( PortletP rops.get(C aretStrPoo l.FILE_TEM P_STORE) +  name );
  4135                             InputS tream inpu tStream =  new FileIn putStream(  uploadFil e );
  4136                             Output Blob outpu tBlob = ne w OutputBl ob ( input Stream, up loadFile.l ength() );
  4137                             long d ocumId = C ounterLoca lServiceUt il.increme nt( Docum. class.getN ame() );
  4138                             Docum  document =  DocumLoca lServiceUt il.createD ocum(docum Id);
  4139                             docume nt.setDocu ment(outpu tBlob);
  4140                             docume nt.setDele ted(false) ;
  4141                             docume nt.setClas sPk( attac hment.getC lassPk() ) ;
  4142                             docume nt.setClas sId( attac hment.getC lassId() ) ;
  4143                             docume nt.setType (attachmen t.getType( ));
  4144                             docume nt.setName (name);
  4145                             docume nt.setNote (new Date( ).toString () + "," +  note);
  4146                             docume nt.setUser Id(sc.getU serId());
  4147                             DocumL ocalServic eUtil.addD ocum( docu ment );
  4148                             action Request.ge tPortletSe ssion().re moveAttrib ute(CaretS trPool.LET TER_FILE);
  4149                             FileUt il.delete( uploadFile );
  4150                             return  document. getDocumId ();
  4151                    } ca tch (Excep tion e) {
  4152                             Applic ationWorkF lowExcepti on.handleE xception(e );
  4153                    }
  4154                    retu rn 0;
  4155           }
  4156                    
  4157           pr ivate void  loadSocAs pects(Port letRequest  request,  Map<String ,Object> f orm, Call  call, long  callId) t hrows Port alExceptio n, SystemE xception {
  4158                    form .put("call Date", Too lbox.forma tDateCprs(  call.getC reationDat e() ) );
  4159                    long  loggedPer snId = Car etParam.ge tPersnId(r equest);
  4160                    Pers on loggedU ser = new  Person ( P ersnLocalS erviceUtil .getPersn(  loggedPer snId ) );
  4161                    form .put("logg edPersnId" , loggedPe rsnId );
  4162                    form .put("logg edUserName ", loggedU ser.getFir stName() + " "+ logge dUser.getL astName()  );
  4163                    List <ClSoc> so cList = Cl SocLocalSe rviceUtil. findByCall Id(callId) ;
  4164  
  4165                    //in t attemptN um = socLi st.size()+ 1;
  4166                    //fo rm.put("at temptNum",  attemptNu m);
  4167                    int  numOfSoc =  socList.s ize();
  4168                    form .put("numO fSoc", num OfSoc);
  4169                    if(n umOfSoc >  0){
  4170                             boolea n enableVi ewSoc = fa lse;
  4171                             _log.i nfo("enabl eViewSoc =  " + enabl eViewSoc ) ;
  4172                             reques t.setAttri bute("enab leViewSoc" , enableVi ewSoc );
  4173                             //
  4174                             List<M ap<String, String>> s ocHistory  = new Arra yList<Map< String,Str ing>>();
  4175                             Map<St ring,Strin g> map = n ull;
  4176                             //for( ClSoc oneS oc : socLi st){
  4177                                      ClSoc on eSoc = soc List.get(s ocList.siz e() - 1);
  4178                                      map = ne w HashMap< String,Str ing>();
  4179                                      map.put( "clSocId",  oneSoc.ge tClSocId()  + "");
  4180                                      map.put( "attempNum ", oneSoc. getAttempt Num());
  4181                                      map.put( "tresholdM et", oneSo c.getTresh oldMet());
  4182                                      map.put( "date", To olbox.form atDateTime Metadata(o neSoc.getC reationDat e()));
  4183                                      Person c reatedByPe rsn = new  Person ( P ersnLocalS erviceUtil .getPersn(  oneSoc.ge tPersnId()  ) );
  4184                                      String n ame = crea tedByPersn .getFirstN ame()+" "+ createdByP ersn.getLa stName();
  4185                                      map.put( "name", na me);
  4186                                      socHisto ry.add(map ); 
  4187                             //}
  4188                             form.p ut("soc-hi story", so cHistory);
  4189                    }  
  4190           }
  4191           
  4192           pr ivate void  loadSocVi ewAspects( PortletReq uest reque st, Map<St ring,Objec t> form, C all call,  ClSoc clSo c) throws  PortalExce ption, Sys temExcepti on {
  4193                    _log .info("MAc tion debug ....CaretA ctionComma nd.loadSoc ViewAspect s...start" );
  4194                    if ( request !=  null && f orm != nul l && call  != null &&  clSoc !=  null) {
  4195                    form .put("call Date", Too lbox.forma tDateCprs(  call.getC reationDat e() ) );
  4196                             long l oggedPersn Id = Caret Param.getP ersnId(req uest);
  4197                             Person  loggedUse r = new Pe rson ( Per snLocalSer viceUtil.g etPersn( l oggedPersn Id ) );
  4198                             form.p ut("logged PersnId",  loggedPers nId );
  4199                             form.p ut("logged UserName",  loggedUse r.getFirst Name() +"  "+ loggedU ser.getLas tName() );
  4200                             //  
  4201                             Map<St ring,Strin g> viewMap  = null;
  4202                             viewMa p = new Ha shMap<Stri ng,String> ();
  4203                             viewMa p.put("pri maryKey",c lSoc.getPr imaryKey()  + "");
  4204                             viewMa p.put("clS ocId",clSo c.getClSoc Id() + "") ;
  4205                             viewMa p.put("cal lId",clSoc .getCallId () + "");
  4206                             viewMa p.put("per snId",clSo c.getPersn Id() + "") ;
  4207                             viewMa p.put("sur veyStatus" ,clSoc.get SurveyStat us() + "") ;
  4208                             viewMa p.put("sur veyComment ",clSoc.ge tSurveyCom ment() + " ");
  4209                             viewMa p.put("cre ationDate" ,clSoc.get CreationDa te() + "") ;
  4210                             viewMa p.put("att emptNum",c lSoc.getAt temptNum()  + "");
  4211                             viewMa p.put("cal lerAvailab le",clSoc. getCallerA vailable()  + "");
  4212                             viewMa p.put("wil lingToAnsQ ues",clSoc .getWillin gToAnsQues () + "");
  4213                             viewMa p.put("cal ledCsl",cl Soc.getCal ledCsl() +  "");
  4214                             viewMa p.put("csl Knowledgab le",clSoc. getCslKnow ledgable()  + "");
  4215                             viewMa p.put("csl Supportive ",clSoc.ge tCslSuppor tive() + " ");
  4216                             viewMa p.put("loc alResSugge sted",clSo c.getLocal ResSuggest ed() + "") ;
  4217                             viewMa p.put("loc alResConta cted",clSo c.getLocal ResContact ed() + "") ;
  4218                             viewMa p.put("rsn LocalResNo tContacted ",clSoc.ge tRsnLocalR esNotConta cted() + " ");
  4219                             viewMa p.put("loc alResHelpf ul",clSoc. getLocalRe sHelpful()  + "");
  4220                             viewMa p.put("con cernsAnswe red",clSoc .getConcer nsAnswered () + "");
  4221                             viewMa p.put("und erstandNex tSteps",cl Soc.getUnd erstandNex tSteps() +  "");
  4222                             viewMa p.put("cal lCslAgain" ,clSoc.get CallCslAga in() + "") ;
  4223                             viewMa p.put("rec ommendCsl" ,clSoc.get RecommendC sl() + "") ;
  4224                             viewMa p.put("sug gestions", clSoc.getS uggestions () + "");
  4225                             viewMa p.put("fol lowupCall" ,clSoc.get FollowupCa ll() + "") ;
  4226                             viewMa p.put("com pleted",To olbox.from BoolToYesN o(clSoc.ge tCompleted ()));
  4227                             //view Map.put("r equestedCa llbackTime ",clSoc.ge tRequested CallbackTi me() + "") ;
  4228                             viewMa p.put("req uestedCall backTime",  clSoc.get FollowupCa llTime() +  " " + clS oc.getRequ estedCallb ackTime()) ;
  4229                             viewMa p.put("tre sholdMet", clSoc.getT resholdMet () + "");
  4230                             viewMa p.put("dat e", Toolbo x.formatDa teCprs(clS oc.getCrea tionDate() ));
  4231                             Person  cslPersn  = new Pers on ( Persn LocalServi ceUtil.get Persn( clS oc.getPers nId() ) );
  4232                             String  cslName =  cslPersn. getFirstNa me()+" "+  cslPersn.g etLastName ();
  4233                             viewMa p.put("csl Name", csl Name);
  4234                             Person  callerPer sn = new P erson( Per snLocalSer viceUtil.g etPersn(ca ll.getCall erPersnId( )));
  4235                             String  callerNam e = caller Persn.getF irstName()  + " " + c allerPersn .getLastNa me();
  4236                             String  callerPho ne = calle rPersn.get Phone() +  " " + call erPersn.ge tPhone2();
  4237                             viewMa p.put("cal lerName",  callerName );
  4238                             viewMa p.put("cal lerPhone",  callerPho ne);
  4239                             Person  veteranPe rsn = new  Person( Pe rsnLocalSe rviceUtil. getPersn(c all.getVet eranPersnI d()));
  4240                             String  veteranNa me = veter anPersn.ge tFirstName () + " " +  veteranPe rsn.getLas tName();
  4241                             String  veteranPh one = vete ranPersn.g etPhone()  + " " + ve teranPersn .getPhone2 ();
  4242                             viewMa p.put("vet eranName",  veteranNa me);
  4243                             viewMa p.put("vet eranPhone" , veteranP hone);
  4244                             //_log .info("MAc tion debug ....viewMa p: " + vie wMap.toStr ing());
  4245                             form.p ut("view-s oc",viewMa p);
  4246                    }
  4247           } 
  4248  
  4249           pr ivate void  loadCespA spects(Por tletReques t request,  Map<Strin g,Object>  form, Call  call, lon g callId)  throws Por talExcepti on, System Exception  {
  4250                    
  4251                    long  loggedPer snId = Car etParam.ge tPersnId(r equest);
  4252                    form .put("logg edPersnId" , loggedPe rsnId );
  4253  
  4254                    //ch eck if the re are any  cesp for  the call
  4255                    List <Cesp> ces pList = Ce spLocalSer viceUtil.f indByCallI d(callId);         
  4256                    int  numOfCesp  = cespList .size();
  4257                    form .put("numO fCesp", nu mOfCesp);
  4258                    
  4259                    Stri ng cespSta tus = Stri ngPool.BLA NK;
  4260  
  4261                    if(n umOfCesp >  0){
  4262                             form.p ut("step",  CaretStrP ool.CESP_S TEP2);
  4263                                       
  4264                             List<C espBean> c espHistory  = new Arr ayList<Ces pBean>();
  4265                             for(Ce sp oneCesp  : cespLis t){
  4266                                      Person c reatedByPe rsn = new  Person ( P ersnLocalS erviceUtil .getPersn(  oneCesp.g etCreatedB yPersnId()  ) );
  4267                                      String n ame = crea tedByPersn .getFirstN ame()+" "+ createdByP ersn.getLa stName();
  4268  
  4269                                      CespBean  oneBean =  new CespB ean();
  4270                                      oneBean. setCesp(on eCesp);
  4271                                      oneBean. setFormatt edCreatedD ate(Toolbo x.formatDa teTimeMeta data(oneCe sp.getCrea tionDate() ));
  4272                                      oneBean. setCespCre atedByName (name);
  4273                                      cespHist ory.add(on eBean);        
  4274                                      
  4275                                      if(oneCe sp.getStat us().equal s(CaretStr Pool.CESP_ STATUS_CLO SED)){
  4276                                               cespStatus  = "closed ";
  4277                                      }
  4278                             }
  4279                             form.p ut("cesp-h istory", c espHistory );
  4280                    }els e{
  4281                             form.p ut("step",  CaretStrP ool.CESP_S TEP1);
  4282                    }
  4283  
  4284                    form .put("cesp Status", c espStatus) ;
  4285           }
  4286           
  4287           
  4288           @P rocessActi on (name=" loadEntry" )
  4289           pu blic void  loadEntry(  ActionReq uest actio nRequest,  ActionResp onse actio nResponse  ) {
  4290                    Stri ng entry =  ParamUtil .get(actio nRequest,  "entry", S tringPool. BLANK);
  4291                    _log .info("loa dEntry..."  +  entry  );
  4292   //               acti onResponse .setRender Parameter( CaretStrPo ol.MVC_PAT H, "/jsp/i nternal/"+  action +  ".jsp" );
  4293   //               _log .info("act ion..." +   entry );
  4294                    try{
  4295                             if ( C aretStrPoo l.CREATE_R EFERRAL.eq uals(entry ) ){
  4296                                      if ( CAc tion.canDo Caret(acti onRequest,  CaretCan. CREATE_REF ERRAL.name () ) || CA ction.canD oCaret(act ionRequest , CaretCan .VIEW_FUNC TION ) ){
  4297                                               boolean is CallReferr al = loadR eferral(ac tionReques t);
  4298                                               if ( isCal lReferral  ){
  4299                                                       ac tionRespon se.setRend erParamete r(CaretStr Pool.MVC_P ATH, Caret StrPool.ED IT_CALL_PA GE);
  4300                                               } else {
  4301                                                       ac tionRespon se.setRend erParamete r(CaretStr Pool.MVC_P ATH, Caret StrPool.ED IT_REFERRA L_PAGE);
  4302                                               }
  4303                                      }
  4304                                      else if  ( CAction. canDoCaret (actionReq uest, Care tCan.VIEW_ REFERRAL.n ame() ) ){
  4305                                               boolean is CallReferr al = loadR eferral(ac tionReques t);
  4306                                               if ( isCal lReferral  ){
  4307                                                       ac tionRespon se.setRend erParamete r(CaretStr Pool.MVC_P ATH, Caret StrPool.ED IT_CALL_PA GE);
  4308                                               } else {
  4309                                                       ac tionRespon se.setRend erParamete r(CaretStr Pool.MVC_P ATH, Caret StrPool.ED IT_REFERRA L_PAGE);
  4310                                               }      
  4311                                      }       
  4312                             } else  if ( "MAN AGE_VCG".e quals(entr y) ){
  4313                                      if ( CAc tion.canDo Caret(acti onRequest,  CaretCan. MANAGE_VCG .name() )  ){
  4314                                               loadVcgMan agement (a ctionReque st, action Response);
  4315                                               if ( Resul tMap.getFo rm( action Request ). get("vcg")  != null )  {
  4316                                                       ac tionRespon se.setRend erParamete r(CaretStr Pool.MVC_P ATH, Caret StrPool.VC G_MANAGEME NT_PAGE);
  4317                                               } else {
  4318                                                       _l og.warn("u ser does n ot have ac cess to VC G page");
  4319                                               }
  4320                                      }
  4321                             } else  if ( Care tStrPool.C REATE_CALL S.equals(e ntry) ){
  4322                                      if ( CAc tion.canDo Caret(acti onRequest,  CaretCan. CREATE_CAL LS.name()  ) || CActi on.canDoCa ret(action Request, C aretCan.VI EW_FUNCTIO N ) ){
  4323                                               loadCall ( actionRequ est);
  4324                                               actionResp onse.setRe nderParame ter(CaretS trPool.MVC _PATH, Car etStrPool. EDIT_CALL_ PAGE);
  4325                                      }
  4326                             } else  if ( "CRE ATE_CALL_T YPE".equal s(entry) ) {
  4327                                      if ( CAc tion.canDo Caret(acti onRequest,  CaretCan. CREATE_CAL L_TYPE.nam e() ) ){
  4328                                               loadCallTy pe (action Request);
  4329                                               actionResp onse.setRe nderParame ter(CaretS trPool.MVC _PATH, Car etStrPool. ADD_CALLTY PE_PAGE);
  4330                                      }
  4331                             }  els e if ( "lo ad-new-cal l-existing -ident".eq uals(entry ) ){
  4332                                      this.loa dNewCallUs eExistingI dentities( actionRequ est);
  4333                                      actionRe quest.setA ttribute(" enableSoc" , false);
  4334                                      actionRe quest.setA ttribute(" isDisabled ", false);
  4335                                      actionRe sponse.set RenderPara meter(Care tStrPool.M VC_PATH, C aretStrPoo l.EDIT_CAL L_PAGE); 
  4336                                      
  4337                             }  els e if ( "vi ew-existin g-call".eq uals(entry ) || (CAct ion.canDoC aret(actio nRequest,  CaretCan.V IEW_FUNCTI ON ) && !C Action.can DoCaret(ac tionReques t, CaretCa n.TECH_FUN CTION) ) ) {
  4338                                      loadExis tingCall ( actionRequ est);
  4339                                      actionRe quest.setA ttribute(" enableSoc" , false);
  4340                                      actionRe quest.setA ttribute(" isDisabled ", true);
  4341                                      actionRe sponse.set RenderPara meter(Care tStrPool.M VC_PATH, C aretStrPoo l.EDIT_CAL L_PAGE);
  4342                             } else  if ( "soc ".equals(e ntry) ){
  4343                                      _log.inf o("loadEnt ry for 'so c'");
  4344                                      String s ocSource =  actionReq uest.getPa rameter("s ocSource") ;
  4345                                      if ( CAc tion.canDo Caret(acti onRequest,  CaretCan. CREATE_SOC .name() )  ){
  4346                                      loadCall  (actionRe quest);
  4347                                      //enable Soc is onl y set on r equests co ming from  SOCs Pendi ng Queue o r SOCs Pen ding Searc h
  4348                                      actionRe quest.setA ttribute(" enableSoc" , true);
  4349                                      actionRe quest.setA ttribute(" isDisabled ", true);
  4350                                      if (socS ource.equa lsIgnoreCa se("groupS ocActions" )) {
  4351                                               actionRequ est.setAtt ribute("so cSourceRes ponse", "s earchOrQue ue");
  4352                                      }
  4353                                      actionRe sponse.set RenderPara meter(Care tStrPool.M VC_PATH, C aretStrPoo l.EDIT_CAL L_PAGE);
  4354                                      //  load Letter(act ionRequest );
  4355                                      }
  4356                             } else  if ( "vie w-soc".equ als(entry)  || (CActi on.canDoCa ret(action Request, C aretCan.VI EW_FUNCTIO N ) && !CA ction.canD oCaret(act ionRequest , CaretCan .TECH_FUNC TION) ) ){
  4357                                      //if ( C Action.can DoCaret(ac tionReques t, CaretCa n.VIEW_SOC .name() )  ){
  4358                                      loadCall AndSoc (ac tionReques t);
  4359                                      //enable Soc is onl y set on r equests co ming from  SOCs Pendi ng Queue o r SOCs Pen ding Searc h
  4360                                      //action Request.se tAttribute ("enableVi ewSoc", tr ue);
  4361                                      actionRe quest.setA ttribute(" enableSoc" , false);
  4362                                      actionRe quest.setA ttribute(" myHiddenVS ", true);
  4363                                      actionRe sponse.set RenderPara meter(Care tStrPool.M VC_PATH, " /jsp/inter nal/myView Soc.jsp");
  4364                                      //}
  4365                             } else  if ( "vie w-soc-retu rn".equals (entry) ||  (CAction. canDoCaret (actionReq uest, Care tCan.VIEW_ FUNCTION )  && !CActi on.canDoCa ret(action Request, C aretCan.TE CH_FUNCTIO N) ) ){
  4366                                      loadCall FromSocVie w (actionR equest);
  4367                                      actionRe quest.setA ttribute(" enableSoc" , true);
  4368                                      actionRe quest.setA ttribute(" isDisabled ", true);
  4369                                      actionRe sponse.set RenderPara meter(Care tStrPool.M VC_PATH, C aretStrPoo l.EDIT_CAL L_PAGE);
  4370                             } else  if ( "can cel-csl-cr eate-vcg". equals(ent ry) ){
  4371                                      cancelCs lCreateVcg (actionReq uest);                                  
  4372                             } else  if ( "ces p".equals( entry) ){
  4373  
  4374                                      if ( CAc tion.canDo Caret(acti onRequest,  CaretCan. CREATE_CES P.name() )  ){
  4375                                               loadCall ( actionRequ est);
  4376                                               actionRequ est.setAtt ribute("en ableCesp",  true);
  4377                                               actionRequ est.setAtt ribute("is Disabled",  true);
  4378                                               actionResp onse.setRe nderParame ter(CaretS trPool.MVC _PATH, Car etStrPool. EDIT_CALL_ PAGE);
  4379                                               //                        loadLe tter(actio nRequest);
  4380                                      }
  4381                             } else  if ( "cbo pcWork".eq uals(entry ) ){
  4382                                      
  4383                             } else  if ( "CRE ATE_VCG".e quals(entr y) || "SET _GENERAL_C G".equals( entry) ){
  4384                                      if ( CAc tion.canDo Caret(acti onRequest,  CaretCan. CREATE_VCG .name() )  ){
  4385                                               ResultMap. getForm(ac tionReques t).put("ve teranRequi red", Coll ections.si ngletonMap ("lastTrea tmentPlace ", "hidden -element") );
  4386                                               long veter anId = Par amUtil.get Long(actio nRequest,  CaretStrPo ol.VETERAN _ID );
  4387                                               if ( veter anId > 0 ) {
  4388                                                       Pe rsn person ;
  4389                                                       tr y {
  4390                                                                pers on = Persn LocalServi ceUtil.get Persn(vete ranId);
  4391                                                                Resu ltMap.getF orm(action Request).p ut(CaretSt rPool.LAST NAME, new  Person(per son));
  4392                                                       }  catch (Por talExcepti on e) {
  4393                                                                Appl icationWor kFlowExcep tion.handl eException (e);
  4394                                                       }  catch (Sys temExcepti on e) {
  4395                                                                Appl icationWor kFlowExcep tion.handl eException (e);
  4396                                                       }
  4397                                               }
  4398                                               ResultMap. getForm(ac tionReques t).put("as sociate",  ParamUtil. getBoolean (actionReq uest, "ass ociate"));
  4399                                               if ( Param Util.getLo ng(actionR equest, "w orImId") >  0 ){
  4400                                                       tr y {
  4401                                                                Resu ltMap.getF orm(action Request).p ut("workIt em", 
  4402                                                                                  new Work ItemSuppor t ( WorImL ocalServic eUtil.getW orIm( Para mUtil.getL ong(action Request, " worImId")  ) ) ); 
  4403                                                       }  catch (Por talExcepti on e1) {
  4404                                                                Appl icationWor kFlowExcep tion.handl eException (e1);
  4405                                                       }  catch (Sys temExcepti on e1) {
  4406                                                                Appl icationWor kFlowExcep tion.handl eException (e1);
  4407                                                       }
  4408                                               }
  4409                                               actionRequ est.setAtt ribute( Ca retStrPool .TRACKER,  CaretParam .trackNdx(  actionReq uest ) );
  4410  
  4411                                               Map<String , Object>  caret = Re sultMap.ge tCaretMap( actionRequ est);
  4412                                               if ( actio nRequest.g etPortletS ession().g etAttribut e(CaretStr Pool.DASHB OARD_CONFI G) instanc eof Facili tyDashboar dConfig )  {
  4413                                                       ca ret.put( C aretStrPoo l.VHA_MEMB ER, CaretU til.getVha OrgList( a ctionReque st ) );
  4414                                                       tr y {
  4415                                                                care t.put(Care tStrPool.S TATES, Reg ionService Util.getRe gions( Cou ntryConsta nts.DEFAUL T_COUNTRY_ ID ) );
  4416                                                                care t.put(Care tStrPool.C OUNTRIES,  CaretUtil. getCountry Map() );
  4417                                                       }  catch (Sys temExcepti on e) {
  4418                                                                Appl icationWor kFlowExcep tion.handl eException (e);
  4419                                                       }
  4420                                                       ca ret.put( C aretStrPoo l.VHA_ORGT REE, false  );
  4421                                               } else {
  4422                                                       lo adStatesAn dFacilitie s( actionR equest );
  4423                                                       ca ret.put( C aretStrPoo l.VHA_ORGT REE , true  );
  4424                                               }
  4425                                               //TODO: re quired att ributes...
  4426                                              
  4427                                               CaretViewC ontroller. getViewCon troller(). loadRequir edInputs(  CaretStrPo ol.NEW_VCG _VETERAN_F ORM, Resul tMap.getFo rm(actionR equest) )  ;
  4428                                              
  4429                                               caret.put( "genderTyp es", Portl etProps.ge t("persn.g ender.type s").split( StringPool .COMMA) )  ;
  4430                                               actionResp onse.setRe nderParame ter(CaretS trPool.MVC _PATH, Car etStrPool. CREATE_VCG _PAGE );
  4431                                               //                        loadLe tter(actio nRequest);
  4432                                      }
  4433           //                         loadCbop cWork(acti onRequest) ;
  4434                             } else  if ( "ASS OCIATE_CAL LS".equals (entry) ||  "ASSOCIAT E_REFERRAL ".equals(e ntry)){
  4435                                      boolean  isReferral  =  "ASSOC IATE_REFER RAL".equal s(entry) ?  true : fa lse;
  4436                                      boolean  canDoCaret  = isRefer ral ?
  4437                                                       CA ction.canD oCaret(act ionRequest , CaretCan .ASSOCIATE _REFERRAL. name()) :
  4438                                                       CA ction.canD oCaret(act ionRequest , CaretCan .ASSOCIATE _CALLS.nam e());
  4439                                      _log.inf o("ASSOCIA TE CALLS:  isReferral : " + isRe ferral);
  4440                                      _log.inf o("ASSOCIA TE CALLS:  canDoCaret : " + canD oCaret);
  4441                                      if ( can DoCaret ){
  4442                                               ResultMap. getForm(ac tionReques t).put("ve teranRequi red", Coll ections.si ngletonMap ("lastTrea tmentPlace ", "hidden -element") );
  4443  
  4444                                               long veter anId = 0;
  4445                                               long worIm Id = 0;
  4446                                               long prima ryKey = 0;
  4447                                               long vcgId  = 0;                                    
  4448                                               long callI d = ParamU til.getLon g(actionRe quest, "ca llId" );
  4449                                               boolean as sociate =  ParamUtil. getBoolean (actionReq uest, "ass ociate");
  4450                                               //
  4451                                               Call call  = null;
  4452                                               Persn pers on = null;
  4453                                               WorIm work Item = nul l;
  4454                                               WorIm work Item2 = nu ll;
  4455                                               //
  4456                                               if (vetera nId == 0 & & callId >  0) {
  4457                                                       tr y {call =  CallLocalS erviceUtil .getCall(c allId);}
  4458                                                       ca tch(Except ion e) {Ap plicationW orkFlowExc eption.han dleExcepti on(e);}
  4459                                                       if  (call !=  null) {vet eranId = c all.getVet eranPersnI d();}
  4460                                               }
  4461                                               if ( veter anId > 0 ) {
  4462                                                       tr y {
  4463                                                                pers on = Persn LocalServi ceUtil.get Persn(vete ranId);
  4464                                                                Resu ltMap.getF orm(action Request).p ut(CaretSt rPool.LAST NAME, new  Person(per son));
  4465                                                       }  catch (Por talExcepti on e) {
  4466                                                                Appl icationWor kFlowExcep tion.handl eException (e);
  4467                                                       }  catch (Sys temExcepti on e) {
  4468                                                                Appl icationWor kFlowExcep tion.handl eException (e);
  4469                                                       }
  4470                                               }
  4471                                               //
  4472                                               if (call ! = null &&  call.getWo rkPrimaryK ey() > 0)  {worImId =  call.getW orkPrimary Key();}
  4473                                               //
  4474                                               if (worImI d == 0) {
  4475                                                       Se rviceConte xt sc = Ca retParam.s etCaretSer viceContex t(actionRe quest);
  4476                                                       Da shboardCon fig dashCo nfig = ( D ashboardCo nfig ) act ionRequest .getPortle tSession() .getAttrib ute( Caret StrPool.DA SHBOARD_CO NFIG );
  4477                                                       Wo rkType wor kType;
  4478                                                       if  ( dashCon fig instan ceof CslDa shboardCon fig ){
  4479                                                                work Type = isR eferral ?  WorkType.C SL_REFERRA L : WorkTy pe.CALL_RE FERRAL;
  4480                                                       }  else {
  4481                                                                try{
  4482                                                                         workTy pe = WorkT ype.valueO f( dashCon fig.getRol e() + "_RE FERRAL");
  4483                                                                } ca tch(Except ion e){
  4484                                                                         workTy pe = WorkT ype.REFERR AL;
  4485                                                                }
  4486                                                       }
  4487                                                       wo rkItem = C aretUtil.c reateWorkI tem(sc, pe rson.getGr oupId(), c all, workT ype, veter anId, call .getCaller PersnId()  );
  4488  
  4489                                                       tr y {
  4490                                                                work Item2 = Wo rImLocalSe rviceUtil. updateWorI m(workItem );
  4491                                                       }
  4492                                                       ca tch(Except ion e) {
  4493                                                                Appl icationWor kFlowExcep tion.handl eException (e);
  4494                                                       }
  4495                                                       Li st<WorIm>  list = (Li st<WorIm>)  WorImLoca lServiceUt il.findByC lassPk(cal lId);
  4496                                                       if  (list.siz e() > 0) {
  4497                                                                work Item2 = li st.get(0);
  4498                                                       }
  4499                                                       wo rImId = wo rkItem2.ge tWorImId() ;
  4500                                                       if  (worImId  > 0) {
  4501                                                                call .setWorkPr imaryKey(w orImId);
  4502                                                                try  {CallLocal ServiceUti l.updateCa ll(call);}
  4503                                                                catc h(Exceptio n e) {Appl icationWor kFlowExcep tion.handl eException (e);}
  4504                                                       }
  4505                                               }
  4506                                               //
  4507                                               ResultMap. getForm(ac tionReques t).put("as sociate",  associate) ;
  4508                                               if ( worIm Id > 0 ){
  4509                                                       tr y {
  4510                                                                Resu ltMap.getF orm(action Request).p ut("workIt em", 
  4511                                                                new  WorkItemSu pport ( Wo rImLocalSe rviceUtil. getWorIm(  worImId )  ) ); 
  4512                                                       }  catch (Por talExcepti on e1) {
  4513                                                                Appl icationWor kFlowExcep tion.handl eException (e1);
  4514                                                       }  catch (Sys temExcepti on e1) {
  4515                                                                Appl icationWor kFlowExcep tion.handl eException (e1);
  4516                                                       }
  4517                                               }
  4518                                               actionRequ est.setAtt ribute( Ca retStrPool .TRACKER,  CaretParam .trackNdx(  actionReq uest ) );
  4519  
  4520                                               Map caret  = ResultMa p.getCaret Map(action Request);
  4521                                               if ( actio nRequest.g etPortletS ession().g etAttribut e(CaretStr Pool.DASHB OARD_CONFI G) instanc eof Facili tyDashboar dConfig )  {
  4522                                                       ca ret.put( C aretStrPoo l.VHA_MEMB ER, CaretU til.getVha OrgList( a ctionReque st ) );
  4523                                                       tr y {
  4524                                                                care t.put(Care tStrPool.S TATES, Reg ionService Util.getRe gions( Cou ntryConsta nts.DEFAUL T_COUNTRY_ ID ) );
  4525                                                       }  catch (Sys temExcepti on e) {
  4526                                                                Appl icationWor kFlowExcep tion.handl eException (e);
  4527                                                       }
  4528                                                       ca ret.put( C aretStrPoo l.VHA_ORGT REE, false  );
  4529                                               } else {
  4530                                                       lo adStatesAn dFacilitie s( actionR equest );
  4531                                                       ca ret.put( C aretStrPoo l.VHA_ORGT REE , true  );
  4532                                               }
  4533                                               //TODO: re quired att ributes...
  4534                                               CaretViewC ontroller. getViewCon troller(). loadRequir edInputs(  CaretStrPo ol.NEW_VCG _VETERAN_F ORM, Resul tMap.getFo rm(actionR equest) )  ;
  4535                                              
  4536                                               caret.put( "genderTyp es", Portl etProps.ge t("persn.g ender.type s").split( StringPool .COMMA) )  ;
  4537                                               DashboardC onfig dash Config = (  Dashboard Config ) a ctionReque st.getPort letSession ().getAttr ibute( Car etStrPool. DASHBOARD_ CONFIG );
  4538                                               if ( dashC onfig inst anceof Csl DashboardC onfig ){
  4539                                                       ac tionReques t.setAttri bute("subm itVcgIsDia bled", tru e);
  4540                                                       ac tionReques t.setAttri bute("subm itVcgCallI d", callId );
  4541                                               }
  4542                                               else {
  4543                                                       ac tionReques t.setAttri bute("subm itVcgIsDia bled", fal se);
  4544                                               }                                          
  4545                                               actionResp onse.setRe nderParame ter(CaretS trPool.MVC _PATH, Car etStrPool. CREATE_VCG _PAGE );
  4546                                               //  loadLe tter(actio nRequest);
  4547                                      }
  4548                                      //  load CbopcWork( actionRequ est); 
  4549  
  4550                             } else  if ( "LOA D_1010_APP LICATION". equals(ent ry) ){
  4551   //                                 long wor ImId = Par amUtil.get Long(actio nRequest,  CaretStrPo ol.WORK_ID );
  4552   //                                 try {
  4553   //                                          WorkItemSu pport work Item = new  WorkItemS upport( Wo rImLocalSe rviceUtil. getWorIm(  worImId )  );
  4554   //                                          VcgSupport  vcg = Vcg Support.ge tVcgSuppor t( workIte m.getVcgId () );
  4555   //                                          VcgApplica tion vcgAn  = new Vcg Applicatio n( vcg.get PersonVcgA n( workIte m.getCareg iverId() )  );
  4556   //                                          Person vet eran = new  Veteran(  PersnLocal ServiceUti l.getPersn ( vcgAn.ge tVeteranId () ) );
  4557   //                                          ResultMap. getForm( a ctionReque st ).put(  CaretStrPo ol.VETERAN _PERSN, ve teran );
  4558   //                                          CaretViewC ontroller. getViewCon troller(). loadAddres s( ResultM ap.getCare tMap(actio nRequest),  veteran,  CaretStrPo ol.VETERAN _PERSN );
  4559   //                                         
  4560   //                                          actionRequ est.setAtt ribute("is Disabled",  true);
  4561   //                                         
  4562   //                                          Person pri mary = new  Primary(  PersnLocal ServiceUti l.getPersn ( vcgAn.ge tPrimaryId () ) );
  4563   //                                          CaretViewC ontroller. getViewCon troller(). loadAddres s( ResultM ap.getCare tMap(actio nRequest),  primary,  CaretStrPo ol.PRIMARY _PERSN );
  4564   //                                          ResultMap. getForm( a ctionReque st ).put(  CaretStrPo ol.PRIMARY _PERSN, pr imary );
  4565   //                                          ResultMap. getForm( a ctionReque st ).put(  CaretStrPo ol.VCGAN,  vcgAn );
  4566   //                                          //TODO: Wo rk in prog ress...
  4567   //                                          _log.info(  vcgAn.get Comments()  ) ;
  4568   //                                          _log.info(  vcgAn.get Applicatio nDate() );
  4569   //                                          _log.info(  vcgAn.get PrimarySig nDate() ==  null? "CS C FORM" :  "ONLINE FO RM");
  4570   //                                          actionRequ est.setAtt ribute ( " vcgAn", vc gAn );
  4571   //                                          loadRelati onshipList s(actionRe quest);
  4572   //                                          actionRequ est.setAtt ribute("RE FERRAL_101 0", DocumL ocalServic eUtil.getA ppByOwnerI d( vcgAn.g etPrimaryK ey() ) ); 
  4573   //                                         
  4574   //                                          if ( vcgAn .getSecond aryId() >  0 ){
  4575   //                                                  Re sultMap.ge tForm( act ionRequest  ).put( Ca retStrPool .SECONDARY _PERSN, ne w Person(  PersnLocal ServiceUti l.getPersn ( vcgAn.ge tSecondary Id() ) ) ) ;
  4576   //                                                  vc gAn.getSec ondaryRela tionship() ;
  4577   //                                          }
  4578   //                                          if ( vcgAn .getSecond aryTwoId()  > 0 ){
  4579   //                                                  Re sultMap.ge tForm( act ionRequest  ).put( Ca retStrPool .SECONDARY _TWO_PERSN , new Pers on( PersnL ocalServic eUtil.getP ersn( vcgA n.getSecon daryTwoId( ) ) ) );
  4580   //                                                  vc gAn.getSec ondaryTwoR elationshi p();
  4581   //                                          }
  4582   //                                          Map<String , Object>  caret = Re sultMap.ge tCaretMap( actionRequ est);
  4583   //                                          if ( actio nRequest.g etPortletS ession().g etAttribut e(CaretStr Pool.DASHB OARD_CONFI G) instanc eof Facili tyDashboar dConfig )  {
  4584   //                                                  ca ret.put( C aretStrPoo l.VHA_MEMB ER, CaretU til.getVha OrgList( a ctionReque st ) );
  4585   //                                                  tr y {
  4586   //                                                           care t.put(Care tStrPool.S TATES, Reg ionService Util.getRe gions( Cou ntryConsta nts.DEFAUL T_COUNTRY_ ID ) );
  4587   //                                                  }  catch (Sys temExcepti on e) {
  4588   //                                                           Appl icationWor kFlowExcep tion.handl eException (e);
  4589   //                                                  }
  4590   //                                                  ca ret.put( C aretStrPoo l.VHA_ORGT REE, false  );
  4591   //                                          } else {
  4592   //                                                  lo adStatesAn dFacilitie s( actionR equest );
  4593   //                                                  ca ret.put( C aretStrPoo l.VHA_ORGT REE , true  );
  4594   //                                          }
  4595   //                                          //TODO: re quired att ributes...
  4596   //                                         
  4597   //                                          caret.put( "genderTyp es", Portl etProps.ge t("persn.g ender.type s").split( StringPool .COMMA) )  ;
  4598   //                                          actionResp onse.setRe nderParame ter(CaretS trPool.MVC _PATH, Car etStrPool. CREATE_APP LICATION_P AGE );
  4599   //                                 } catch  (PortalExc eption e)  {
  4600   //                                          e.printSta ckTrace();
  4601   //                                 } catch  (SystemExc eption e)  {
  4602   //                                          e.printSta ckTrace();
  4603   //                                 }
  4604                                      
  4605   //                                 //form_[ 'veteranPe rsn']
  4606                             } else  if ( "CRE ATE_APPLIC ATIONS".eq uals(entry ) ){
  4607                                      if ( CAc tion.canDo Caret(acti onRequest,  CaretCan. CREATE_APP LICATIONS. name() ) ) {
  4608                    //                         loadStates AndFacilit ies( actio nRequest ) ;
  4609                                               createEntr y(actionRe quest, act ionRespons e);
  4610                                               long callI d = ParamU til.getLon g(actionRe quest, Car etStrPool. CALL_ID );
  4611                                               if ( callI d > 0 ){
  4612                                                       tr y {
  4613                                                                Call  call = Ca llLocalSer viceUtil.g etCall(cal lId);
  4614                                                                Pers on person  = new Pers on(PersnLo calService Util.getPe rsn( call. getCallerP ersnId() )  );
  4615                                                                pers on.setRela tionship(  call.getCa llerRelati onship() ) ;
  4616                                                                acti onRequest. setAttribu te( "calle r", person .getJsonOb ject() );
  4617                                                                pers on = new P erson( Per snLocalSer viceUtil.g etPersn( c all.getVet eranPersnI d() ) );
  4618                                                                Resu ltMap.getF orm( actio nRequest ) .put( Care tStrPool.V ETERAN_PER SN, person  );
  4619                                                                Care tViewContr oller.getV iewControl ler().load Address( R esultMap.g etCaretMap (actionReq uest), per son, Caret StrPool.VE TERAN_PERS N );
  4620                                                                
  4621                                                                List <Docum> te n10 = Docu mLocalServ iceUtil.ge tByClass(  callId, Po rtalUtil.g etClassNam eId(Call.c lass), Fil eType.REFE RRAL_1010. name() );
  4622                                                                if (  !ten10.is Empty() ){
  4623                                                                         action Request.se tAttribute ("REFERRAL _1010", te n10.get(0)  );
  4624                                                                }
  4625                                                                
  4626                                                       }  catch (Por talExcepti on e) {
  4627                                                                Appl icationWor kFlowExcep tion.handl eException (e);
  4628                                                       }  catch (Sys temExcepti on e) {
  4629                                                                Appl icationWor kFlowExcep tion.handl eException (e);
  4630                                                       }
  4631                                               }
  4632                                      }
  4633                             } else  if ( "PRO CESS_APPLI CATIONS".e quals(entr y) ){
  4634                                      if ( CAc tion.canDo Caret(acti onRequest,  CaretCan. MANAGE_VCG .name() )  ){
  4635                                               loadProces sApplicati on(actionR equest, ac tionRespon se);
  4636                                              
  4637                                      }
  4638                             } else  if ( "INT ERNAL_MESS AGE".equal s(entry) ) {
  4639                                      if ( CAc tion.canDo Caret(acti onRequest,  CaretCan. INTERNAL_M ESSAGE.nam e() ) ){
  4640                                               PMPortlet. render(act ionRequest , actionRe sponse);
  4641                                               actionResp onse.setRe nderParame ter(CaretS trPool.MVC _PATH, Car etStrPool. INTERNAL_M ESSAGES_PA GE+actionR equest.get Attribute( "targetPat h"));
  4642                                      }
  4643                             } else  if ( "VIE W_BLS_RATE S".equals( entry) ){
  4644                                      if ( CAc tion.canDo Caret(acti onRequest,  CaretCan. VIEW_BLS_R ATES.name( ) ) ){
  4645                                               loadBlsRat es(actionR equest, ac tionRespon se);
  4646                                      }
  4647                             }
  4648                    } ca tch (Appli cationWork FlowExcept ion e) {
  4649                             Applic ationWorkF lowExcepti on.handleE xception (  e );
  4650                    }
  4651           }
  4652           
  4653  
  4654  
  4655           pr ivate void  searchEnt ry( Portle tRequest r equest ) {
  4656   //               Map< String, In teger> tot al = Resul tMap.getRe sultTotalM ap( reques t );
  4657   //               Map< String, Li st<?>> res ults = Res ultMap.get ResultList Map(reques t);
  4658                    _log .info("sea rchEntry") ;
  4659           }
  4660           
  4661           @P rocessActi on (name=" saveEntry" )
  4662           pu blic void  saveEntry(  ActionReq uest actio nRequest,  ActionResp onse actio nResponse  ) {
  4663                    Stri ng entry =  ParamUtil .get(actio nRequest,  "entry", S tringPool. BLANK);
  4664  
  4665                    _log .info("sav e entry... " +  entry  );
  4666                    
  4667   ///*             
  4668                    Stri ng tracker  = ParamUt il.getStri ng(actionR equest, Ca retStrPool .TRACKER,  StringPool .BLANK );
  4669                    if (  ! CaretPa ram.isTrac ked( actio nRequest,  tracker, t rue ) ){
  4670                             _log.w arn("TRACK ER BLOCKIN G action.. . ");
  4671                             action Request.se tAttribute (CaretStrP ool.INVALI D_REQUEST,  true);
  4672                             return ;
  4673                    }
  4674   //*/
  4675                    try  {
  4676                             if ( " vcg".equal s(entry) ) {
  4677                                      if ( CAc tion.canDo Caret(acti onRequest,  CaretCan. MANAGE_VCG .name() )  ){
  4678                                               saveVcgEnt ry(actionR equest, ac tionRespon se);
  4679                                      }
  4680                             } else  if ( "SAV E_CALL_DIS POSITION". equals(ent ry) ){
  4681                                      if ( CAc tion.canDo Caret(acti onRequest,  CaretCan. DISPOSITIO N_CALLS.na me() ) ){
  4682                                               saveCallDi sposition(  actionReq uest, acti onResponse  );
  4683                                      }                                  
  4684                             } else  if ( "CRE ATE_REFERR AL".equals (entry) ){
  4685                                      if ( CAc tion.canDo Caret(acti onRequest,  CaretCan. CREATE_REF ERRAL.name () ) ){
  4686                                               saveReferr al(actionR equest);
  4687                                      } else i f ( CActio n.canDoCar et(actionR equest, Ca retCan.DIS POSITION_C ALLS.name( ) ) ){
  4688                                               saveCallDi sposition(  actionReq uest, acti onResponse  );
  4689                                      }
  4690                             } else  if ( "CRE ATE_CALLS" .equals(en try) ){
  4691                                      if ( CAc tion.canDo Caret(acti onRequest,  CaretCan. CREATE_CAL LS.name()  ) ){
  4692                                               saveCall(a ctionReque st);
  4693                                      }
  4694                                      if ( CAc tion.canDo Caret(acti onRequest,  CaretCan. DISPOSITIO N_CALLS.na me() ) ){
  4695                                               saveCallDi sposition(  actionReq uest, acti onResponse  );
  4696                                      }
  4697                             } else  if ( "soc ".equals(e ntry) ){
  4698                                      String s ocSourceRe sponsePath  = actionR equest.get Parameter( "socSource ResponsePa th");
  4699                                      if ( CAc tion.canDo Caret(acti onRequest,  CaretCan. CREATE_SOC .name() )  ){
  4700                                               saveSoc(ac tionReques t);
  4701                                               if (socSou rceRespons ePath != n ull && soc SourceResp onsePath.e quals("sea rchOrQueue ")) {
  4702                                                       ac tionRespon se.setRend erParamete r(CaretStr Pool.MVC_P ATH, "/jsp /internal/ performSoc Response.j sp");
  4703                                               }
  4704                                      }
  4705                             }else  if("cesp". equals(ent ry)){
  4706                                      if ( CAc tion.canDo Caret(acti onRequest,  CaretCan. CREATE_CES P.name() )  ){
  4707                                               saveCesp(a ctionReque st);
  4708                                      }
  4709                             }else  if ( "vcgA n".equals( entry) ){
  4710                                      if ( CAc tion.canDo Caret(acti onRequest,  CaretCan. CREATE_APP LICATIONS. name() ) ) {
  4711                                               saveVcgAn( actionRequ est);
  4712                                      }
  4713                             } else  if ( "csc Waiver".eq uals(entry ) ){
  4714                                      if ( !CA ction.canD oCaret(act ionRequest , CaretCan .CREATE_CS C_WAIVER)  ) {
  4715                                               _log.error ("permissi oning... " );
  4716                                               return;
  4717                                      }
  4718                                      saveCSCW aiver(acti onRequest) ;
  4719                             } else  if ( "csc AppealOutc ome".equal s(entry) ) {
  4720                                      if ( !CA ction.canD oCaret(act ionRequest , CaretCan .DISPOSITI ON_VCG ) )  {
  4721                                               _log.error ("permissi oning... " );
  4722                                               return;
  4723                                      }
  4724                                      saveCSCA ppealOutco me( action Request, a ctionRespo nse );
  4725                             } else  if ( "csc Appeal".eq uals(entry ) ){                                   
  4726                                      if ( !CA ction.canD oCaret(act ionRequest , CaretCan .DISPOSITI ON_VCG ) )  {
  4727                                               _log.error ("permissi oning... " );
  4728                                               return;
  4729                                      }
  4730                                      saveCSCA ppeal( act ionRequest , actionRe sponse );
  4731                             }
  4732                                                                                  
  4733                    } ca tch (Appli cationWork FlowExcept ion e) {
  4734                             Applic ationWorkF lowExcepti on.handleE xception (  e );
  4735                    }
  4736           }
  4737           
  4738           
  4739  
  4740  
  4741           pr ivate void  saveCallD isposition (ActionReq uest actio nRequest,  ActionResp onse actio nResponse)  {
  4742                    if (  !CAction. canDoCaret (actionReq uest, Care tCan.DISPO SITION_CAL LS ) ) {
  4743                             _log.e rror("perm issioning. .. ");
  4744                             return ;
  4745                    }
  4746                    _log .info("sav eCallDispo sition..."   );
  4747                    long  callId =  ParamUtil. getLong(ac tionReques t, "call_p rimaryKey" );
  4748                    Stri ng transfe rRemarksEx istingValu e = "";
  4749                    Stri ng summary ExistingVa lue = "";                                  
  4750                    Stri ng comment  = actionR equest.get Parameter( CaretStrPo ol.WORK_CO MMENT);
  4751                    //
  4752                    if (  callId >  0 ){
  4753                             try {
  4754                                      ServiceC ontext sc  = CaretPar am.setCare tServiceCo ntext(acti onRequest) ;
  4755                                      CallSupp ort call =  new CallS upport(Cal lLocalServ iceUtil.ge tCall(call Id));
  4756                                      transfer RemarksExi stingValue  = call.ge tTransferR emarks_asS tring(); 
  4757                                      summaryE xistingVal ue = call. getSummary _asString( );                                 
  4758                                      //
  4759                                      call.set CompoundVa lue(action Request,"t ransferRem arks","cal l_", trans ferRemarks ExistingVa lue);
  4760                                      call.set CompoundVa lue(action Request,"s ummary","c all_", sum maryExisti ngValue);
  4761                                      call.set CompoundVa lue(action Request,"m essage","c all_", com ment);
  4762                                      CaretPar am.loadMod el( action Request, c all, call. getModelAt tributes() .keySet(),  "call_");                  
  4763   //
  4764                                      //_log.i nfo("saveC allDisposi tion call. getMessage _asString( ): " + cal l.getMessa ge_asStrin g() );
  4765                                      //_log.i nfo("saveC allDisposi tion call. getTransfe rRemarks_a sString():  " + call. getTransfe rRemarks_a sString()  );
  4766                                      //_log.i nfo("saveC allDisposi tion call. call.getSu mmary_asSt ring(): "  + call.get Summary_as String() ) ;                               
  4767                                      
  4768                                      call.set Modificati onDate( sc .getCreate Date() );
  4769                                      String c allState =  actionReq uest.getPa rameter("c all_callSt ate");
  4770                                      call.set CallState(  callState  );
  4771                                      
  4772                                      WorkItem Support wo rk = new W orkItemSup port( WorI mLocalServ iceUtil.ge tWorIm( ca ll.getWork PrimaryKey () ) );
  4773                                      if ( wor k.getVcgId () > 0 ){
  4774                                               VcgSupport  vcgSuppor t = VcgSup port.getVc gSupport(  work.getVc gId() );
  4775                                               if (vcgSup port != nu ll) {
  4776                                                       vc gSupport.s etNote("ca llDispComm ent", comm ent,
  4777                                                                         sc.get UserId(),  sc.getCrea teDate(),  NoteSuppor t.NoteGrou p.REFERRAL .groupId() );
  4778                                                       vc gSupport.s etNote("ca llDisposit ion", call State, sc. getUserId( ), sc.getC reateDate( ), NoteSup port.NoteG roup.REFER RAL.groupI d());
  4779                                                       Ca retLocalSe rviceUtil. save(vcgSu pport);
  4780                                                       wo rk.useNote ("callDisp Comment",  vcgSupport .getNote(" callDispCo mment") );
  4781                                                       wo rk.useNote ("callDisp osition",  vcgSupport .getNote(" callDispos ition") );
  4782                                                       ac tionReques t.setAttri bute( Care tStrPool.V CGID, vcgS upport.get VcgId() );
  4783                                               } else {
  4784                                                       wo rk.setNote ("callDisp Comment",  comment, s c.getUserI d(), sc.ge tCreateDat e(), NoteS upport.Not eGroup.CAL L_NOTE.gro upId() );
  4785                                                       wo rk.setNote ("callDisp osition",  callState,  sc.getUse rId(), sc. getCreateD ate(), Not eSupport.N oteGroup.D ISPOSITION .groupId()  );                                               
  4786                                               }
  4787                                      } else {
  4788                                               work.setNo te("callDi spComment" , comment,  sc.getUse rId(), sc. getCreateD ate(), Not eSupport.N oteGroup.C ALL_NOTE.g roupId() ) ;
  4789                                               work.setNo te("callDi sposition" , callStat e, sc.getU serId(), s c.getCreat eDate(), N oteSupport .NoteGroup .DISPOSITI ON.groupId () );
  4790                                      }
  4791                                      
  4792                                      if ( cal lState.con tains("com pleted") ) {
  4793                                               work.setSt atus(WorkS tatus.COMP LETE.name( ));
  4794                                               work.setCo mpletionBy ( sc.getUs erId() );
  4795                                               work.setCo mpletionDa te( sc.get CreateDate () );
  4796                                      }
  4797                                      CaretLoc alServiceU til.save(w ork);
  4798                                      call = ( CallSuppor t) CaretLo calService Util.save(  call );
  4799                                      
  4800                                      if ( "VC G_MANAGEME NT_PAGE".e quals( Par amUtil.get String( ac tionReques t, "onPage Complete",  StringPoo l.BLANK) )  ){
  4801                                               actionResp onse.setRe nderParame ter(CaretS trPool.MVC _PATH, Car etStrPool. VCG_MANAGE MENT_PAGE) ;
  4802                                               loadVcgMan agement(ac tionReques t, actionR esponse);
  4803                                      }
  4804                                      
  4805                             } catc h (PortalE xception e ) {
  4806                                      Applicat ionWorkFlo wException .handleExc eption(e);
  4807                             } catc h (SystemE xception e ) {
  4808                                      Applicat ionWorkFlo wException .handleExc eption(e);
  4809                             }
  4810                    }
  4811           }        
  4812           
  4813           pr ivate void  loadCallS elects(Por tletReques t request  ) throws A pplication WorkFlowEx ception{
  4814                    Map< String,Obj ect> form  = ResultMa p.getForm  (request);
  4815                    
  4816                    Stri ng callTyp e = Portle tProps.get ("call.typ e");
  4817                    if (  !callType .isEmpty()  ){
  4818                             form.p ut( "stand ard-call-t ypes", cal lType.spli t(StringPo ol.COMMA)  );
  4819                    }
  4820                    form .put( "cus tom-call-t ypes", Box GpLocalSer viceUtil.g etBoxGroup s("custom- call-types ") );
  4821                    
  4822                    
  4823                    Stri ng callerL earnAbout  = PortletP rops.get(" call.calle rLearnAbou t");
  4824                    if (  !callerLe arnAbout.i sEmpty() ) {
  4825                             reques t.setAttri bute("call erLearnAbo ut", calle rLearnAbou t.split(St ringPool.C OMMA) );
  4826                    }
  4827                    Stri ng callerC aregiverTy pe = Portl etProps.ge t("call.ca llerCaregi verType");
  4828                    if (  !callerCa regiverTyp e.isEmpty( ) ){
  4829                             reques t.setAttri bute("call erCaregive rType", ca llerCaregi verType.sp lit(String Pool.COMMA ) );
  4830                    }
  4831                    
  4832                    load Relationsh ipLists(re quest);
  4833           }
  4834           
  4835           pr ivate void  loadMoreR eferralInf o ( Portle tRequest r equest, lo ng veteran Id ) throw s Applicat ionWorkFlo wException {
  4836                    
  4837                    List <BoxGp> gr oups = Box GpLocalSer viceUtil.g etBoxGroup s(CaretStr Pool.REFER RAL_QUESTI ONAIRE_YN) ;
  4838                    Map< String,Lis t<BoxGp>>  boxGpMap =  new HashM ap<String, List<BoxGp >>();
  4839                    int  i = 0;
  4840                    List <BoxGp> bo xGpList =  new ArrayL ist<BoxGp> (5);
  4841                    for  ( BoxGp bo xGp: group s ){
  4842                             boxGpL ist.add( b oxGp );
  4843                             if ( i  % 2 == 1  ){
  4844                                      boxGpMap .put( boxG p.getBoxSu bGroup(),  boxGpList  );
  4845                                      boxGpLis t = new Ar rayList<Bo xGp>(5);
  4846                             }
  4847                             i++;
  4848                    }
  4849                    
  4850                    Map< String, Ob ject> form  = ResultM ap.getForm (request);
  4851                    form .put( "ref -prescreen -meets-pca fc", Caret Util.loadB oxGroup (  "referral- questionai re-radio",  "ref-pres creen-meet s-pcafc" )  );
  4852                    form .put( "ref -enrolled- in-va-heal th", Caret Util.loadB oxGroup (  "referral- questionai re-radio",  "ref-enro lled-in-va -health" )  );
  4853                    form .put( "ref -discharge d-after-91 1", CaretU til.loadBo xGroup ( " referral-q uestionair e-radio",  "ref-disch arged-afte r-911" ) ) ;
  4854                    form .put( "ref -veteran-h as-sc-cond ition", Ca retUtil.lo adBoxGroup  ( "referr al-questio naire-radi o", "ref-v eteran-has -sc-condit ion" ) );
  4855                    
  4856                    Map< Long,Boole an> enable dBxGps =   new CaretM ap<Long,Bo olean>( fa lse );
  4857                    form .put(Caret StrPool.BO X_GROUP, e nabledBxGp s);
  4858                    
  4859                    if (  veteranId  > 0 ){
  4860                             for (  BgAsn bgAs n0: BoxGpL ocalServic eUtil.getB oxGroupAss ociations(  veteranId , true ) )  {
  4861                                      enabledB xGps.put(  bgAsn0.get BoxGpId(),  true );
  4862                             }
  4863                    }                 
  4864                    
  4865                    //if  ( CAction .canDoCare t(request,  CaretCan. LOD_QA.nam e() ) ){
  4866                             //form .put( Care tStrPool.H EC_QUESTIO NAIRE, Car etUtil.loa dBoxGroup  ( CaretStr Pool.HEC_Q UESTIONAIR E, CaretSt rPool.HEC_ QUESTIONAI RE ) );
  4867                             form.p ut( CaretS trPool.HEC _QUESTIONA IRE, getHe cQuestiona ire() );
  4868                    //}
  4869           }
  4870           
  4871           pr ivate void  loadMoreC allInfo (  PortletReq uest reque st ) throw s Applicat ionWorkFlo wException {
  4872                    Stri ng timeZon es = Portl etProps.ge t("time.zo nes");
  4873                    if (  !timeZone s.isEmpty( ) ){
  4874                             reques t.setAttri bute("time Zones", ti meZones.sp lit(String Pool.COMMA ) );
  4875                    }
  4876                    
  4877                    Stri ng support LineTransf er = Portl etProps.ge t("call.su pportLineT ransfer");
  4878                    if (  !supportL ineTransfe r.isEmpty( ) ){
  4879                             reques t.setAttri bute("supp ortLineTra nsfers", s upportLine Transfer.s plit(Strin gPool.COMM A) );
  4880                    }
  4881                    
  4882                    Stri ng heardFr omUs = Por tletProps. get("call. heardFromU s");
  4883                    if (  !supportL ineTransfe r.isEmpty( ) ){
  4884                             reques t.setAttri bute("hear dFromUs",  heardFromU s.split(St ringPool.C OMMA) );
  4885                    }                 
  4886                    
  4887                    Stri ng service Branches =  PortletPr ops.get("c all.servic eBranches" );
  4888                    if (  !serviceB ranches.is Empty() ){
  4889                             reques t.setAttri bute("serv iceBranche s", servic eBranches. split(Stri ngPool.COM MA) );
  4890                    }
  4891                    
  4892                    Stri ng eraServ iceTypes =  PortletPr ops.get("c all.eraSer viceTypes" );
  4893                    if (  !eraServi ceTypes.is Empty() ){
  4894                             reques t.setAttri bute("eraS erviceType s", eraSer viceTypes. split(Stri ngPool.COM MA) );
  4895                    }
  4896                    
  4897                    long  callId =  ParamUtil. getLong(re quest, Car etStrPool. CALL_ID, 0  );
  4898   //               Set< Long> bgAs nSet = new  HashSet<L ong>();
  4899                    
  4900                    Map< Long,Boole an> boxGrp  =  new Ca retMap<Lon g,Boolean> ( false );
  4901                    
  4902                    Map< String, Ob ject> form  = ResultM ap.getForm (request);
  4903                    form .put(Caret StrPool.BO X_GROUP, b oxGrp);
  4904                    
  4905                    if (  callId >  0 ){
  4906                             for (  BgAsn bgAs n0: BoxGpL ocalServic eUtil.getB oxGroupAss ociations(  callId, t rue ) ) {
  4907                                      boxGrp.p ut( bgAsn0 .getBoxGpI d(), true  );
  4908                             }
  4909                    }
  4910                    Resu ltMap.getF orm(reques t);
  4911   //               form .put( subN ame, group s );
  4912                    form .put( "vet eran-prima ry-diagnos is", Caret Util.loadB oxGroup (  "veteran-p rimary-dia gnosis", " veteran-pr imary-diag nosis" ) ) ;
  4913                    form .put( "oth er-primary -diagnosis ", CaretUt il.loadBox Group ( "o ther-prima ry-diagnos is", "othe r-primary- diagnosis"  ) );
  4914                    form .put( "pub lic-law-11 1-163-reas ons", Care tUtil.load BoxGroup (  "public-l aw-111-163 -reasons",  "public-l aw-111-163 -reasons")  );
  4915   //               form .put( "hea rd-from-us ", CaretUt il.loadBox Group ( "h eard-from- us", "hear d-from-us"  ) );
  4916  
  4917   //               form .put( "pre screen-mee ts-pcafc",  CaretUtil .loadBoxGr oup ( "ref erral-ques tionaire-y n", "presc reen-meets -pcafc" )  );
  4918   //               form .put( "enr olled-in-v a-health",  CaretUtil .loadBoxGr oup ( "ref erral-ques tionaire-y n", "enrol led-in-va- health" )  );
  4919   //               form .put( "dis charged-af ter-911",  CaretUtil. loadBoxGro up ( "refe rral-quest ionaire-yn ", "discha rged-after -911" ) );
  4920   //               form .put( "vet eran-has-s c-conditio n", CaretU til.loadBo xGroup ( " referral-q uestionair e-yn", "ve teran-has- sc-conditi on" ) );
  4921                    form .put( "ref -prescreen -meets-pca fc", Caret Util.loadB oxGroup (  "referral- questionai re-radio",  "ref-pres creen-meet s-pcafc" )  );
  4922                    form .put( "ref -enrolled- in-va-heal th", Caret Util.loadB oxGroup (  "referral- questionai re-radio",  "ref-enro lled-in-va -health" )  );
  4923                    form .put( "ref -discharge d-after-91 1", CaretU til.loadBo xGroup ( " referral-q uestionair e-radio",  "ref-disch arged-afte r-911" ) ) ;
  4924                    form .put( "ref -veteran-h as-sc-cond ition", Ca retUtil.lo adBoxGroup  ( "referr al-questio naire-radi o", "ref-v eteran-has -sc-condit ion" ) );
  4925                    
  4926   //               form .put( "sup port-lines -transfer" , CaretUti l.loadBoxG roup ( "su pport-line s", "suppo rt-lines-t ransfer")  );
  4927                    form .put( "sup port-lines -number-pr ovided", C aretUtil.l oadBoxGrou p ( "suppo rt-lines",  "support- lines-numb er-provide d") );
  4928                    form .put( "int erventions -applied-f amily", Ca retUtil.lo adBoxGroup  ( "interv entions-ap plied", "i nterventio ns-applied -family")  );
  4929                    form .put( "int erventions -applied-c are", Care tUtil.load BoxGroup (  "interven tions-appl ied", "int erventions -applied-c are") );
  4930                    form .put( "int erventions -applied-r espite", C aretUtil.l oadBoxGrou p ( "inter ventions-a pplied", " interventi ons-applie d-respite" ) );
  4931                    form .put( "int erventions -applied-c ounseling" , CaretUti l.loadBoxG roup ( "in tervention s-applied" , "interve ntions-app lied-couns eling") );
  4932                    form .put( "int erventions -applied-d irectives" , CaretUti l.loadBoxG roup ( "in tervention s-applied" , "interve ntions-app lied-direc tives") );
  4933                    form .put( "int erventions -applied-o ther", Car etUtil.loa dBoxGroup  ( "interve ntions-app lied", "in tervention s-applied- other") );
  4934                    
  4935                    //if  ( CAction .canDoCare t(request,  CaretCan. LOD_QA.nam e() ) ){
  4936                             //form .put( Care tStrPool.H EC_QUESTIO NAIRE, Car etUtil.loa dBoxGroup  ( CaretStr Pool.HEC_Q UESTIONAIR E, CaretSt rPool.HEC_ QUESTIONAI RE ) );
  4937                             form.p ut( CaretS trPool.HEC _QUESTIONA IRE, getHe cQuestiona ire() );
  4938                    //}
  4939           }
  4940           
  4941           pu blic stati c List<Box Gp> getHec Questionai re() {
  4942                    _log .info("[ge tHecQuesti onnaire(). .");
  4943                    List <BoxGp> r_ lbxg = new  ArrayList <BoxGp>();
  4944                    try  {
  4945                             List<B oxGp> lbxg  = CaretUt il.loadBox Group ( Ca retStrPool .HEC_QUEST IONAIRE, C aretStrPoo l.HEC_QUES TIONAIRE ) ;
  4946                             String  lbxgOut =  Collectio nUtils.isE mpty(lbxg)  ? "HEC Q  BOX GROUP  IS EMPTY"  : lbxg.siz e() + "";
  4947                             _log.i nfo("HEC Q  BOX: " +  lbxgOut);
  4948                             for(Bo xGp bxg :  lbxg) {
  4949                                      _log.inf o("[boxGro up: " + bx g.getBoxGr oup() + ". " + bxg.ge tLabel());
  4950                                      if (bxg. getLabel() .equalsIgn oreCase("r ef-lodQa-l ineOfDuty" )) {r_lbxg .add(bxg); }
  4951                             }
  4952                    }
  4953                    catc h(Exceptio n e) {
  4954                             Applic ationWorkF lowExcepti on.handleE xception(e );
  4955                    }
  4956                    retu rn r_lbxg;
  4957           }   
  4958           
  4959           
  4960           
  4961           
  4962           pu blic boole an loadRef erral(Port letRequest  request)  throws App licationWo rkFlowExce ption {
  4963                    requ est.setAtt ribute( Ca retStrPool .TRACKER,  CaretParam .trackNdx(  request )  );
  4964  
  4965                    Stri ng service Status = P ortletProp s.get("vet eran.suppl emental.se rviceStatu ses");
  4966                    if (  !serviceS tatus.isEm pty() ){
  4967                             reques t.setAttri bute(Caret StrPool.SE RVICE_STAT US, servic eStatus.sp lit(String Pool.COMMA ) );
  4968                    }
  4969                    Map< String,Obj ect> form  = ResultMa p.getForm(  request ) ;
  4970                    bool ean newIns tance = Ca retStrPool .NEW.equal s( request .getParame ter(CaretS trPool.STA TUS) ) ;
  4971                    try  {
  4972                             CaretV iewControl ler contro ller = Car etViewCont roller.get ViewContro ller();
  4973                             long c allId = Pa ramUtil.ge tLong(requ est, Caret StrPool.CA LL_ID, 0 ) ;
  4974                             long v eteranId =  0;
  4975                             if ( c allId > 0  ){
  4976                                      _log.inf o("loadRef erral..cal lId: " + c allId);
  4977                                      Map<Stri ng,Object>  caret = R esultMap.g etCaretMap (request);
  4978                                      
  4979                                      //Call c all = Call LocalServi ceUtil.get Call( call Id );
  4980                                      CallSupp ort call =  new CallS upport(Cal lLocalServ iceUtil.ge tCall( cal lId ));
  4981                                      if ( new Instance )  {
  4982                                               call.setCa llId(0);
  4983                                               call.setWo rkPrimaryK ey(0);
  4984                                      } else i f ( "send- referral". equals( ca ll.getCall State() )  ) {
  4985                                               loadCall (  request ) ;
  4986                                               return tru e;
  4987                                      }
  4988                                      form.put ( CaretStr Pool.CALL,  call );
  4989                                      request. setAttribu te("messag e_", call. getMessage _asString( ));
  4990                                      request. setAttribu te("transf erRemarks_ ", call.ge tTransferR emarks_asS tring());
  4991                                      
  4992                                      if ( cal l.getWorkP rimaryKey( ) > 0 ){
  4993                                               WorIm work Item = Wor ImLocalSer viceUtil.g etWorIm( c all.getWor kPrimaryKe y() );
  4994                                               form.put(" workItem",  workItem  );                                            
  4995                                               request.se tAttribute ("worImId" , workItem .getWorImI d() + "");
  4996                                               request.se tAttribute ("callCall State", ca ll.getCall State());
  4997                                              
  4998                                               if ( workI tem != nul l && ( wor kItem.getU serId() >  0 || workI tem.getCom pletionBy( ) > 0 )  ) {
  4999                                                       _l og.info("l oadReferra l..workIte m userId,  completion By: " + wo rkItem.get UserId() +  " , " +   workItem.g etCompleti onBy());
  5000                                                       re quest.setA ttribute(" isDisabled ", true);
  5001                                                       if  ( workIte m.getStatu s() != nul l ){
  5002                                                                _log .info("loa dReferral:  workItem. getStatus( ): " + wor kItem.getS tatus());
  5003                                                                if (  ! workIte m.getStatu s().toLowe rCase().co ntains("co mpleted")  ){
  5004                                                                         reques t.setAttri bute("disp ositionCal l", CActio n.canDoCar et(request , CaretCan .DISPOSITI ON_CALLS.n ame() ) );
  5005                                                                }
  5006                                                       }  else {
  5007                                                                requ est.setAtt ribute("di spositionC all", CAct ion.canDoC aret(reque st, CaretC an.DISPOSI TION_CALLS .name() )  );
  5008                                                       }
  5009                                               }
  5010                                               else {
  5011                                                       _l og.info("l oadReferra l..workIte m no userI d: ");
  5012                                               }
  5013                                      }
  5014                                      
  5015                                      Person p erson = ne w Person(  PersnLocal ServiceUti l.getPersn ( call.get CallerPers nId() ) );
  5016                                      form.put (CaretStrP ool.CALLER _PERSN, pe rson );
  5017                                      controll er.loadAdd ress( care t, person,  CaretStrP ool.CALLER _PERSN );
  5018                                      veteranI d = call.g etVeteranP ersnId();
  5019                                      person =  new Perso n ( PersnL ocalServic eUtil.getP ersn( vete ranId ) );
  5020                                      form.put (CaretStrP ool.VETERA N_PERSN, p erson );
  5021                                      controll er.loadAdd ress( care t, person,  CaretStrP ool.VETERA N_PERSN );
  5022  
  5023   //                                 if ( ( c all.getCal lState() ! = null &&
  5024   //                                                  ca ll.getCall State().to LowerCase( ).contains (CaretStrP ool.CALL_S TATE_COMPL ETE) ) ||                                           
  5025   //                                                  !  CAction.ca nDoCaret(r equest, CA ction.Care tCan.CREAT E_REFERRAL .name() )  ){
  5026   //                                          request.se tAttribute ("isDisabl ed", true) ;
  5027   //                                 }
  5028                                      request. setAttribu te("isDisa bled", !ne wInstance  && call.ge tCallId()  > 0);
  5029                                      Dashboar dConfig da shConfig =  (Dashboar dConfig)re quest.getP ortletSess ion().getA ttribute(C aretStrPoo l.DASHBOAR D_CONFIG);
  5030                                      if ( das hConfig in stanceof C slDashboar dConfig ){
  5031                                               _log.info( "loadRefer ral(HEC) f or CSL.... ..");
  5032                                               request.se tAttribute ("isDisabl ed", true) ;       
  5033                                               request.se tAttribute ("disposit ionCall",  false);
  5034                                      }
  5035                                      else if  (dashConfi g instance of CscDash boardConfi g) {
  5036                                               _log.info( "loadRefer ral(HEC) f or CSC.... ..");
  5037                                               request.se tAttribute ("isDisabl ed", true) ;       
  5038                                               request.se tAttribute ("disposit ionCall",  true);                                     
  5039                                      }
  5040                                      else                               
  5041                                      if (!CAc tion.canDo Caret(requ est, Caret Can.CREATE _REFERRAL. name() ))  {
  5042                                               if (CActio n.canDoCar et(request , CaretCan .VIEW_REFE RRAL.name( ) )) {
  5043                                                       _l og.info("l oadReferra l(HEC) for  CREATE_RE FERRAL=no  VIEW_REFER RAL=yes.." );
  5044                                                       re quest.setA ttribute(" isDisabled ", true);         
  5045                                                       re quest.setA ttribute(" dispositio nCall", fa lse);
  5046                                               }
  5047                                      }       
  5048                             }
  5049                             
  5050                             loadCa llSelects(  request ) ;
  5051                             loadMo reReferral Info(reque st, callId  );
  5052                             
  5053                             Result Map.getCar etMap(requ est).put(" genderType s", Portle tProps.get ("persn.ge nder.types ").split(S tringPool. COMMA) ) ;
  5054                             
  5055                             loadSt atesAndFac ilities( r equest );
  5056  
  5057                             Dashbo ardConfig  config = ( DashboardC onfig)requ est.getPor tletSessio n().getAtt ribute(Car etStrPool. DASHBOARD_ CONFIG);
  5058                             if ( c onfig != n ull ){
  5059                                      request. setAttribu te(CaretSt rPool.ROLE , config.g etRole() ) ;
  5060                             }
  5061                             contro ller.loadR equiredInp uts( Caret StrPool.RE FFERAL, fo rm );
  5062                             
  5063                             if ( C Action.can DoCaret(re quest, CAc tion.Caret Can.REFERR AL_ATTACHM ENT.name()  ) || CAct ion.canDoC aret(reque st, CActio n.CaretCan .MANAGE_VC G.name() )  ){
  5064                                      if ( cal lId > 0 )  {
  5065                                               List<Docum > supportD ocs = Docu mLocalServ iceUtil.ge tByPrimary Key( callI d );
  5066                                               form.put(" supportDoc s", suppor tDocs );
  5067                                      }
  5068                                      form.put ("hasDocum entAcess",  true);
  5069                             } else  {
  5070                                      form.put ("hasDocum entAcess",  false);
  5071                             }
  5072                             
  5073   //                        form.p ut("noteCo ntext", Ca retStrPool .CALL );
  5074                             Result Map.getCar etMap(requ est).put(" noteContex t", CaretS trPool.CAL L);
  5075                             
  5076                    } ca tch (Excep tion e) {
  5077                             throw  new Applic ationWorkF lowExcepti on(e);
  5078                    }
  5079                    retu rn false;
  5080           }
  5081           
  5082           
  5083           pu blic void  takeOwners hipCall (  ActionRequ est reques t, ActionR esponse ac tionRespon se ){
  5084                    _log .info("tak eOwnership Call");
  5085                    
  5086                    long  callId =  ParamUtil. getLong(re quest, Car etStrPool. CALL_ID);
  5087                    try  {
  5088                             Servic eContext s c = CaretP aram.setCa retService Context(re quest);
  5089                             Call w orkItem =  CallLocalS erviceUtil .getCall(c allId);
  5090                             workIt em.setUser Id( sc.get UserId() ) ;
  5091   //                        workIt em.setStat us(WorkSta tus.IN_PRO CESS.name( ));
  5092                             CaretL ocalServic eUtil.save (workItem) ;
  5093                             
  5094   //                        update VcgAnStatu s(workItem );
  5095                             
  5096                    } ca tch (Porta lException  e) {
  5097                             Applic ationWorkF lowExcepti on.handleE xception(e );
  5098                    } ca tch (Syste mException  e) {
  5099                             Applic ationWorkF lowExcepti on.handleE xception(e );
  5100                    }
  5101                    
  5102           }
  5103           
  5104           pu blic void  takeOwners hip ( Acti onRequest  request, A ctionRespo nse action Response ) {
  5105                    if (  !( CActio n.canDoCar et( reques t, CaretCa n.MANAGE_V CG ) || CA ction.canD oCaret( re quest, Car etCan.VACO _FUNCTION  ) ) ) {
  5106                             _log.e rror("perm issioning. .. ");
  5107                             return ;
  5108                    }
  5109                    _log .info("tak eOwnership ");
  5110                    
  5111                    long  worImId =  ParamUtil .getLong(r equest, Ca retStrPool .WORK_ID);
  5112                    try  {
  5113                             Servic eContext s c = CaretP aram.setCa retService Context(re quest);
  5114                             WorkIt emSupport  workItem =  new WorkI temSupport ( WorImLoc alServiceU til.getWor Im(worImId ) );
  5115                             workIt em.setUser Id( sc.get UserId() ) ;
  5116  
  5117                             Dashbo ardConfig  config = ( DashboardC onfig) req uest.getPo rtletSessi on().getAt tribute( C aretStrPoo l.DASHBOAR D_CONFIG);
  5118                             if ( c onfig inst anceof Cbo pcDashboar dConfig ){
  5119                                      occSibli ngAssignMe (config, w orkItem, s c, true);
  5120                             }
  5121   //                        if ( c onfig inst anceof Fac ilityDashb oardConfig  ){
  5122   //                                 if ( Car etStrPool. NEW.equals ( workItem .getStatus () ) ) {
  5123   //                                          workItem.s etStatus(C aretStrPoo l.IN_PROCE SS);
  5124   //                                 }
  5125   //                        }
  5126                             
  5127                             CaretL ocalServic eUtil.save (workItem) ;
  5128                             checkC ontext( re quest, act ionRespons e, workIte m.getVcgId () );
  5129                             
  5130                    } ca tch (Porta lException  e) {
  5131                             Applic ationWorkF lowExcepti on.handleE xception(e );
  5132                    } ca tch (Syste mException  e) {
  5133                             Applic ationWorkF lowExcepti on.handleE xception(e );
  5134                    }
  5135           }
  5136  
  5137           pr ivate void  checkCont ext(Action Request re quest, Act ionRespons e actionRe sponse, lo ng vcgId )  {
  5138                    // T ODO Auto-g enerated m ethod stub
  5139                    Stri ng context  = request .getParame ter("conte xt");
  5140                    if (  "manageVc g".equals(  context )  && vcgId  > 0 ){
  5141                             reques t.setAttri bute( Care tStrPool.V CGID, vcgI d );
  5142                             loadVc gManagemen t(request,  actionRes ponse);
  5143                             Result Map.getCar etMap(requ est).put(" scrollCont ext", "ope nWork" );
  5144                             action Response.s etRenderPa rameter(Ca retStrPool .MVC_PATH,  CaretStrP ool.VCG_MA NAGEMENT_P AGE);
  5145                    } el se if ( "d ashboard". equals( co ntext ) ){
  5146                             if ( ! Toolbox.is Empty(Para mUtil.getS tring(requ est, "worI m_status")  ) ) {
  5147                                      _log.inf o("APP DEL AY context ");
  5148                             } else  {
  5149                                      ResultMa p.getCaret Map(reques t).put("ta bContext",  "search"  );
  5150                                      ResultMa p.getCaret Map(reques t).put("la stSearch",  request.g etPortletS ession().g etAttribut e("lastSea rch"));
  5151                             }
  5152                    }
  5153                    _log .info("con text is "  + context  );
  5154           }
  5155           pu blic void  unassignTo  ( ActionR equest req uest, Acti onResponse  actionRes ponse ){
  5156                    
  5157                    long  primKey =  ParamUtil .getLong(r equest, Ca retStrPool .WORK_ID);
  5158                    if (  primKey >  0 && ( CA ction.canD oCaret(req uest, Care tCan.OVERW RITE_CONTR OL) || !CA ction.canD oCaret(req uest, Care tCan.CBOPC _FUNCTION  ) ) ){
  5159                             try {
  5160                                      WorIm wo rkItem = W orImLocalS erviceUtil .getWorIm( primKey);
  5161                                      workItem .setUserId (0);
  5162                                      ServiceC ontext sc  = CaretPar am.setCare tServiceCo ntext(requ est);
  5163                                      Dashboar dConfig co nfig = (Da shboardCon fig) reque st.getPort letSession ().getAttr ibute( Car etStrPool. DASHBOARD_ CONFIG );
  5164                                      CaretLoc alServiceU til.save(  workItem ) ;
  5165  
  5166                                      if ( con fig instan ceof Cbopc DashboardC onfig ){
  5167                                               occSibling AssignMe(c onfig, wor kItem, sc,  false);
  5168                                      }
  5169                                      checkCon text( requ est, actio nResponse,  workItem. getVcgId()  );
  5170                             } catc h (PortalE xception e ) {
  5171                                      Applicat ionWorkFlo wException .handleExc eption(e);
  5172                             } catc h (SystemE xception e ) {
  5173                                      Applicat ionWorkFlo wException .handleExc eption(e);
  5174                             } 
  5175                    }                 
  5176           }
  5177  
  5178           pu blic void  assignTo (  ActionReq uest reque st, Action Response a ctionRespo nse ){
  5179                    if (  !( CActio n.canDoCar et( reques t, CaretCa n.MANAGE_V CG ) || CA ction.canD oCaret( re quest, Car etCan.VACO _FUNCTION  ) ) ) {
  5180                             _log.e rror("perm issioning. .. ");
  5181                             return ;
  5182                    }
  5183                    long  primKey =  ParamUtil .getLong(r equest, Ca retStrPool .WORK_ID);
  5184                    long  userId =  ParamUtil. getLong(re quest, "fo rm_userNam e");
  5185                    if (  primKey >  0 && user Id > 0 ){
  5186                             try {
  5187                                      ServiceC ontext sc  = CaretPar am.setCare tServiceCo ntext(requ est);
  5188                                      WorkItem Support wo rkItem = n ew WorkIte mSupport (  WorImLoca lServiceUt il.getWorI m(primKey)  );
  5189                                      workItem .setNote(" assign", P aramUtil.g et(request , CaretStr Pool.WORK_ COMMENT, S tringPool. BLANK ),
  5190                                                       sc .getUserId (), sc.get CreateDate (), NoteSu pport.Note Group.WORK _ASSIGN_NO TE.groupId ());
  5191                                      
  5192                                      workItem .setUserId (userId);
  5193                                      
  5194                                      Dashboar dConfig co nfig = (Da shboardCon fig) reque st.getPort letSession ().getAttr ibute( Car etStrPool. DASHBOARD_ CONFIG );
  5195                                      if ( con fig instan ceof Cbopc DashboardC onfig ){
  5196                                               occSibling AssignTo(c onfig, wor kItem, use rId, sc);
  5197                                      }
  5198                                                       
  5199                                      CaretLoc alServiceU til.save(  workItem ) ;
  5200  
  5201   //                                 updateVc gAnStatus( workItem);
  5202                                      checkCon text( requ est, actio nResponse,  workItem. getVcgId()  );
  5203                             } catc h (PortalE xception e ) {
  5204                                      Applicat ionWorkFlo wException .handleExc eption(e);
  5205                             } catc h (SystemE xception e ) {
  5206                                      Applicat ionWorkFlo wException .handleExc eption(e);
  5207                             } 
  5208                    }                 
  5209           }
  5210           
  5211           pu blic void  withdrawAp peal ( Act ionRequest  request,  ActionResp onse actio nResponse  ) throws A pplication WorkFlowEx ception{
  5212                    
  5213                    long  apealId =  ParamUtil .getLong(r equest, "a pealId");
  5214                    
  5215                    Apea l appeal;
  5216                    try  {
  5217                             if ( C Action.can DoCaret(re quest, CAc tion.Caret Can.WITHDR AW_APPEAL  ) ) {
  5218                                      
  5219                                      appeal =  ApealLoca lServiceUt il.fetchAp eal(apealI d);
  5220                                      appeal.s etReason(" withdrawn" );
  5221                                      CaretLoc alServiceU til.save(a ppeal);
  5222                                      
  5223                             }
  5224                    } ca tch (Syste mException  e) {
  5225                             e.prin tStackTrac e();
  5226                    }
  5227           }
  5228  
  5229           pu blic void  correctWor k ( Action Request re quest, Act ionRespons e actionRe sponse ){
  5230                    if (  !( CActio n.canDoCar et( reques t, CaretCa n.CBOPC_MY _CSC_Q) ||  CAction.c anDoCaret(  request,  CaretCan.T ECH_FUNCTI ON) || 
  5231                                      CAction. canDoCaret ( request,  CaretCan. CSC_FUNCTI ON) ) || C Action.can DoCaret( r equest, Ca retCan.VAC O_FUNCTION  ) ) {
  5232                             _log.e rror("perm issioning. .. ");
  5233                             return ;
  5234                    }
  5235                    
  5236                    long  primKey =  ParamUtil .getLong(r equest, Ca retStrPool .WORK_ID);
  5237                    if (  primKey >  0 ){ //TO DO:// CAct ion.canDoC aret(reque st, CORREC T WORK ) 
  5238                             try {
  5239                                      ServiceC ontext sc  = CaretPar am.setCare tServiceCo ntext(requ est);
  5240                                      
  5241                                      WorkItem Support wo rkItem = n ew WorkIte mSupport(  WorImLocal ServiceUti l.getWorIm (primKey)  );
  5242                                      workItem .setStatus ( WorkStat us.CORRECT ED_WORK.na me() );
  5243                                      
  5244                                      String n oteAtt = " CorrectedN ote";
  5245                                      String c omment = P aramUtil.g et(request , CaretStr Pool.WORK_ COMMENT, S tringPool. BLANK );
  5246                                      Note not e = CaretU til.create Note( sc.g etCreateDa te(), prim Key, NoteS upport.Not eGroup.COR RECTIVE_RE SPONSE.gro upId(), sc .getUserId (), commen t);
  5247                                      note.set VcgId(work Item.getVc gId());
  5248                                      workItem .useNote(  noteAtt, n ote );
  5249                                      
  5250                                      if ( sc. getUserId( ) != workI tem.getUse rId() ){// change bac k to last  OCC user
  5251                                               for ( WorS e workItem Step: WorS eLocalServ iceUtil.ge tByWorkId(  workItem. getWorImId () ) ){
  5252                                                       tr y {
  5253                                                                for  ( long rol eId : User LocalServi ceUtil.get User( work ItemStep.g etUserId()  ).getRole Ids() ){
  5254                                                                         if ( C Action.can DoCaret( s c.getCompa nyId(), CA ction.Care tCan.CBOPC _FUNCTION,  roleId) ) {
  5255                                                                                  workItem .setUserId ( workItem Step.getUs erId() );
  5256                                                                         }
  5257                                                                }
  5258                                                       }  catch (Sys temExcepti on e) {
  5259                                                                e.pr intStackTr ace();
  5260                                                       }  catch (Por talExcepti on e) {
  5261                                                                e.pr intStackTr ace();
  5262                                                       }
  5263                                               }
  5264                                      }
  5265                                      CaretLoc alServiceU til.save(  workItem ) ;
  5266  
  5267                                      WorSe wo rkItemStep  = new Wor SeImpl();
  5268                                      workItem Step.setWo rImId( wor kItem.getW orImId() ) ;
  5269                                      workItem Step.setCr eationDate ( sc.getCr eateDate()  );
  5270                                      workItem Step.setUs erId( sc.g etUserId()  );
  5271                                      int coun t = WorSeL ocalServic eUtil.getC ount ( wor kItem.getW orImId() ) ;
  5272                                      workItem Step.setSt ep( (count  < 10? "0" :StringPoo l.BLANK) +  count + S tringPool. COLON + wo rkItem.get Type() + S tringPool. COLON + wo rkItem.get Status() ) ;
  5273                                      workItem Step.setSt epNumber(c ount+1);
  5274                                      CaretLoc alServiceU til.save(  workItemSt ep );
  5275                                      checkCon text( requ est, actio nResponse,  workItem. getVcgId()  );
  5276                             } catc h (PortalE xception e ) {
  5277                                      Applicat ionWorkFlo wException .handleExc eption(e);
  5278                             } catc h (SystemE xception e ) {
  5279                                      Applicat ionWorkFlo wException .handleExc eption(e);
  5280                             }
  5281                    }
  5282           }
  5283           
  5284           pu blic void  occSibling AssignMe (  Dashboard Config con fig, WorIm  workItem,  ServiceCo ntext sc,  boolean as sign ) thr ows Applic ationWorkF lowExcepti on {
  5285                    Coll ection<Lon g> collect ion = ((Cb opcDashboa rdConfig)c onfig).get OwnerQueue Ids();
  5286                    List <WorIm> wo rImList =  WorImLocal ServiceUti l.findByOp enQueueIds ( ArrayUti l.toArray(  collectio n.toArray( new Long[c ollection. size()]) ) , workItem .getVcgId( ) );
  5287                    for  ( WorIm wo rIm: worIm List ){
  5288                             boolea n update =  true;
  5289                             if ( w orIm.getWo rImId() ==  workItem. getWorImId () ) {
  5290                                      update =  false;
  5291                             }
  5292                             if ( O wnerQueue. CORRECTION _Q.name(). equals( wo rkItem.get Status() )  ){
  5293                                      if ( wor kItem.getU serId() !=  0  ){
  5294                                               try {
  5295                                                       fo r ( long r oleId : Us erLocalSer viceUtil.g etUser( wo rkItem.get UserId() ) .getRoleId s() ){
  5296                                                                if (  CAction.c anDoCaret(  sc.getCom panyId(),  CAction.Ca retCan.CSC _FUNCTION,  roleId) ) {
  5297                                                                         update  = false;
  5298                                                                }
  5299                                                       }
  5300                                               } catch (S ystemExcep tion e) {
  5301                                                       e. printStack Trace();
  5302                                               } catch (P ortalExcep tion e) {
  5303                                                       e. printStack Trace();
  5304                                               }
  5305                                      }
  5306                             }
  5307                             if ( u pdate ){
  5308                                      WorkItem Support si bling = ne w WorkItem Support (w orIm);
  5309                                      sibling. setUserId(  assign? s c.getUserI d() : 0 );
  5310                                      sibling. setNote(as sign? "ass ign": "una ssign", wo rkItem.get WorImId()  + (assign?  " Sibling  assignmen t": " Sibl ing unassi gnment"),  sc.getUser Id(), sc.g etCreateDa te(), Note Support.No teGroup.WO RK_ASSIGN_ NOTE.group Id());
  5311                                      CaretLoc alServiceU til.save(s ibling);
  5312                             }
  5313                    }
  5314           }
  5315           
  5316           
  5317           pu blic void  occSibling AssignTo (  Dashboard Config con fig, WorIm  workItem,  long assi gnee, Serv iceContext  sc ) thro ws Applica tionWorkFl owExceptio n{
  5318                    
  5319                    try  {
  5320                             List<R ole> roles  = RoleLoc alServiceU til.getUse rRoles(ass ignee);
  5321                             
  5322                             Collec tion<Long>  collectio n = ((Cbop cDashboard Config)con fig).getOw nerQueueId s();
  5323                             List<W orIm> worI mList = Wo rImLocalSe rviceUtil. findByOpen QueueIds(  ArrayUtil. toArray( c ollection. toArray(ne w Long[col lection.si ze()]) ),  workItem.g etVcgId()  );
  5324                             List<W orIm> sibl ingList =  new ArrayL ist<WorIm> ();
  5325                             for (  WorIm worI m: worImLi st ){
  5326                                      boolean  update = t rue;
  5327                                      if ( wor Im.getWorI mId() == w orkItem.ge tWorImId()  ) {
  5328                                               update = f alse;
  5329                                      }
  5330                                      if ( Own erQueue.CO RRECTION_Q .name().eq uals( work Item.getSt atus() ) ) {
  5331                                               if ( workI tem.getUse rId() != 0   ){
  5332                                                       tr y {
  5333                                                                List <Role> rol es2 = Role LocalServi ceUtil.get UserRoles( workItem.g etUserId() );
  5334                                                                for  ( Role rol e : roles2  ){
  5335                                                                         if ( C Action.can DoCaret( s c.getCompa nyId(), CA ction.Care tCan.CSC_F UNCTION, r ole.getRol eId() ) ){  //already  picked up  by CSC
  5336                                                                                  update =  false;
  5337                                                                                  WorSe wo rkItemStep  = new Wor SeImpl();
  5338                                                                                  workItem Step.setWo rImId( wor kItem.getW orImId() ) ;
  5339                                                                                  workItem Step.setCr eationDate ( sc.getCr eateDate()  );
  5340                                                                                  workItem Step.setUs erId( assi gnee );
  5341                                                                                  int coun t = WorSeL ocalServic eUtil.getC ount ( wor kItem.getW orImId() ) ;
  5342                                                                                  workItem Step.setSt ep( (count  < 10? "0" :StringPoo l.BLANK) +  count + S tringPool. COLON + wo rkItem.get Type() + S tringPool. COLON + wo rkItem.get Status() ) ;
  5343                                                                                  workItem Step.setSt epNumber(c ount+1);
  5344                                                                                  CaretLoc alServiceU til.save(  workItemSt ep );
  5345                                                                         }
  5346                                                                }
  5347                                                       }  catch (Sys temExcepti on e) {
  5348                                                                e.pr intStackTr ace();
  5349                                                       }  catch (Por talExcepti on e) {
  5350                                                                e.pr intStackTr ace();
  5351                                                       }
  5352                                               } else {
  5353                                                       Wo rSe workIt emStep = n ew WorSeIm pl();
  5354                                                       wo rkItemStep .setWorImI d( workIte m.getWorIm Id() );
  5355                                                       wo rkItemStep .setCreati onDate( sc .getCreate Date() );
  5356                                                       wo rkItemStep .setUserId ( assignee  );
  5357                                                       in t count =  WorSeLocal ServiceUti l.getCount  ( workIte m.getWorIm Id() );
  5358                                                       wo rkItemStep .setStep(  count < 10 ? "0":Stri ngPool.BLA NK + count  + StringP ool.COLON  + workItem .getType()  + StringP ool.COLON  + workItem .getStatus () );
  5359                                                       Ca retLocalSe rviceUtil. save( work ItemStep ) ;
  5360                                               }
  5361                                      }
  5362                                      if ( upd ate ){
  5363                                               String que ueName = n ew WorkIte mSupport ( worIm).get QueueName( );
  5364                                              
  5365                                               if ( !Tool box.isEmpt y(queueNam e) ){
  5366                                                       Ca retCan act ion = Care tCan.value Of( CbopcD ashboardCo nfig.NDX +  queueName  ); 
  5367                                                       fo r ( Role r ole : role s ){
  5368                                                                try  {
  5369                                                                         if ( C Action.can DoCaret( s c.getCompa nyId(), ac tion, role .getRoleId () ) ){
  5370                                                                                  siblingL ist.add(wo rIm);
  5371                                                                                  break;
  5372                                                                         }
  5373                                                                } ca tch (Porta lException  e) {
  5374                                                                         e.prin tStackTrac e();
  5375                                                                }
  5376                                                       }
  5377                                               }
  5378                                      }
  5379                             }
  5380                                      
  5381                             for (  WorIm worI m: sibling List ){
  5382                                      WorkItem Support si bling = ne w WorkItem Support (w orIm);
  5383                                      sibling. setUserId(  assignee  );
  5384                                      sibling. setNote("a ssign", wo rkItem.get WorImId()  + " Siblin g assignme nt", sc.ge tUserId(),  sc.getCre ateDate(),  NoteSuppo rt.NoteGro up.WORK_AS SIGN_NOTE. groupId()) ;
  5385                                      CaretLoc alServiceU til.save(s ibling);
  5386                             }
  5387                             
  5388                    } ca tch (Syste mException  e) {
  5389                             e.prin tStackTrac e();
  5390                    }
  5391           }
  5392           
  5393           
  5394           pu blic void  reviewMyWo rk ( Actio nRequest r equest, Ac tionRespon se actionR esponse ){
  5395                    
  5396                    if (  !CAction. canDoCaret (request,  CAction.Ca retCan.CBO PC_FUNCTIO N ) ) {
  5397                             _log.w arn("permi ssioning.. . ");
  5398                             return ;
  5399                    }
  5400                             
  5401                    long  primKey =  ParamUtil .getLong(r equest, Ca retStrPool .WORK_ID);
  5402                    Stri ng workImS tatus = Pa ramUtil.ge t(request,  "worIm_st atus", Str ingPool.BL ANK);
  5403                    long  workUserI d = 0;
  5404   //               Stri ng workIte mStepName  = ParamUti l.get(requ est, "worI m_step", w orkImStatu s );
  5405                    QueA ction queA ction = Qu eAction.va lueOf( wor kImStatus  );
  5406                    if (  primKey >  0 && ! To olbox.isEm pty(workIm Status) ){  //TODO://  CAction.c anDoCaret( request, q ueAction.n ame() ) 
  5407                             try {
  5408                                      ServiceC ontext sc  = CaretPar am.setCare tServiceCo ntext(requ est);
  5409                                      
  5410                                      WorkItem Support wo rkItem = n ew WorkIte mSupport(  WorImLocal ServiceUti l.getWorIm (primKey)  );
  5411                                      workUser Id = workI tem.getUse rId();
  5412                                      long not eGrpId;
  5413                                      OwnerQue ue nextQue ue = Owner Queue.valu eOf( queAc tion.getNe xtQueue()  );
  5414                                      boolean  workItemSt epCreated  = false;
  5415                                      if ( Own erQueue.CO RRECTION_Q  == nextQu eue ){
  5416                                               workItem.s etStatus(  OwnerQueue .CORRECTIO N_Q.name()  );
  5417   //                                          workItemSt epName = w orkItemSte pName + St ringPool.C OMMA_AND_S PACE + Par amUtil.get (request,  "worIm_cor rection",  "Other");
  5418                                               noteGrpId  = NoteSupp ort.NoteGr oup.CORREC TION_REQUE ST.groupId ();
  5419                                               workItem.s etLeaAttr(  "Correcti onType", P aramUtil.g et(request , "worIm_c orrection" , "Other")  );
  5420                                               for ( WorS e workItem Step: WorS eLocalServ iceUtil.ge tByWorkId(  workItem. getWorImId () ) ){//c hange back  to last C SC user
  5421                                                       tr y {
  5422                                                                for  ( long rol eId : User LocalServi ceUtil.get User( work ItemStep.g etUserId()  ).getRole Ids() ){
  5423                                                                         if ( C Action.can DoCaret( s c.getCompa nyId(), CA ction.Care tCan.CSC_F UNCTION, r oleId) ){
  5424                                                                                  workItem .setUserId ( workItem Step.getUs erId() );
  5425                                                                         }
  5426                                                                }
  5427                                                       }  catch (Sys temExcepti on e) {
  5428                                                                e.pr intStackTr ace();
  5429                                                       }  catch (Por talExcepti on e) {
  5430                                                                e.pr intStackTr ace();
  5431                                                       }
  5432                                               }
  5433                                      } else {
  5434                                               if ( workI tem.getQue ueId() !=  nextQueue. getQueueId () ){
  5435                                                       Da shboardCon fig config  = (Dashbo ardConfig)  request.g etPortletS ession().g etAttribut e( CaretSt rPool.DASH BOARD_CONF IG);
  5436                                                       if  ( config. getQueueId s().indexO f( String. valueOf( n extQueue.g etQueueId( ) ) ) == - 1 ){
  5437                                                                work Item.setUs erId(0);
  5438                                                       }
  5439                                               }
  5440                                               noteGrpId  = NoteSupp ort.NoteGr oup.OCC_RE VIEW_1.gro upId();
  5441                                               boolean ch angeStatus  = true;
  5442                                               if ( nextQ ueue.getQu eueId() ==  -1 ){
  5443                                                       if  ( OwnerQu eue.CORREC TION_Q.nam e().equals ( workItem .getStatus () ) ){
  5444  
  5445                                                                if (  queAction .getWorkMa rkation(). isEmpty()  ){
  5446                                                                         change Status = f alse;
  5447                                                                }
  5448                                                                
  5449                                                                if (  sc.getUse rId() != w orkUserId  ){//change  back to l ast OCC us er
  5450                                                                         for (  WorSe work ItemStep:  WorSeLocal ServiceUti l.getByWor kId( workI tem.getWor ImId() ) ) {
  5451                                                                                  try {
  5452                                                                                           for ( long  roleId :  UserLocalS erviceUtil .getUser(  workItemSt ep.getUser Id() ).get RoleIds()  ){
  5453                                                                                                   if  ( CAction .canDoCare t( sc.getC ompanyId() , CAction. CaretCan.C BOPC_FUNCT ION, roleI d) ){
  5454                                                                                                            work Item.setUs erId( work ItemStep.g etUserId()  );
  5455                                                                                                   }
  5456                                                                                           }
  5457                                                                                  } catch  (SystemExc eption e)  {
  5458                                                                                           e.printSta ckTrace();
  5459                                                                                  } catch  (PortalExc eption e)  {
  5460                                                                                           e.printSta ckTrace();
  5461                                                                                  }
  5462                                                                         }
  5463                                                                }
  5464                                                                work Item.setQu eueId( Own erQueue.RE VIEW_Q.que ueId );
  5465                                                       }
  5466                                               } else {
  5467                                                       wo rkItem.set QueueId( n extQueue.g etQueueId( ) );
  5468                                                       if  ( workIte m.getQueue Id() == Ow nerQueue.V ERIFIED_CO MPLETED_Q. queueId ){
  5469   //                                                           work Item.setCa lculationI nfoCalenda r( Stipend Config.get Payday( Ca lendar.get Instance()  ) );
  5470                                                                work ItemStepCr eated = wo rkItem.cal cInfoVerif ied( sc );
  5471                                                       }  else if (  QueAction. REVOKE_COM PLETE.name ().equals(  workImSta tus ) ){
  5472                                                                work Item.calcI nfoRevoked  ( sc );
  5473                                                       }  else if (  (workItem. getQueueId () == Owne rQueue.VEN DOR_Q.queu eId && Que Action.REV IEW_VENDOR .name().eq uals( work ImStatus ) ) ||
  5474                                                                ( wo rkItem.get QueueId()  == OwnerQu eue.VERIFY _Q.queueId  && QueAct ion.REVIEW _VENDORIZA TION_COMPL ETE.name() .equals( w orkImStatu s ) ) ){
  5475                                                                Dash boardConfi g dashConf ig = (Dash boardConfi g) request .getPortle tSession() .getAttrib ute( Caret StrPool.DA SHBOARD_CO NFIG);
  5476                                                                work Item.verif yVendor( s c, dashCon fig.getQue ueIds() );
  5477                                                       }
  5478                                               }
  5479                                               if ( workU serId != s c.getUserI d() ) {
  5480                                                       ch eckContext ( request,  actionRes ponse, wor kItem.getV cgId() );
  5481                                                       _l og.error(" System blo cked OCC p rocess ste p for non- owner of w ork item") ;
  5482                                                       re turn;
  5483                                               }
  5484                                              
  5485                                               if ( chang eStatus ){
  5486                                                       if  ( queActi on.getWork Markation( ).isEmpty( ) ){
  5487                                                                work Item.setSt atus( work ImStatus ) ;
  5488                                                       }  else {
  5489                                                                work Item.setSt atus( queA ction.getW orkMarkati on() );
  5490                                                       }
  5491                                               }
  5492                                               OwnerQueue  oq = Owne rQueue.get OwnerQue(w orkItem.ge tQueueId() );
  5493                                               if ( oq !=  null && o q == Owner Queue.VERI FIED_COMPL ETED_Q ) {
  5494                                                       wo rkItem.che ckChampVaT ype();
  5495                                                       
  5496                                                       wo rkItem.set Completion By( sc.get UserId() ) ;
  5497                                                       wo rkItem.set Completion Date( sc.g etCreateDa te() );
  5498                                               }
  5499                                      }
  5500                                      
  5501                                      String c omment = P aramUtil.g et(request , CaretStr Pool.WORK_ COMMENT, S tringPool. BLANK );
  5502                                      Note not e = CaretU til.create Note( sc.g etCreateDa te(), prim Key, noteG rpId, sc.g etUserId() , comment) ;
  5503                                      workItem .useNote(  "ReviewNot e", note ) ;
  5504                                      CaretLoc alServiceU til.save(  workItem ) ;
  5505                                      if ( !wo rkItemStep Created ){
  5506                                               WorSe work ItemStep =  new WorSe Impl();
  5507                                               workItemSt ep.setWorI mId( workI tem.getWor ImId() );
  5508                                               workItemSt ep.setCrea tionDate(  sc.getCrea teDate() ) ;
  5509                                               workItemSt ep.setUser Id( sc.get UserId() ) ;
  5510                                               int count  = WorSeLoc alServiceU til.getCou nt ( workI tem.getWor ImId() );
  5511                                               workItemSt ep.setStep ( (count <  10? "0":S tringPool. BLANK) + c ount + Str ingPool.CO LON + work Item.getTy pe() + Str ingPool.CO LON + work Item.getSt atus() );
  5512                                               workItemSt ep.setStep Number(cou nt+1);
  5513                                               CaretLocal ServiceUti l.save( wo rkItemStep  );
  5514                                      }
  5515                                      checkCon text( requ est, actio nResponse,  workItem. getVcgId()  );
  5516                             } catc h (PortalE xception e ) {
  5517                                      Applicat ionWorkFlo wException .handleExc eption(e);
  5518                             } catc h (SystemE xception e ) {
  5519                                      Applicat ionWorkFlo wException .handleExc eption(e);
  5520                             }
  5521                    }
  5522           }
  5523           
  5524           pu blic void  reviewAppD elay ( Act ionRequest  request,  ActionResp onse actio nResponse  ){
  5525                    
  5526                    if (  !CAction. canDoCaret (request,  CAction.Ca retCan.VIS N_CSC_WAIV ER_Q ) ) {
  5527                             _log.w arn("permi ssioning.. . ");
  5528                             return ;
  5529                    }
  5530                    
  5531                    long  primKey =  ParamUtil .getLong(r equest, Ca retStrPool .WORK_ID);
  5532                    Stri ng workImS tatus = Pa ramUtil.ge t(request,  "worIm_st atus", Str ingPool.BL ANK);
  5533                    if (  primKey >  0 && ! To olbox.isEm pty(workIm Status) &&  CAction.c anDoCaret( request, C Action.Car etCan.CREA TE_VACO_WA IVER) ){
  5534                             try {
  5535                                      ServiceC ontext sc  = CaretPar am.setCare tServiceCo ntext(requ est);
  5536  
  5537                                      WorkItem Support wo rkItem = n ew WorkIte mSupport(  WorImLocal ServiceUti l.getWorIm (primKey)  );
  5538  
  5539                                      if ( wor kImStatus. equals( Ca retStrPool .COMPLETE  ) && 
  5540                                                       wo rkItem.get WorkType()  == WorkTy pe.APP_DEL AY && 
  5541                                                       wo rkItem.get CreateId()  == sc.get UserId() ) {
  5542                                               _log.warn( "App Delay  Cannot mo ve to comp lete by cr eator of w ork item") ;
  5543                                               return;
  5544                                      }
  5545  
  5546                                      workItem .setStatus ( workImSt atus );
  5547  
  5548                                      String n oteAtt = " ReviewNote ";
  5549                                      VcgSuppo rt vcg = V cgSupport. getVcgSupp ort( workI tem.getVcg Id() );
  5550                                      String c omment = P aramUtil.g et(request , CaretStr Pool.WORK_ COMMENT, S tringPool. BLANK );
  5551                                      vcg.setN ote(noteAt t, comment , sc.getUs erId(), sc .getCreate Date(), No teSupport. NoteGroup. DELAY_REVI EWED.group Id());
  5552                                      CaretLoc alServiceU til.save(  vcg );
  5553                                      
  5554                                      if ( !wo rkImStatus .equals( C aretStrPoo l.IN_PROCE SS ) ){
  5555                                               workItem.s etCompleti onBy(Porta lUtil.getU serId(requ est) );
  5556                                               workItem.s etCompleti onDate( sc .getCreate Date() );
  5557                                               Waivr waiv er = Waivr LocalServi ceUtil.get ByOwner( w orkItem.ge tApplicati onId(), wo rkItem.get CaregiverI d() );
  5558                                               waiver.set Completion Date( sc.g etCreateDa te() );
  5559                                               waiver.set Adjudicati on( workIm Status );
  5560                                               CaretLocal ServiceUti l.save( wa iver );
  5561                                              
  5562                                               VcgAn vcgA n = vcg.ge tPersonVcg An( workIt em.getCare giverId()  );
  5563                                               WorkItemSu pport work AppDelay =   new Work ItemSuppor t(CaretUti l.createWo rkItem(sc,  workItem. getGroupId (), vcgAn,  WorkType. DELAY_REVI EWED, work Item.getPe rsnId(), w orkItem.ge tCaregiver Id()));
  5564                                               workAppDel ay.setVcgI d( vcg.get VcgId() );
  5565   //                                          workAppDel ay.setQueI d( waiver. getUserId( ) );
  5566                                              
  5567                                               workAppDel ay.useNote (noteAtt,  vcg.getNot e(noteAtt) );
  5568                                               CaretLocal ServiceUti l.save(wor kAppDelay) ;
  5569                                      }
  5570                                      workItem .useNote(n oteAtt, vc g.getNote( noteAtt) ) ;
  5571                                      CaretLoc alServiceU til.save(  workItem ) ;
  5572                                      checkCon text( requ est, actio nResponse,  workItem. getVcgId()  );
  5573                             } catc h (PortalE xception e ) {
  5574                                      Applicat ionWorkFlo wException .handleExc eption(e);
  5575                             } catc h (SystemE xception e ) {
  5576                                      Applicat ionWorkFlo wException .handleExc eption(e);
  5577                             } 
  5578                    }                 
  5579           }
  5580           
  5581           
  5582           
  5583           pu blic void  updateVcgA nStatus (  WorIm work Item ){
  5584                    
  5585                    try{
  5586                             String [] types =  PortletPr ops.get(Ca retStrPool .APP_TYPES ).split(St ringPool.C OMMA);
  5587                             
  5588                             boolea n updateSt atus = fal se;
  5589                             for (S tring appT ype: types ) { 
  5590                                      if(workI tem.getTyp e().equals (appType))
  5591                                      {
  5592                                       updateS tatus = tr ue;
  5593                                 }
  5594                             }
  5595                             
  5596                             if(upd ateStatus)
  5597                             {        
  5598                                      long vcg AnId = wor kItem.getC lassPk();
  5599                                      VcgAn vc gAn = VcgA nLocalServ iceUtil.ge tVcgAn(vcg AnId);
  5600                                      vcgAn.se tStatus(Ap plicationS tatus.IN_R EVIEW.name ());
  5601                                      VcgAnLoc alServiceU til.update VcgAn(vcgA n);
  5602                             }
  5603                             
  5604                    } ca tch (Porta lException  e) {
  5605                             Applic ationWorkF lowExcepti on.handleE xception(e );
  5606                    } ca tch (Syste mException  e) {
  5607                             Applic ationWorkF lowExcepti on.handleE xception(e );
  5608                    }                 
  5609           }
  5610  
  5611           
  5612           pu blic void  facilTrans fer ( Acti onRequest  request, A ctionRespo nse action Response ) {
  5613                    
  5614                    Stri ng tracker  = ParamUt il.getStri ng(request , CaretStr Pool.TRACK ER, String Pool.BLANK  );
  5615                    if (  ! CaretPa ram.isTrac ked( reque st, tracke r, true )  ){
  5616                             _log.w arn("TRACK ER BLOCKIN G action.. . ");
  5617                             reques t.setAttri bute(Caret StrPool.IN VALID_REQU EST, true) ;
  5618                             return ;
  5619                    }
  5620                    if (  !CAction. canDoCaret (request,  CAction.Ca retCan.UPD ATE_ACTIVE _VCG_FACIL ITY)  ) {
  5621                             _log.w arn("permi ssioning.. . ");
  5622                             return ;
  5623                    }
  5624                    
  5625                    long  primKey =  ParamUtil .getLong(r equest, Ca retStrPool .VCGID);
  5626                    long  groupId =  ParamUtil .getLong(r equest, "t ransfer_gr oupId");
  5627                    Serv iceContext  sc = Care tParam.set CaretServi ceContext( request);
  5628                    if (  primKey >  0 ) {
  5629                             VcgSup port vcg;
  5630                             try {
  5631                                      vcg = ne w VcgSuppo rt( VcgLoc alServiceU til.getVcg (primKey)  );
  5632                                      if ( vcg .getTransf erId() > 0  ) {
  5633                                               _log.error ("One tran sfer-to-Fa cility req uest per V CG allowed ");
  5634                                               return;
  5635                                      }
  5636                                      if ( vcg .getGroupI d() == gro upId ) {
  5637                                               _log.warn( "Cannot tr ansfer to  own facili ty.");
  5638                                               return;
  5639                                      }
  5640                                      WorkItem Support wo rkItem = n ew WorkIte mSupport( 
  5641                                                       Ca retUtil.cr eateWorkIt em ( sc, v cg.getGrou pId(), vcg , WorkType .VCG_TRANS FER, vcg.g etVeteranI d(), vcg.g etWorkCare giverId()  ) );
  5642                                      vcg.setT ransferId(  groupId ) ;
  5643                                      workItem .setQueId(  groupId ) ;
  5644                                      workItem .setVcgId(  vcg.getVc gId() );
  5645                                      workItem .setQueueI d( OwnerQu eue.TRANSF ER_COMPLET ED_WORK.qu eueId );
  5646                                      CaretLoc alServiceU til.save(  workItem ) ;
  5647                                      Note not e = CaretU til.create Note( sc.g etCreateDa te(), work Item.getWo rImId(), N oteSupport .NoteGroup .TRANSFER. groupId(),  sc.getUse rId(), Par amUtil.get (request,  CaretStrPo ol.WORK_CO MMENT, Str ingPool.BL ANK ));
  5648                                      note.set VcgId( vcg .getVcgId( ) );
  5649                                      workItem .useNote(" transferRe ason", not e);
  5650                                      CaretLoc alServiceU til.save(  workItem ) ;
  5651                                      checkCon text( requ est, actio nResponse,  workItem. getVcgId()  );
  5652                             } catc h (PortalE xception |  SystemExc eption e)  {
  5653                                      e.printS tackTrace( );
  5654                             }
  5655                    } el se {
  5656                             primKe y = ParamU til.getLon g(request,  CaretStrP ool.WORK_I D);
  5657                             if ( p rimKey > 0  && groupI d > 0 ){
  5658                                      try {
  5659                                               WorkItemSu pport work Item = new  WorkItemS upport( Wo rImLocalSe rviceUtil. getWorIm(p rimKey) );
  5660                                               workItem.s etQueId(gr oupId);
  5661                                               workItem.s etQueueId(  OwnerQueu e.TRANSFER _COMPLETED _WORK.queu eId );
  5662                                               workItem.s etNote("tr ansferReas on", Param Util.get(r equest, Ca retStrPool .WORK_COMM ENT, Strin gPool.BLAN K ),
  5663                                                                sc.g etUserId() , sc.getCr eateDate() , NoteSupp ort.NoteGr oup.TRANSF ER.groupId () );
  5664                                               CaretLocal ServiceUti l.save( wo rkItem );
  5665                                               checkConte xt( reques t, actionR esponse, w orkItem.ge tVcgId() ) ;
  5666                                      } catch  (PortalExc eption e)  {
  5667                                               Applicatio nWorkFlowE xception.h andleExcep tion(e);
  5668                                      } catch  (SystemExc eption e)  {
  5669                                               Applicatio nWorkFlowE xception.h andleExcep tion(e);
  5670                                      } 
  5671                             }//aud it log to  contain
  5672                             //reas on for tra nsfer and  date trans fer accept ed
  5673                    }
  5674           }
  5675           
  5676           pu blic void  transferCa ncel ( Act ionRequest  request,  ActionResp onse actio nResponse  ) throws P ortalExcep tion, Syst emExceptio n{
  5677                    comp leteTransf er ( reque st, action Response,  "Cancel Tr ansfer", f alse );
  5678           }
  5679           
  5680           pu blic void  acceptTran sfer ( Act ionRequest  request,  ActionResp onse actio nResponse  ) throws P ortalExcep tion, Syst emExceptio n{
  5681                    comp leteTransf er ( reque st, action Response,  ParamUtil. get(reques t, CaretSt rPool.WORK _COMMENT,  StringPool .BLANK ),  ParamUtil. getBoolean (request,  "transfer" ) );
  5682           }
  5683           
  5684           pu blic void  transferTo Mine ( Act ionRequest  request,  ActionResp onse actio nResponse  ) throws P ortalExcep tion, Syst emExceptio n{
  5685                    Stri ng tracker  = ParamUt il.getStri ng(request , CaretStr Pool.TRACK ER, String Pool.BLANK  );
  5686                    if (  ! CaretPa ram.isTrac ked( reque st, tracke r, true )  ){
  5687                             _log.w arn("TRACK ER BLOCKIN G action.. . ");
  5688                             reques t.setAttri bute(Caret StrPool.IN VALID_REQU EST, true) ;
  5689                             return ;
  5690                    }
  5691                    if (  !CAction. canDoCaret (request,  CAction.Ca retCan.UPD ATE_ACTIVE _VCG_FACIL ITY)  ) {
  5692                             _log.w arn("permi ssioning.. . ");
  5693                             return ;
  5694                    }
  5695                    long  vcgId = P aramUtil.g etLong(req uest, Care tStrPool.V CGID );
  5696                    long  groupId =  ParamUtil .getLong(r equest, Ca retStrPool .GROUP_ID  );
  5697                    if (  vcgId > 0  ){
  5698                             Servic eContext s c = CaretP aram.setCa retService Context(re quest);
  5699                             WorIm  worIm = Wo rImLocalSe rviceUtil. getLastWor k( vcgId,  WorkType.V CG_TRANSFE R_SOUGHT.n ame(), gro upId );
  5700                             if ( w orIm == nu ll || !Wor kStatus.NE W.name().e quals( wor Im.getStat us() ) ) {
  5701                                      VcgSuppo rt vcg = n ew VcgSupp ort( VcgLo calService Util.getVc g(vcgId) ) ;
  5702                                      WorkItem Support wo rkItem = n ew WorkIte mSupport(  CaretUtil. createWork Item( sc,  groupId, v cg, WorkTy pe.VCG_TRA NSFER_SOUG HT, vcg.ge tVeteranId (), vcg.ge tWorkCareg iverId() )  );
  5703                                      workItem .setVcgId( vcg.getVcg Id());
  5704                                      workItem .setQueueI d(OwnerQue ue.TRANSFE R_COMPLETE D_WORK.que ueId);
  5705                                      workItem .setQueId(  ParamUtil .getLong(r equest, "f orm_transf erMineGrou p") );
  5706                                      workItem .setGroupI d(vcg.getG roupId());
  5707                                      workItem .setNote(" transferRe ason", Par amUtil.get (request,  "transfer_ comments",  StringPoo l.BLANK ),
  5708                                                       sc .getUserId (), sc.get CreateDate (), NoteSu pport.Note Group.TRAN SFER.group Id() );
  5709                                      CaretLoc alServiceU til.save(  workItem ) ;
  5710                             } else  {
  5711                                      _log.war n("Transfe r already  requested  for this f acility... ");
  5712                             }
  5713                    }
  5714           }
  5715           
  5716           pu blic void  completeTr ansfer ( A ctionReque st request , ActionRe sponse act ionRespons e, String  comment, b oolean acc ept ) thro ws PortalE xception,  SystemExce ption{
  5717                    Stri ng tracker  = ParamUt il.getStri ng(request , CaretStr Pool.TRACK ER, String Pool.BLANK  );
  5718                    if (  ! CaretPa ram.isTrac ked( reque st, tracke r, true )  ){
  5719                             _log.w arn("TRACK ER BLOCKIN G action.. . ");
  5720                             reques t.setAttri bute(Caret StrPool.IN VALID_REQU EST, true) ;
  5721                             return ;
  5722                    }
  5723                    if (  !CAction. canDoCaret (request,  CAction.Ca retCan.UPD ATE_ACTIVE _VCG_FACIL ITY)  ) {
  5724                             _log.w arn("permi ssioning.. . ");
  5725                             return ;
  5726                    }
  5727                    long  primKey =  ParamUtil .getLong(r equest, Ca retStrPool .VCGID);
  5728                    Serv iceContext  sc = Care tParam.set CaretServi ceContext( request);
  5729                    
  5730                    if (  primKey >  0 ){
  5731  
  5732                             VcgSup port vcg =  new VcgSu pport( Vcg LocalServi ceUtil.get Vcg(primKe y) );
  5733                             if ( a ccept ){
  5734                                      if ( Car etUtil.get VhaOrgList ( request  ).contains Key( vcg.g etTransfer Id() ) ){
  5735                                               vcg.setGro upId( vcg. getTransfe rId() );
  5736                                               vcg.setTra nsferId(0) ;
  5737                                      }
  5738                                      WorIm wo rkItem = W orImLocalS erviceUtil .getLastWo rk( primKe y, WorkTyp e.VCG_TRAN SFER.name( ) );
  5739                                      workItem .setGroupI d( workIte m.getQueId () );
  5740                                      workItem .setQueId( 0);
  5741                                      workItem .setQueueI d(0);
  5742                                      workItem .setStatus (WorkStatu s.COMPLETE .name());
  5743                                      workItem .setComple tionDate(s c.getCreat eDate());
  5744                                      workItem .setComple tionBy(sc. getUserId( ));
  5745                                      CaretLoc alServiceU til.save(  workItem ) ;
  5746                                      transfer VcgWorkIte ms( workIt em, accept , sc );
  5747                             } else  {
  5748                                      vcg.setT ransferId( 0);
  5749                             }
  5750                             if ( v cg.getLast UpdatedUse rId() != P ortalUtil. getUserId( request) ) {
  5751                                      vcg.setL astUpdated UserId(0);
  5752                             }
  5753                             Persn  veteran =  PersnLocal ServiceUti l.getPersn ( vcg.getV eteranId()  );
  5754                             if ( v cg.getGrou pId() != v eteran.get GroupId()  ){
  5755                                      veteran. setGroupId ( vcg.getG roupId() ) ;
  5756                                      CaretLoc alServiceU til.save(  veteran );
  5757                             }
  5758                             vcg.se tNote("tra nsferRespo nse", comm ent,
  5759                                               sc.getUser Id(), sc.g etCreateDa te(), Note Support.No teGroup.TR ANSFER.gro upId() );
  5760                             CaretL ocalServic eUtil.save ( vcg );
  5761                             checkC ontext( re quest, act ionRespons e, primKey  );
  5762                             
  5763                    } el se {
  5764                             primKe y = ParamU til.getLon g(request,  CaretStrP ool.WORK_I D);
  5765                             if ( p rimKey > 0  ){
  5766                                      WorkItem Support wo rkItem = n ew WorkIte mSupport(  WorImLocal ServiceUti l.getWorIm (primKey)  );
  5767                                      long tar getId = wo rkItem.get QueId();
  5768                                      workItem .setQueId( 0);
  5769                                      if ( acc ept ){
  5770                                               if ( workI tem.getQue ueId() ==  OwnerQueue .TRANSFER_ COMPLETED_ WORK.queue Id ){
  5771                                                       if  ( workIte m.getUserI d() != Por talUtil.ge tUserId(re quest) ){
  5772                                                                work Item.setUs erId(0);
  5773                                                       }
  5774                                               }
  5775                                               workItem.s etGroupId(  targetId  );
  5776                                               if ( workI tem.getVcg Id() > 0 ) {
  5777                                                       tr ansferVcgW orkItems(  workItem,  accept, sc  );
  5778                                               }
  5779                                      }
  5780                                      workItem .setQueueI d(0);
  5781                                      
  5782                                      if ( wor kItem.getT ype().star tsWith("VC G_TRANSFER ") ) {
  5783                                               workItem.s etStatus(  WorkStatus .COMPLETE. name() );
  5784                                               workItem.s etCompleti onDate( sc .getCreate Date() );
  5785                                               workItem.s etCompleti onBy( sc.g etUserId()  );
  5786                                      }
  5787                                      Persn ve teran = Pe rsnLocalSe rviceUtil. getPersn(  workItem.g etPersnId( ) );
  5788                                      if ( acc ept && wor kItem.getG roupId() ! = veteran. getGroupId () ){
  5789                                               veteran.se tGroupId(  workItem.g etGroupId( ) );
  5790                                               CaretLocal ServiceUti l.save( ve teran );
  5791                                      }
  5792                                      workItem .setNote(" transferRe sponse", c omment,
  5793                                                       sc .getUserId (), sc.get CreateDate (), NoteSu pport.Note Group.TRAN SFER.group Id() );
  5794                                      CaretLoc alServiceU til.save(  workItem ) ;
  5795                                      checkCon text( requ est, actio nResponse,  workItem. getVcgId()  );
  5796                             }
  5797                    }
  5798                    
  5799           }
  5800  
  5801           
  5802           pr ivate void  transferV cgWorkItem s ( WorIm  workItem,  boolean ac cept, Serv iceContext  sc ) thro ws Applica tionWorkFl owExceptio n {
  5803                    
  5804                    for  ( WorIm wo rIm : WorI mLocalServ iceUtil.fi ndByVcgId(  workItem. getVcgId()  ) ){
  5805                             if ( w orIm.getWo rImId() ==  workItem. getWorImId () ) conti nue;
  5806                             //work Types.cont ains(worIm .getType() ) && ( wor Im.getQueI d() > 0 ||
  5807                             if ( a ccept && w orIm.getGr oupId() !=  workItem. getGroupId () ) {
  5808                                      if ( acc ept ){
  5809                                               if (worIm. getQueueId () == Owne rQueue.TRA NSFER_COMP LETED_WORK .queueId){
  5810                                                       wo rIm.setQue ueId(0);
  5811                                               }
  5812                                               worIm.setG roupId( wo rkItem.get GroupId()  );
  5813                                               worIm.setU serId(0);
  5814   //Should w e prevent  the transf er/overwri te of comp eting to a nother Fac ility requ est?
  5815                                               worIm.setQ ueId( 0 );
  5816                                               if ( worIm .getType() .startsWit h("VCG_TRA NSFER") )  {
  5817                                                       wo rIm.setCom pletionDat e(sc.getCr eateDate() );
  5818                                                       wo rIm.setCom pletionBy( sc.getUser Id());
  5819                                               }
  5820                                              
  5821                                      }
  5822                                      CaretLoc alServiceU til.save(  worIm );
  5823                             }
  5824                    }
  5825                    if (  accept &&  workItem. getVcgId()  > 0 ){
  5826                             try {
  5827                                      Vcg vcg  = VcgLocal ServiceUti l.getVcg(  workItem.g etVcgId()  );
  5828                                      vcg.setG roupId( wo rkItem.get GroupId()  );
  5829                                      vcg.setT ransferId( 0);
  5830                                      CaretLoc alServiceU til.save(v cg);
  5831                             } catc h (PortalE xception |  SystemExc eption e)  {
  5832                                      throw ne w Applicat ionWorkFlo wException (e);
  5833                             }
  5834                    }
  5835                    
  5836           }
  5837           
  5838           
  5839  
  5840           @P rocessActi on (name=" createEntr y")
  5841           pu blic void  createEntr y( ActionR equest act ionRequest , ActionRe sponse act ionRespons e ) {
  5842                    
  5843                    if (  !CAction. canDoCaret ( actionRe quest, CAc tion.Caret Can.CREATE _APPLICATI ONS ) ) {
  5844                             _log.w arn("permi ssioning.. . ");
  5845                             return ;
  5846                    }
  5847                    
  5848                    Stri ng entry =  ParamUtil .get(actio nRequest,  "entry", S tringPool. BLANK);
  5849                    _log .info("cre ateEntry.. ." +  entr y );
  5850                    
  5851                    acti onRequest. setAttribu te( CaretS trPool.TRA CKER, Care tParam.tra ckNdx( act ionRequest  ) );
  5852                    Resu ltMap.getC aretMap(ac tionReques t).put("ge nderTypes" , PortletP rops.get(" persn.gend er.types") .split(Str ingPool.CO MMA) ) ;
  5853   //               load StatesAndF acilities(  actionReq uest );
  5854                    try  {
  5855                             Result Map.getCar etMap(acti onRequest) .put(Caret StrPool.ST ATES, Regi onServiceU til.getReg ions( Coun tryConstan ts.DEFAULT _COUNTRY_I D ) );
  5856                             Result Map.getCar etMap(acti onRequest) .put(Caret StrPool.CO UNTRIES, C aretUtil.g etCountryM ap() );
  5857                    } ca tch (Syste mException  e) {
  5858                             Applic ationWorkF lowExcepti on.handleE xception(e );
  5859                    }
  5860                    try  {
  5861                             Result Map.getCar etMap( act ionRequest  ).put( Ca retStrPool .VHA_MEMBE R, CaretUt il.getVhaO rgList( ac tionReques t ) );
  5862                    } ca tch (Appli cationWork FlowExcept ion e1) {
  5863                             e1.pri ntStackTra ce();
  5864                    }
  5865                    load Relationsh ipLists( a ctionReque st );
  5866                    
  5867                    acti onRequest. setAttribu te("isDisa bled", tru e);
  5868                    
  5869                    Map< String,Obj ect> form  = ResultMa p.getForm  (actionReq uest);
  5870                    Care tViewContr oller cont roller = C aretViewCo ntroller.g etViewCont roller();
  5871                    cont roller.loa dRequiredI nputs( Car etStrPool. VETERAN_PE RSN, form  );
  5872                    cont roller.loa dRequiredI nputs( Car etStrPool. PRIMARY_PE RSN, form  );
  5873                    cont roller.loa dRequiredI nputs( Car etStrPool. SECONDARY_ PERSN, for m );
  5874                    cont roller.loa dRequiredI nputs( Car etStrPool. SECONDARY_ TWO_PERSN,  form );
  5875  
  5876                    try  {
  5877                             String   extensio ns = Strin gUtil.merg e(PrefsPro psUtil.get StringArra y(PropsKey s.DL_FILE_ EXTENSIONS , StringPo ol.COMMA)) ;
  5878                             long m axSize = L ong.parseL ong(PrefsP ropsUtil.g etString(P ropsKeys.D L_FILE_MAX _SIZE)) /  1024;
  5879                             //_log .info("ext ensions =  " + extens ions + ",  maxSize="  + maxSize  );
  5880                             form.p ut("extens ions",  ex tensions ) ;
  5881                             form.p ut("maxSiz e",  maxSi ze );
  5882                    } ca tch (Syste mException  e) {
  5883                             Applic ationWorkF lowExcepti on.handleE xception(e );
  5884                    }
  5885  
  5886                    acti onResponse .setRender Parameter( CaretStrPo ol.MVC_PAT H, CaretSt rPool.CREA TE_APPLICA TION_PAGE) ;
  5887           }
  5888           
  5889           
  5890           pu blic void  loadRelati onshipList s ( Portle tRequest r equest ) {
  5891                    Care tViewContr oller.getV iewControl ler().load Relationsh ipLists(re quest);
  5892           }
  5893           
  5894           @P rocessActi on (name=" uploadTemp File")
  5895           pu blic void  uploadTemp File ( Act ionRequest  request,  ActionResp onse actio nResponse  ) throws F ileNotFoun dException {
  5896                    
  5897                    if (  !CAction. canDoCaret ( request,  CAction.C aretCan.UP LOAD_FILE  ) ) {
  5898                             _log.w arn("permi ssioning.. . ");
  5899                             return ;
  5900                    }
  5901                    
  5902                    Uplo adPortletR equest upl oadRequest  = PortalU til.getUpl oadPortlet Request(re quest);
  5903                    Stri ng type =  ParamUtil. get(reques t, CaretSt rPool.TYPE , StringPo ol.BLANK);
  5904                    Stri ng name =  uploadRequ est.getFil eName(Care tStrPool.F ILE);
  5905                    File  uploadFil e = upload Request.ge tFile(Care tStrPool.F ILE);
  5906                    Stri ng tracker  = ParamUt il.getStri ng(request , CaretStr Pool.TRACK ER, String Pool.BLANK  );
  5907                    
  5908                    if (  ParamUtil .getBoolea n(request,  CaretStrP ool.REPLAC E ) ){
  5909                             remove File( requ est, actio nResponse  );
  5910                    }
  5911                    
  5912                    long  documId =  0;
  5913                    try  {
  5914                             documI d = Counte rLocalServ iceUtil.in crement( D ocum.class .getName()  );
  5915                    } ca tch (Syste mException  e1) {
  5916                             e1.pri ntStackTra ce();
  5917                    }
  5918                    Docu m document  = DocumLo calService Util.creat eDocum(doc umId);
  5919  
  5920                    Inpu tStream in putStream  = new File InputStrea m( uploadF ile );
  5921                    Outp utBlob out putBlob =  new Output Blob ( inp utStream,  uploadFile .length()  );
  5922                    
  5923                    docu ment.setDo cument(out putBlob);
  5924                    docu ment.setNo te( tracke r );
  5925                    docu ment.setTy pe( type ) ;
  5926                    docu ment.setNa me( name ) ;
  5927                    docu ment.setCl assId( Cla ssNameLoca lServiceUt il.getClas sNameId( D ummy.class ) );
  5928                    try  {
  5929                             DocumL ocalServic eUtil.addD ocum( docu ment );
  5930                             FileUt il.delete( uploadFile );
  5931                    } ca tch (Excep tion e) {
  5932                             Applic ationWorkF lowExcepti on.handleE xception(e );
  5933                    } fi nally {
  5934                             if (in putStream  != null) {
  5935                                      try {
  5936                                               inputStrea m.close();
  5937                                      } catch  (IOExcepti on e) {
  5938                                               Applicatio nWorkFlowE xception.h andleExcep tion(e);
  5939                                      }
  5940                             }
  5941                    }
  5942           }
  5943           
  5944           @P rocessActi on (name=" removeFile ")
  5945           pu blic void  removeFile  ( ActionR equest req uest, Acti onResponse  actionRes ponse ) th rows FileN otFoundExc eption{
  5946                    
  5947                    if (  !( ( CAct ion.canDoC aret( requ est, CActi on.CaretCa n.UPLOAD_F ILE ) && P aramUtil.g etBoolean( request, C aretStrPoo l.REPLACE  ) ) ||
  5948                                      CAction. canDoCaret ( request,  CAction.C aretCan.DE LETE_FILE  ) ) ) {
  5949                             _log.w arn("permi ssioning.. . ");
  5950                             return ;
  5951                    }
  5952                    
  5953                    Stri ng tracker Note = req uest.getPa rameter(Ca retStrPool .TRACKER);
  5954                    Stri ng type =  request.ge tParameter ( CaretStr Pool.TYPE  );
  5955                    Stri ng name =  request.ge tParameter ("fileName ");
  5956                    requ est.setAtt ribute(Car etStrPool. MVC_PATH,  CaretStrPo ol.METADAT A);
  5957                    try  {
  5958                             for (  Docum toDe lete : Doc umLocalSer viceUtil.g etByTracke rNote( tra ckerNote,  type ) ){
  5959                                      if ( toD elete.getC lassPk() = = 0 && ( P aramUtil.g etBoolean( request, C aretStrPoo l.REPLACE  ) || name. equals(toD elete.getN ame()) ) ) {
  5960                                               DocumLocal ServiceUti l.deleteDo cum(toDele te);
  5961                                               break;
  5962                                      }
  5963                             }
  5964                    } ca tch (Appli cationWork FlowExcept ion e) {
  5965                             e.prin tStackTrac e();
  5966                    } ca tch (Syste mException  e) {
  5967                             e.prin tStackTrac e();
  5968                    }
  5969           }
  5970           
  5971           @P rocessActi on (name=" uploadFile ")
  5972           pu blic void  uploadFile  ( ActionR equest req uest, Acti onResponse  actionRes ponse ) th rows FileN otFoundExc eption{
  5973                    
  5974                    if (  !CAction. canDoCaret ( request,  CAction.C aretCan.UP LOAD_FILE  ) ) {
  5975                             _log.w arn("permi ssioning.. . ");
  5976                             return ;
  5977                    }
  5978                    
  5979                    Uplo adPortletR equest upl oadRequest  = PortalU til.getUpl oadPortlet Request(re quest);
  5980                    
  5981                    Stri ng type =  ParamUtil. get(reques t, "type",  StringPoo l.BLANK);
  5982                    //_l og.info("f ile type i s : "+type );
  5983  
  5984                    
  5985                    long  size = up loadReques t.getSize( "file");
  5986                    //_l og.info("s ize=" + si ze );
  5987                    if (  size == 0  ){
  5988                             _log.i nfo("retur ning since  size is 0 ...");
  5989                             return ;
  5990                    }
  5991  
  5992                    File  uploadFil e = upload Request.ge tFile("fil e");
  5993                    Stri ng tempLoc ation = Pr opsUtil.ge t(CaretStr Pool.FILE_ TEMP_STORE );
  5994                    Stri ng name =  uploadRequ est.getFil eName("fil e");
  5995                    
  5996                    File  file = ne w File(tem pLocation  + name);
  5997                    try  {
  5998                             FileUt il.copyFil e( uploadF ile, file  );
  5999                    } ca tch (IOExc eption e)  {
  6000                             Applic ationWorkF lowExcepti on.handleE xception(e );
  6001                    }
  6002                    
  6003                    //_l og.info("p ath is ...  " + uploa dFile.getP ath() + ",  name=" +  name );
  6004                    //St ring fileP ath = "";
  6005                    //St ring fileN ame = "";
  6006                    if(C aretStrPoo l.TEN_TEN_ CG.equals( type) ){
  6007                             //file Path = Car etStrPool. FILE_PATH;
  6008                             //file Name = Car etStrPool. FILE_NAME;
  6009                             reques t.getPortl etSession( ).setAttri bute(Caret StrPool.FI LE_PATH, f ile.getPat h() );
  6010                             reques t.getPortl etSession( ).setAttri bute(Caret StrPool.FI LE_NAME, n ame);
  6011                    } el se if( Car etStrPool. POA.equals (type) ){
  6012                             //file Path = Car etStrPool. POA_FILE_P ATH;
  6013                             //file Name = Car etStrPool. POA_FILE_N AME;                          
  6014                             reques t.getPortl etSession( ).setAttri bute(Caret StrPool.PO A_FILE_PAT H, file.ge tPath() );
  6015                             reques t.getPortl etSession( ).setAttri bute(Caret StrPool.PO A_FILE_NAM E, name);
  6016                    } el se {
  6017                             reques t.getPortl etSession( ).setAttri bute(Caret StrPool.FI LE_PATH, f ile.getPat h() );
  6018                             reques t.getPortl etSession( ).setAttri bute(Caret StrPool.FI LE_NAME, n ame);
  6019                    }
  6020                    _log .info("pat h is ... "  + file.ge tPath() +  ", name="  + name );
  6021           }
  6022  
  6023  
  6024           
  6025           @P rocessActi on (name=" cscWaiver" )
  6026           pu blic void  cscWaiver(  ActionReq uest actio nRequest,  ActionResp onse actio nResponse  ) {
  6027                    
  6028                    if (  !CAction. canDoCaret ( actionRe quest, CAc tion.Caret Can.CREATE _CSC_WAIVE R ) ) {
  6029                             _log.w arn("permi ssioning.. . ");
  6030                             return ;
  6031                    }
  6032                    
  6033                    _log .info("csc Waiver.... ");
  6034                    acti onRequest. setAttribu te( CaretS trPool.TRA CKER, Care tParam.tra ckNdx( act ionRequest  ));
  6035                    
  6036                    Stri ng workIte mId = Para mUtil.get( actionRequ est, "work ItemId", S tringPool. BLANK);
  6037                    Stri ng vcgAnId  = ParamUt il.get(act ionRequest , "vcgAnId ", StringP ool.BLANK) ;
  6038                    Stri ng receive dDate = Pa ramUtil.ge t(actionRe quest, "re ceivedDate ", StringP ool.BLANK) ;
  6039                    Stri ng daysPas sed = Para mUtil.get( actionRequ est, "days Passed", S tringPool. BLANK);
  6040                                      
  6041                    Map< String,Obj ect> form  = ResultMa p.getForm  (actionReq uest);
  6042                    form .put("work ItemId", w orkItemId) ;
  6043                    form .put("vcgA nId", vcgA nId);
  6044                    form .put("rece ivedDate",  receivedD ate);
  6045                    form .put("days Passed", d aysPassed) ;
  6046                    
  6047                    try  {
  6048                             long l oggedPersn Id = Caret Param.getP ersnId(act ionRequest );
  6049                             form.p ut("logged PersnId",  loggedPers nId );
  6050                    } ca tch (Appli cationWork FlowExcept ion e) {
  6051                             Applic ationWorkF lowExcepti on.handleE xception(e );
  6052                    }
  6053  
  6054                    acti onResponse .setRender Parameter( CaretStrPo ol.MVC_PAT H, CaretSt rPool.CSC_ WAIVER_PAG E);
  6055           }
  6056  
  6057           
  6058           pu blic void  saveCSCWai ver( Actio nRequest a ctionReque st) throws  Applicati onWorkFlow Exception  {
  6059                    if (  !CAction. canDoCaret ( actionRe quest, CAc tion.Caret Can.CREATE _CSC_WAIVE R ) ) {
  6060                             _log.w arn("permi ssioning.. . ");
  6061                             return ;
  6062                    }
  6063                    
  6064                    getO utput(acti onRequest) ;
  6065                    
  6066                    try  {
  6067                             Servic eContext s c = CaretP aram.setCa retService Context(ac tionReques t);
  6068                             Waivr  w = new Wa ivrImpl();
  6069                             Waivr  waiver = ( Waivr) Car etParam.lo adModel(ac tionReques t, new Wai vrImpl(),  w.getModel Attributes ().keySet( ), CaretSt rPool.WAIV ER_UNDERLI NE);
  6070                             waiver .setUserId ( PortalUt il.getUser Id( action Request )  );
  6071                             waiver .setCreati onDate(new  Date());
  6072                             
  6073                             CaretL ocalServic eUtil.save ( waiver ) ;
  6074                                                                                  
  6075                    } ca tch (Appli cationWork FlowExcept ion e) {
  6076                             Applic ationWorkF lowExcepti on.handleE xception(e );
  6077                    } 
  6078           }
  6079  
  6080           pu blic void  saveCSCApp ealOutcome ( ActionRe quest acti onRequest,  ActionRes ponse resp onse )  {
  6081                    if (  !CAction. canDoCaret ( actionRe quest, CAc tion.Caret Can.VISN_C SC_WAIVER_ Q ) ) {
  6082                             _log.w arn("permi ssioning.. . ");
  6083                             return ;
  6084                    }
  6085                    getO utput(acti onRequest) ;
  6086                    
  6087                    try  {
  6088                             Servic eContext s c = CaretP aram.setCa retService Context(ac tionReques t);
  6089                             Apeal  a = new Ap ealImpl();
  6090                             Apeal  apeal = (A peal) Care tParam.loa dModel(act ionRequest , new Apea lImpl(), a .getModelA ttributes( ).keySet() , CaretStr Pool.APPEA LED_UNDERL INE);
  6091                             apeal. setCreatio nDate(new  Date());
  6092                             
  6093                             CaretL ocalServic eUtil.save ( apeal );
  6094                             
  6095                             String  tracker =  ParamUtil .getString (actionReq uest, Care tStrPool.T RACKER, St ringPool.B LANK );
  6096                             List<D ocum> docu ments = Do cumLocalSe rviceUtil. getByTrack erNote( tr acker );
  6097                             for (  Docum docu m : docume nts ){
  6098                                      if ( doc um.getClas sPk() == 0  ){
  6099                                               docum.setC lassPk(ape al.getApea lId());
  6100                                               docum.setC lassId(Por talUtil.ge tClassName Id(Apeal.c lass));
  6101                                               docum.setN ote(String Pool.BLANK );
  6102                                               try {
  6103                                                       Do cumLocalSe rviceUtil. updateDocu m(docum);
  6104                                               } catch (S ystemExcep tion e) {
  6105                                                       e. printStack Trace();
  6106                                               }
  6107                                      }
  6108                             }
  6109                             
  6110                             
  6111                    } ca tch (Appli cationWork FlowExcept ion e) {
  6112                             Applic ationWorkF lowExcepti on.handleE xception(e );
  6113                    } 
  6114           }
  6115           
  6116           pr ivate void  createMan ualPayment ( ActionRe quest requ est, Actio nResponse  response)  throws Por talExcepti on, System Exception   {
  6117                                      
  6118                    if (  !CAction. canDoCaret (request,  CaretCan.M ANUAL_PAYM ENT) ) {
  6119                             throw  new System Exception( "Missing p ermissions ...");
  6120                    }
  6121  
  6122                    long  paymentLo gId = Para mUtil.getL ong(reques t, "paymen tLogId");
  6123                    long  worImId =  ParamUtil .getLong(r equest, "w orImId");
  6124                    
  6125                    if (  paymentLo gId == 0 & & worImId  == 0 ) {
  6126                             return ;
  6127                    }
  6128                    
  6129                    Serv iceContext  sc = Care tParam.set CaretServi ceContext( request);
  6130                    WorI m worIm =  WorImLocal ServiceUti l.getWorIm (worImId);
  6131                    Stri ng comment s = reques t.getParam eter("worI m_manualPa ymentReaso n");
  6132                    Cale ndar calen dar = Cale ndar.getIn stance();
  6133                    
  6134                    Doub le dollarA mount = nu ll;
  6135                    PayL g payLg =  PayLgLocal ServiceUti l.fetchPay Lg(payment LogId);
  6136                    if (  payLg !=  null ) {
  6137                             dollar Amount = p ayLg.getAm ount();
  6138                             calend ar.setTime ( payLg.ge tPaymentDa te() );
  6139                    } el se try {
  6140                             Object  dollarAmo untObj = N umberForma t.getCurre ncyInstanc e(Locale.g etDefault( )).parseOb ject(reque st.getPara meter("dol larAmount" ));
  6141                             dollar Amount = D ouble.valu eOf(dollar AmountObj. toString() );
  6142                             calend ar.set( Ca lendar.MON TH, ParamU til.getInt eger(reque st, "confi g_cycle_mo nth") );
  6143                             calend ar.set( Ca lendar.YEA R, ParamUt il.getInte ger(reques t, "config _cycle_yea r") );
  6144                             calend ar.set( Ca lendar.DAY _OF_MONTH,  1);
  6145                             calend ar.set( Ca lendar.HOU R_OF_DAY,  0);
  6146                             calend ar.set( Ca lendar.MIN UTE, 0);
  6147                    } ca tch (Parse Exception  e) {
  6148                             e.prin tStackTrac e();
  6149                    }
  6150                    
  6151                    long  vendrId =  ParamUtil .getLong(r equest, "v endrId");
  6152                    int  count = St iPtLocalSe rviceUtil. countByOne Time( vend rId, dolla rAmount.to String(),  calendar.g etTime() ) ;
  6153                    int  oneTimeCou nt = Param Util.getIn teger(requ est, "oneT imeCount") ;
  6154                    if (  count !=  oneTimeCou nt ) {
  6155                             _log.e rror("Coun t user acc epted does  not match  current s tate");
  6156                             return ;
  6157                    }
  6158                    
  6159                    Note  note = nu ll;
  6160   //               Date  eventDate  = Toolbox .parseDate (request.g etParamete r("checkDa te"));
  6161                    
  6162                    Stip endConfig  manualPayC onf = null ;
  6163                    Work ItemSuppor t workItem  = new Wor kItemSuppo rt(CaretUt il.createW orkItem( s c, worIm.g etGroupId( ), 
  6164                                      worIm.ge tClassId() , worIm.ge tClassPk() , worIm.ge tPersnId() , WorkType .MANUAL_PA YMENT.name (),
  6165                                      worIm.ge tCaregiver Id(), Tool box.adjust Date( Cbop cDashboard Config.OCC _DUE_DAYS,  sc.getCre ateDate(),  true) ) ) ;
  6166                    
  6167                    if (  payLg !=  null ) {
  6168                             StiPt  stiPt = ne w PaymentL og(payLg). getStipend Config();
  6169                             manual PayConf =  new Stipen dConfig( S tipendConf ig.getStip endConfig(  stiPt.get StipendSta rtDate(),  null, stiP t.getTierH ours(), st iPt.getBls RateHourly () ) );
  6170                             manual PayConf.se tVendrId(  stiPt.getV endrId() ) ;
  6171  
  6172                             payLg. setStatus(  "manual-p ayment-ver ified" );
  6173                             CaretL ocalServic eUtil.save ( payLg );
  6174                    } el se {
  6175                             manual PayConf =  new Stipen dConfig( n ew StiPtIm pl() );
  6176                             manual PayConf.se tStipendSt artDate( c alendar.ge tTime() );
  6177                             manual PayConf.se tVendrId(  vendrId );
  6178                    }
  6179                    manu alPayConf. setOneTime Payment( d ollarAmoun t.toString () );
  6180                    manu alPayConf. setStipend Type(Stipe ndConfig.O NE_TIME);
  6181                    manu alPayConf. setStipend ApprovedDa te( new Da te() );
  6182                    manu alPayConf. setVcgId(  worIm.getV cgId() );
  6183                    manu alPayConf. setStipend Status(Sti pendConfig .PAYMENT_F INANCE);
  6184  
  6185                    work Item.setQu eueId(Work Type.MANUA L_PAYMENT. workName.g etQueueId( ));
  6186                    work Item.setVc gId( worIm .getVcgId( ) );
  6187                    work Item.setSt atus("Edit ed, Approv ed");
  6188                    work Item.setCo mpletionDa te(sc.getC reateDate( ));
  6189                    work Item.setCo mpletionBy (sc.getUse rId());
  6190                    Care tLocalServ iceUtil.sa ve( workIt em );
  6191                    
  6192                    note  = CaretUt il.createN ote(sc.get CreateDate (), worIm. getClassPk (), NoteSu pport.Note Group.MANU AL_PAYMENT .groupId() , sc.getUs erId(), co mments);
  6193                    note .setVcgId( workItem.g etVcgId()) ;
  6194  
  6195                    WorS e workItem State = ne w WorSeImp l();
  6196                    work ItemState. setWorImId ( workItem .getWorImI d() );
  6197   //               long  ownerId =  Vendor.ge tPaymentSt ep( sc ).g etOwnerId( );
  6198   //               work ItemState. setStepNum ber( (int)  ownerId ) ;
  6199                    work ItemState. setCreatio nDate( cal endar.getT ime() );// stores the  Calendar  paymentMon thDate of  origin
  6200                    work ItemState. setStep(co mments.sub string(0,  Math.min(  comments.l ength(), W orkItemSup port.WORK_ ITEM_SUPPO RT_NOTE_LE NGTH ) ) ) ;
  6201                    Care tLocalServ iceUtil.sa ve( workIt emState );
  6202                    
  6203   //               manu alPayConf. setWorSeId ( ownerId  );
  6204                    manu alPayConf. setWorImId (workItem. getWorImId ());
  6205                    Care tLocalServ iceUtil.sa ve( manual PayConf );
  6206                    
  6207   //               for  ( StiPt pt  : StiPtLo calService Util.findB yOneTimeSt atus( manu alPayConf. getVendrId (), new St ring[] { S tipendConf ig.PAYMENT _FINANCE }  ) ){
  6208   //                        if ( p t.getWorSe Id() == wo rkItemStat e.getWorSe Id() ) con tinue;
  6209   //                        pt.set WorSeId( o wnerId );
  6210   //                        CaretL ocalServic eUtil.save ( manualPa yConf );
  6211   //               }
  6212                    
  6213                    Resu ltMap.getC aretMap(re quest).put ("tabConte xt", "sear ch" );
  6214                    Resu ltMap.getC aretMap(re quest).put ("lastSear ch", reque st.getPort letSession ().getAttr ibute("las tSearch")) ;
  6215           }
  6216           
  6217           pu blic void  stagePayme nts( Actio nRequest r equest, Ac tionRespon se respons e) throws  Applicatio nWorkFlowE xception,  SystemExce ption {
  6218                    
  6219                    Stri ng tracker  = ParamUt il.getStri ng(request , CaretStr Pool.TRACK ER, String Pool.BLANK  );
  6220                    if (  ! CaretPa ram.isTrac ked( reque st, tracke r, true )  ){
  6221                             _log.w arn("TRACK ER BLOCKIN G action.. . ");
  6222                             reques t.setAttri bute(Caret StrPool.IN VALID_REQU EST, true) ;
  6223                             return ;
  6224                    }
  6225                    if (  !CAction. canDoCaret (request,  CAction.Ca retCan.CBO PC_SUPERVI SOR_Q)  )  {
  6226                             _log.w arn("permi ssioning.. . ");
  6227                             return ;
  6228                    }
  6229                    
  6230                    Serv iceContext  sc = Care tParam.set CaretServi ceContext( request);/ /ParamUtil .print( re quest )
  6231                    BgLa e bgLae =  null;
  6232                    long  lockId =  0;
  6233                    int  count = 0;
  6234                    for  ( String i d: request .getParame ter( "paym entConfig_ rowChecker Ids").spli t(StringPo ol.COMMA )  ) {
  6235                             
  6236                             if ( " on".equals (id)) {
  6237                                      continue ;
  6238                             }
  6239                             
  6240                             StiPt  stiPt = St iPtLocalSe rviceUtil. fetchStiPt ( Long.val ueOf(id) ) ;
  6241                             if ( s tiPt != nu ll && stiP t.getCycle Id() > 0 ) {
  6242                                      BgLae bg l = BgLaeL ocalServic eUtil.fetc hBgLae( st iPt.getCyc leId() );
  6243                                      if ( bgl  != null & &  //daily  was alrea dy staged/ submitted  for this p ayment... 
  6244                                                       bg l.getLarge Text().sta rtsWith(St ipendConfi g.STAGED)  || 
  6245                                                       bg l.getBoxGp Id() == bg Lae.getBox GpId() ) {  
  6246                                               _log.warn( "Manual Pa yment subm itted prev iously " +  stiPt.get StiPtId()  + " with t ransaction  ID " + bg l);
  6247                                               continue;
  6248                                      }
  6249                             }
  6250                             if ( b gLae == nu ll ) {
  6251                                      bgLae =  FmsOgSuppo rt.stageDa ily( sc );
  6252                                      lockId =  NonCluste redMonitor .lock(bgLa e.getBoxGp Id(), bgLa e.getBgLae Id());
  6253                                      if ( bgL ae.getBgLa eId() != l ockId ){// could not  capture lo ck...
  6254                                               _log.error ("multiple  screens n ot allowed  to submit  to OCC FM  for payme nt concurr ently");
  6255                                               //protect  against ra ce conditi on, 1 subm it to OCC  FM at a ti me...
  6256                                               return;
  6257                                      }
  6258                             }
  6259                             
  6260                             stiPt. setCycleId ( bgLae.ge tBgLaeId()  );
  6261                             CaretL ocalServic eUtil.save ( stiPt );
  6262                             _log.i nfo("Stage d manual p ayment:" +  stiPt.get OneTimePay ment() + "  for Vendo r:" + stiP t.getVendr Id() + " w ith cycleI d:" + bgLa e.getBgLae Id() );
  6263                             NonClu steredMoni tor.unlock ( bgLae.ge tBoxGpId()  );
  6264                             count+ +;
  6265                    }
  6266                    if (  count > 0  ) {
  6267                             if ( C aretUtil.i sEmailEnab led() ) {
  6268                                      _log.inf o("Send em ail for st aged manua l payment  to:" + Pro psUtil.get ( "stage.d aily.email .to" ) );
  6269                                      Map<Stri ng,Object>  otherInfo  = new Has hMap<Strin g,Object>( );
  6270                                      otherInf o.put("to" , PropsUti l.get( "st age.daily. email.to"  ) );
  6271                                       otherInfo. put("from" , PropsUti l.get( "st age.daily. email.from " ) );//"
P II                               "
  6272                                      otherInf o.put("sub ject", Por tletProps. get( "stag e.daily.em ail.subjec t" ) );
  6273                                      otherInf o.put("bod y", Portle tProps.get ( "stage.d aily.email .body" ) ) ;
  6274                                      CaretUti l.sendPaym entNotific ationMail(  otherInfo  );
  6275                             } else  {
  6276                                      _log.inf o("Staged  manual pay ment: Emai l not enab led");
  6277                             }
  6278                    }
  6279                    
  6280           }
  6281           
  6282           pu blic void  createOccW ork( Actio nRequest r equest, Ac tionRespon se respons e) throws  PortalExce ption, Sys temExcepti on  {
  6283                    
  6284                    if (  !CAction. canDoCaret ( request,  CAction.C aretCan.MA NUAL_PAYME NT ) ) {
  6285                             _log.w arn("permi ssioning.. . ");
  6286                             return ;
  6287                    }
  6288                    
  6289                    Stri ng tracker  = ParamUt il.getStri ng(request , CaretStr Pool.TRACK ER, String Pool.BLANK  );
  6290                    if (  ! CaretPa ram.isTrac ked( reque st, tracke r, true )  ){
  6291                             _log.w arn("TRACK ER BLOCKIN G action.. . ");
  6292                             reques t.setAttri bute(Caret StrPool.IN VALID_REQU EST, true) ;
  6293                             return ;
  6294                    }
  6295                    
  6296                    Stri ng type =  request.ge tParameter ("type");
  6297                    Work Type workT ype = null ;
  6298                    if (  "Lost Che ck".equals (type)) {
  6299                             workTy pe = WorkT ype.LOST_C HECK;
  6300                    } el se if ( "R eturned/Re jected Pay ment".equa ls(type))  {
  6301                             workTy pe = WorkT ype.RETURN ED_PAYMENT ;
  6302                    } el se if ( "H eld Paymen t".equals( type) ) {
  6303                             workTy pe = WorkT ype.HELD_P AYMENT;
  6304                    } el se if ( "R eturned Pa yment".equ als(type))  {
  6305                             workTy pe = WorkT ype.REJECT ED_PAYMENT ;
  6306                    } el se if ( "R ecoup Paym ent".equal s(type)) {
  6307                             workTy pe = WorkT ype.RECOUP MENT;
  6308                    } el se {
  6309                             try {
  6310                                      workType  = WorkTyp e.valueOf( type);
  6311                             } catc h (Excepti on e) {
  6312                                      _log.err or("Trying  to parse  type:" + t ype );
  6313                             }
  6314                    }
  6315                    if (  workType  == WorkTyp e.MANUAL_P AYMENT ) {
  6316                             create ManualPaym ent(reques t, respons e);
  6317                             return ;
  6318                    }
  6319                    Serv iceContext  sc = Care tParam.set CaretServi ceContext( request);
  6320  
  6321                    if (  workType  == WorkTyp e.RECOUPME NT ) {
  6322                             
  6323                             WorkIt emSupport  workItemSu pport = ne w WorkItem Support(Wo rImLocalSe rviceUtil. getWorIm(  ParamUtil. getLong(re quest, "wo rImId") )) ;
  6324                             WorIm  recoupment  = Recoupm entView.cr eate(Caret Param.setC aretServic eContext(r equest), w orkItemSup port.getCa lcInfo(),  workItemSu pport );
  6325                             Note n otei = Car etUtil.cre ateNote(sc .getCreate Date(), re coupment.g etGroupId( ), NoteSup port.NoteG roup.RECOU PMENT.grou pId(), sc. getUserId( ), request .getParame ter("worIm _comments" ));
  6326                             notei. setVcgId(r ecoupment. getVcgId() );
  6327                             notei. setChainId (recoupmen t.getWorIm Id());
  6328                             NoteLo calService Util.addNo te(notei);
  6329                             return ;
  6330                    }
  6331  
  6332                    long  paymentLo gId = Para mUtil.getL ong(reques t, "paymen tLogId");
  6333                    long  worImId =  ParamUtil .getLong(r equest, "w orImId");
  6334  
  6335                    if (  paymentLo gId == 0 & & worImId  == 0 ) {
  6336                             return ;
  6337                    }
  6338                    
  6339                    WorI m worIm =  WorImLocal ServiceUti l.getWorIm (worImId);
  6340                    Stri ng comment s = reques t.getParam eter("worI m_comments ");
  6341  
  6342                    long  groupId =  0;
  6343                    PayL g payLg =  PayLgLocal ServiceUti l.fetchPay Lg(payment LogId);
  6344                    if (  payLg !=  null ) {
  6345                             groupI d = paymen tLogId;
  6346                    } el se {
  6347                             groupI d = worImI d;
  6348                    }
  6349                    Work ItemSuppor t manualWo rkItem = n ew WorkIte mSupport(C aretUtil.c reateWorkI tem( 
  6350                                      sc, grou pId, 
  6351                                      worIm.ge tClassId() , worIm.ge tClassPk() , worIm.ge tPersnId() , workType .name(),
  6352                                      worIm.ge tCaregiver Id(), Tool box.adjust Date(Cbopc DashboardC onfig.OCC_ DUE_DAYS,  sc.getCrea teDate(),  true) ) );
  6353                    Vend r vendr =  VendrLocal ServiceUti l.findByPe rsnId( man ualWorkIte m.getCareg iverId() ) ;
  6354                    long  vendrId =  vendr.get VendrId();
  6355                    manu alWorkItem .setQueueI d(workType .workName. getQueueId ());
  6356                    manu alWorkItem .setVcgId( worIm.getV cgId());
  6357                    
  6358                    
  6359                    Note  note = nu ll;
  6360                    StiP t secondar y = null;
  6361                    Date  checkDate  = Toolbox .parseDate ( request. getParamet er("checkD ate") );
  6362                    int  checkNum =  ParamUtil .getIntege r(request,  "checkNum ber");
  6363                    WorS e workItem State = ne w WorSeImp l();
  6364                    
  6365                    if (  workType  == WorkTyp e.LOST_CHE CK || work Type == Wo rkType.RET URNED_PAYM ENT || wor kType == W orkType.RE JECTED_PAY MENT ) {
  6366                             manual WorkItem.s etStatus(C aretStrPoo l.PENDING) ;
  6367                             long n oteGroupId ;
  6368                             if ( w orkType ==  WorkType. LOST_CHECK  ) {
  6369                                      noteGrou pId = Note Support.No teGroup.LO ST_CHECK.g roupId();
  6370                             } else  { //Manua l Reject P ayment...  WorkType.R ETURNED_PA YMENT
  6371                                      noteGrou pId = Note Support.No teGroup.RE TURNED_PAY MENT.group Id();
  6372                                      manualWo rkItem.set Status("Ho ld placed  on account ");
  6373                                      for ( St iPt toHold  : StiPtLo calService Util.findB yRecurrent Vendor(ven drId, new  String[] { StipendCon fig.PAYMEN T_FINANCE} ) ){
  6374                                               toHold.set StipendSta tus(Stipen dConfig.ON _HOLD);
  6375                                               CaretLocal ServiceUti l.save(toH old);
  6376                                               _log.info( "hold plac ed on recu rring stiP t:" + toHo ld.getStiP tId() );
  6377                                      }
  6378                                      
  6379                             }
  6380                             
  6381                             note =  CaretUtil .createNot e(sc.getCr eateDate() , paymentL ogId, note GroupId, s c.getUserI d(), comme nts);
  6382                             
  6383                             second ary = new  StiPtImpl( );
  6384                             if ( p ayLg != nu ll ) {
  6385                                      payLg.se tStatus( " CREATED:"  + workType .name() );
  6386                                      CaretLoc alServiceU til.save(  payLg );
  6387  
  6388                                      manualWo rkItem.set GroupId( p ayLg.getPa ymentLogId () );
  6389                                      
  6390                                      secondar y.setOneTi mePayment(  payLg.get Amount().t oString()  );
  6391                                      secondar y.setVendr Id(payLg.g etVendrId( ));
  6392                             } else  {
  6393                                      Object d ollarAmoun tObj;
  6394                                      try {
  6395                                               dollarAmou ntObj = Nu mberFormat .getCurren cyInstance (Locale.ge tDefault() ).parseObj ect(reques t.getParam eter("chec kAmount")) ;
  6396                                               secondary. setOneTime Payment( d ollarAmoun tObj.toStr ing() );
  6397                                      } catch  (ParseExce ption e) {
  6398                                               e.printSta ckTrace();
  6399                                      }
  6400                             }
  6401                             second ary.setSti pendType(S tipendConf ig.ONE_TIM E);
  6402                             workIt emState.se tStep(comm ents.subst ring(0, Ma th.min( co mments.len gth(), Wor kItemSuppo rt.WORK_IT EM_SUPPORT _NOTE_LENG TH ) ) );
  6403                             Calend ar cycleMo nth = Cale ndar.getIn stance();
  6404                             cycleM onth.set(M ath.max(20 11, ParamU til.getInt eger(reque st, "confi g_cycle_ye ar")), Mat h.min(11,  ParamUtil. getInteger (request,  "config_cy cle_month" )), 1);
  6405                             second ary.setSti pendStartD ate(cycleM onth.getTi me());
  6406                             second ary.setSti pendStatus ( StipendC onfig.ON_H OLD );
  6407                    }  e lse if ( w orkType ==  WorkType. RECOUPMENT  ) {
  6408   //                        manual WorkItem.s etStatus(C aretStrPoo l.RECOUPME NT_INITIAT ED);
  6409   //                        note =  CaretUtil .createNot e(sc.getCr eateDate() , paymentL ogId, Note Support.No teGroup.RE COUPMENT.g roupId(),  sc.getUser Id(), comm ents);
  6410                    } el se if ( wo rkType ==  WorkType.H ELD_PAYMEN T ) {
  6411                             manual WorkItem.s etStatus(" Hold place d on accou nt");
  6412                             
  6413                             second ary = StiP tLocalServ iceUtil.fi ndByWorIm( worImId);
  6414                             if ( P aramUtil.g etBoolean( request, " holdAllPay ments") )  {
  6415                                      
  6416                                      vendr.se tStatus( S tipendConf ig.ON_HOLD  );
  6417                                      CaretLoc alServiceU til.save(v endr);
  6418                                      
  6419                                      for ( St iPt sp: St iPtLocalSe rviceUtil. findByVend orId( seco ndary.getV endrId(),  new String [] {Stipen dConfig.PA YMENT_FINA NCE} ) ) {
  6420                                               if ( Stipe ndConfig.P AYMENT_FIN ANCE.equal s( sp.getS tipendStat us() ) ) {
  6421                                                       if  ( sp.getS tiPtId() = = secondar y.getStiPt Id() ) {
  6422                                                                seco ndary.setS tipendStat us(Stipend Config.ON_ HOLD);
  6423                                                       }  else {
  6424                                                                sp.s etStipendS tatus(Stip endConfig. ON_HOLD);
  6425                                                                Care tLocalServ iceUtil.sa ve(sp);
  6426                                                       }
  6427                                               }
  6428                                      }
  6429                                      manualWo rkItem.set GroupId( s econdary.g etVendrId( ) );
  6430                                      workItem State.setS tep(CaretS trPool.HOL D_PLACED_O N_ACCOUNT) ;
  6431                                      checkDat e = sc.get CreateDate ();
  6432                             } else  {
  6433                                      if ( Sti pendConfig .PAYMENT_F INANCE.equ als( secon dary.getSt ipendStatu s() ) ) {
  6434                                               secondary. setStipend Status(Sti pendConfig .ON_HOLD);
  6435   //                                          manualWork Item.setGr oupId( sec ondary.get StiPtId()  );
  6436                                      }
  6437                                      workItem State.setS tep(Stipen dConfig.ON _HOLD);
  6438                             }
  6439                             workIt emState.se tOldStep(  request.ge tParameter ("worIm_he ldPaymentR eason") );
  6440                             note =  CaretUtil .createNot e(sc.getCr eateDate() , secondar y.getVcgId (), NoteSu pport.Note Group.HELD _PAYMENT.g roupId(),  sc.getUser Id(), comm ents);
  6441                    }
  6442                    Care tLocalServ iceUtil.sa ve( manual WorkItem ) ;
  6443  
  6444                    note .setVcgId( manualWork Item.getVc gId());
  6445                    note .setChainI d(manualWo rkItem.get WorImId()) ;
  6446                    Note LocalServi ceUtil.add Note(note) ;
  6447                    
  6448                    if (  secondary .getStiPtI d() == 0 )  {
  6449                             second ary.setVcg Id( manual WorkItem.g etVcgId()  );
  6450                             second ary.setWor ImId( manu alWorkItem .getWorImI d() );
  6451                             second ary.setVen drId( vend rId );
  6452                    }
  6453                    Care tLocalServ iceUtil.sa ve( second ary );
  6454                    
  6455                    
  6456                    work ItemState. setStepNum ber(checkN um);
  6457                    work ItemState. setWorImId ( manualWo rkItem.get WorImId()  );
  6458                    
  6459                    work ItemState. setUserId( sc.getUser Id());
  6460                    work ItemState. setCreatio nDate(chec kDate);
  6461                    Care tLocalServ iceUtil.sa ve( workIt emState );
  6462                    
  6463                    
  6464   //               if (  secondary  != null )  {
  6465   //                        second ary.setWor ImId(workI tem.getWor ImId());
  6466   //                        CaretL ocalServic eUtil.save ( secondar y );
  6467   //               }
  6468   //               
  6469   //               if (  payLg !=  null ) {
  6470   //                        payLg. setStatus(  workType. name() );
  6471   //                        CaretL ocalServic eUtil.save ( payLg );
  6472   //               }
  6473                    
  6474                    Resu ltMap.getC aretMap(re quest).put ("tabConte xt", "sear ch" );
  6475                    if (  workType  == WorkTyp e.HELD_PAY MENT ) {
  6476                             reques t.getPortl etSession( ).getAttri bute("last Search");
  6477                    }
  6478                    Resu ltMap.getC aretMap(re quest).put ("lastSear ch", reque st.getPort letSession ().getAttr ibute("las tSearch")) ;
  6479                    
  6480           }
  6481           
  6482           pu blic void  saveCSCApp eal( Actio nRequest a ctionReque st, Action Response r esponse)   {
  6483                    if (  !CAction. canDoCaret ( actionRe quest, CAc tion.Caret Can.DISPOS ITION_VCG  ) ) {
  6484                             _log.w arn("permi ssioning.. . ");
  6485                             return ;
  6486                    }
  6487                    getO utput(acti onRequest) ;
  6488                    
  6489                    try  {
  6490                             Servic eContext s c = CaretP aram.setCa retService Context(ac tionReques t);
  6491                             Apeal  a = new Ap ealImpl();
  6492                             Apeal  apeal = (A peal) Care tParam.loa dModel(act ionRequest , new Apea lImpl(), a .getModelA ttributes( ).keySet() , CaretStr Pool.APPEA LED_UNDERL INE);
  6493                             apeal. setCreatio nDate(new  Date());
  6494                             
  6495                             CaretL ocalServic eUtil.save ( apeal );
  6496                             
  6497                             String  tracker =  ParamUtil .getString (actionReq uest, Care tStrPool.T RACKER, St ringPool.B LANK );
  6498                             List<D ocum> docu ments = Do cumLocalSe rviceUtil. getByTrack erNote( tr acker );
  6499                             for (  Docum docu m : docume nts ){
  6500                                      if ( doc um.getClas sPk() == 0  ){
  6501                                               docum.setC lassPk(ape al.getApea lId());
  6502                                               docum.setC lassId(Por talUtil.ge tClassName Id(Apeal.c lass));
  6503                                               docum.setN ote(String Pool.BLANK );
  6504                                               try {
  6505                                                       Do cumLocalSe rviceUtil. updateDocu m(docum);
  6506                                               } catch (S ystemExcep tion e) {
  6507                                                       e. printStack Trace();
  6508                                               }
  6509                                      }
  6510                             }
  6511                             
  6512                             
  6513                    } ca tch (Appli cationWork FlowExcept ion e) {
  6514                             Applic ationWorkF lowExcepti on.handleE xception(e );
  6515                    } 
  6516           }
  6517           
  6518           pu blic void  saveVCGSup portingDoc ument( Act ionRequest  actionReq uest, Acti onResponse  response)   {
  6519                    if (  !CAction. canDoCaret ( actionRe quest, CAc tion.Caret Can.UPLOAD _VCG_FILE  ) ) {
  6520                             _log.w arn("permi ssioning.. . ");
  6521                             return ;
  6522                    }
  6523                    getO utput(acti onRequest) ;
  6524                    try  {
  6525                             Servic eContext s c = CaretP aram.setCa retService Context(ac tionReques t);
  6526                             String  tracker =  ParamUtil .getString (actionReq uest, Care tStrPool.T RACKER, St ringPool.B LANK );
  6527                             List<D ocum> docu ments = Do cumLocalSe rviceUtil. getByTrack erNote( tr acker );
  6528                             long v cgId = Par amUtil.get Long(actio nRequest,  CaretStrPo ol.VCGID ) ;
  6529                             String  type = Pa ramUtil.ge t(actionRe quest, Car etStrPool. TYPE, Stri ngPool.BLA NK);
  6530                             
  6531                             VcgAn  vcgAn;
  6532                             for (  Docum docu m : docume nts ){
  6533                                      vcgAn =  VcgAnLocal ServiceUti l.getRecen t(vcgId);
  6534                                      Long vcg AnId = vcg An.getVcgA nId();
  6535                                      if ( doc um.getClas sPk() == 0  ){
  6536                                               docum.setC lassPk(vcg AnId);
  6537                                               docum.setC lassId(Por talUtil.ge tClassName Id(VcgAn.c lass));
  6538                                               docum.setN ote(String Pool.BLANK );
  6539                                               docum.setT ype(type);
  6540                                               try {
  6541                                                       Do cumLocalSe rviceUtil. updateDocu m(docum);
  6542                                               } catch (S ystemExcep tion e) {
  6543                                                       e. printStack Trace();
  6544                                               }
  6545                                      }
  6546                             }
  6547                             
  6548                    } ca tch (Appli cationWork FlowExcept ion e) {
  6549                             Applic ationWorkF lowExcepti on.handleE xception(e );
  6550                    } 
  6551           }
  6552           
  6553           @P rocessActi on (name=" messageAct ions")
  6554           pu blic void  messageAct ions( Acti onRequest  actionRequ est, Actio nResponse  actionResp onse ) {
  6555                    Stri ng message Action = P aramUtil.g et(actionR equest, "m essageActi on", Strin gPool.BLAN K);
  6556                    _log .info("mes sageAction s..." +  m essageActi on );
  6557                                      PMPortle t.render(a ctionReque st, action Response);
  6558                                      actionRe sponse.set RenderPara meter(Care tStrPool.M VC_PATH, C aretStrPoo l.INTERNAL _MESSAGES_ PAGE+actio nRequest.g etAttribut e("targetP ath"));
  6559           }
  6560           
  6561           
  6562           
  6563           @P rocessActi on (name=" electPayme nt")
  6564           pu blic void  electPayme nt ( Actio nRequest r equest, Ac tionRespon se actionR esponse )  throws Sys temExcepti on {
  6565                    
  6566                    if (  !CAction. canDoCaret ( request,  CAction.C aretCan.AP PLY_FM_PAY MENT ) ) {
  6567                             _log.w arn("permi ssioning.. . ");
  6568                             return ;
  6569                    }
  6570                    Serv iceContext  sc = Care tParam.set CaretServi ceContext( request);
  6571                    Stri ng tracker  = ParamUt il.getStri ng(request , CaretStr Pool.TRACK ER, String Pool.BLANK  ); 
  6572                    Stri ng type =  ParamUtil. getString( request, C aretStrPoo l.TYPE, St ringPool.B LANK );
  6573                    
  6574   //               Cale ndar today  = Calenda r.getInsta nce();
  6575   //               Date  payDate =  today.get Time();
  6576   //               
  6577   //               bool ean isThur sday = fal se;
  6578   //               bool ean isMont hLastDay =  false;
  6579   //               
  6580   //               if (  today.get (Calendar. DAY_OF_WEE K) == Cale ndar.THURS DAY ) {
  6581   //                        isThur sday = tru e;
  6582   //               }
  6583   //               toda y.roll(Cal endar.DAY_ OF_MONTH,  true);
  6584   //               if (  today.get (Calendar. DAY_OF_MON TH) == 1 )  {
  6585   //                        isMont hLastDay =  true;
  6586   //               }
  6587                    
  6588                    try  {
  6589   //                        BgLae  bgLae = nu ll;
  6590   //                        if ( i sThursday  || isMonth LastDay )  {
  6591   //                                 bgLae =  Vendor.get PaymentSte p(sc);
  6592   //                                 
  6593   //                                 if (     bgLae.getL argeText() .startsWit h(StipendC onfig.SUBM ITTED) || 
  6594   //                                                  bg Lae.getLar geText().s tartsWith( StipendCon fig.COMPLE TED) ) { / /payment w as already  sent, re- issue as d aily...
  6595   //                                         
  6596   //                                          bgLae = nu ll;
  6597   //                                 }
  6598   //                        } 
  6599   //                        
  6600   ////                      Calend ar calenda r = Calend ar.getInst ance();
  6601   //
  6602   //                        if ( b gLae == nu ll ){
  6603   //                                 BoxGp bo xGp = Vend or.getOneT imeBg(Cale ndar.getIn stance());
  6604   //                                 bgLae =  new BgLaeI mpl();
  6605   //                                 bgLae.se tOwnerId(  Toolbox.ge tBgLaeDay( ) );
  6606   //                                 bgLae.se tBoxGpId(  boxGp.getB oxGpId() ) ;
  6607   //                        }
  6608   //                        
  6609   //                        bgLae. setLargeTe xt( "PENDI NG-" + Too lbox.forma tDateTime(  sc.getCre ateDate())  );
  6610   //                        CaretL ocalServic eUtil.save (bgLae);
  6611   //
  6612   //                        
  6613   //                        Calend ar cal = C alendar.ge tInstance( );
  6614   //                        cal.se tTime(payD ate);
  6615   //                        cal.ro ll(Calenda r.SECOND,  true);
  6616   //                        Date l ogDate = c al.getTime ();
  6617   //                        
  6618   //                        for (  StiPt stiP t : StiPtL ocalServic eUtil.find ByUpdatePe nding(Stip endConfig. ONE_TIME,  logDate) )  {//those  approved,  never paid , one-time , with sta rt date be fore logDa te
  6619   //                                 _log.inf o("payment :" + stiPt .getOneTim ePayment()  + " for V endor:" +  stiPt.getV endrId() +  " gets ne w worseId: " + bgLae. getBgLaeId () );
  6620   //                                 stiPt.se tCycleId(  bgLae.getB gLaeId() ) ;
  6621   //                                 CaretLoc alServiceU til.save(  stiPt );
  6622   //                        }
  6623   //               
  6624   //                        CaretL ocalServic eUtil.setF msOut( pay Date, bgLa e, true);
  6625                                                       
  6626   //                        try {
  6627   //                                 long nex tCycleId =  Vendor.in itMonth( c al, false  ).getBgLae Id();
  6628   //                                 StiPtLoc alServiceU til.findBy UpdatePend ing(Stipen dConfig.RE CURRING, l ogDate);
  6629   //                                 for ( St iPt stiPt  : StiPtLoc alServiceU til.findBy UpdatePend ing(Stipen dConfig.RE CURRING, l ogDate) )  {
  6630   //                                          _log.info( "payment:"  + stiPt.g etOneTimeP ayment() +  " for Ven dor:" + st iPt.getVen drId() + "  gets new  worseId:"  + bgLae.ge tBgLaeId()  );
  6631   //                                          stiPt.setC ycleId( ne xtCycleId  );
  6632   //                                          CaretLocal ServiceUti l.save( st iPt );
  6633   //                                 }
  6634   //                        } catc h (SystemE xception e 1) {
  6635   //                                 e1.print StackTrace ();
  6636   //                        }
  6637                             FmsOgS upport.Sub mitStagedP ayments();
  6638                    } ca tch (Appli cationWork FlowExcept ion e) {
  6639                             e.prin tStackTrac e();
  6640                    }
  6641           }
  6642                    
  6643           @P rocessActi on (name=" occFmSubmi t")
  6644           pu blic void  occFmSubmi t( ActionR equest req uest, Acti onResponse  actionRes ponse ) {
  6645                    
  6646                    Stri ng tracker  = ParamUt il.getStri ng(request , CaretStr Pool.TRACK ER, String Pool.BLANK  ); 
  6647                    Stri ng type =  ParamUtil. getString( request, C aretStrPoo l.TYPE, St ringPool.B LANK );
  6648                    
  6649   //               _log .info("moc kService:"  + request .getParame ter("mockS ervice") ) ;
  6650                    
  6651                    Serv iceContext  sc = Care tParam.set CaretServi ceContext( request);
  6652  
  6653                    if (  CAction.C aretCan.FM S_SERVICE. name().equ als(type)  ) {
  6654                             try {
  6655                                      electPay ment(reque st, action Response);
  6656                             } catc h (SystemE xception e ) {
  6657                                      e.printS tackTrace( );
  6658                             }
  6659                    }
  6660                    
  6661                    bool ean annual Increase =  ParamUtil .getBoolea n(request,   "annualI ncrease");
  6662                    if (  annualInc rease ) {
  6663                             try {
  6664                                      new Annu alRateIncr ease(Calen dar.getIns tance().ge t(Calendar .YEAR)).pe rformAnnua lRateIncre ase(sc);
  6665                             } catc h (PortalE xception |  SystemExc eption e)  {
  6666                                      e.printS tackTrace( );
  6667                             }
  6668                    }
  6669                    
  6670                    if (  CAction.C aretCan.UP DATE_FUNDI NG.name(). equals(typ e) ) {
  6671                             
  6672                             Double  funds = 0 .0;
  6673                             Double  trhld = 0 .0;
  6674                             try {
  6675                                      Object d ollarAmoun tObj = Num berFormat. getCurrenc yInstance( Locale.get Default()) .parseObje ct(request .getParame ter("amoun t"));
  6676                                      funds =  Double.val ueOf(dolla rAmountObj .toString( ));
  6677                                      
  6678                                      dollarAm ountObj =  NumberForm at.getCurr encyInstan ce(Locale. getDefault ()).parseO bject(requ est.getPar ameter("th reshold")) ;
  6679                                      trhld =  Double.val ueOf(dolla rAmountObj .toString( ));
  6680                             } catc h (ParseEx ception e1 ) {
  6681                                      e1.print StackTrace ();
  6682                             }
  6683  
  6684                             String  obligatio nDate = Pa ramUtil.ge tString(re quest, "ob ligationDa te", Strin gPool.BLAN K );
  6685                             String  poNumber  = ParamUti l.getStrin g(request,  "poNumber ", StringP ool.BLANK  );
  6686                             String  obligatio nNote = Pa ramUtil.ge tString(re quest, "ob ligation_n ote", Stri ngPool.BLA NK );
  6687                             
  6688                             _log.i nfo("amoun t..." +  f unds );
  6689                             _log.i nfo("oblig ationDate. .." +  obl igationDat e );
  6690                             _log.i nfo("poNum ber..." +   poNumber  );
  6691                             _log.i nfo("oblig ationNote. .." +  obl igationNot e );
  6692                             
  6693                             boolea n fundingU pdates = f alse;
  6694                             if ( f unds > 0 ) {
  6695                                      try {
  6696                                               BoxNumberS upport num  = new Box NumberSupp ort( BoxGp LocalServi ceUtil.get BoxGroupBg Num( Cbopc FmDashboar dConfig.AV AILABLE_ID  ).get(0)  );
  6697                                               String dir ection = P aramUtil.g etString(r equest, "f unds" );
  6698                                               if ( "incr ease".equa ls(directi on) ) {
  6699                                                       nu m.setValue ( num.getV alue() + f unds );
  6700                                               } else {
  6701                                                       nu m.setValue ( num.getV alue() - f unds );
  6702                                               }
  6703                                               CaretLocal ServiceUti l.save(num );
  6704                                               fundingUpd ates = tru e;
  6705                                      } catch  (Applicati onWorkFlow Exception  e) {
  6706                                               e.printSta ckTrace();
  6707                                      }
  6708                             }
  6709                             if ( t rhld > 0 ) {
  6710                                      try {
  6711                                               BoxNumberS upport num  = new Box NumberSupp ort ( BoxG pLocalServ iceUtil.ge tBoxGroupB gNum( Cbop cFmDashboa rdConfig.T HRESHOLD_I D ).get(0)  );
  6712                                               num.setVal ue( trhld  );
  6713                                               CaretLocal ServiceUti l.save(num );
  6714                                               fundingUpd ates = tru e;
  6715                                      } catch  (Applicati onWorkFlow Exception  e) {
  6716                                               e.printSta ckTrace();
  6717                                      }
  6718                             }
  6719                             
  6720                             try {
  6721                                      BoxNumbe rSupport n um = new B oxNumberSu pport ( Bo xGpLocalSe rviceUtil. getBoxGrou pBgNum( Cb opcFmDashb oardConfig .THRESHOLD _ID ).get( 0) );
  6722                                      BgNum av ail = new  BoxNumberS upport( Bo xGpLocalSe rviceUtil. getBoxGrou pBgNum( Cb opcFmDashb oardConfig .AVAILABLE _ID ).get( 0) );
  6723                                      if ( num .getValue( ) > avail. getValue()  ) {
  6724                                               _log.info( "Email occ fm.thresho ld.email.t o:" + Prop sUtil.get(  "occfm.th reshold.em ail.to" )  );
  6725                                               if ( Caret Util.isEma ilEnabled( ) ) {
  6726                                                       Ma p<String,O bject> oth erInfo = n ew HashMap <String,Ob ject>();
  6727                                                       ot herInfo.pu t("to", Pr opsUtil.ge t( "occfm. threshold. email.to"  ) );
  6728                                                       ot herInfo.pu t("from",  PropsUtil. get( "occf m.threshol d.email.fr om" ) );
  6729                                                       ot herInfo.pu t("subject ", Portlet Props.get(  "occfm.th reshold.em ail.subjec t" ) );
  6730                                                       ot herInfo.pu t("body",  PortletPro ps.get( "o ccfm.thres hold.email .body" ) ) ;
  6731                                                       Ca retUtil.se ndPaymentN otificatio nMail(othe rInfo);
  6732                                               } else {
  6733                                                       _l og.warn("E mail occfm .threshold .email.to  not enable d");
  6734                                               }
  6735                                      } else {
  6736                                               _log.info(  "Threshol d val:" +  num.getVal ue() + ",  Avail Val: " + avail. getValue()  + " " + (  num.getVa lue() > av ail.getVal ue() ) );
  6737                                      }
  6738                             } catc h (Applica tionWorkFl owExceptio n e) {
  6739                                      e.printS tackTrace( );
  6740                             }
  6741                             
  6742                             
  6743                             String  note = re quest.getP arameter(" obligation _note");
  6744                             try {
  6745                                      Dashboar dConfig da shConfig =  ( Dashboa rdConfig )  request.g etPortletS ession().g etAttribut e( CaretSt rPool.DASH BOARD_CONF IG );
  6746                                      NoteLoca lServiceUt il.addNote ( CaretUti l.createNo te(sc.getC reateDate( ), dashCon fig.getRol eId(), Not eSupport.N oteGroup.O CC_FM.grou pId(), Por talUtil.ge tUserId(re quest), no te));
  6747                             } catc h (SystemE xception e ) {
  6748                                      e.printS tackTrace( );
  6749                             }
  6750                    }
  6751           }
  6752           
  6753           @P rocessActi on (name=" selectRole ")
  6754           pu blic void  selectRole ( ActionRe quest requ est, Actio nResponse  actionResp onse ) thr ows Applic ationWorkF lowExcepti on, Portal Exception,  SystemExc eption {
  6755                    
  6756                    if (  StringPoo l.TRUE.equ als( Portl etProps.ge t(CaretStr Pool.ROLES _SELECTION _ENABLED )  ) ) {
  6757                             String  tracker =  ParamUtil .getString (request,  CaretStrPo ol.TRACKER , StringPo ol.BLANK ) ;
  6758           
  6759                             if ( !  CaretPara m.isTracke d( request , tracker,  true ) ){
  6760                                      _log.war n("TRACKER  BLOCKING  action...  ");
  6761                                      request. setAttribu te(CaretSt rPool.INVA LID_REQUES T, true);
  6762                                      return;
  6763                             }
  6764                             long r oleId = Pa ramUtil.ge tLong(requ est,  "rol e" );
  6765                             _log.i nfo("reach ed save se lected Rol e..... " +  roleId);
  6766                             if ( r oleId > 0  ){
  6767                                      Role rol e = RoleLo calService Util.getRo le(roleId) ;
  6768                                      long org Id = 0;
  6769                                      boolean  validates  = true;
  6770                                      if ( rol e.getName( ).toLowerC ase().star tsWith("cs c") ){
  6771                                               validates  = (orgId =  ParamUtil .getLong(r equest,  " facility"  )) > 0;
  6772                                      } else i f ( role.g etName().t oLowerCase ().startsW ith("visn" ) ){
  6773                                               validates  = (orgId =  ParamUtil .getLong(r equest,  " visn" )) >  0;
  6774                                      }
  6775                                      if ( val idates ){
  6776                                               Long[] org Ids = orgI d > 0? new  Long[]{or gId}: new  Long[0];
  6777                                               CodifiedRo le.updateC linicRole(  PortalUti l.getUserI d(request) , new long []{ role.g etRoleId()  }, orgIds  );
  6778                                      }
  6779                             }
  6780                    }
  6781           }
  6782           pu blic void  cancelCslC reateVcg(P ortletRequ est reques t) throws  Applicatio nWorkFlowE xception {
  6783                    long  callId =  ParamUtil. getLong(re quest, "ca llId", 0 ) ;
  6784                    _log .info("can celCslCrea teVcg: cal lId: " + c allId);
  6785                    Call  call = nu ll;
  6786                    try  {
  6787                             call =  CallLocal ServiceUti l.getCall( callId);
  6788                             if (ca ll != null ) {
  6789                                      _log.inf o("cancelC slCreateVc g: worImId : " + call .getWorkPr imaryKey() );
  6790                                      long wor ImId = cal l.getWorkP rimaryKey( );
  6791                                      if (worI mId > 0) {
  6792                                               WorImLocal ServiceUti l.deleteWo rIm(worImI d);
  6793                                               call.setWo rkPrimaryK ey(0l);
  6794                                               CallLocalS erviceUtil .updateCal l(call);
  6795                                      }
  6796                             }
  6797                    }
  6798                    catc h(Exceptio n e) {
  6799                             Applic ationWorkF lowExcepti on.handleE xception(e );
  6800                    }
  6801           }        
  6802           
  6803           pr ivate stat ic Log _lo g = LogFac toryUtil.g etLog( Car etActionCo mmand.clas s );
  6804  
  6805           @O verride
  6806           pu blic boole an pastMax Time(Actio nRequest r equest) {
  6807                    try  {
  6808                             String  maxSessio nTime = Ca retUtil.ge tExpandoVa lue(Portal Util.getUs er(request ).getExpan doBridge() , CaretStr Pool.MAX_S ESSION_TIM E);
  6809                             if ( V alidator.i sNumber(ma xSessionTi me) ) {
  6810                                      Calendar  max = Cal endar.getI nstance();
  6811                                      max.setT imeInMilli s(Long.val ueOf(maxSe ssionTime) );
  6812                                      
  6813                                      if ( Cal endar.getI nstance(). after( max  ) ) {
  6814                                               _log.error ("User has  bypassed  the maximu m allowed  time per s ession...  user will  need to si gn-in once  more" );
  6815                                               CaretUtil. setExpando Value( Por talUtil.ge tUser(requ est), Care tStrPool.M AX_SESSION _TIME, ""  );
  6816                                               return tru e;
  6817                                      }
  6818                             }
  6819                    } ca tch (Porta lException  | SystemE xception e ) {
  6820                             e.prin tStackTrac e();
  6821                    }
  6822                    retu rn false;
  6823           }
  6824   }