116. EPMO Open Source Coordination Office Redaction File Detail Report

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

116.1 Files compared

# Location File Last Modified
1 VCCM.zip\VCCM\CRM_solutions\VCCMResources\WebResources ftp_VeteranJScriptpcmmjs395353A2-524D-E711-944F-0050568D743D Tue Nov 7 11:34:40 2017 UTC
2 VCCM.zip\VCCM\CRM_solutions\VCCMResources\WebResources ftp_VeteranJScriptpcmmjs395353A2-524D-E711-944F-0050568D743D Thu Nov 30 17:07:55 2017 UTC

116.2 Comparison summary

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

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

116.4 Active regular expressions

No regular expressions were active.

116.5 Comparison detail

  1   var PCMMGr idMembers  = []; /*us ed by old  PCMMTeamDi splay.html  web resou rce*/
  2   var _pcmmR esponse =  null;
  3   var finish edGettingP rimaryCare Providers  = false;
  4   var finish edGettingM HTC = fals e;
  5   //******** ********** ********** ********** **
  6   //Set new  PCMM Enabl ed flag to  True as d efault, th en read fr om 'Active  Settings'
  7   var pcmm_E nabled = t rue;
  8   //******** ********** ********** ********** **
  9  
  10   var _PactT eamRolesIn Order = [
  11           "P RIMARY CAR E PROVIDER ",
  12           "P CP",
  13           "A SSOCIATE P ROVIDER",
  14           "R EGISTERED  NURSE",
  15           "R N",
  16           "C ARE MANAGE R",
  17           "L ICENSED PR ACTICAL NU RSE",
  18           "L PN",
  19           "L VN",
  20           "L PN/LVN",
  21           "C LINICAL AS SOCIATE",
  22           "A DMINISTRAT IVE ASSOCI ATE",
  23           "M SA",
  24           "A DMINISTRAT IVE POC",
  25           "P ACT CLINIC AL PHARMAC IST",
  26           "P HARMACIST" ,
  27           "S OCIAL WORK ER"
  28   ];
  29  
  30   function p erformPCMM WebService Call(pFaci lityCode,  pICN) {
  31           // this funct ion is fir ed after r etrieving  the vetera n's Prefer red Facili ty from ES R
  32           wr iteToConso le("begin  performPCM MWebServic eCall()");
  33           Xr m.Page.ui. clearFormN otificatio n("noPACTF romPCMM");
  34           Xr m.Page.ui. clearFormN otificatio n("onlyPen dingPACTFr omPCMM");
  35           pc mm_Enabled  = (_retri evedSettin gs.hasOwnP roperty("f tp_IsPCMME nabled") & & _retriev edSettings .ftp_IsPCM MEnabled ! = null) ?  _retrieved Settings.f tp_IsPCMME nabled : t rue;
  36           wr iteToConso le("pcmm_E nabled: "  + pcmm_Ena bled);
  37           if (pcmm_Enab led && _re trievedSet tings.hasO wnProperty ("ftp_Pati entSummary APIURL") & & !!_retri evedSettin gs.ftp_Pat ientSummar yAPIURL){
  38                    var  facilityCo de = _notP rod ? "991 " : pFacil ityCode;
  39                    writ eToConsole ("_notProd : " + _not Prod);
  40                    writ eToConsole ("facility Code used  in PCMM qu ery: " + f acilityCod e);
  41                    var  ICN = !!pI CN ? pICN  : !!_ICN ?  _ICN : nu ll;
  42                    if(! !facilityC ode && !!I CN){
  43                             PCMMGr idMembers  = []; /*cl ear the PC MMGridMemb ers array  before col lecting ne w data fro m PCMM*/
  44                             _pcmmR esponse =  null;
  45                             var pc mmUrl = _r etrievedSe ttings.ftp _DACURL +  _retrieved Settings.f tp_Patient SummaryAPI URL + faci lityCode +  "/" + ICN  + "?idTyp e=ICN";
  46                             writeT oConsole(" firing GET  against P CMM url: "  + pcmmUrl );                        
  47                             $.ajax ({
  48                                      type: "G ET",
  49                                      contentT ype: "appl ication/js on; charse t=utf-8",
  50                                      datatype : "json",
  51                                      url: pcm mUrl,
  52                                      beforeSe nd: functi on (XMLHtt pRequest)  {
  53                                               //Specifyi ng this he ader ensur es that th e results  will be re turned as  JSON.
  54                                               XMLHttpReq uest.setRe questHeade r("Accept" , "applica tion/json" );
  55                                      },
  56                                      success:  function  (response,  textStatu s, XmlHttp Request) {
  57                                               _pcmmRespo nse = resp onse;
  58                                               var return Object = r esponse;
  59                                               writeToCon sole("insi de PCMM su ccess call back");
  60                                               //parse th e returnOb ject JSON  object for  data from  PCMM.
  61                                               if (typeof  returnObj ect != "un defined" & & $.isPlai nObject(re turnObject ) && !$.is EmptyObjec t(returnOb ject)) {
  62                                                       if (!$.isXMLD oc(returnO bject)){
  63                                                                if ( returnObje ct.ErrorOc curred ==  true || re turnObject .ErrorMess age != nul l || retur nObject.De bugInfo !=  null) {
  64                                                                         writeT oConsole(" error retr ieving PCM M data:");
  65                                                                         writeT oConsole(r eturnObjec t.DebugInf o);
  66                                                                         fillFt p_pactIdWi thPlacehol derPactTea m("Error o ccurred re trieving P CMM data f or facilit y: " + fac ilityCode  + (_notPro d ? "(Non- Prod)" : " "));
  67                                                                }
  68                                                                else  {
  69                                                                         if (re turnObject .hasOwnPro perty("Dat a")) {
  70                                                                                  var data  = returnO bject.Data ;
  71                                                                                  writeToC onsole("go t data obj ect from P CMM: ");
  72                                                                                  writeToC onsole(dat a);
  73                                                                                  var summ aryText =  data.Patie ntSummaryT ext;
  74                                                                                  if (data .hasOwnPro perty("pat ientAssign ments") &&  $.isArray (data.pati entAssignm ents) && d ata.patien tAssignmen ts.length  > 0) {
  75                                                                                           //this is  the happy  path
  76                                                                                           var patien tAssignmen t = data.p atientAssi gnments[0] ;
  77                                                                                           writeToCon sole("got  patientAss ignment fr om data.") ;
  78                                                                                           processAss ignments(p atientAssi gnment);
  79                                                                                           processMen talHealthP rovider(pa tientAssig nment);
  80                                                                                  }
  81                                                                                  else if  (summaryTe xt.trim()  == "No PAC T assigned  at any VA  location. ") {
  82                                                                                           PCMMGridMe mbers.push ({ Name: s ummaryText .trim(), T eamRoleNam e: "" });
  83                                                                                           fillFtp_pa ctIdWithPl aceholderP actTeam("T his vetera n does not  have a PA CT assigne d at any V A location s" + (_not Prod ? " ( Non-Prod)"  : ""));
  84                                                                                           return;
  85                                                                                  }
  86                                                                                  else if  (summaryTe xt.trim()  == "Patien t was not  found for  local site !") {
  87                                                                                           PCMMGridMe mbers.push ({ Name: s ummaryText .trim(), T eamRoleNam e: "" });
  88                                                                                           fillFtp_pa ctIdWithPl aceholderP actTeam("P CMM did no t find vet eran at fa cility: "  + facility Code + (_n otProd ? "  (Non-Prod )" : ""));
  89                                                                                           return;
  90                                                                                  }
  91                                                                                  else {
  92                                                                                           //if we do n't find A NY patient Assignment s and also  don't hav e a "no re sults mess age", just  assign th e placehol der PACT t eam
  93                                                                                           fillFtp_pa ctIdWithPl aceholderP actTeam("P CMM did no t return a ny data fo r veteran  at facilit y: " + fac ilityCode  + (_notPro d ? " (Non -Prod)" :  ""));
  94                                                                                  }
  95                                                                         }
  96                                                                }
  97                                                       }
  98                                                       el se{
  99                                                                fill Ftp_pactId WithPlaceh olderPactT eam("PCMM  returned d ata for ve teran at f acility "  + facility Code + ",  but it is  in the wro ng format. \nCheck yo ur CRM org anization' s Active S ettings.") ;
  100                                                       }
  101                                               }
  102                                               else {
  103                                                       fi llFtp_pact IdWithPlac eholderPac tTeam("PCM M did not  return any  data for  veteran at  facility:  " + facil ityCode +  (_notProd  ? "(Non-Pr od)" : "") );
  104                                               }
  105                                      },
  106                                      error: f unction (X MLHttpRequ est, textS tatus, err orThrown)  {
  107                                               writeToCon sole("insi de PCMM er ror callba ck: " + er rorThrown) ;
  108                                               fillFtp_pa ctIdWithPl aceholderP actTeam("E rror query ing PCMM:  " + errorT hrown);
  109                                      },
  110                                      async: t rue,
  111                                      cache: f alse
  112                             });
  113                    }
  114           }
  115           el se{
  116                    writ eToConsole ("PCMM is  disabled o r we are m issing ftp _PatientSu mmaryAPIUR L from Act ive Settin gs.");
  117                    
  118                    Xrm. Page.getCo ntrol("Web Resource_V eteranPACT Team").set Visible(fa lse);
  119                    Xrm. Page.getCo ntrol("ftp _pactid"). setVisible (false);
  120                    Xrm. Page.getAt tribute("f tp_pactid" ).setSubmi tMode("alw ays");
  121                    Xrm. Page.getCo ntrol("ftp _primaryca reprovider ").setVisi ble(false) ;
  122                    Xrm. Page.getAt tribute("f tp_primary careprovid er").setSu bmitMode(" always");
  123                    
  124                    fill Ftp_pactId WithPlaceh olderPactT eam("PCMM  web servic e calls ar e disabled , or we ar e missing  the Patien t Summary  API from A ctive Sett ings. Cont act your a dministrat or.");
  125           }
  126   }
  127  
  128   function p rocessAssi gnments(pP atientAssi gnment) {
  129       writeT oConsole(" begin proc essAssignm ents()");
  130       if (!! pPatientAs signment)  {
  131                    /* S ummary
  132                             pPatie ntAssignme nt will ha ve either  'primaryCa reAssignme nts' or 'p rimaryCare HBPCAssign ments' (ho me bound a ssignments ).
  133                             The pr imaryCareA ssignments  array can  have mult iple teams , with sta tuses of ' Active' or  'Pending' .
  134                             Not su re if a pr imaryCareH BPCAssignm ents array  can also  have multi ple teams  with varyi ng statuse s.  Not en ough test  data. -kkn ab 9/28/17
  135                             Cycle  through th e one with  data and  store them  in the te amMembersF romPCMM ar ray and th e PCMMGrid Members ar ray.
  136                    */
  137                    
  138                    var  teamName =  "";
  139                    var  teamMember sFromPCMM  = []; //em pty array  intended t o hold obj ects of sc hema { Nam e, TeamRol eName }
  140                    
  141                    if ( pPatientAs signment.h asOwnPrope rty("prima ryCareAssi gnments")  && Array.i sArray(pPa tientAssig nment.prim aryCareAss ignments)  && pPatien tAssignmen t.primaryC areAssignm ents.lengt h > 0) {
  142                             //prim aryCareAss ignments a rray
  143                             writeT oConsole(" found prim aryCareAss ignments") ;
  144                             var fo undActiveA ssignment  = false;
  145                             var fo undPending Assignment  = false;
  146                             for(va r x in pPa tientAssig nment.prim aryCareAss ignments){
  147                                      var this PCAssignme nt = pPati entAssignm ent.primar yCareAssig nments[x];
  148                                      var pcAs signmentSt atus = thi sPCAssignm ent.assign mentStatus  != undefi ned ? this PCAssignme nt.assignm entStatus  : "Pending ";
  149                                      if(pcAss ignmentSta tus.toLowe rCase() ==  "active") {
  150                                               teamName =  !!thisPCA ssignment. teamName ?  thisPCAss ignment.te amName : " ";
  151                                               foundActiv eAssignmen t = true;
  152                                               writeToCon sole("foun d the acti ve primary CareAssign ment: " +  teamName);
  153                                               if (thisPC Assignment .hasOwnPro perty("tea mletMember s") && $.i sArray(thi sPCAssignm ent.teamle tMembers)  && thisPCA ssignment. teamletMem bers.lengt h > 0) {
  154                                                       fo r (var i =  0, l = th isPCAssign ment.teaml etMembers. length; i  < l; i++)  {
  155                                                                var  thisTeamle tMember =  thisPCAssi gnment.tea mletMember s[i];
  156                                                                if ( thisTeamle tMember.ha sOwnProper ty("StaffC ontact") & & !!thisTe amletMembe r.StaffCon tact) {
  157                                                                         var sc  = thisTea mletMember .StaffCont act;
  158                                                                         if (sc .hasOwnPro perty("Nam e") && !!s c.Name &&  sc.hasOwnP roperty("T eamRoleNam e") && !!s c.TeamRole Name) {
  159                                                                                  var pers on = { Nam e: sc.Name , TeamRole Name: sc.T eamRoleNam e };
  160                                                                                  teamMemb ersFromPCM M.push(per son);
  161                                                                                  PCMMGrid Members.pu sh(person) ;
  162                                                                         }
  163                                                                }
  164                                                       }
  165                                                       fi nishedGett ingPrimary CareProvid ers = true ;
  166                                               }
  167                                               else {
  168                                                       fi nishedGett ingPrimary CareProvid ers = true ;
  169                                               }
  170                                      }
  171                                      else if( pcAssignme ntStatus.t oLowerCase () == "pen ding"){
  172                                               foundPendi ngAssignme nt = true;
  173                                      }
  174                             }
  175                             
  176                             if(fou ndPendingA ssignment  && !foundA ctiveAssig nment){
  177                                      var aler tText = "T his vetera n has a pe nding Care  Team Assi gnment but  does not  have an ac tive Care  Team Assig nment.";
  178                                      Xrm.Page .ui.setFor mNotificat ion(alertT ext, "WARN ING", "onl yPendingPA CTFromPCMM ");
  179                             }
  180                    }
  181                    else  if (pPati entAssignm ent.hasOwn Property(" primaryCar eHBPCAssig nments") & & Array.is Array(pPat ientAssign ment.prima ryCareHBPC Assignment s) && pPat ientAssign ment.prima ryCareHBPC Assignment s.length >  0) {
  182                             //prim aryCareHBP CAssignmen ts array
  183                             writeT oConsole(" found prim aryCareHBP CAssignmen ts");
  184                             var ho meboundPCA ssignment  = pPatient Assignment .primaryCa reHBPCAssi gnments[0] ;
  185                             teamNa me = !!hom eboundPCAs signment.t eamName ?  homeboundP CAssignmen t.teamName  : "";
  186                             if (ho meboundPCA ssignment. hasOwnProp erty("team Members")  && homebou ndPCAssign ment.teamM embers.len gth > 0) {
  187                                      for (var  i = 0, l  = homeboun dPCAssignm ent.teamMe mbers.leng th; i < l;  i++) {
  188                                               var thisTe amMember =  homebound PCAssignme nt.teamMem bers[i];
  189                                               if (thisTe amMember.h asOwnPrope rty("Name" ) && !!thi sTeamMembe r.Name &&  thisTeamMe mber.hasOw nProperty( "TeamRoleN ame") && ! !thisTeamM ember.Team RoleName)  {
  190                                                       va r person =  { Name: t hisTeamMem ber.Name,  TeamRoleNa me: thisTe amMember.T eamRoleNam e };
  191                                                       te amMembersF romPCMM.pu sh(person) ;
  192                                                       PC MMGridMemb ers.push(p erson);
  193                                               }
  194                                      }
  195                                      finished GettingPri maryCarePr oviders =  true;
  196                             }
  197                             else {
  198                                      finished GettingPri maryCarePr oviders =  true;
  199                             }
  200                    }
  201                    else  {
  202                             //all  care assig nment arra ys are emp ty
  203                             finish edGettingP rimaryCare Providers  = true;
  204                    }
  205                    
  206                    if ( !!teamName ) {
  207                             /*
  208                             Now th at we have  the activ e PACT tea m and its  members fr om PCMM, f ind or cre ate that f tp_pact re cord in CR M.
  209                             Then,  cycle thro ugh the PA CT team's  teamletMem bers and f ind or cre ate them i n the syst emuser tab le, linkin g them to  the ftp_pa ct record  as you go.
  210                                      - this i s done in  the matchP CMMTeamMem bersToCRMP ACTTeam()  method, wh ich recurs ively call s itself f or every t eamletMemb er
  211                             While  cycling th rough the  teamletMem bers, thro w each one  into the  trySetPrim aryCarePro viderField () functio n, which w ill only w ork for th e 'Primary  Care Prov ider' or ' Associate  Provider'
  212                             After  linking al l appropri ate system user recor ds to this  ftp_pact  record, re move any s ystemuser  records th at should  no longer  be linked  to it, by  virtue of  not being  in this PA CT team's  teamletMem bers array
  213                                      - this i s done in  the unlink UsersFromP ACTTeam()  method
  214                             */
  215                             writeT oConsole(" retrieving  ftp_pact  record: "  + teamName );
  216                             //find  or create  a PACT te am record  called nam ed <teamNa me>
  217                             var re trievedPAC TTeams = [ ];
  218                             var qu eryString  = "$select =ftp_name, ftp_pactId ,ftp_ftp_p act_system user/First Name,ftp_f tp_pact_sy stemuser/L astName,ft p_ftp_pact _systemuse r/SystemUs erId,ftp_f tp_pact_sy stemuser/F ullName,ft p_ftp_pact _systemuse r/DomainNa me"; 
  219                             queryS tring += " &$filter=f tp_name eq  '" + team Name + "'"
  220                             queryS tring += " &$expand=f tp_ftp_pac t_systemus er";
  221                             SDK.RE ST.retriev eMultipleR ecords(
  222                                      "ftp_pac t",
  223                                      queryStr ing,
  224                                      function  (retrieve dRecords)  {
  225                                               if (typeof  retrieved Records !=  "undefine d" && !!re trievedRec ords) retr ievedPACTT eams = ret rievedPACT Teams.conc at(retriev edRecords) ;
  226                                      },
  227                                      errorHan dler,
  228                                      function  () {
  229                                               if (retrie vedPACTTea ms.length  > 0) {
  230                                                       wr iteToConso le("found  " + teamNa me + " PAC T team rec ord in CRM ");
  231                                                       se tftp_pacti d(retrieve dPACTTeams [0]);
  232                                                       ma tchPCMMTea mMembersTo CRMPACTTea m(retrieve dPACTTeams [0], teamM embersFrom PCMM, fals e, null);  //after ca lling it h ere, this  method cal ls itself  for the re st of the  PACT team  members fr om PCMM
  233                                               }
  234                                               else {
  235                                                       wr iteToConso le("did no t find " +  teamName  + " PACT t eam record  in CRM, c reating.") ;
  236                                                       va r newPact  = {
  237                                                                ftp_ name: team Name
  238                                                       };
  239                                                       SD K.REST.cre ateRecord(
  240                                                                newP act,
  241                                                                "ftp _pact",
  242                                                                func tion (crea tedPACTTea m) {
  243                                                                         setftp _pactid(cr eatedPACTT eam);
  244                                                                         matchP CMMTeamMem bersToCRMP ACTTeam(cr eatedPACTT eam, teamM embersFrom PCMM, fals e, null);  //after ca lling it h ere, this  method cal ls itself  for the re st of the  PACT team  members fr om PCMM
  245                                                                },
  246                                                                erro rHandler
  247                                                       );
  248                                               }
  249                                      });
  250                    }
  251                    else  {
  252                             /*If w e didn't f ind a team Name from  the primar yCareAssig nments or  primaryCar eHBPCAssig nments nod es, set ft p_pactId o n the vete ran to the  designate d placehol der ftp_pa ct record* /
  253                             fillFt p_pactIdWi thPlacehol derPactTea m();
  254                    }
  255           }
  256           el se{
  257                    writ eToConsole ("patient  assingnmen t object i s empty.") ;
  258           fi nishedGett ingPrimary CareProvid ers = true ;
  259           re turn;
  260           }
  261   }
  262  
  263   function p rocessMent alHealthPr ovider(pPa tientAssig nment) {
  264           /*  Summary
  265                    pPat ientAssign ment will  have a men talHealthA ssignments  property  that is an  array.
  266                    Cycl e through  the array  and store  its member s in the t eamMembers FromPCMM a rray and t he PCMMGri dMembers a rray.
  267           */
  268           wr iteToConso le("begin  processMen talHealthP rovider()" );
  269           if (!!pPatien tAssignmen t){
  270                    if ( pPatientAs signment.h asOwnPrope rty("menta lHealthAss ignments")  && !!pPat ientAssign ment.menta lHealthAss ignments & & Array.is Array(pPat ientAssign ment.menta lHealthAss ignments)  && pPatien tAssignmen t.mentalHe althAssign ments.leng th > 0) {
  271                             var me ntalHealth Assignment  = pPatien tAssignmen t.mentalHe althAssign ments[0];
  272                             if (me ntalHealth Assignment .hasOwnPro perty("tea mName") &&  !!mentalH ealthAssig nment.team Name) {
  273                                      var team Name = men talHealthA ssignment. teamName;
  274                                      if (ment alHealthAs signment.h asOwnPrope rty("menta lHealthTre atmentCoor d") && !!m entalHealt hAssignmen t.mentalHe althTreatm entCoord)  {
  275                                               var MHTC =  mentalHea lthAssignm ent.mental HealthTrea tmentCoord ;
  276                                               writeToCon sole("got  mentalHeal thAssignme nt.mentalH ealthTreat mentCoord  object.");
  277                                               PCMMGridMe mbers.push (MHTC);
  278                                               finishedGe ttingMHTC  = true;
  279  
  280                                               //find or  create the  PACT Team  record ma tching tea mName
  281                                               if (!!team Name) {
  282                                                       // find or cr eate a PAC T team rec ord called  named <te amName>
  283                                                       va r retrieve dPACTTeams  = [];
  284                                                       va r queryStr ing = "$fi lter=ftp_n ame eq '"  + teamName  + "' and  statecode/ Value eq 0 &$expand=f tp_ftp_pac t_systemus er&$select =ftp_name, ftp_pactId ,ftp_ftp_p act_system user/First Name,ftp_f tp_pact_sy stemuser/L astName,ft p_pactId,f tp_ftp_pac t_systemus er/FullNam e,ftp_ftp_ pact_syste muser/Syst emUserId";
  285                                                       SD K.REST.ret rieveMulti pleRecords (
  286                                                                "ftp _pact",
  287                                                                quer yString,
  288                                                                func tion (retr ievedRecor ds) {
  289                                                                         if (ty peof retri evedRecord s != "unde fined") re trievedPAC TTeams = r etrievedPA CTTeams.co ncat(retri evedRecord s);
  290                                                                },
  291                                                                erro rHandler,
  292                                                                func tion () {
  293                                                                         if (re trievedPAC TTeams.len gth > 0) {
  294                                                                                  matchMHT CToPACTTea m(retrieve dPACTTeams [0], MHTC) ;
  295                                                                         } 
  296                                                                         else {
  297                                                                                  var newP act = {
  298                                                                                           ftp_name:  teamName
  299                                                                                  };
  300                                                                                  SDK.REST .createRec ord(
  301                                                                                           newPact,
  302                                                                                           "ftp_pact" ,
  303                                                                                           function ( createdPAC TTeam) {
  304                                                                                                   ma tchMHTCToP ACTTeam(cr eatedPACTT eam, MHTC) ;
  305                                                                                           },
  306                                                                                           errorHandl er
  307                                                                                  );
  308                                                                         }
  309                                                                }
  310                                                       );
  311                                               }
  312                                      }
  313                                      else {
  314                                               finishedGe ttingMHTC  = true;
  315                                      }
  316                             }
  317                             else {
  318                                      finished GettingMHT C = true;
  319                             }
  320                    }
  321                    else  {
  322                             finish edGettingM HTC = true ;
  323                    }
  324           }
  325           el se{
  326                    writ eToConsole ("patient  assingment  object is  empty.");
  327           fi nishedGett ingMHTC =  true;
  328           re turn;
  329           }
  330   }
  331  
  332   function s etftp_pact id(pPACTTe amFromCRM) {
  333           wr iteToConso le("begin  setftp_pac tid()");
  334           va r attr = X rm.Page.ge tAttribute ("ftp_pact id");
  335           if (!!pPACTTe amFromCRM  && !!attr) {
  336                VCCM.USD Helper.Cop yDataToRep lacementPa rameters(" PCMM", ["P ACTTeam="  + pPACTTea mFromCRM.f tp_name],  false);
  337                    attr .setValue( [{
  338                             id: pP ACTTeamFro mCRM.ftp_p actId,
  339                             name:  pPACTTeamF romCRM.ftp _name,
  340                             entity Type: "ftp _pact"
  341                    }]);
  342                    attr .setSubmit Mode("alwa ys");
  343                    Xrm. Page.getAt tribute("f tp_pactid" ).addOnCha nge(ftp_pa ctid_onCha nge);
  344           }
  345   }
  346  
  347   function m atchPCMMTe amMembersT oCRMPACTTe am(pPACTTe amFromCRM,  pPACTTeam MembersFro mPCMM, pAl readySetPr imaryCareP roviderFie ld, pUsers ToUnlinkFr omPACTTeam ) {
  348           wr iteToConso le("");
  349           wr iteToConso le("begin  matchPCMMT eamMembers ToCRMPACTT eam()... p PACTTeamMe mbersFromP CMM.length  = " + pPA CTTeamMemb ersFromPCM M.length);
  350           
  351           // usersToUnl ink is an  array that  will end  up holding  a list of  users to  update, se tting thei r ftp_PACT id field n ull
  352           va r usersToU nlink = pU sersToUnli nkFromPACT Team; 
  353           // populate u sersToUnli nk from pP ACTTeamFro mCRM only  if we have n't alread y passed i n an array  of system user recor ds (pUsers ToUnlinkFr omPACTTeam )
  354           if (usersToUn link == nu ll){
  355                    user sToUnlink  = [];
  356                    var  initialUse rList = ge tDeepPrope rty("ftp_f tp_pact_sy stemuser.r esults", p PACTTeamFr omCRM);
  357                    if(A rray.isArr ay(initial UserList)  && initial UserList.l ength > 0) {
  358                             writeT oConsole(i nitialUser List.lengt h + " CRM  users alre ady connec ted to the  " + pPACT TeamFromCR M.ftp_name  + " PACT  team, befo re we add/ remove any body");
  359                             for (v ar i = 0,  l = initia lUserList. length; i  < l; i++)  {
  360                                      usersToU nlink.push (initialUs erList[i]) ;
  361                             }
  362                    }
  363                    else {
  364                             writeT oConsole(" no CRM use rs are cur rently con nected to  the " + pP ACTTeamFro mCRM.ftp_n ame + " PA CT team, b efore we a dd/remove  anybody");
  365                    }
  366           }
  367           
  368           if (pPACTTeam MembersFro mPCMM.leng th > 0){
  369                    var  alreadySet PrimaryCar eProviderF ield = pAl readySetPr imaryCareP roviderFie ld != null  ? pAlread ySetPrimar yCareProvi derField :  false;
  370                    var  thisTeamMe mber = pPA CTTeamMemb ersFromPCM M.shift();  //cut the  length of  pPACTTeam MembersFro mPCMM down  one at a  time
  371                    var  teamRoleIn dexValue =  _PactTeam RolesInOrd er.indexOf (thisTeamM ember.Team RoleName.t oUpperCase ());
  372                    var  desiredSor tOrderValu e = (teamR oleIndexVa lue > -1 ?  pad(teamR oleIndexVa lue,2).toS tring() :  "") + this TeamMember .TeamRoleN ame.toUppe rCase();
  373                    var  splitName  = thisTeam Member.Nam e.split(", ");
  374                    var  lastName =  splitName [0].trim() ;
  375                    var  splitFirst MiddleName s = splitN ame.length  > 1 ? spl itName[1]. trim().spl it(" ") :  "";
  376                    var  firstName  = !!splitF irstMiddle Names ? sp litFirstMi ddleNames[ 0] : "";
  377                    var  middleName  = !!split FirstMiddl eNames &&  splitFirst MiddleName s.length >  1 ? split FirstMiddl eNames[1]  : "";
  378                    var  fakeFullNa me = lastN ame + ", "  + firstNa me + " " +  middleNam e;
  379                     var domain Name = fir stName + " ." + lastN ame + "@no domainacco unt. DNS     ";/*see if  we can ge t PCMM to  return ema il address es*/
  380                    var  userQueryS tring = "$ select=Fir stName,Las tName,Syst emUserId,f tp_PACTId, ftp_PACTTe amRole,ftp _PACTSortO rder,IsDis abled,Doma inName,Ful lName"
  381                    user QueryStrin g += "&$fi lter=Domai nName eq ' " + domain Name + "'" ;
  382                    writ eToConsole ("thisTeam Member: "  + fakeFull Name + " ( " + domain Name + ")" );
  383                    var  retrievedU sers = [];
  384                    SDK. REST.retri eveMultipl eRecords(
  385                             "Syste mUser",
  386                             userQu eryString,
  387                             functi on (retrie vedRecords ) {
  388                                      if (type of retriev edRecords  != "undefi ned" && !! retrievedR ecords) re trievedUse rs = retri evedUsers. concat(ret rievedReco rds);
  389                             },
  390                             errorH andler,
  391                             functi on () {
  392                                      if (retr ievedUsers .length >  0) {
  393                                               var foundU ser = retr ievedUsers [0];
  394                                               if(!foundU ser.IsDisa bled){
  395                                                       wr iteToConso le("found  systemuser  " + found User.Domai nName + "  in CRM");
  396                                                       if  (foundUse r.hasOwnPr operty("ft p_PACTId")  && !!foun dUser.ftp_ PACTId &&  foundUser. ftp_PACTId .Id == pPA CTTeamFrom CRM.ftp_pa ctId &&
  397                                                                foun dUser.hasO wnProperty ("ftp_PACT TeamRole")  && foundU ser.ftp_PA CTTeamRole  == thisTe amMember.T eamRoleNam e &&
  398                                 fo undUser.ha sOwnProper ty("ftp_PA CTSortOrde r") && fou ndUser.ftp _PACTSortO rder == de siredSortO rderValue)  {
  399                                                                writ eToConsole (foundUser .FullName  + " is alr eady linke d to the "  + pPACTTe amFromCRM. ftp_name +  " and has  the corre ct PACT Te am Role an d PACT Sor t Order; s kipping up date.");
  400                                                                user sToUnlink  = removeUs erFromUser sToUnlink( foundUser,  usersToUn link);
  401                                                                if ( !alreadySe tPrimaryCa reProvider Field) alr eadySetPri maryCarePr oviderFiel d = trySet PrimaryCar eProviderF ield(found User);
  402                                                                matc hPCMMTeamM embersToCR MPACTTeam( pPACTTeamF romCRM, pP ACTTeamMem bersFromPC MM, alread ySetPrimar yCareProvi derField,  usersToUnl ink);//run  this meth od again
  403                                                       }
  404                                                       el se {
  405                                                                foun dUser.ftp_ PACTId = {
  406                                                                         Id: pP ACTTeamFro mCRM.ftp_p actId,
  407                                                                         Logica lName: "ft p_pact",
  408                                                                         Name:  pPACTTeamF romCRM.ftp _name
  409                                                                };
  410                                                                foun dUser.ftp_ PACTTeamRo le = thisT eamMember. TeamRoleNa me;
  411                                                                foun dUser.ftp_ PACTSortOr der = desi redSortOrd erValue;
  412                                                                SDK. REST.updat eRecord(
  413                                                                         foundU ser.System UserId,
  414                                                                         foundU ser,
  415                                                                         "Syste mUser",
  416                                                                         functi on () {
  417                                                                             wr iteToConso le("update d " + foun dUser.Doma inName + "  with PACT  team (" +  pPACTTeam FromCRM.ft p_name + " ),  PACT t eam role ( " + thisTe amMember.T eamRoleNam e + "), an d PACT tea m sort ord er (" + de siredSortO rderValue  + ")");
  418                                                                                  usersToU nlink = re moveUserFr omUsersToU nlink(foun dUser, use rsToUnlink );
  419                                                                                  if (!alr eadySetPri maryCarePr oviderFiel d) already SetPrimary CareProvid erField =  trySetPrim aryCarePro viderField (foundUser );
  420                                                                                  matchPCM MTeamMembe rsToCRMPAC TTeam(pPAC TTeamFromC RM, pPACTT eamMembers FromPCMM,  alreadySet PrimaryCar eProviderF ield, user sToUnlink) ;//run thi s method a gain
  421                                                                         },
  422                                                                         errorH andler
  423                                                                );
  424                                                       }
  425                                               }
  426                                               else{
  427                                                       wr iteToConso le("found  systemuser " + foundU ser.Domain Name + ",  but this u ser is dis abled.  Sk ipping use r update." );
  428                                               }
  429                                      }
  430                                      
  431                                      //If we  didn't fin d thisTeam Member in  CRM as a u ser, then  retrieve t he 'PACT U ser' CRM t eam, and c reate the  new user,  and make t he user a  member of  the team
  432                                      else { 
  433                                               writeToCon sole("did  not find "  + domainN ame + " in  CRM, crea ting syste muser.");
  434                                               var PACTUs erCRMTeam  = null;
  435                                               var teamQu ery = "$se lect=Name, TeamId,Bus inessUnitI d&$filter= Name eq 'P ACT User'  and TeamTy pe/Value e q 0";
  436                                               var retrie vedCRMTeam s = [];
  437                                               SDK.REST.r etrieveMul tipleRecor ds(
  438                                                       "T eam",
  439                                                       te amQuery,
  440                                                       fu nction (re trievedRec ords) {
  441                                                                if ( typeof ret rievedReco rds != "un defined" & & !!retrie vedRecords ) retrieve dCRMTeams  = retrieve dCRMTeams. concat(ret rievedReco rds);
  442                                                       },
  443                                                       er rorHandler ,
  444                                                       fu nction ()  {
  445                                                                if ( retrievedC RMTeams.le ngth > 0)  {
  446                                                                         PACTUs erCRMTeam  = retrieve dCRMTeams[ 0];
  447                                                                         
  448                                                                         //buil d newUser  object
  449                                                                         var ne wUser = {
  450                                                                                  FirstNam e: firstNa me,
  451                                                                                  LastName : lastName ,
  452                                                                                  MiddleNa me: middle Name,
  453                                                                                  ftp_PACT TeamRole:  thisTeamMe mber.TeamR oleName,
  454                                                                                  ftp_PACT SortOrder:  desiredSo rtOrderVal ue,
  455                                                                                  IsIntegr ationUser:  false,
  456                                                                                  UserLice nseType: 3 ,
  457                                                                                  AccessMo de: {
  458                                                                                           Value: 0
  459                                                                                  },
  460                                                                                  DomainNa me: domain Name,
  461                                                                                  Business UnitId: {
  462                                                                                           Id: PACTUs erCRMTeam. BusinessUn itId.Id,
  463                                                                                           LogicalNam e: PACTUse rCRMTeam.B usinessUni tId.Logica lName,
  464                                                                                           Name: PACT UserCRMTea m.Business UnitId.Nam e
  465                                                                                  },
  466                                                                                  ftp_PACT Id: {
  467                                                                                           Id: pPACTT eamFromCRM .ftp_pactI d,
  468                                                                                           LogicalNam e: "ftp_pa ct",
  469                                                                                           Name: pPAC TTeamFromC RM.ftp_nam e
  470                                                                                  }
  471                                                                         };
  472                                                                         SDK.RE ST.createR ecord(
  473                                                                                  newUser,
  474                                                                                  "SystemU ser",
  475                                                                                  function  (createdU ser) {
  476                                                                                           writeToCon sole("crea ted system user: " +  fakeFullNa me + " ("  + domainNa me + "). G UID: " + c reatedUser .SystemUse rId);
  477                                                                                           addUsersTo Team(creat edUser.Sys temUserId,  PACTUserC RMTeam.Tea mId);
  478                                                                                           if (!alrea dySetPrima ryCareProv iderField)  alreadySe tPrimaryCa reProvider Field = tr ySetPrimar yCareProvi derField(c reatedUser );
  479                                                                                           matchPCMMT eamMembers ToCRMPACTT eam(pPACTT eamFromCRM , pPACTTea mMembersFr omPCMM, al readySetPr imaryCareP roviderFie ld, usersT oUnlink);  //run this  method ag ain
  480                                                                                  },
  481                                                                                  errorHan dler
  482                                                                         );
  483                                                                }
  484                                                       }
  485                                               );
  486                                      }
  487                             }
  488                    );
  489           }
  490           el se{
  491                    //if  all prima ry care te am members  PCMM are  now in CRM  as system users, lin ked to the  PACT team , we can n ow update  any remain ing system users that  should be  be linked  to this P ACT team
  492                    unli nkUsersFro mPACTTeam( usersToUnl ink);
  493           }
  494   }
  495  
  496   function r emoveUserF romUsersTo Unlink(pUs er, pUsers ToUnlink){
  497           fo r(var i =  0, l = pUs ersToUnlin k.length;  i < l; i++ ){
  498                    if(p UsersToUnl ink[i].Sys temUserId  == pUser.S ystemUserI d){
  499                             pUsers ToUnlink.s plice(i,1) ;
  500                             break;
  501                    }
  502           }
  503           re turn pUser sToUnlink;
  504   }
  505  
  506   function u nlinkUsers FromPACTTe am(pUsers) {
  507           wr iteToConso le("begin  unlinkUser sFromPACTT eam()");
  508       if (!! pUsers &&  Array.isAr ray(pUsers ) && pUser s.length >  0) {
  509                    writ eToConsole ("pUsers.l ength: " +  pUsers.le ngth);
  510                    var  thisUser =  pUsers.sh ift();
  511                    if ( thisUser.h asOwnPrope rty("Syste mUserId")  && !!thisU ser.System UserId) {
  512                             thisUs er.ftp_PAC TId = {
  513                                      Id: null ,
  514                                      LogicalN ame: null,
  515                                      Name: nu ll
  516                             };
  517                             SDK.RE ST.updateR ecord(
  518                                      thisUser .SystemUse rId,
  519                                      thisUser ,
  520                                      "SystemU ser",
  521                                      function  () {
  522                                               //do nothi ng else wi th this us er
  523                                               writeToCon sole("clea red ftp_PA CTId field  on system user:" + t hisUser.Fu llName + "  {" + this User.Syste mUserId +  "}");
  524                                              
  525                                               //re-enter  this func tion until  pUsers is  empty
  526                                               unlinkUser sFromPACTT eam(pUsers );
  527                                      },
  528                                      errorHan dler
  529                             );
  530                    }
  531           }
  532           el se{
  533                    writ eToConsole ("no users  to unlink .");
  534           }
  535   }
  536  
  537   function t rySetPrima ryCareProv iderField( pUser) {
  538       if (!p User || !p User.ftp_P ACTTeamRol e || !pUse r.FullName ) return f alse;
  539       if (!( pUser.ftp_ PACTTeamRo le == "Pri mary Care  Provider"  || pUser.f tp_PACTTea mRole == " Associate  Provider") ) return f alse;
  540       
  541           Xr m.Page.get Attribute( "ftp_prima rycareprov ider").set Value(pUse r.FullName );
  542       Xrm.Pa ge.getAttr ibute("ftp _primaryca reprovider ").setSubm itMode("al ways");
  543           wr iteToConso le("set Ve teran's ft p_primaryc areprovide r with sys temuser.Fu llName: "  + pUser.Fu llName);
  544           VC CM.USDHelp er.CopyDat aToReplace mentParame ters("PCMM ", ["PCP="  + pUser.F ullName],  false);
  545           Xr m.Page.get Attribute( "ftp_prima rycareprov ider").fir eOnChange( );
  546       return  true;
  547   }
  548  
  549   function m atchMHTCTo PACTTeam(p PACTTeamFr omCRM, pMH TC) {
  550           wr iteToConso le("begin  matchMHTCT oPACTTeam( )");
  551           if  (!pPACTTe amFromCRM)  return;
  552       //don' t set the  ftp_pactid  lookup fi eld on the  vet form
  553  
  554       //save  to an arr ay the cur rent list  of users w ho current ly referen ce pPACTTe amFromCRM,  so that w e can remo ve that re ference if  they NO L ONGER are  a member o f pPACTTea mFromCRM a ccording t o PCMM
  555           // for a ment al health  PACT team. ..it shoul d just be  one user
  556           // for a newl y-created  ftp_pact r ecord, thi s list of  users will  be empty
  557       var us ersToUnlin k = [];
  558       var in itialUserL ist = getD eepPropert y("ftp_ftp _pact_syst emuser.res ults", pPA CTTeamFrom CRM);
  559       if (Ar ray.isArra y(initialU serList) & & initialU serList.le ngth > 0)  {
  560           wr iteToConso le(initial UserList.l ength + "  CRM users  currently  connected  to the " +  pPACTTeam FromCRM.ft p_name + "  Mental He alth PACT  team, befo re we add/ remove any body");
  561           fo r (var i =  0, l = in itialUserL ist; i < l ; i++) {
  562                usersToU nlink.push (initialUs erList[i]) ;
  563           }
  564       }
  565  
  566       if (!! pMHTC) {
  567           va r teamQuer y = "$sele ct=Name,Te amId,Busin essUnitId& $filter=Na me eq 'PAC T User' an d TeamType /Value eq  0";
  568           va r retrieve dCRMTeams  = [];
  569           SD K.REST.ret rieveMulti pleRecords (
  570                             "Team" ,
  571                             teamQu ery,
  572                             functi on (retrie vedRecords ) {
  573                                      if (type of retriev edRecords  != "undefi ned" && !! retrievedR ecords) re trievedCRM Teams = re trievedCRM Teams.conc at(retriev edRecords) ;
  574                             },
  575                             errorH andler,
  576                             functi on () {
  577                                      if (retr ievedCRMTe ams.length  > 0) {
  578                                               var PACTUs erCRMTeam  = retrieve dCRMTeams[ 0];
  579  
  580                                               //find or  create a s ystemuser  for the Me ntal Healt h Treatmen t Coordina tor (pMHTC )
  581                                          //se t their ft p_PACTId l ookup fiel d to pPACT TeamFromCR M
  582                                               //add the  user to th e 'PACT Us er' CRM te am, so it  will inher it the tea m's securi ty roles
  583                                          //if  their ftp _PACTId an d ftp_PACT TeamRole a re fine, r emove that  person fr om usersTo Unlink arr ay
  584  
  585                                               //pMHTC sc hema: { Na me, TeamRo leName, Te amRoleCode , Phone, P ager, Ien  }
  586                                               writeToCon sole("sear ching for  " + pMHTC. Name + " t o connect  their CRM  user recor d to the "  + pPACTTe amFromCRM. ftp_name +  " PACT te am in CRM" );
  587                                               var splitN ame = pMHT C.Name.spl it(",");
  588                                               var lastNa me = split Name[0];
  589                                               var splitF irstMiddle Names = sp litName.le ngth > 1 ?  splitName [1].trim() .split(" " ) : "";
  590                                               var firstN ame = !!sp litFirstMi ddleNames  ? splitFir stMiddleNa mes[0] : " ";
  591                                               var middle Name = !!s plitFirstM iddleNames  && splitF irstMiddle Names.leng th > 1 ? s plitFirstM iddleNames [1] : "";
  592                                               var fakeFu llName = l astName +  ", " + fir stName + "  " + middl eName;
  593                                                var domain Name = fir stName + " ." + lastN ame + "@no domainacco unt. DNS     ";
  594                                               var userQu ery = "$se lect=First Name,LastN ame,System UserId,ftp _PACTId,ft p_PACTTeam Role,IsDis abled,Doma inName,Ful lName&$fil ter=Domain Name eq '"  + domainN ame + "'";
  595                                               var retrie vedUsers =  [];
  596                                               SDK.REST.r etrieveMul tipleRecor ds(
  597                                                       "S ystemUser" ,
  598                                                       us erQuery,
  599                                                       fu nction (re trievedRec ords) {
  600                                                                if ( typeof ret rievedReco rds != "un defined" & & !!retrie vedRecords ) retrieve dUsers = r etrievedUs ers.concat (retrieved Records);
  601                                                       },
  602                                                       er rorHandler ,
  603                                                       fu nction ()  {
  604                                                                if ( retrievedU sers.lengt h > 0) {
  605                                                                         writeT oConsole(" found syst emuser: "  + domainNa me + ", up dating sys temuser.") ;
  606                                                                         var fo undUser =  retrievedU sers[0];
  607                                                                         if(!fo undUser.Is Disabled){
  608                                                                             if  (foundUse r.hasOwnPr operty("ft p_PACTId")  && !!foun dUser.ftp_ PACTId &&  foundUser. ftp_PACTId .Id == pPA CTTeamFrom CRM.ftp_pa ctId &&
  609                                                                                           foundUser. hasOwnProp erty("ftp_ PACTTeamRo le") && fo undUser.ft p_PACTTeam Role == pM HTC.TeamRo leName) {
  610                                                                                  writeToC onsole(fou ndUser.Ful lName + "  is already  linked to  the " + p PACTTeamFr omCRM.ftp_ name + " a nd has the  correct P ACT Team R ole; skipp ing update .");
  611                                                                                  //remove  this pers on from th e usersToU nlink arra y, because  their ftp _PACTId an d ftp_PACT TeamRole a re already  fine
  612                                                                                  usersToU nlink.spli ce(i, 1);
  613                                                                                           setMentalH ealthTeamF ield(found User);
  614                                                                                  } 
  615                                                                                  else {
  616                                                                                           foundUser. ftp_PACTId  = {
  617                                                                                               Id: pP ACTTeamFro mCRM.ftp_p actId,
  618                                                                                                   Lo gicalName:  "ftp_pact ",
  619                                                                                                   Na me: pPACTT eamFromCRM .ftp_name
  620                                                                                           };
  621                                                                                           foundUser. ftp_PACTTe amRole = p MHTC.TeamR oleName;
  622                                                                                           SDK.REST.u pdateRecor d(
  623                                                                                                   fo undUser.Sy stemUserId ,
  624                                                                                                   fo undUser,
  625                                                                                                   "S ystemUser" ,
  626                                                                                                   fu nction ()  {
  627                                                                                                        writeToC onsole("up dated " +  foundUser. DomainName  + " with  PACT team  (" + pPACT TeamFromCR M.ftp_name  + ") and  PACT team  role (" +  pMHTC.Team RoleName +  ")");
  628                                                                                                            setM entalHealt hTeamField (foundUser );
  629                                                                                                   },
  630                                                                                                   er rorHandler
  631                                                                                           );
  632                                                                                  }
  633                                                                         }
  634                                                                         else{
  635                                                                                  writeToC onsole("fo und system user" + fo undUser.Do mainName +  ", but th is user is  disabled.   Skipping  user upda te.");
  636                                                                         }
  637                                                                }
  638                                                                else  {
  639                                                                         writeT oConsole(" did not fi nd systemu ser: " + d omainName  + ", creat ing system user.");
  640                                                                         //buil d user obj ect
  641                                                                         var ne wUser = {
  642                                                                                  FirstNam e: firstNa me,
  643                                                                                  LastName : lastName ,
  644                                                                                  MiddleNa me: middle Name,
  645                                                                                  ftp_PACT TeamRole:  pMHTC.Team RoleName,
  646                                                                                  IsIntegr ationUser:  false,
  647                                                                                  UserLice nseType: 3 ,
  648                                                                                  AccessMo de: {
  649                                                                                           Value: 0
  650                                                                                  },
  651                                                                                  DomainNa me: domain Name,
  652                                                                                  Business UnitId: {
  653                                                                                           Id: PACTUs erCRMTeam. BusinessUn itId.Id,
  654                                                                                           LogicalNam e: PACTUse rCRMTeam.B usinessUni tId.Logica lName,
  655                                                                                           Name: PACT UserCRMTea m.Business UnitId.Nam e
  656                                                                                  },
  657                                                                                  ftp_PACT Id: {
  658                                                                                      Id:  pPACTTeamF romCRM.ftp _pactId,
  659                                                                                           LogicalNam e: "ftp_pa ct",
  660                                                                                           Name: pPAC TTeamFromC RM.ftp_nam e
  661                                                                                  }
  662                                                                         };
  663                                                                         //crea te it
  664                                                                         SDK.RE ST.createR ecord(
  665                                                                                  newUser,
  666                                                                                  "SystemU ser",
  667                                                                                  function  (createdU ser) {
  668                                                                                           writeToCon sole("crea ted system user: " +  fakeFullNa me + " ("  + domainNa me + "). G UID: " + c reatedUser .SystemUse rId);
  669                                                                                           setMentalH ealthTeamF ield(creat edUser);
  670                                                                                           addUsersTo Team(creat edUser.Sys temUserId,  PACTUserC RMTeam.Tea mId);
  671                                                                                  },
  672                                                                                  errorHan dler
  673                                                                         );
  674                                                                }
  675                                                       }
  676                                               );
  677                                      }
  678                             }
  679                    );
  680       }
  681           el se {
  682           // even if we  don't lin k a new MH TC user to  pPACTTeam FromCRM fo r the firs t time, st ill need t o unlink " old" membe rs of pPAC TTeamFromC RM
  683           un linkUsersF romPACTTea m(usersToU nlink);
  684       }
  685   }
  686  
  687   function s etMentalHe althTeamFi eld(pUser)  {
  688           wr iteToConso le("begin  setMentalH ealthTeamF ield()");
  689       if (!! pUser && ! !pUser.ftp _PACTTeamR ole && !!p User.FullN ame) {
  690           if  (pUser.ft p_PACTTeam Role == "( mhtc) Addi ction Ther apist") {
  691                             var MH TCAttr = X rm.Page.ge tAttribute ("ftp_ment alhealthte am");
  692                             if(!!M HTCAttr){
  693                                      MHTCAttr .setValue( pUser.Full Name);
  694                                      MHTCAttr .setSubmit Mode("alwa ys");
  695                                      writeToC onsole("se t ftp_ment alhealthte am to " +  pUser.Full Name);
  696                             }
  697                             else{
  698                                      writeToC onsole("di d not set  ftp_mental healthteam  to becaus e attribut e is not o n form.");
  699                             }
  700           }
  701       }
  702   }
  703  
  704   function a ddUsersToT eam(pUserI ds, pTeamI d) {
  705           wr iteToConso le("begin  addUsersTo Team.  pTe amId: " +  pTeamId);
  706       var se rviceURL =  Xrm.Page. context.ge tClientUrl () + "/XRM Services/2 011/Organi zation.svc /web";
  707       var re questMain  = "";
  708       reques tMain += " <s:Envelop e xmlns:s= \"http://s chemas.xml soap.org/s oap/envelo pe/\">";
  709       reques tMain += "   <s:Body> ";
  710       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\">";
  711       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\"> ";
  712       reques tMain += "         <a :Parameter s xmlns:c= \"http://s chemas.dat acontract. org/2004/0 7/System.C ollections .Generic\" >";
  713       reques tMain += "            <a:KeyValu ePairOfstr inganyType >";
  714       reques tMain += "              <c:key>T eamId</c:k ey>";
  715       reques tMain += "              <c:value  i:type=\" d:guid\" x mlns:d=\"h ttp://sche mas.micros oft.com/20 03/10/Seri alization/ \">" + pTe amId + "</ c:value>";
  716       reques tMain += "            </a:KeyVal uePairOfst ringanyTyp e>";
  717       reques tMain += "            <a:KeyValu ePairOfstr inganyType >";
  718       reques tMain += "              <c:key>M emberIds</ c:key>";
  719       reques tMain += "              <c:value  i:type=\" d:ArrayOfg uid\" xmln s:d=\"http ://schemas .microsoft .com/2003/ 10/Seriali zation/Arr ays\">";
  720       if (Ar ray.isArra y(pUserIds )) {
  721           fo r (var i =  0, l = pU serIds.len gth; i < l ; i++) {
  722                             writeT oConsole(" adding sys temuser {"  + pUserId s[i] + "}  to team {"  + pTeamId  + "}");
  723                requestM ain += "                <d:guid> " + pUserI ds[i] + "< /d:guid>";
  724           }
  725       } else  {
  726                    writ eToConsole ("adding s ystemuser  {" + pUser Ids + "} t o team {"  + pTeamId  + "}");
  727           re questMain  += "               <d :guid>" +  pUserIds +  "</d:guid >";
  728       }
  729       reques tMain += "              </c:valu e>";
  730       reques tMain += "            </a:KeyVal uePairOfst ringanyTyp e>";
  731       reques tMain += "         </ a:Paramete rs>";
  732       reques tMain += "         <a :RequestId  i:nil=\"t rue\" />";
  733       reques tMain += "         <a :RequestNa me>AddMemb ersTeam</a :RequestNa me>";
  734       reques tMain += "       </re quest>";
  735       reques tMain += "     </Exec ute>";
  736       reques tMain += "   </s:Body >";
  737       reques tMain += " </s:Envelo pe>";
  738       var re q = new XM LHttpReque st();
  739       req.op en("POST",  serviceUR L, true);
  740       // Res ponses wil l return X ML. It isn 't possibl e to retur n JSON.
  741       req.se tRequestHe ader("Acce pt", "appl ication/xm l, text/xm l, */*");
  742       req.se tRequestHe ader("Cont ent-Type",  "text/xml ; charset= utf-8");
  743       req.se tRequestHe ader("SOAP Action", " http://sch emas.micro soft.com/x rm/2011/Co ntracts/Se rvices/IOr ganization Service/Ex ecute");
  744       var su ccessCallb ack = null ;
  745       var er rorCallbac k = null;
  746       req.on readystate change = f unction ()  { };
  747       req.se nd(request Main);
  748           wr iteToConso le("sent r equest to  add user t o team.");
  749   }
  750  
  751   function f tp_primary careprovid er_onChang e(){
  752       VCCM.U SDHelper.C opyDataToR eplacement Parameters ("PCMM", [ "PCP=" + X rm.Page.ge tAttribute ("ftp_prim arycarepro vider").ge tValue()],  false);
  753   }
  754  
  755   function f tp_pactid_ onChange()  {
  756           wr iteToConso le("begin  ftp_pactid _onChange( )");
  757       //cycl e through  users unde r selected  PACT who  have a rol e, and upd ate some f ields on t he form wi th their n ames
  758       var pa ctTeamValu e = Xrm.Pa ge.getAttr ibute("ftp _pactid"). getValue() ;
  759       if (!p actTeamVal ue) return ;
  760       VCCM.U SDHelper.C opyDataToR eplacement Parameters ("PCMM", [ "PACTTeam= " + pactTe amValue[0] .name], fa lse);
  761           wr iteToConso le("PACT t eam: " + p actTeamVal ue[0].name );
  762       var qu eryString  = "$select =FullName, ftp_PACTId &$filter=f tp_PACTId/ Id eq guid '" + pactT eamValue[0 ].id + "'  and ftp_PA CTTeamRole  ne null";
  763       var re trievedUse rs = [];
  764       SDK.RE ST.retriev eMultipleR ecords(
  765           "S ystemUser" ,
  766           qu eryString,
  767           fu nction (re trievedRec ords) {
  768                if (type of retriev edRecords  != "undefi ned" && !! retrievedR ecords) re trievedUse rs = retri evedUsers. concat(ret rievedReco rds);
  769           },
  770           er rorHandler ,
  771           fu nction ()  {
  772                if (retr ievedUsers .length >  0) {
  773                                      writeToC onsole("fo und " + re trievedUse rs.length  + " users  on this PA CT team.") ;
  774                    var  alreadySet PrimaryCar eProviderF ield = fal se;
  775                    var  alreadySet MentalHeal thTeamFiel d = false;
  776                                      writeToC onsole("cy cling thro ugh users  to find Pr imary Care  Provider  (or Associ ate Provid er), and ( mhtc) Addi ction Ther apist.");
  777                    for  (var i = 0 , l = retr ievedUsers .length; i  < l && (! alreadySet PrimaryCar eProviderF ield || !a lreadySetM entalHealt hTeamField ) ; i++) {
  778                         var thisUs er = retri evedUsers[ i];
  779                         if (!alrea dySetPrima ryCareProv iderField  && (thisUs er.ftp_PAC TTeamRole  == "Primar y Care Pro vider" ||  thisUser.f tp_PACTTea mRole == " Associate  Provider") ) {
  780                             alread ySetPrimar yCareProvi derField =  trySetPri maryCarePr oviderFiel d(thisUser );
  781                         }
  782                         if (!alrea dySetMenta lHealthTea mField &&  thisUser.f tp_PACTTea mRole == " (mhtc) Add iction The rapist") {
  783                             alread ySetMental HealthTeam Field = se tMentalHea lthTeamFie ld(thisUse r);
  784                         }
  785                    }
  786                }
  787           }
  788       );
  789   }
  790  
  791   function f illFtp_pac tIdWithPla ceholderPa ctTeam(pPC MMErrorTex t) {
  792           wr iteToConso le("begin  fillFtp_pa ctIdWithPl aceholderP actTeam()" );
  793       var re trievedPAC TTeams = [ ];
  794           va r placehol derPACTTea mName = "P ACT team n ot assigne d";
  795       var qu eryString  = "$select =ftp_name, ftp_pactId &$filter=f tp_name eq  '" + plac eholderPAC TTeamName  + "'";
  796       SDK.RE ST.retriev eMultipleR ecords(
  797           "f tp_pact",
  798           qu eryString,
  799           fu nction (re trievedRec ords) {
  800                if (type of retriev edRecords  != "undefi ned" && !! retrievedR ecords) re trievedPAC TTeams = r etrievedPA CTTeams.co ncat(retri evedRecord s);
  801           },
  802           er rorHandler ,
  803           fu nction ()  {
  804                if (retr ievedPACTT eams.lengt h > 0) {
  805                    var  placeholde rPACTRecor d = retrie vedPACTTea ms[0];
  806                                      writeToC onsole("go t placehol der ftp_pa ct record  :" + place holderPACT TeamName);
  807                    Xrm. Page.getAt tribute("f tp_pactid" ).setValue ([{
  808                         id: placeh olderPACTR ecord.ftp_ pactId,
  809                         name: plac eholderPAC TRecord.ft p_name,
  810                         entityType : "ftp_pac t"
  811                    }
  812                    ]);
  813                                      Xrm.Page .getAttrib ute("ftp_p actid").se tSubmitMod e("always" );
  814                                      writeToC onsole("se t Veteran' s ftp_pact id field") ;
  815                    if ( pcmm_Enabl ed == true ) {
  816                         var alertT ext = !!pP CMMErrorTe xt ? pPCMM ErrorText  : "Notify  your PCMM  Administra tor to set  up this v eteran's C are Team A ssignment  in PCMM. Y ou cannot  assign Req uests unti l this is  complete." ;
  817                         Xrm.Page.u i.setFormN otificatio n(alertTex t, "INFO",  "noPACTFr omPCMM");
  818                    }
  819  
  820                    fini shedGettin gPrimaryCa reProvider s = true;
  821                    fini shedGettin gMHTC = tr ue;
  822                }
  823           }
  824       );
  825   }
  826  
  827   function p ad(pNum, p Size) {
  828       var s  = pNum + " ";
  829       while  (s.length  < pSize) s  = "0" + s ;
  830       return  s;
  831   }