14. EPMO Open Source Coordination Office Redaction File Detail Report

Produced by Araxis Merge on 12/4/2017 8:32:29 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.

14.1 Files compared

# Location File Last Modified
1 VCCM.zip\VCCM\CRM_solutions\FTPResources\FTPResources_3_35.zip\WebResources ftp_VeteranPactTeamAssignFormScriptVeteranPactTeam6509E884-AD13-E611-9436-0050568D743D Thu Nov 17 16:48:12 2016 UTC
2 VCCM.zip\VCCM\CRM_solutions\FTPResources\FTPResources_3_35.zip\WebResources ftp_VeteranPactTeamAssignFormScriptVeteranPactTeam6509E884-AD13-E611-9436-0050568D743D Thu Nov 30 16:21:50 2017 UTC

14.2 Comparison summary

Description Between
Files 1 and 2
Text Blocks Lines
Unchanged 5 2184
Changed 4 8
Inserted 0 0
Removed 0 0

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

14.4 Active regular expressions

No regular expressions were active.

14.5 Comparison detail

  1   //VeteranP actTeamAss ignFormScr ipt.js
  2   //Contains  variables  and funct ions used  to allocat e a pact t eam to a v eteran
  3   //Requires  jQuery lo aded on th e form
  4   //Used in  conjunctio n with the  Veteran ( contact) e ntity form  load even t.
  5  
  6   //Static G lobal Vari ables
  7   vpta_crmOd ataEndPoin t = '/XRMS ervices/20 11/Organiz ationData. svc';
  8   vpta_serve rUrl = Xrm .Page.cont ext.getCli entUrl();
  9   //vpta_pat ientsummar yUrl = 'ht tps://qacr mdac.np.cr m.vrm.vba. DNS     /WebParts/ INT/api/PC MM/Patient Summary/1. 0/json/ftp CRM/';    //OLD MANU AL DEV URL
  10   vpta_patie ntsummaryU rl = '';
  11   //GET CRM  SETTINGS W EB SERVICE  URLS
  12   vpta_condi tionalFilt er = "(mcs _name eq ' Active Set tings')";
  13  
  14   // main fu nction
  15   function v pta_getPat ientSummar yData(vpta _crmfacili tycode, vp ta_crmpati enticn, pc mmUrl) {
  16       try {
  17           $. get(pcmmUr l, functio n (data, s tatus) {
  18  
  19                // Notif ication bo oleans
  20                var prim aryHomeBou ndCareNoti fication =  true;
  21                var pmen talHealthN otificatio n = true;
  22                var ptcm Notificati on = true;
  23  
  24                if (data  != null & & typeof d ata != und efined) {
  25                    var  vpta_objmo del = data ['Data'];
  26                    if ( vpta_objmo del != nul l && typeo f vpta_obj model != u ndefined)  {
  27  
  28                         if (vpta_o bjmodel.pa tientAssig nments[0]  != null &&  typeof vp ta_objmode l.patientA ssignments [0] != und efined &&  typeof (vp ta_objmode l.patientA ssignments [0].length ) !== 0) {
  29                             var pa tientAssig nments = v pta_objmod el.patient Assignment s[0];
  30                             primar yHomeBound CareNotifi cation = P rimaryCare orHomeBoun dProviderP rocessing( patientAss ignments);
  31                             pmenta lHealthNot ification  = MentalHe althProvid erProcessi ng(patient Assignment s);
  32                             // ptc mNotificat ion = TCMA ssignments ProviderPr ocessing(p atientAssi gnments);
  33                         }
  34  
  35                         //   UserN otificatio ns(primary HomeBoundC areNotific ation, pme ntalHealth Notificati on, ptcmNo tification );
  36                    }
  37                }
  38           }) ;
  39       }
  40       catch  (err) {
  41           al ert('Veter an form lo ad, PCMM I ntegration  Service F unction Er ror (vpta_ getPatient SummaryDat a): ' + er r.message) ;
  42       }
  43   }
  44  
  45   // Payload  section p rocessing  functions
  46   function P rimaryCare orHomeBoun dProviderP rocessing( patientAss ignments)  {
  47       try {
  48           va r primaryH omeBoundCa reNotifica tion = fal se;
  49           va r vpta_tea mname = nu ll;
  50           va r vpta_tea mmembers =  null;
  51           va r HBProces sing = fal se;
  52           va r PriProce ssing = fa lse;
  53  
  54           //  Primary C are data h andling
  55           if  (typeof ( patientAss ignments.p rimaryCare Assignment s[0]) !==  'undefined '
  56                && patie ntAssignme nts.primar yCareAssig nments[0]  !== null)  {
  57                if (type of (patien tAssignmen ts.primary CareAssign ments[0].l ength) !==  0) {
  58                    PriP rocessing  = true;
  59                    vpta _teamname  = patientA ssignments .primaryCa reAssignme nts[0].tea mName;
  60                    if ( typeof (pa tientAssig nments.pri maryCareAs signments[ 0].teamlet Members.le ngth) !==  0 && typeo f patientA ssignments .primaryCa reAssignme nts[0].tea mletMember s !== unde fined) {
  61                         vpta_teamm embers = p atientAssi gnments.pr imaryCareA ssignments [0].teamle tMembers;
  62                         //var vpta _teammembe rs = [{"Te amRole":{" Descriptio n":"PRIMAR Y CARE PRO VIDER","Ex pirationDa te":null," Name":"PRI MARY CARE  PROVIDER", "Code":"43 ","Ien":"6 7","Primar yCare":"tr ue","Suppo rtStaff":" false"},"S taffContac t":{"TeamR oleName":" Primary Ca re Provide r","TeamRo leCode":"4 3","Name": "Potter,Ha rry","Phon e":"","Pag er":"","Ie n":"520642 422"}}];
  63                    }
  64                }
  65           }
  66                // Home  Bound data  handling
  67           el se if (typ eof (patie ntAssignme nts.primar yCareHBPCA ssignments [0]) !== ' undefined'
  68                && patie ntAssignme nts.primar yCareHBPCA ssignments [0] !== nu ll) {
  69                if (type of (patien tAssignmen ts.primary CareHBPCAs signments. length) != = 0) {
  70                    HBPr ocessing =  true;
  71                    vpta _teamname  = patientA ssignments .primaryCa reHBPCAssi gnments[0] .teamName;
  72                    if ( typeof (pa tientAssig nments.pri maryCareHB PCAssignme nts[0].tea mMembers.l ength) !=  0 && typeo f (patient Assignment s.primaryC areHBPCAss ignments[0 ].teamMemb ers) != un defined) {
  73                         vpta_teamm embers = p atientAssi gnments.pr imaryCareH BPCAssignm ents[0].te amMembers;
  74                    }
  75                }
  76           }
  77  
  78           // Continue p rocessing  if primary CareAssign ments OR p rimaryCare HBPCAssign ments team  name has  a value
  79           if  (vpta_tea mname !==  null && ty peof (vpta _teamname)  !== 'unde fined') {
  80                // proce ss team na me always
  81                vpta_pro cessTeamNa me(vpta_te amname);
  82  
  83                
  84           }
  85           el se { prima ryHomeBoun dCareNotif ication =  true; }
  86                    
  87                    // H ome Bound  or Primary  Care proc essing che ck
  88                if (vpta _teammembe rs.length  > 0) {
  89                    if ( HBProcessi ng) {
  90                                      setTimeo ut(vpta_pr ocessHBTea mMembers(v pta_teamme mbers, vpt a_teamname ), 500);
  91                    }
  92                    else  if (PriPr ocessing)  {
  93                         setTimeout (vpta_proc essPrimary TeamMember s(vpta_tea mmembers,  vpta_teamn ame), 500) ;
  94                    }
  95                }
  96           re turn prima ryHomeBoun dCareNotif ication;
  97       }
  98       catch  (e) {
  99           al ert(e.mess age);
  100           re turn prima ryHomeBoun dCareNotif ication;
  101       }
  102   }
  103  
  104   function M entalHealt hProviderP rocessing( patientAss ignments)  {
  105       try {
  106           va r pmentalH ealthNotif ication =  false;
  107           va r vmta_tea mname = nu ll;
  108           va r vmta_cor rdinatorNa me = null;
  109           va r vmta_cor rdinatorRo leName = n ull;
  110           va r vmta_cor rdinatorRo leCode = n ull;
  111           va r vmta_cor rdinatorRo lePhone =  null;
  112           va r vmta_cor rdinatorRo lePager =  null;
  113           va r vmta_cor rdinatorRo leIen = nu ll;
  114  
  115           if  (patientA ssignments .mentalHea lthAssignm ents[0] != = null &&  typeof pat ientAssign ments.ment alHealthAs signments[ 0].teamNam e !== unde fined) {
  116                vmta_tea mname = pa tientAssig nments.men talHealthA ssignments [0].teamNa me;
  117  
  118                if (vmta _teamname  !== null & & typeof ( vmta_teamn ame) !== ' undefined' ) {
  119                    if ( typeof (pa tientAssig nments.men talHealthA ssignments [0].mental HealthTrea tmentCoord .length) ! == 0 && ty peof (pati entAssignm ents.menta lHealthAss ignments[0 ].mentalHe althTreatm entCoord)  !== undefi ned) {
  120                         if (patien tAssignmen ts.mentalH ealthAssig nments[0]. mentalHeal thTreatmen tCoord.Nam e !== null  && typeof  (patientA ssignments .mentalHea lthAssignm ents[0].me ntalHealth TreatmentC oord.Name)  !== 'unde fined') {  vmta_corrd inatorName  = patient Assignment s.mentalHe althAssign ments[0].m entalHealt hTreatment Coord.Name ; }
  121                         if (patien tAssignmen ts.mentalH ealthAssig nments[0]. mentalHeal thTreatmen tCoord.Tea mRoleName  !== null & & typeof ( patientAss ignments.m entalHealt hAssignmen ts[0].ment alHealthTr eatmentCoo rd.TeamRol eName) !==  'undefine d') { vmta _corrdinat orRoleName  = patient Assignment s.mentalHe althAssign ments[0].m entalHealt hTreatment Coord.Team RoleName;  }
  122                         if (patien tAssignmen ts.mentalH ealthAssig nments[0]. mentalHeal thTreatmen tCoord.Tea mRoleCode  !== null & & typeof ( patientAss ignments.m entalHealt hAssignmen ts[0].ment alHealthTr eatmentCoo rd.TeamRol eCode) !==  'undefine d') { vmta _corrdinat orRoleCode  = patient Assignment s.mentalHe althAssign ments[0].m entalHealt hTreatment Coord.Team RoleCode;  }
  123                         if (patien tAssignmen ts.mentalH ealthAssig nments[0]. mentalHeal thTreatmen tCoord.Pho ne !== nul l && typeo f (patient Assignment s.mentalHe althAssign ments[0].m entalHealt hTreatment Coord.Phon e) !== 'un defined')  { vmta_cor rdinatorRo lePhone =  patientAss ignments.m entalHealt hAssignmen ts[0].ment alHealthTr eatmentCoo rd.Phone;  }
  124                         if (patien tAssignmen ts.mentalH ealthAssig nments[0]. mentalHeal thTreatmen tCoord.Pag er !== nul l && typeo f (patient Assignment s.mentalHe althAssign ments[0].m entalHealt hTreatment Coord.Page r) !== 'un defined')  { vmta_cor rdinatorRo lePager =  patientAss ignments.m entalHealt hAssignmen ts[0].ment alHealthTr eatmentCoo rd.Pager;  }
  125                         if (patien tAssignmen ts.mentalH ealthAssig nments[0]. mentalHeal thTreatmen tCoord.Ien  !== null  && typeof  (patientAs signments. mentalHeal thAssignme nts[0].men talHealthT reatmentCo ord.Ien) ! == 'undefi ned') { vm ta_corrdin atorRoleIe n = patien tAssignmen ts.mentalH ealthAssig nments[0]. mentalHeal thTreatmen tCoord.Ien ; }
  126                    }
  127  
  128                    // v pta_proces sTeamName( vmta_teamn ame);
  129  
  130                    // f tp_ftp_pac t_contact_ MentalHeal thTeam
  131                    if ( vmta_corrd inatorName  !== null  && typeof  (vmta_corr dinatorNam e) !== 'un defined')  {
  132                         vmta_proce ssMentalHe althCorrid inator(vmt a_teamname ,
  133                                                   vmta_c orrdinator Name,
  134                                                   vmta_c orrdinator RoleName,
  135                                                   vmta_c orrdinator RoleCode,
  136                                                   vmta_c orrdinator RolePhone,
  137                                                   vmta_c orrdinator RolePager,
  138                                                   vmta_c orrdinator RoleIen);
  139                    }
  140                }
  141           }
  142           el se { pment alHealthNo tification  = true; }
  143  
  144           re turn pment alHealthNo tification ;
  145       }
  146       catch  (e) {
  147           al ert(e.mess age);
  148           re turn pment alHealthNo tification ;
  149       }
  150   }
  151  
  152   function T CMAssignme ntsProvide rProcessin g() {
  153       //     tcmAssignm ents":[
  154       //     {
  155       //         "teamN ame":"OEF* 987*1",
  156       //         "leadC oordinator ":
  157       //         {
  158       //             "T eamRoleNam e":"Lead C oordinator ",
  159       //             "T eamRoleCod e":"29",
  160       //             "N ame":"Smit h,Cindy L" ,
  161       //             "P hone":"972 -605-3000" ,
  162       //             "P ager":"972 -605-3001" ,
  163       //             "I en":"52062 9207"
  164       //         }
  165       //     }
  166       //],
  167  
  168       try {
  169           va r ptcmNoti fication =  false;
  170  
  171       }
  172       catch  (e) {
  173           al ert(e.mess age);
  174       }
  175  
  176  
  177   }
  178  
  179   function v pta_proces sHBTeamMem bers(vpta_ teammember s, vpta_te amname) {
  180       try {
  181           va r tm = vpt a_teammemb ers;
  182           va r pactUser TeamId = v pta_retrie veProvider (vpta_serv erUrl + vp ta_crmOdat aEndPoint  + "/TeamSe t?$filter= Name eq 'P ACT User'" );
  183           va r usersOnT eam = [];
  184           va r teamId =  vpta_retr ieveTeamId (vpta_team name);
  185           fo r (i = 0;  i < vpta_t eammembers .length; i ++) {
  186                var name  = tm[i].N ame;
  187                var spli tname = na me.split(" ,");
  188                var last  = splitna me[0];
  189                var firs tmiddle =  splitname[ 1];
  190                var firs t = firstm iddle.spli t(" ");
  191                first =  first[0];
  192                var vpta _entitySet Name = 'Sy stemUserSe t';
  193                var vpta _attribute Set = 'Fir stName, La stName, Sy stemUserId ';
  194                var vpta _condition alFilter =  "FirstNam e eq '" +  first + "' & LastName  eq '" + l ast + "'";
  195                var vpta _jsonQuery  = vpta_se rverUrl +  vpta_crmOd ataEndPoin t + '/' +  vpta_entit ySetName +  '?$select =' + vpta_ attributeS et + '&$fi lter=' + v pta_condit ionalFilte r;
  196                var prov ider = vpt a_retrieve Provider(v pta_jsonQu ery);
  197  
  198                // getti ng current  users sys tem user r ecord to g et the cur rent busin ess unit I D
  199                var curr entUser =  Xrm.Page.c ontext.get UserId();
  200                currentU ser = curr entUser.re place(/({| })/g, '');
  201                currentU ser = curr entUser.to LowerCase( );
  202                var user  = vpta_re trieveProv ider(vpta_ serverUrl  + vpta_crm OdataEndPo int + "/Sy stemUserSe t(guid'" +  currentUs er + "')?$ select=*") ;
  203  
  204                if (prov ider.d.res ults.lengt h == 0) {  // only pr ocess if c urrent loo ped record  not found
  205                    var  vpta_provi der = new  Object();
  206                    vpta _provider. FirstName  = first;
  207                    vpta _provider. LastName =  last;
  208                    vpta _provider. ftp_PACTId  = {
  209                         Id: teamId ,
  210                         LogicalNam e: 'ftp_pa ct',
  211                         Name: vpta _teamname
  212                    };
  213                    vpta _provider. ftp_PACTTe amRole = t m[i].TeamR oleName;
  214                    vpta _provider. IsIntegrat ionUser =  false;
  215                    vpta _provider. UserLicens eType = 3;
  216                    vpta _provider. AccessMode  = {
  217                         Value: 0
  218                    };
  219                      vpta_provi der.Domain Name = fir st + "." +  last + "@ nodomainac count. DNS     ";
  220                    vpta _provider. BusinessUn itId = {
  221                         Id: user.d .BusinessU nitId.Id,
  222                         LogicalNam e: user.d. BusinessUn itId.Logic alName,
  223                         Name: user .d.Busines sUnitId.Na me
  224                    };
  225                    var  vpta_jsonE ntityData  = JSON.str ingify(vpt a_provider );
  226                    var  vpta_entit ySetName =  'SystemUs erSet';
  227                    var  vpta_creat eQuery = v pta_server Url + vpta _crmOdataE ndPoint +  '/' + vpta _entitySet Name;
  228                    var  vpta_newPr oviderId =  vpta_exec uteCrmOdat aPostReque st(vpta_cr eateQuery,  false, vp ta_jsonEnt ityData, ' CREATE', ' SystemUser Id');
  229                                      debugger ;
  230                    // a ssign to C RM OOB Tea mset for s ecurity ro les
  231                    vpta _assignTea m(vpta_new ProviderId , pactUser TeamId.d.r esults[0]. TeamId);
  232                    user sOnTeam.pu sh(vpta_ne wProviderI d);
  233                    if ( vpta_newPr oviderId ! == null &&  vpta_newP roviderId  === 'FAIL' ) {
  234                         vpta_pacti d = vpta_p actTeamId;   // this  is only se t in vpta_ processTea mName_resp onse and h as a local  scope the re
  235                         vpta_pactn ame = vpta _teamname;
  236                         //Notify U ser that n ew record  was create d
  237                         Xrm.Page.u i.setFormN otificatio n('This Ve teran’s  PACT Team  Provider ( ' + last +  ',' + fir st + ') wa s not foun d.  As a r esult, you  will only  be able t o assign R equests to  the PACT  Team or to  other pro viders fro m this PAC T, but not  to (' + l ast + ','  + first +  ').', 'WAR NING', 'PA CT_CREATE' );
  238                    }
  239                }
  240  
  241                var role  = tm[i].T eamRoleNam e;
  242                if (prov ider.d.res ults.lengt h > 0) {
  243                    var  providerRo le = new O bject();
  244                    prov iderRole.f tp_PACTTea mRole = ro le;
  245                    prov iderRole.f tp_PACTId  = {
  246                         Id: teamId ,
  247                         LogicalNam e: 'ftp_pa ct',
  248                         Name: vpta _teamname
  249                    };
  250                    var  vpta_jsonE ntityData  = JSON.str ingify(pro viderRole) ;
  251                    user sOnTeam.pu sh(provide r.d.result s[0].Syste mUserId);
  252                                      vpta_con firmMember ship(provi der.d.resu lts[0].Sys temUserId,  pactUserT eamId.d.re sults[0].T eamId);
  253                    var  vpta_entit ySetName =  'SystemUs erSet';
  254                    var  vpta_jsonQ uery = vpt a_serverUr l + vpta_c rmOdataEnd Point + "/ " + vpta_e ntitySetNa me + "(gui d'" + prov ider.d.res ults[0].Sy stemUserId  + "')";
  255                    vpta _executeCr mOdataPost Request(vp ta_jsonQue ry, false,  vpta_json EntityData , 'UPDATE' , 'SystemU serId');
  256                }
  257           }
  258  
  259           re moveNonMem bers(users OnTeam, te amId);
  260       }
  261       catch  (e) { aler t("Error o ccured whi le process ing Home B ound Provi ders. ERRO R:" + e);  }
  262   }
  263  
  264   // vpta_pr ocessPrima ryTeamMemb ers and vm ta_process MentalHeal thCorridin ator funct ions shoul d be broke n out into  
  265   // smaller  reusable  functions  when time
  266   // Process es Primary  Care and  Home Bound  provider  members in to CRM
  267   function v pta_proces sPrimaryTe amMembers( vpta_teamm embers, vp ta_teamnam e) {
  268       try {
  269           va r tm = vpt a_teammemb ers;  // s ee if this  is necess ary
  270           va r pactUser TeamId = v pta_retrie veProvider (vpta_serv erUrl + vp ta_crmOdat aEndPoint  + "/TeamSe t?$filter= Name eq 'P ACT User'" );
  271           va r usersOnT eam = [];
  272           va r teamId =  vpta_retr ieveTeamId (vpta_team name);
  273           fo r (i = 0;  i < tm.len gth; i++)  {
  274                if (tm[i ].StaffCon tact != nu ll && tm[i ].StaffCon tact != un defined) {
  275                    // i f provider  indicated  by StaffC ontact the n check to  see if in  System Us er
  276                    var  name = tm[ i].StaffCo ntact.Name ;
  277                    var  splitname  = name.spl it(",");
  278                    var  last = spl itname[0];
  279                    var  firstmiddl e = splitn ame[1];
  280                    var  first = fi rstmiddle. split(" ") ;
  281                    firs t = first[ 0];
  282                    var  vpta_entit ySetName =  'SystemUs erSet';
  283                    var  vpta_attri buteSet =  'FirstName , LastName , SystemUs erId';
  284                    var  vpta_condi tionalFilt er = "Firs tName eq ' " + first  + "'& Last Name eq '"  + last +  "'";
  285                    var  vpta_jsonQ uery = vpt a_serverUr l + vpta_c rmOdataEnd Point + '/ ' + vpta_e ntitySetNa me + '?$se lect=' + v pta_attrib uteSet + ' &$filter='  + vpta_co nditionalF ilter;
  286                    var  provider =  vpta_retr ieveProvid er(vpta_js onQuery);
  287  
  288                    // g etting cur rent users  system us er record  to get the  current b usiness un it ID
  289                    var  currentUse r = Xrm.Pa ge.context .getUserId ();
  290                    curr entUser =  currentUse r.replace( /({|})/g,  '');
  291                    curr entUser =  currentUse r.toLowerC ase();
  292                    var  user = vpt a_retrieve Provider(v pta_server Url + vpta _crmOdataE ndPoint +  "/SystemUs erSet(guid '" + curre ntUser + " ')?$select =*");
  293  
  294                    if ( provider.d .results.l ength == 0 ) {
  295                         // provide r indicate d by Staff Contact wa s not foun d so creat ing the sy stem user  record
  296                         var vpta_p rovider =  new Object ();
  297                         vpta_provi der.FirstN ame = firs t;
  298                         vpta_provi der.LastNa me = last;
  299                         vpta_provi der.ftp_PA CTId = {
  300                             Id: te amId,
  301                             Logica lName: 'ft p_pact',
  302                             Name:  vpta_teamn ame
  303                         };
  304                         vpta_provi der.ftp_PA CTTeamRole  = tm[i].S taffContac t.TeamRole Name;
  305                         vpta_provi der.IsInte grationUse r = false;
  306                         vpta_provi der.UserLi censeType  = 3;
  307                         vpta_provi der.Access Mode = {
  308                             Value:  0
  309                         };
  310                          vpta_provi der.Domain Name = fir st + "." +  last + "@ nodomainac count. DNS     ";
  311                         vpta_provi der.Busine ssUnitId =  {
  312                             Id: us er.d.Busin essUnitId. Id,
  313                             Logica lName: use r.d.Busine ssUnitId.L ogicalName ,
  314                             Name:  user.d.Bus inessUnitI d.Name
  315                         };
  316                         var vpta_j sonEntityD ata = JSON .stringify (vpta_prov ider);
  317                         var vpta_e ntitySetNa me = 'Syst emUserSet' ;
  318                         var vpta_c reateQuery  = vpta_se rverUrl +  vpta_crmOd ataEndPoin t + '/' +  vpta_entit ySetName;
  319                         var vpta_n ewProvider Id = vpta_ executeCrm OdataPostR equest(vpt a_createQu ery, false , vpta_jso nEntityDat a, 'CREATE ', 'System UserId');
  320                                               debugger;
  321                         // assign  to CRM OOB  Teamset f or securit y roles
  322                         vpta_assig nTeam(vpta _newProvid erId, pact UserTeamId .d.results [0].TeamId );
  323                         usersOnTea m.push(vpt a_newProvi derId);
  324                         if (vpta_n ewProvider Id !== nul l && vpta_ newProvide rId === 'F AIL') {
  325                             vpta_p actid = vp ta_pactTea mId;  // t his is onl y set in v pta_proces sTeamName_ response a nd has a l ocal scope  there
  326                            vpta_pa ctname = v pta_teamna me;
  327                             //Noti fy User th at new rec ord was cr eated
  328                             Xrm.Pa ge.ui.setF ormNotific ation('Thi s Veteranâ €™s PACT T eam Provid er (' + la st + ',' +  first + ' ) was not  found.  As  a result,  you will  only be ab le to assi gn Request s to the P ACT Team o r to other  providers  from this  PACT, but  not to ('  + last +  ',' + firs t + ').',  'WARNING',  'PACT_CRE ATE');
  329                         }
  330                    }
  331  
  332                    var  role = tm[ i].StaffCo ntact.Team RoleName;
  333                    if ( provider.d .results.l ength > 0)  {
  334                         var provid erRole = n ew Object( );
  335                         providerRo le.ftp_PAC TTeamRole  = role;
  336                         providerRo le.ftp_PAC TId = {
  337                             Id: te amId,
  338                             Logica lName: 'ft p_pact',
  339                             Name:  vpta_teamn ame
  340                         };
  341                         var vpta_j sonEntityD ata = JSON .stringify (providerR ole);
  342                         usersOnTea m.push(pro vider.d.re sults[0].S ystemUserI d);
  343                                               vpta_confi rmMembersh ip(provide r.d.result s[0].Syste mUserId, p actUserTea mId.d.resu lts[0].Tea mId);
  344                         var vpta_e ntitySetNa me = 'Syst emUserSet' ;
  345                         var vpta_j sonQuery =  vpta_serv erUrl + vp ta_crmOdat aEndPoint  + "/" + vp ta_entityS etName + " (guid'" +  provider.d .results[0 ].SystemUs erId + "') ";
  346                         vpta_execu teCrmOdata PostReques t(vpta_jso nQuery, fa lse, vpta_ jsonEntity Data, 'UPD ATE', 'Sys temUserId' );
  347                    }
  348                }
  349           }
  350  
  351           re moveNonMem bers(users OnTeam, te amId);
  352       }
  353       catch  (e) {
  354           al ert("Error  occured w hile proce ssing Prim ary Care P roviders.  ERROR:" +  e);
  355       }
  356   }
  357  
  358   // Process es Team in to CRM
  359   function v pta_proces sTeamName( vpta_teamn ame) {
  360       try {
  361           // Check if T eam Name f rom PCMM i ntegration  service a lready exi st in CRM
  362           va r vpta_con ditionalFi lter = "(f tp_name eq  '" + vpta _teamname  + "')";
  363           vp ta_getMult ipleEntity DataAsync( 'ftp_pactS et', 'ftp_ pactId, ft p_name', v pta_condit ionalFilte r, 'ftp_na me', 'asc' , 0, vpta_ processTea mName_resp onse, vpta _teamname) ;
  364       }
  365       catch  (err) {
  366           al ert('Veter an form lo ad, PCMM I ntegration  Service F unction Er ror (vpta_ processTea mName): '  + err.mess age);
  367       }
  368   }
  369  
  370   function v pta_proces sTeamName_ response(v pta_pactDa ta, vpta_l astSkip, v pta_teamna me) {
  371       try {
  372           // vpta__last Skip is th e starting  point in  the result  (use if m ore than 5 0 records)  //Not use d in this  scenario
  373           va r vpta_pac tid = null ;
  374           va r vpta_pac tname = nu ll;
  375           fo r (var i =  0; i <= v pta_pactDa ta.d.resul ts.length  - 1; i++)  {
  376                //Get in fo
  377                if (vpta _pactData. d.results[ i].ftp_pac tId != nul l) { vpta_ pactid = v pta_pactDa ta.d.resul ts[i].ftp_ pactId; }
  378                if (vpta _pactData. d.results[ i].ftp_nam e != null)  { vpta_pa ctname = v pta_pactDa ta.d.resul ts[i].ftp_ name; }
  379                break;
  380           }
  381  
  382           // Check if t he pact te am was fou nd, if not  add it.
  383           if  (vpta_pac tname == n ull) {
  384                var vpta _pactTeam  = new Obje ct();
  385                vpta_pac tTeam.ftp_ name = vpt a_teamname ;
  386                var vpta _jsonEntit yData = JS ON.stringi fy(vpta_pa ctTeam);
  387                var vpta _entitySet Name = 'ft p_pactSet' ;
  388                var vpta _jsonQuery  = vpta_se rverUrl +  vpta_crmOd ataEndPoin t + '/' +  vpta_entit ySetName;
  389                var vpta _pactTeamI d = vpta_e xecuteCrmO dataPostRe quest(vpta _jsonQuery , false, v pta_jsonEn tityData,  'CREATE',  'ftp_pactI d');
  390                if (vpta _pactTeamI d != null  && vpta_pa ctTeamId ! = 'FAIL')  {
  391                    vpta _pactid =  vpta_pactT eamId; //  this is on ly set in  vpta_proce ssTeamName _response  and has a  local scop e there
  392                    vpta _pactname  = vpta_tea mname;
  393                    //No tify User  that new r ecord was  created
  394                    //Xr m.Page.ui. setFormNot ification( 'This Vete ran’s PA CT Team ('  + vpta_te amname + ' ) was not  found.  As  a result,  you will  only be ab le to assi gn Request s to the P ACT Team,  not to ind ividuals o n the team .', 'WARNI NG', 'PACT _CREATE');
  395                }
  396           }
  397  
  398           // Populate C RM Veteran  form with  PACT Team  data and  update con tact/veter an record  directly
  399           if  (vpta_pac tid != nul l) {
  400                var vpta _lookupRef erence = [ ];
  401                vpta_loo kupReferen ce[0] = {} ;
  402                vpta_loo kupReferen ce[0].id =  vpta_pact id;
  403                vpta_loo kupReferen ce[0].enti tyType = ' ftp_pact';
  404                vpta_loo kupReferen ce[0].name  = vpta_pa ctname;
  405                Xrm.Page .getAttrib ute('ftp_p actid').se tValue(vpt a_lookupRe ference);
  406  
  407                //Update  CRM
  408                var vpta _contactVe teran = ne w Object() ;
  409                vpta_con tactVetera n.ftp_PACT Id = {
  410                    Id:  vpta_pacti d,
  411                    Logi calName: ' ftp_pact',
  412                    Name : vpta_tea mname
  413                };
  414  
  415                var vpta _jsonEntit yData = JS ON.stringi fy(vpta_co ntactVeter an);
  416                var vpta _entitySet Name = 'Co ntactSet';
  417                var vpta _jsonQuery  = vpta_se rverUrl +  vpta_crmOd ataEndPoin t + "/" +  vpta_entit ySetName +  "(guid'"  + Xrm.Page .data.enti ty.getId()  + "')";
  418                vpta_exe cuteCrmOda taPostRequ est(vpta_j sonQuery,  false, vpt a_jsonEnti tyData, 'U PDATE', 'C ontactId') ;
  419                             
  420                             
  421           }
  422       }
  423       catch  (err) {
  424           al ert('Veter an form lo ad, PCMM I ntegration  Service F unction Er ror(vpta_p rocessTeam Name_respo nse) Error  Detail: '  + err.mes sage);
  425       }
  426   }
  427  
  428   // Process es mental  health pro vider corr dinator in to CRM
  429   function v mta_proces sMentalHea lthCorridi nator(vmta _teamname,
  430                                          vmta _corrdinat orName,
  431                                          vmta _corrdinat orRoleName ,
  432                                          vmta _corrdinat orRoleCode ,
  433                                          vmta _corrdinat orRolePhon e,
  434                                          vmta _corrdinat orRolePage r,
  435                                          vmta _corrdinat orRoleIen)  {
  436  
  437       // ret rieve PACT  Team ID p ointer fro m CRM OOB  Team
  438       var pa ctUserTeam Id = vpta_ retrievePr ovider(vpt a_serverUr l + vpta_c rmOdataEnd Point + "/ TeamSet?$f ilter=Name  eq 'PACT  User'");
  439       // var  usersOnTe am = [];
  440       // ret rieve PACT  Team ID f rom PACT T eam entity
  441       //var  teamId = v pta_retrie veTeamId(v mta_teamna me);
  442  
  443       // par se out nam e for syst em user re cord query
  444       var sp litname =  vmta_corrd inatorName .split("," );
  445       var la st = split name[0];
  446       var fi rstmiddle  = splitnam e[1];
  447       var fi rst = firs tmiddle.sp lit(" ");
  448       first  = first[0] ;
  449  
  450  
  451       // ***  returns n othing
  452       // que ry the sys tem User's  record
  453       var vm ta_entityS etName = ' SystemUser Set';
  454       var vm ta_attribu teSet = 'F irstName,  LastName,  SystemUser Id';
  455       var vm ta_conditi onalFilter  = "FirstN ame eq '"  + first +  "'& LastNa me eq '" +  last + "' ";
  456       var vm ta_jsonQue ry = vpta_ serverUrl  + vpta_crm OdataEndPo int + '/'  + vmta_ent itySetName  + '?$sele ct=' + vmt a_attribut eSet + '&$ filter=' +  vmta_cond itionalFil ter;
  457       var pr ovider = v pta_retrie veProvider (vmta_json Query);
  458  
  459       // get ting the c urrent CRM  users sys tem user r ecord to g et the cur rent busin ess unit.
  460       // var  orgName =  Xrm.Page. context.ge tOrgUnique Name();
  461       var cu rrentUser  = Xrm.Page .context.g etUserId() ;
  462       curren tUser = cu rrentUser. replace(/( {|})/g, '' );
  463       curren tUser = cu rrentUser. toLowerCas e();
  464       var us er = vpta_ retrievePr ovider(vpt a_serverUr l + vpta_c rmOdataEnd Point + "/ SystemUser Set(guid'"  + current User + "') ?$select=* ");
  465  
  466       // if  provider w as not fou nd create  the system  user reco rd
  467       if (pr ovider.d.r esults.len gth == 0)  {
  468           va r vmta_pro vider = ne w Object() ;
  469           vm ta_provide r.FirstNam e = first;
  470           vm ta_provide r.LastName  = last;
  471  
  472           // vmta_provi der.ftp_PA CTId = {
  473           //     Id: te amId,
  474           //     Logica lName: 'ft p_pact',
  475           //     Name:  vmta_teamn ame
  476           // };
  477  
  478           vm ta_provide r.ftp_PACT TeamRole =  vmta_corr dinatorRol eName;
  479           vm ta_provide r.IsIntegr ationUser  = false;
  480           vm ta_provide r.UserLice nseType =  3;
  481           vm ta_provide r.AccessMo de = {
  482                Value: 0
  483           };
  484  
  485             vmta_provi der.Domain Name = fir st + "." +  last + "@ nodomainac count. DNS     ";
  486           vm ta_provide r.Business UnitId = {
  487                Id: user .d.Busines sUnitId.Id ,
  488                LogicalN ame: user. d.Business UnitId.Log icalName,
  489                Name: us er.d.Busin essUnitId. Name
  490           };
  491  
  492           va r vmta_jso nEntityDat a = JSON.s tringify(v mta_provid er);
  493           va r vmta_ent itySetName  = 'System UserSet';
  494           va r vmta_cre ateQuery =  vpta_serv erUrl + vp ta_crmOdat aEndPoint  + '/' + vm ta_entityS etName;
  495           va r vmta_new ProviderId  = vpta_ex ecuteCrmOd ataPostReq uest(vmta_ createQuer y, false,  vmta_jsonE ntityData,  'CREATE',  'SystemUs erId');
  496  
  497           //  assign to  CRM OOB T eamset for  security  roles
  498           vp ta_assignT eam(vmta_n ewProvider Id, pactUs erTeamId.d .results[0 ].TeamId);
  499           us ersOnTeam. push(vmta_ newProvide rId);
  500           if  (vmta_new ProviderId  != null & & vmta_new ProviderId  == 'FAIL' ) {
  501                vmta_pac tid = vpta _pactTeamI d; // this  is only s et in vpta _processTe amName_res ponse and  has a loca l scope th ere
  502                vmta_pac tname = vm ta_teamnam e;
  503                //Notify  User that  new recor d was crea ted
  504                Xrm.Page .ui.setFor mNotificat ion('This  Veteran’ s PACT Tea m Provider  (' + last  + ',' + f irst + ')  was not fo und.  As a  result, y ou will on ly be able  to assign  Requests  to the PAC T Team or  to other p roviders f rom this P ACT, but n ot to (' +  last + ', ' + first  + ').', 'W ARNING', ' PACT_CREAT E');
  505           }
  506  
  507           //  give the  user roles
  508           if  (provider .d.results .length >  0) {
  509                var prov iderRole =  new Objec t();
  510                provider Role.ftp_P ACTTeamRol e = vmta_c orrdinator RoleName;
  511                /*provid erRole.ftp _PACTId =  {
  512                    Id:  teamId,
  513                    Logi calName: ' ftp_pact',
  514                    Name : vmta_tea mname
  515                };*/
  516                var vpta _jsonEntit yData = JS ON.stringi fy(provide rRole);
  517                var vpta _entitySet Name = 'Sy stemUserSe t';
  518                var vpta _jsonQuery  = vpta_se rverUrl +  vpta_crmOd ataEndPoin t + "/" +  vmta_entit ySetName +  "(guid'"  + provider .d.results [0].System UserId + " ')";
  519                vpta_exe cuteCrmOda taPostRequ est(vpta_j sonQuery,  false, vpt a_jsonEnti tyData, 'U PDATE', 'S ystemUserI d');
  520           }
  521       }
  522   }
  523  
  524   // HDR ser vice opera tion
  525   function v pta_getPac tTeamViaPC MM(id) {
  526       //Perf orms web s ervice cal l to the P CMM Interg ation Serv ice via th e patientS ummary met hod
  527           va r ftype =  Xrm.Page.u i.getFormT ype();
  528           if (ftype ==  1){
  529                    retu rn;
  530           }
  531       try {
  532           se ttings = r etrieveSet tings();
  533           // var site =  Xrm.Page. getAttribu te("ftp_fa cilityid") .getValue( );
  534           // var icn =  Xrm.Page.g etAttribut e("bah_mvi patientide ntitifier" ).getValue ();
  535  
  536                    //Je ff testing  new user
  537                    //va r site = ' 987';
  538                    //va r icn ='10 12871347V6 62728';
  539                    
  540           //  This has  no primary  care assi gnment dat a
  541           va r site = ' 987';
  542           va r icn = id ;
  543  
  544           //  this has  no mental  health ass ignment da ta
  545           //  var site  = '991';
  546           //  var icn =  '10126671 10V216290' ;
  547  
  548           va r pcmmUrl  = settings .d.results [0].ftp_DA CURL + set tings.d.re sults[0].f tp_Patient SummaryAPI URL + site  + '/' + i cn + '?idT ype=ICN';
  549           // Determine  Form State
  550           if  (Xrm.Page .ui.getFor mType() ==  1) { retu rn false;  } //Form i n Create M ode abort
  551           // Get contac t guid
  552           va r vpta_con tactGuid =  Xrm.Page. data.entit y.getId();
  553  
  554           // Get vetera n/contact  data
  555           va r vpta_crm facilityid  = null; / /Home Faci lity
  556           va r vpta_crm patienticn  = null; / /Patient I CN
  557  
  558           if  (Xrm.Page .getAttrib ute("ftp_f acilityid" ) != null)  {
  559                if (Xrm. Page.getAt tribute("f tp_facilit yid").getV alue() !=  null) {
  560                    vpta _crmfacili tyid = Xrm .Page.getA ttribute(" ftp_facili tyid").get Value()[0] .id;
  561                }
  562           }
  563  
  564           if  (Xrm.Page .getAttrib ute("tri_v eteranid")  != null)  {
  565                if (Xrm. Page.getAt tribute("t ri_veteran id").getVa lue() != n ull) {
  566                    vpta _crmpatien ticn = Xrm .Page.getA ttribute(" tri_vetera nid").getV alue()[0]. id;
  567                }
  568           }
  569  
  570           // Get facili ty data
  571           va r vpta_crm facilityco de = null;  //Facilit y Numeric  code (int3 2)
  572           va r vpta_fac ilityData  = vpta_get SingleEnti tyDataSync ('ftp_faci litySet',  'ftp_facil itycode',  vpta_crmfa cilityid);
  573           if  (vpta_fac ilityData  != null) {
  574                if (vpta _facilityD ata.d.ftp_ facilityco de != null ) { vpta_c rmfacility code = vpt a_facility Data.d.ftp _facilityc ode; }
  575           }
  576  
  577           if  (vpta_crm facilityco de == null ) {
  578                //Insuff icient dat a to perfo rm MCMM In tegration  Service ca ll
  579                return f alse;
  580           }
  581  
  582           // Call PCMM  Integratio n Service  (patient s ummary)
  583           vp ta_getPati entSummary Data(vpta_ crmfacilit ycode, vpt a_crmpatie nticn, pcm mUrl);
  584       }
  585       catch  (err) {
  586           al ert('Veter an form lo ad, PCMM I ntegration  Service F unction Er ror (vpta_ getPactTea mViaPCMM):  ' + err.m essage);
  587       }
  588   }
  589  
  590   // databas e operatio n function s
  591   function v pta_execut eCrmOdataG etRequest( vpta_jsonQ uery, vpta _aSync, vp ta_aSyncCa llback, vp ta_skipCou nt, vpta_o ptionArray ) {
  592       //This  function  executes a  CRM Odata  web servi ce call to  retrieve  Crm data
  593       //*vpt a_jsonQuer y* - a pro perly form atted CRM  Odata Quer y string ( required)
  594       //*vpt a_aSync* -  specify ' true' to e xecute asy nchronousl y otherwis e 'false'  (required)
  595       //*vpt a_aSyncCal lback* - s pecify the  name of t he return  function t o call upo n completi on (requir ed if vpta _aSync = t rue.  Othe rwise '')
  596       //*vpt a_skipCoun t* - Initi al setting  is always  '0', incr ements by  50 per CRM  SDK Odata  standards  (required )
  597       //*vpt a_optionAr ray* - is  an optiona l array or  single va lue, that  contains a dditional  task speci fic variab les that c an be pass ed between  functions  (pass 'nu ll' if not  used)
  598       try {
  599           va r vpta_ent ityData =  null;
  600           $. ajax({
  601                type: 'G ET',
  602                contentT ype: 'appl ication/js on; charse t=utf-8',
  603                datatype : 'json',
  604                url: vpt a_jsonQuer y,
  605                beforeSe nd: functi on (XMLHtt pRequest)  {
  606                    XMLH ttpRequest .setReques tHeader('A ccept', 'a pplication /json');
  607                },
  608                success:  function  (data, tex tStatus, X mlHttpRequ est) {
  609                    vpta _entityDat a = data;
  610                    if ( vpta_aSync  == true)  {
  611                         vpta_aSync Callback(v pta_entity Data, vpta _skipCount , vpta_opt ionArray);
  612                    }
  613                },
  614                error: f unction (X MLHttpRequ est, textS tatus, err orThrown)  {
  615                    aler t('Fail: A jax Error  in vpta_ex ecuteCrmOd ataGetRequ est: ' + e rrorThrown );
  616                },
  617                async: v pta_aSync,
  618                cache: f alse
  619           }) ;
  620           re turn vpta_ entityData ;
  621       }
  622       catch  (err) {
  623           al ert('An er ror occure d in the v pta_execut eCrmOdataG etRequest  function.   Error Det ail Messag e: ' + err );
  624       }
  625   }
  626  
  627   function v pta_getSin gleEntityD ataSync(vp ta_entityS etName, vp ta_attribu teSet, vpt a_entityId ) {
  628       //This  function  returns a  CRM JSON d ataset for  a single  entity rec ord based  on the ent ity id pro vided Sync ronously
  629       //*vpt a_entitySe tName* - i s the name  of the en tity set e .g 'Contac tSet'
  630       //*vpt a_attribut eSet* -  i s a string  containin g the Crm  Attributes  to retrie ve e.g. 'F irstName,  LastName,  Telephone1 , EMailAdd ress1'
  631       //*vpt a_entityId * - is the  Guid for  the entity  record
  632  
  633       try {
  634           va r vpta_ent ityIdNoBra cket = vpt a_entityId .replace(/ ({|})/g, ' ');
  635           va r vpta_sel ectString  = '(guid'  + "'" + vp ta_entityI dNoBracket  + "'" + ' )?$select= ' + vpta_a ttributeSe t;
  636           va r vpta_jso nQuery = v pta_server Url + vpta _crmOdataE ndPoint +  '/' + vpta _entitySet Name + vpt a_selectSt ring;
  637           va r vpta_ent ityData =  vpta_execu teCrmOdata GetRequest (vpta_json Query, fal se, '', 0,  null);
  638           re turn vpta_ entityData ;
  639       }
  640       catch  (err) {
  641           al ert('An er ror occure d in the v pta_getSin gleEntityD ataSync fu nction.  E rror Detai l Message:  ' + err);
  642       }
  643   }
  644  
  645   function v pta_getMul tipleEntit yDataAsync (vpta_enti tySetName,  vpta_attr ibuteSet,  vpta_condi tionalFilt er, vpta_s ortAttribu te, vpta_s ortDirecti on, vpta_s kipCount,  vpta_aSync Callback,  vpta_optio nArray) {
  646       //This  function  returns a  CRM JSON d ataset for  all entit y records  matching c riteria pr ovided Asy ncronously
  647       //*vpt a_entitySe tName* - i s the name  of the en tity set e .g 'Contac tSet'
  648       //*vpt a_attribut eSet* -  i s a string  containin g the Crm  Attributes  to retrie ve e.g. 'F irstName,  LastName,  Telephone1 , EMailAdd ress1'
  649       //*vpt a_conditio nalFilter*  - is the  conditiona l filter v alue place d on the d ata values  retrived  e.g. 'Stat eCode/Valu e eq 0'  t o retrieve  active co ntact reco rds only
  650       //*vpt a_sortAttr ibute* - i s a string  containin g the name  of the at tribute to  sort the  result set  by e.g. ' LastName'
  651       //*vpt a_sortDire ction* - i s a string  specifyin g the sort  as Ascend ing or Des cending e. g. 'asc' o r 'desc'
  652       //*vpt a_skipCoun t* - is th e starting  point in  the result  (use if m ore than 5 0), (Put 0  if not us ed)
  653       //*vpt a_aSyncCal lback* - i s the name  of the fu nction to  call when  returning  the result
  654       //*vpt a_optionAr ray* - is  an optiona l array, t hat contai ns additio nal task s pecific va riables th at can be  passed bet ween funct ions
  655  
  656       try {
  657           va r vpta_jso nQuery = v pta_server Url + vpta _crmOdataE ndPoint +  '/' + vpta _entitySet Name + '?$ select=' +  vpta_attr ibuteSet +  '&$filter =' + vpta_ conditiona lFilter +  '&$orderby =' + vpta_ sortAttrib ute + ' '  + vpta_sor tDirection  + '&$skip =' + vpta_ skipCount;
  658           vp ta_execute CrmOdataGe tRequest(v pta_jsonQu ery, true,  vpta_aSyn cCallback,  vpta_skip Count, vpt a_optionAr ray);
  659       }
  660       catch  (err) {
  661           al ert('An er ror occure d in the v pta_getMul tipleEntit yDataAsync  function.   Error De tail Messa ge: ' + er r);
  662       }
  663   }
  664  
  665   function v pta_execut eCrmOdataP ostRequest (vpta_json Query, vpt a_aSync, v pta_jsonEn tityData,  vpta_recor dAction, v pta_crmGui dFieldName ) {
  666       //This  function  executes a  CRM Odata  web servi ce call to  create/up date a Crm  Record
  667       //*vpt a_jsonQuer y* - the c omplete qu ery (url)  to be exec uted
  668       //*vpt a_aSync* -  specify ' true' to e xecute asy nchronousl y otherwis e 'false'  (required)
  669       //*vpt a_jsonEnti tyData* -  the crm en tity data  record to  be created /updated
  670       //*vpt a_recordAc tion* - th e action t o be perfo rmed in CA PS 'CREATE ', 'UPDATE , 'DELETE'
  671       //*vpt a_crmGuidF ieldName*  - the name  of the un ique ident ifier fiel d that has  the Guid/ Id for the  crm recor d created
  672  
  673       try {
  674           va r vpta_crm EntityId =  'FAIL';
  675  
  676           $. ajax({
  677                type: 'P OST',
  678                contentT ype: 'appl ication/js on; charse t=utf-8',
  679                datatype : 'json',
  680                url: vpt a_jsonQuer y,
  681                data: vp ta_jsonEnt ityData,
  682                beforeSe nd: functi on (XMLHtt pRequest)  {
  683                    XMLH ttpRequest .setReques tHeader('A ccept', 'a pplication /json');
  684                    if ( vpta_recor dAction ==  'UPDATE')  { XMLHttp Request.se tRequestHe ader('X-HT TP-Method' , 'MERGE') ; }
  685                    if ( vpta_recor dAction ==  'DELETE')  { XMLHttp Request.se tRequestHe ader('X-HT TP-Method' , 'DELETE' ); }
  686                },
  687                success:  function  (data, tex tStatus, X mlHttpRequ est) {
  688                    if ( vpta_recor dAction ==  'CREATE')  { vpta_cr mEntityId  = data.d[v pta_crmGui dFieldName ].toString (); }
  689                },
  690                error: f unction (X mlHttpRequ est, textS tatus, err orThrown)  {
  691                    aler t('Ajax Er ror in vpt a_executeC rmOdataPos tRequest:  ' + errorT hrown);
  692                    vpta _crmEntity Id = 'FAIL ';
  693                },
  694                async: v pta_aSync
  695           }) ;
  696           if  (vpta_rec ordAction  == 'CREATE ') { retur n vpta_crm EntityId;  }
  697       }
  698       catch  (err) {
  699           al ert('An er ror occure d in the v pta_execut eCrmOdataP ostRequest  function.   Error De tail Messa ge: ' + er r);
  700       }
  701   }
  702  
  703   function v pta_retrie veVeteran( query) {
  704       try {
  705           // Initialize  the retur n value
  706           va r EntityDa ta = null;
  707           $. ajax({
  708                type: "G ET",
  709                contentT ype: "appl ication/js on; charse t=utf-8",
  710                datatype : "json",
  711                url: que ry,
  712                beforeSe nd: functi on (XMLHtt pRequest)  {
  713                    //Sp ecifying t his header  ensures t hat the re sults will  be return ed as JSON .
  714                    XMLH ttpRequest .setReques tHeader("A ccept", "a pplication /json");
  715                },
  716                success:  function  (data, tex tStatus, X mlHttpRequ est) {
  717                    //Ge t the data  values
  718                    Enti tyData = d ata;
  719  
  720                },
  721                error: f unction (X MLHttpRequ est, textS tatus, err orThrown)  {
  722                    aler t('Fail: A jax Error  in TRIBRID GE.Retriev eAllAttrib utesByEnti tySync: '  + errorThr own);
  723                },
  724                async: f alse,
  725                cache: f alse
  726           }) ;
  727  
  728       }
  729       catch  (e) {
  730           al ert("Error  occurred  while retr ieving set tings in P CMM integr ation. Err or data:"  + e);
  731       }
  732  
  733   }
  734  
  735   function v pta_retrie veProvider (query) {
  736       try {
  737  
  738           // Initialize  the retur n value
  739           va r EntityDa ta = null;
  740           $. ajax({
  741                type: "G ET",
  742                contentT ype: "appl ication/js on; charse t=utf-8",
  743                datatype : "json",
  744                url: que ry,
  745                beforeSe nd: functi on (XMLHtt pRequest)  {
  746                    //Sp ecifying t his header  ensures t hat the re sults will  be return ed as JSON .
  747                    XMLH ttpRequest .setReques tHeader("A ccept", "a pplication /json");
  748                },
  749                success:  function  (data, tex tStatus, X mlHttpRequ est) {
  750                    //Ge t the data  values
  751                    Enti tyData = d ata;
  752  
  753                },
  754                error: f unction (X MLHttpRequ est, textS tatus, err orThrown)  {
  755                    aler t('Fail: A jax Error  in vpta_re trieveVete ran: ' + e rrorThrown );
  756                },
  757                async: f alse,
  758                cache: f alse
  759           }) ;
  760           re turn Entit yData;
  761       }
  762       catch  (e) {
  763           al ert("Error  occurred  while retr ieving set tings in P CMM integr ation. Err or data:"  + e);
  764       }
  765   }
  766  
  767   function v pta_confir mMembershi p(vpta_Pro viderId, v pta_TeamId ){
  768           tr y {
  769                    debu gger;
  770                    var  context =  Xrm.Page.c ontext.get ClientUrl( );
  771           va r ODATA_EN DPOINT = " /XRMServic es/2011/Or ganization Data.svc";
  772           // Construct  the JSON Q uery
  773           va r EntitySe tName = "T eamMembers hipSet";
  774           va r selectSt ring = "?$ select=*&$ filter=Tea mId eq (gu id'" + vpt a_TeamId +  "') and S ystemUserI d eq (guid '"+vpta_Pr oviderId+" ')";
  775           va r jsonQuer y = contex t + ODATA_ ENDPOINT +  "/" + Ent itySetName  + selectS tring;
  776           // Initialize  the retur n value
  777           va r EntityDa ta = null;
  778           $. ajax({
  779                type: "G ET",
  780                contentT ype: "appl ication/js on; charse t=utf-8",
  781                datatype : "json",
  782                url: jso nQuery,
  783                beforeSe nd: functi on (XMLHtt pRequest)  {
  784                    //Sp ecifying t his header  ensures t hat the re sults will  be return ed as JSON .
  785                    XMLH ttpRequest .setReques tHeader("A ccept", "a pplication /json");
  786                },
  787                success:  function  (data, tex tStatus, X mlHttpRequ est) {
  788                    //Ge t the data  values
  789                    Enti tyData = d ata;
  790  
  791                },
  792                error: f unction (X MLHttpRequ est, textS tatus, err orThrown)  {
  793                    aler t('Fail: A jax Error  in vpta_re trieveVete ran: ' + e rrorThrown );
  794                },
  795                async: f alse,
  796                cache: f alse
  797           }) ;
  798                    if(E ntityData. d.results. length > 0 ){
  799                             return ;
  800                    }
  801                    else {
  802                             vpta_a ssignTeam( vpta_Provi derId, vpt a_TeamId);
  803                    }
  804           
  805       }
  806       catch  (e) {
  807           al ert("Error  occurred  while conf irming Tea m Membersh ip in PCMM  integrati on. Error  data:" + e );
  808       }
  809           
  810   }
  811   function v pta_retrie veTeamId(t eamname) {
  812       try {
  813           va r context  = Xrm.Page .context.g etClientUr l();
  814           va r ODATA_EN DPOINT = " /XRMServic es/2011/Or ganization Data.svc";
  815           // Construct  the JSON Q uery
  816           va r EntitySe tName = "f tp_pactSet ";
  817           va r selectSt ring = "?$ select=*&$ filter=ftp _name eq ' " + teamna me + "'";
  818           va r jsonQuer y = contex t + ODATA_ ENDPOINT +  "/" + Ent itySetName  + selectS tring;
  819           // Initialize  the retur n value
  820           va r EntityDa ta = null;
  821           $. ajax({
  822                type: "G ET",
  823                contentT ype: "appl ication/js on; charse t=utf-8",
  824                datatype : "json",
  825                url: jso nQuery,
  826                beforeSe nd: functi on (XMLHtt pRequest)  {
  827                    //Sp ecifying t his header  ensures t hat the re sults will  be return ed as JSON .
  828                    XMLH ttpRequest .setReques tHeader("A ccept", "a pplication /json");
  829                },
  830                success:  function  (data, tex tStatus, X mlHttpRequ est) {
  831                    //Ge t the data  values
  832                    Enti tyData = d ata;
  833  
  834                },
  835                error: f unction (X MLHttpRequ est, textS tatus, err orThrown)  {
  836                    aler t('Fail: A jax Error  in TRIBRID GE.Retriev eAllAttrib utesByEnti tySync: '  + errorThr own);
  837                },
  838                async: f alse,
  839                cache: f alse
  840           }) ;
  841           re turn Entit yData.d.re sults[0].f tp_pactId;
  842       }
  843       catch  (e) {
  844           al ert("Error  occurred  while retr ieving set tings in P CMM integr ation. Err or data:"  + e);
  845       }
  846   }
  847  
  848   function v pta_assign Team(userI d, teamId)  {
  849       var se rviceURL =  Xrm.Page. context.ge tClientUrl () + "/XRM Services/2 011/Organi zation.svc /web";
  850       var re questMain  = "";
  851       reques tMain += " <s:Envelop e xmlns:s= \"http://s chemas.xml soap.org/s oap/envelo pe/\">";
  852       reques tMain += "   <s:Body> ";
  853       reques tMain += "     <Execu te xmlns=\ "http://sc hemas.micr osoft.com/ xrm/2011/C ontracts/S ervices\"  xmlns:i=\" http://www .w3.org/20 01/XMLSche ma-instanc e\">";
  854       reques tMain += "       <req uest i:typ e=\"b:AddM embersTeam Request\"  xmlns:a=\" http://sch emas.micro soft.com/x rm/2011/Co ntracts\"  xmlns:b=\" http://sch emas.micro soft.com/c rm/2011/Co ntracts\"> ";
  855       reques tMain += "         <a :Parameter s xmlns:c= \"http://s chemas.dat acontract. org/2004/0 7/System.C ollections .Generic\" >";
  856       reques tMain += "            <a:KeyValu ePairOfstr inganyType >";
  857       reques tMain += "              <c:key>T eamId</c:k ey>";
  858       reques tMain += "              <c:value  i:type=\" d:guid\" x mlns:d=\"h ttp://sche mas.micros oft.com/20 03/10/Seri alization/ \">" + tea mId + "</c :value>";
  859       reques tMain += "            </a:KeyVal uePairOfst ringanyTyp e>";
  860       reques tMain += "            <a:KeyValu ePairOfstr inganyType >";
  861       reques tMain += "              <c:key>M emberIds</ c:key>";
  862       reques tMain += "              <c:value  i:type=\" d:ArrayOfg uid\" xmln s:d=\"http ://schemas .microsoft .com/2003/ 10/Seriali zation/Arr ays\">";
  863       reques tMain += "                <d:gui d>" + user Id + "</d: guid>";
  864       reques tMain += "              </c:valu e>";
  865       reques tMain += "            </a:KeyVal uePairOfst ringanyTyp e>";
  866       reques tMain += "         </ a:Paramete rs>";
  867       reques tMain += "         <a :RequestId  i:nil=\"t rue\" />";
  868       reques tMain += "         <a :RequestNa me>AddMemb ersTeam</a :RequestNa me>";
  869       reques tMain += "       </re quest>";
  870       reques tMain += "     </Exec ute>";
  871       reques tMain += "   </s:Body >";
  872       reques tMain += " </s:Envelo pe>";
  873       var re q = new XM LHttpReque st();
  874       req.op en("POST",  serviceUR L, true);
  875       // Res ponses wil l return X ML. It isn 't possibl e to retur n JSON.
  876       req.se tRequestHe ader("Acce pt", "appl ication/xm l, text/xm l, */*");
  877       req.se tRequestHe ader("Cont ent-Type",  "text/xml ; charset= utf-8");
  878       req.se tRequestHe ader("SOAP Action", " http://sch emas.micro soft.com/x rm/2011/Co ntracts/Se rvices/IOr ganization Service/Ex ecute");
  879       var su ccessCallb ack = null ;
  880       var er rorCallbac k = null;
  881       req.on readystate change = f unction ()  { };
  882       req.se nd(request Main);
  883   }
  884  
  885   function r emoveNonMe mbers(user sOnTeam, t eam) {
  886       var pr oviderQuer y = vpta_s erverUrl +  vpta_crmO dataEndPoi nt + "/Sys temUserSet ?$select=S ystemUserI d&$filter= ftp_PACTId /Id eq (gu id'" + tea m + "')";
  887       var al lTeamUsers  = vpta_re trieveProv ider(provi derQuery);
  888       var al lUsersIds  = [];
  889       for (i  = 0; i <  allTeamUse rs.d.resul ts.length;  i++) {
  890           al lUsersIds. push(allTe amUsers.d. results[i] .SystemUse rId);
  891       }
  892  
  893       for (v  = 0; v <  usersOnTea m.length;  v++) {
  894           re moveByValu e(allUsers Ids, users OnTeam[v]) ;
  895       }
  896       for (i  = 0; i <  allUsersId s.length;  i++) {
  897           va r provider Role = new  Object();
  898           pr oviderRole .ftp_PACTT eamRole =  null;
  899           pr oviderRole .ftp_PACTI d = {
  900                Id: null ,
  901                LogicalN ame: null,
  902                Name: nu ll
  903           };
  904           va r vpta_jso nEntityDat a = JSON.s tringify(p roviderRol e);
  905  
  906           va r vpta_ent itySetName  = 'System UserSet';
  907           va r vpta_jso nQuery = v pta_server Url + vpta _crmOdataE ndPoint +  "/" + vpta _entitySet Name + "(g uid'" + al lUsersIds[ i] + "')";
  908           vp ta_execute CrmOdataPo stRequest( vpta_jsonQ uery, fals e, vpta_js onEntityDa ta, 'UPDAT E', 'Syste mUserId');
  909       }
  910   }
  911  
  912   // support  functions
  913   function i nArray(val ue, array)  {
  914       var co unt = arra y.length;
  915       for (v ar i = 0;  i < count;  i++) {
  916           if  (array[i]  === value ) { return  true; }
  917       }
  918       return  false;
  919   }
  920  
  921   function r emoveByVal ue(arr, va l) {
  922       for (v ar i = 0;  i < arr.le ngth; i++)  {
  923           if  (arr[i] = = val) {
  924                arr.spli ce(i, 1);
  925                break;
  926           }
  927       }
  928   }
  929  
  930   function r etrieveSet tings() {
  931       try {
  932           va r context  = Xrm.Page .context.g etClientUr l();
  933           va r ODATA_EN DPOINT = " /XRMServic es/2011/Or ganization Data.svc";
  934           // Construct  the JSON Q uery
  935           va r EntitySe tName = "m cs_setting Set";
  936           va r selectSt ring = "?$ select=*&$ filter=mcs _name eq ' Active Set tings'";
  937           va r jsonQuer y = contex t + ODATA_ ENDPOINT +  "/" + Ent itySetName  + selectS tring;
  938           // Initialize  the retur n value
  939           va r EntityDa ta = null;
  940           $. ajax({
  941                type: "G ET",
  942                contentT ype: "appl ication/js on; charse t=utf-8",
  943                datatype : "json",
  944                url: jso nQuery,
  945                beforeSe nd: functi on (XMLHtt pRequest)  {
  946                    //Sp ecifying t his header  ensures t hat the re sults will  be return ed as JSON .
  947                    XMLH ttpRequest .setReques tHeader("A ccept", "a pplication /json");
  948                },
  949                success:  function  (data, tex tStatus, X mlHttpRequ est) {
  950                    //Ge t the data  values
  951                    Enti tyData = d ata;
  952  
  953                },
  954                error: f unction (X MLHttpRequ est, textS tatus, err orThrown)  {
  955                    aler t('Fail: A jax Error  in TRIBRID GE.Retriev eAllAttrib utesByEnti tySync: '  + errorThr own);
  956                },
  957                async: f alse,
  958                cache: f alse
  959           }) ;
  960           re turn Entit yData;
  961       }
  962       catch  (e) {
  963           al ert("Error  occurred  while retr ieving set tings in P CMM integr ation. Err or data:"  + e);
  964       }
  965   }
  966  
  967   function U serNotific ations(pri maryHomeBo undCareNot ification,  pmentalHe althNotifi cation, pt cmNotifica tion) {
  968       if (pr imaryHomeB oundCareNo tification  && !pment alHealthNo tification ) {
  969           Xr m.Page.ui. setFormNot ification( 'This Vete ran’s PA CT Team ('  + vpta_te amname + ' ) contains  no listed  providers .  As a re sult, you  will only  be able to  assign Re quests to  the PACT T eam, not t o individu als on the  team.', ' WARNING',  'PACT_CREA TE');
  970       }
  971       else i f (!primar yHomeBound CareNotifi cation &&  pmentalHea lthNotific ation) {
  972           Xr m.Page.ui. setFormNot ification( 'This Vete ran’s Me ntal Healt h Team ('  + vmta_tea mname + ')  contains  no listed  providers.   As a res ult, you w ill only b e able to  assign Req uests to t he PACT Te am, not to  individua ls on the  team.', 'W ARNING', ' PACT_CREAT E');
  973       }
  974       else i f (primary HomeBoundC areNotific ation && p mentalHeal thNotifica tion) {
  975           Xr m.Page.ui. setFormNot ification( 'This Vete ran’s PA CT Team ('  + vpta_te amname + ' ) and and  Mental Hea lth Team ( ' + vmta_t eamname +  ') contain s no liste d provider s.  As a r esult, you  will only  be able t o assign R equests to  the PACT  or Mental  Health Tea m(s), not  to individ uals on th e team.',  'WARNING',  'PACT_CRE ATE');
  976       }
  977   }
  978  
  979   function D efaultTeam () {
  980       // def ault team  of PACT Te am 12
  981   }
  982  
  983   // this is  not used  right now
  984   function s pecialtyAs signmentsP roviderPro cessing()  {
  985  
  986   }
  987  
  988   function v eteranMVIS earch() {
  989           de bugger;
  990           va r filter =  "";
  991           va r filterPr efix = "$s elect=*&$f ilter=";
  992           va r edipi =  "";
  993           // var edipi  = Xrm.Page .getAttrib ute("bah_e dipi_text" ).getValue ();
  994           if  (edipi !=  null) {
  995                    if(e dipi.lengt h>11) {
  996                             edipi  = "";
  997                    }
  998           }
  999           el se {
  1000                    edip i = "";
  1001           }
  1002           va r firstnam e = Xrm.Pa ge.getAttr ibute("fir stname").g etValue();
  1003           va r lastname  = Xrm.Pag e.getAttri bute("last name").get Value();
  1004  
  1005           va r dobdate  = Xrm.Page .getAttrib ute("ftp_d ateofbirth ").getValu e();
  1006           va r dobstrin g = "";
  1007           if (dobdate ! = null) {
  1008                    dobs tring =dob date;
  1009           }
  1010  
  1011  
  1012           va r ssn = Xr m.Page.get Attribute( "governmen tid").getV alue();
  1013           if  (ssn != " " && ssn ! = null) {
  1014                    ssn  = ssn.repl ace(/-/g,  "");
  1015           }
  1016  
  1017           // if we have  edipi, se arch using  just it
  1018           if  (edipi !=  "") {
  1019                    filt er = build QueryFilte r("crme_ED IPI", edip i, false);
  1020                    filt er += buil dQueryFilt er("crme_C lassCode",  'MIL', tr ue);
  1021                    filt er += buil dQueryFilt er("crme_S earchType" , 'SearchB yIdentifie r', true);
  1022  
  1023                    //se t search t ype as una ttended
  1024                    filt er += " an d crme_IsA ttended eq  false";
  1025           }
  1026           el se {
  1027                    //ot herwise se arch using  lastname,  firstname , ssn, dob
  1028                    filt er = build QueryFilte r("crme_La stName", l astname, f alse); //a ssuming la stname wil l never be  blank
  1029  
  1030                    if ( firstname  != "" && f irstname ! = null) {
  1031                             filter  += buildQ ueryFilter ("crme_Fir stName", f irstname,  true);
  1032                    }
  1033  
  1034                    if ( ssn != ""  && ssn !=  null) {
  1035                             filter  += buildQ ueryFilter ("crme_SSN ", ssn, tr ue);
  1036                    }
  1037  
  1038                    if ( dobstring  != "") {
  1039                             filter  += " and  crme_DOBSt ring eq '"  + dobstri ng + "'";
  1040                    }
  1041                    filt er += buil dQueryFilt er("crme_S earchType" , 'SearchB yFilter',  true);
  1042  
  1043                    //se t search t ype as att ended (for  now)
  1044                    filt er += " an d crme_IsA ttended eq  true";
  1045           }
  1046  
  1047  
  1048           fi lter = enc odeURIComp onent(filt er);
  1049           fi lter = fil terPrefix  + filter;
  1050           // debugger;
  1051           SD K.REST.ret rieveMulti pleRecords ("crme_per son", filt er, unatte ndedSearch Callback,  function ( error) { a lert(error .message);  }, unatte ndedSearch Complete);
  1052   }
  1053  
  1054   function u nattendedS earchCallb ack(return Data) {
  1055           de bugger;
  1056           if  (returnDa ta != null  && return Data.lengt h==1) {
  1057                    // c heck for e xceptions  1st
  1058                    if ( returnData [0].crme_E xceptionOc cured || ( returnData [0].crme_R eturnMessa ge != null  && return Data[0].cr me_ReturnM essage ==  "An unexpe cted error  occured d uring the  MVI search . Please t ry again o r contact  your syste m administ rator if t he problem  persists. ")) {
  1059                             //do n othing
  1060                    }
  1061                    else  {
  1062                             var pa tientMviId entifier =  returnDat a[0].crme_ PatientMvi Identifier  == null ?  "" : retu rnData[0]. crme_Patie ntMviIdent ifier;
  1063                             if(pat ientMviIde ntifier!=" "){
  1064                                      var idpa rts = pati entMviIden tifier.spl it("^");
  1065                                      
  1066                                      if(idpar ts.length> 0) {
  1067                                               var nation alId = idp arts[0];
  1068                                               _icn = nat ionalId;
  1069                                              
  1070                                               //DO WHATE VER YOU AR E GOING TO  DO WITH T HE ICN HER E
  1071                                               vpta_getPa ctTeamViaP CMM(_icn);
  1072                                      }
  1073                             }
  1074                    }
  1075           }
  1076   }
  1077   function b uildQueryF ilter(fiel d, value,  and) {
  1078           if  (value ==  '') {
  1079                    if ( and) {
  1080                             return  " and " +  field + "  eq null";
  1081                    } el se {
  1082                             return  field + "  eq null";
  1083                    }
  1084           }
  1085           el se {
  1086                    if ( and) {
  1087                             return  " and " +  field + "  eq '" + v alue + "'" ;
  1088                    } el se {
  1089                             return  field + "  eq '" + v alue + "'" ;
  1090                    }
  1091           }
  1092   }
  1093  
  1094   function u nattendedS earchCompl ete() {
  1095           // do nothing
  1096   }