crfVisitNew.js 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312
  1. var crfVisit={};
  2. //crfVisit.config=new Object();
  3. crfVisit.setDebug=
  4. function(debug=null){
  5. if (debug){
  6. this.print=function(msg){debug.this.print(msg);};
  7. this.clear=function(){debug.clear();}
  8. return;
  9. }
  10. //provide default functions if not debug object is available
  11. this.print=function(msg){console.log(msg);}
  12. this.clear=function(){;}
  13. }
  14. crfVisit.setDebug();
  15. crfVisit.init=
  16. function(cb=null){
  17. let that=this;
  18. let action=function(){that.scriptsLoaded(cb);};
  19. let dependencies=new Array();
  20. dependencies.push('crf/runQuery.js');
  21. dependencies.push("crf/crfReviewSection.js");
  22. dependencies.push("crf/participantIdManager.js");
  23. dependencies.push("crf/variableList.js");
  24. dependencies.push("crf/webdav.js");
  25. dependencies.push("crf/crfPrint.js");
  26. dependencies.push("crf/crfSetup.js");
  27. dependencies.push("crf/crfData.js");
  28. dependencies.push("crf/crfHTML.js");
  29. dependencies.push("crf/generateRegistration.js");
  30. dependencies.push("crf/formPortalNew.js");
  31. LABKEY.Utils.requiresScript(dependencies,action);
  32. }
  33. crfVisit.scriptsLoaded=
  34. function(cb=null){
  35. participantIdManager.set(crfSetup,crfData);
  36. webdav.set(this);
  37. crfReviewSection.set(this);
  38. crfPrint.set(this);
  39. crfData.setSetup(crfSetup);
  40. crfHTML.init();
  41. //generateRegistration.init();
  42. let initRegistration=function(){generateRegistration.init(cb);};
  43. let initIdManager=function(){participantIdManager.init(initRegistration);};
  44. let initCrfData=function(){crfData.init(initIdManager)};
  45. let initFormPortal=function(){formPortal.init(initCrfData);};
  46. crfSetup.init(initFormPortal);
  47. }
  48. crfVisit.getContainer=
  49. function(label){
  50. return crfSetup.getContainer(label);
  51. }
  52. crfVisit.getCrfRefFirst=
  53. function(){
  54. //crfRef is part of html call and gets stored in the page
  55. return this.crfRef;
  56. }
  57. crfVisit.getCrfRef=
  58. function (){
  59. //'crfRefId'
  60. return crfData.getCrfEntry()['entryId'];
  61. }
  62. crfVisit.getCrfRefData=
  63. function(){
  64. let parentCrf=crfData.getCrfEntry()['parentCrf'];
  65. if (parentCrf!=undefined) return parentCrf;
  66. return this.getCrfRef();
  67. }
  68. crfVisit.onFailure=
  69. function(errorInfo, options, responseObj){
  70. if (errorInfo && errorInfo.exception)
  71. alert("Failure: " + errorInfo.exception);
  72. else
  73. alert("Failure: " + responseObj.statusText);
  74. }
  75. crfVisit.doNothing=
  76. function (){
  77. this.print('doNothing called');
  78. }
  79. crfVisit.getIdManager=
  80. function(){
  81. if (!("masterForm" in participantIdManager)){
  82. participantIdManager.siteNumber=crfData.getCrfEntry()['Site'];
  83. participantIdManager.masterForm=this.masterForm;
  84. participantIdManager.generateTable();
  85. }
  86. return participantIdManager;
  87. }
  88. crfVisit.getSetupObject=
  89. function(){
  90. if (!("setups" in this))
  91. this.setups=new Object();
  92. return this.setups;
  93. }
  94. crfVisit.getStoredSetup=
  95. function(sectionId){
  96. let sObj=this.getSetupObject();
  97. if (sectionId in sObj) return sObj[sectionId];
  98. return null;
  99. }
  100. crfVisit.addSetup=
  101. function(sectionId,setup){
  102. let sObj=this.getSetupObject();
  103. sObj[sectionId]=setup;
  104. }
  105. crfVisit.makeSetup=
  106. function(sectionId,listName){
  107. //generate setup object whcih should contain fields:
  108. //readonlyFlag - whether the dataset is writeable
  109. //filters - selection fields that allow creation of LABKEY.Filter.create()
  110. //getInputId - formating of unique ids for html elements
  111. //
  112. let fName='[Setup]';
  113. this.print(fName+' '+sectionId+'/'+listName);
  114. let setup=new Object();
  115. setup.queryName=listName;
  116. setup.readonlyFlag=function(vName){return false};
  117. setup.filters=new Object();
  118. setup.filters['crfRef']=this.getCrfRef();
  119. setup.getInputId=function(vName){return sectionId+"_"+vName;}
  120. setup.sectionId=sectionId;
  121. setup.isReview=false;
  122. this.addSetup(sectionId,setup);
  123. setup.setVariables=new Object();
  124. return setup;
  125. }
  126. crfVisit.makeFullAccessSetup=
  127. function(sectionId,listName){
  128. //addApply - whether a submit/Save button is generated
  129. let setup=this.makeSetup(sectionId,listName);
  130. setup.addApply="Save";
  131. return setup;
  132. }
  133. crfVisit.makeReadonlySetup=
  134. function(sectionId,listName){
  135. let setup=this.makeSetup(sectionId,listName);
  136. //see definition of setup object above, change readonly flag
  137. setup.readonlyFlag=function(vName){return true};
  138. return setup;
  139. }
  140. crfVisit.getSetup=
  141. function(sectionId,listName,writeAccess=true){
  142. //change to section granulated permission of type EDIT, COMMENT, READ
  143. //let formStatus=config.formConfig.formStatus;
  144. //equivalent to READ
  145. let setup=this.getStoredSetup(sectionId);
  146. if (setup) return setup;
  147. if (!writeAccess)
  148. //if (formStatus=="Submitted")
  149. return this.makeReadonlySetup(sectionId,listName);
  150. //if (formStatus=="Approved")
  151. // return readonlySetup(listName);
  152. return this.makeFullAccessSetup(sectionId,listName);
  153. }
  154. crfVisit.generateSection=
  155. function(formSetupEntry){
  156. let that=this;
  157. let listName=crfSetup.getMap('inputLists')[formSetupEntry['queryName']];
  158. let sectionId="section"+formSetupEntry['Key'];
  159. //if (!listName) is for debugSection
  160. if (!listName){
  161. listName="debugSection";
  162. }
  163. let fName='[generateSection/'+listName+']';
  164. let sectionTitle=formSetupEntry['title'];
  165. let accessModeColumn=this.role+'Mode';
  166. let accessMode=formSetupEntry[accessModeColumn];
  167. //this will fix it for later use as well
  168. this.print(fName+' title '+sectionTitle);
  169. let tb=crfHTML.createTable(this.masterForm);
  170. tb.className='t2';
  171. let row=tb.insertRow();
  172. let cell=crfHTML.createTblHeader(null,row);
  173. cell.setAttribute("colspan","4");
  174. cell.style.fontSize="20px";
  175. cell.style.textAlign="center";
  176. crfHTML.createTextNode(sectionTitle,null,cell);
  177. cell=row.insertCell();
  178. let input=crfHTML.createButton(null,cell);
  179. input.value="Show";
  180. input.id="toggle"+sectionId+"VisbilityButton";
  181. input.onclick=function(){that.toggleVisibility(sectionId,input.id)};
  182. let div=crfHTML.createDiv(sectionId,this.masterForm);
  183. div.style.display="none";
  184. //here divert for debugArea
  185. if (listName=="debugSection"){
  186. let debugArea=crfHTML.createTextArea(null,div);
  187. debugArea.rows=10;
  188. debugArea.cols=95;
  189. debugArea.id=this.debugId;
  190. return;
  191. }
  192. let additionalData=crfSetup.getAdditionalData(listName);
  193. let divTable=crfHTML.createDiv(sectionId+"Table",null,div);
  194. if ("showFlag" in additionalData) {
  195. additionalData.divName=sectionId+"SubDiv";
  196. additionalData.divQueryName=sectionId+"SubDivList";
  197. let div1=crfHTML.createDiv(additionalData.divName,null,div);
  198. div1.style.display="none";
  199. let div2=crfHTML.createDiv(additionalData.divQueryName,null,div1);
  200. }
  201. this.print(fName+" generate master table");
  202. let writeMode=accessMode=="EDIT";
  203. let setup=this.getSetup(sectionId,listName,writeMode);
  204. setup.setVariables=variableList.parseVariables(formSetupEntry['variableDefinition']);
  205. if ("isReview" in additionalData){
  206. crfReviewSection.set(this);
  207. let action=function(){crfReviewSection.CB();};
  208. crfReviewSection.generateSection(listName,div.id,action);
  209. return;
  210. }
  211. //master table is unique per visit
  212. setup.unique=true;
  213. this.generateTable(listName,divTable.id,additionalData,setup);
  214. this.print("generate master table: done");
  215. let generateSubTable=true;
  216. //generateSubTable equivalent to read/write access to section
  217. if (accessMode != "EDIT")
  218. generateSubTable=false;
  219. if (! ("showFlag" in additionalData) ) generateSubTable=false;
  220. if (generateSubTable){
  221. let qName=additionalData.queryName;
  222. let dName=additionalData.divName;
  223. let subsectionId='sub'+sectionId;
  224. let xsetup=this.makeFullAccessSetup(subsectionId,qName);
  225. //only set master query for additionalData
  226. xsetup.masterQuery=listName;
  227. //if (readonly) setup=readonlySetup(config);
  228. xsetup.subTable=true;
  229. this.generateTable(qName,dName,additionalData,xsetup);
  230. //generateTable(formSetupEntry,qName,dName,additionalData,setup);
  231. }
  232. this.print("generate review");
  233. let divReviewList=crfHTML.createDiv(sectionId+"ReviewList",null,div);
  234. let divReview=crfHTML.createDiv(sectionId+"Review",null,div);
  235. //assume we already have listId (content of config.setupQueryName is listId)
  236. //we need listName also
  237. //qconfig.queryName=config.setupQueryName;
  238. this.generateReview(divReview.id,divReviewList.id,listName,accessMode);
  239. if (accessMode!='GENERATE') return;
  240. this.print('Adding generate button');
  241. //add generateButton
  242. let divGenerateButton=crfHTML.createDiv(listName+"GenerateButton",null,div);
  243. this.print('Adding generate button completed to here');
  244. let cb=function(){that.onGenerateQuery(listName);};
  245. this.generateButton(divGenerateButton.id,'Generate','Generate '+listName,'onGenerateQuery',cb);
  246. this.print(fName+' adding generate button completed');
  247. }
  248. crfVisit.generateReview=
  249. function(divReviewId,divReviewListId, listName, accessMode){
  250. let qMapInvert=crfSetup.invertMap(crfSetup.getMap('inputLists'));
  251. let listId=qMapInvert[listName]
  252. //listId is a number->should it be queryName?
  253. let fName='[generateReview]';
  254. this.print(fName+" list "+listId+'/'+listName);
  255. let reviewSetup=new Object();
  256. reviewSetup.setVariables=new Object();
  257. reviewSetup.readonlyFlag=function(vName){
  258. if (vName=="queryName") return true;
  259. if (vName=="queryname") return true;
  260. if (vName=="ModifiedBy") return true;
  261. return false;};
  262. reviewSetup.addApply="Add Review";
  263. reviewSetup.reviewTable=true;
  264. let generateTableFlag=true;
  265. let formStatus=crfData.getCrfEntry()['FormStatus'];
  266. //COMMENTS allowed or not
  267. //three levels of access: EDIT, COMMENT, READ
  268. if (accessMode == "READ"){
  269. //if (formStatus == "Approved" ){
  270. delete reviewSetup.addApply;
  271. reviewSetup.readonlyFlag=function(vName){return false;}
  272. generateTableFlag=false;
  273. }
  274. reviewSetup.filters=new Object();
  275. reviewSetup.filters["crfRef"]=this.crfRef;
  276. if (crfData.getCrfEntry()['parentCrf']){
  277. let parentCrf=crfData.getCrfEntry()['parentCrf'];
  278. reviewSetup.filters["crfRef"]=this.crfRef+";"+parentCrf;
  279. }
  280. reviewSetup.filters["queryName"]=listId;//entry in reviewComments list is queryname, all in small caps
  281. //needs listName, in argument
  282. reviewSetup.getInputId=function(vName){return listName+"_add"+vName};
  283. reviewSetup.divReviewListId=divReviewListId;
  284. reviewSetup.isReview=true;
  285. this.addSetup(divReviewId,reviewSetup);
  286. let msg="Review: divId: "+divReviewId;
  287. msg+=" inputId: "+reviewSetup.getInputId;
  288. this.print(msg);
  289. this.updateListDisplay(divReviewListId,"reviewComments",reviewSetup.filters,true);
  290. if (! generateTableFlag) return;
  291. this.generateTable("reviewComments",divReviewId,new Object(),reviewSetup);
  292. }
  293. //>>>>>>>>>>trigger visibility of additional lists
  294. crfVisit.setListVisibility=
  295. function(input,setup,readonlyFlag){
  296. let fName="[setListVisibility/"+setup.queryName+"]";
  297. this.print(fName);
  298. let additionalData=crfSetup.getAdditionalData(setup.queryName);
  299. let x = crfHTML.getElement(additionalData.divName);
  300. this.print(fName+": Div: "+x);
  301. x.style.display="none";
  302. let sText;
  303. if (readonlyFlag) sText=input.innerText;
  304. else sText=input.options[input.selectedIndex].text;
  305. this.print(fName+": Selected option text: "+sText);
  306. if (sText == additionalData.showFlagValue){
  307. let filters=new Object();
  308. if ("filters" in additionalData) filters=additionalData.filters;
  309. x.style.display = "block";
  310. this.updateListDisplay(additionalData.divQueryName,
  311. additionalData.queryName,filters,readonlyFlag);
  312. }
  313. }
  314. //>>have list refresh when data is added (not optimal yet)
  315. //
  316. crfVisit.updateListDisplay=
  317. function(divName,queryName,filters,readonlyFlag){
  318. //use Labkey.QueryWebPart to show list
  319. let fName="[updateListDisplay]";
  320. this.print(fName+": UpdateListDisplay: Query - "+queryName
  321. +" div - "+divName);
  322. if (divName=="NONE") return;
  323. let crfRef=this.getCrfRef();
  324. let div=crfHTML.getElement(divName);
  325. this.print(fName+": generating WebPart: "+queryName);
  326. var qconfig=new Object();
  327. qconfig.renderTo=divName;
  328. //point to data container
  329. qconfig.containerPath=this.getContainer('data');
  330. qconfig.schemaName='lists';
  331. qconfig.queryName=queryName;
  332. qconfig.buttonBarPosition='top';
  333. qconfig.filters=[];
  334. for (f in filters){
  335. let fType=LABKEY.Filter.Types.EQUAL;
  336. this.print(fName+' filter ['+f+'] '+filters[f]+'/'+typeof(filters[f])+' ['+fType+']');
  337. if (variableList.isFilterList(filters[f])){
  338. fType=LABKEY.Filter.Types.IN;
  339. }
  340. qconfig.filters.push(LABKEY.Filter.create(f, filters[f],fType));
  341. }
  342. let that=this;
  343. qconfig.success=function(data){that.updateSuccess(data);};
  344. qconfig.failure=function(errorInfo,options,responseObj){that.onFailure(errorInfo,options,responseObj);};
  345. //show only print button
  346. if (readonlyFlag){
  347. qconfig.buttonBar=new Object();
  348. qconfig.buttonBar.items=["print"];
  349. }
  350. LABKEY.QueryWebPart(qconfig);
  351. }
  352. crfVisit.updateSuccess=
  353. function(data){
  354. this.print("Update success");
  355. }
  356. //TODO: this should trigger a data refresh on section, ie populateData(field)
  357. crfVisit.toggleVisibility=
  358. function(sectionId,buttonName){
  359. let fName='[toggleVisibility/'+sectionId+']';
  360. this.print(fName);
  361. let x = crfHTML.getElement(sectionId);
  362. if (x.style.display === "none") {
  363. //exclude non data sections (like debug)...
  364. this.print(fName+': issuing setData(populateSection)');
  365. x.style.display = "block";
  366. crfHTML.getElement(buttonName).value="Hide";
  367. let that=this;
  368. let cb=function(){that.populateSection(sectionId);};
  369. crfData.setData(crfData.getCrfRefForData(),cb);
  370. } else {
  371. x.style.display = "none";
  372. crfHTML.getElement(buttonName).value="Show";
  373. }
  374. }
  375. crfVisit.generateButton=
  376. function(divName,caption,label,callbackLabel,callback=null){
  377. this.print("generateButtonX");
  378. let tb=crfHTML.createTable(divName);
  379. tb.className="t2";
  380. let r1=tb.insertRow();
  381. let th=crfHTML.createTblHeader(null,r1);
  382. th.innerHTML=caption;
  383. //*!*
  384. let c2=r1.insertCell();
  385. let i1=crfHTML.createButton(null,c2);
  386. i1.value=label;
  387. i1.style.fontSize="20px";
  388. let that=this;
  389. if (callback)
  390. i1.onclick=callback;
  391. else
  392. i1.onclick=function(){that[callbackLabel]();};
  393. i1.id='button_'+callbackLabel;
  394. let c1=r1.insertCell();
  395. c1.setAttribute("colspan","1");
  396. //this is only for saveReview?
  397. c1.id=divName+'_reportField';
  398. //c1.id=config.submitReportId;
  399. }
  400. crfVisit.generateSubQuery=
  401. function(input, setup, readonlyFlag){
  402. let fName="[generateSubQuery]";
  403. if (setup.isReview) return;
  404. if (!(setup.queryName in crfSetup.getAdditionalDataObject())){
  405. this.print(fName+': no additionalData entry (probably a subquery)');
  406. return;
  407. }
  408. let additionalData=crfSetup.getAdditionalData(setup.queryName);
  409. if (!("showFlag" in additionalData))
  410. return;
  411. this.print(fName);
  412. let expId=setup.getInputId(additionalData.showFlag);
  413. if (expId!=input.id) {
  414. this.print(fName+": ignoring field "+input.id+"/"+expId);
  415. return;
  416. }
  417. this.print(fName+": Setting onChange to "+input.id);
  418. if (readonlyFlag)
  419. return;
  420. let that=this;
  421. input.onchange=function(){that.setListVisibility(input,setup,readonlyFlag)};
  422. }
  423. //>>populate fields
  424. //
  425. //
  426. //split to field generation and field population
  427. //
  428. crfVisit.addFieldRow=
  429. function(tb,field,setup,additionalData){
  430. let fName="[addFieldRow/"+setup.queryName+':'+field.name+']';
  431. let vName=field.name;
  432. let vType=field.type;
  433. let isLookup=("lookup" in field);
  434. this.print(fName+": ["+vName+"/"+vType+'/'+isLookup+"]");
  435. let row=tb.insertRow();
  436. let cell=crfHTML.createTblHeader(null,row);
  437. cell.style.width='300px';
  438. let text = crfHTML.createTextNode(field.shortCaption,null,cell);
  439. let input=null;
  440. let colSpan="3";
  441. let cell1=row.insertCell();
  442. cell1.colSpan=colSpan;
  443. let readonlyFlag=setup.readonlyFlag(vName);
  444. //set the html input object
  445. while (1){
  446. if (readonlyFlag){
  447. input=crfHTML.createLabel('Loading',null,cell1);
  448. break;
  449. }
  450. //lookup
  451. if (isLookup){
  452. let lookup=field["lookup"];
  453. //get all values from config.formConfig.lookup[X]
  454. let lObject=crfData.getLookup(lookup.queryName);
  455. input = crfHTML.createSelect(lObject.LUT,null,cell1);
  456. break;
  457. }
  458. //date
  459. if (vType=="date"){
  460. input = crfHTML.createDate(null,cell1);
  461. break;
  462. }
  463. //string
  464. if (vType=="string"){
  465. //we have to make sure UNDEF is carried to below
  466. //since we are adapting file to either show
  467. //current file or allow user to select a file
  468. //
  469. //TODO change this so one can always select file
  470. //but also show the selected file
  471. if(vName.search("reviewComment")>-1){
  472. input = crfHTML.createTextArea(null,cell1);
  473. input.cols="65";
  474. input.rows="5";
  475. break;
  476. }
  477. input=crfHTML.createTextInput(null,cell1);
  478. if (vName.search('_file_')<0) break;
  479. cell1.setAttribute('colspan',"1");
  480. let cell2=row.insertCell();
  481. cell2.setAttribute('colspan',"2");
  482. let input1=crfHTML.createFileInput(null,cell2);
  483. input1.id=setup.getInputId(vName)+'_file_';
  484. break;
  485. }
  486. if (vType=="float"){
  487. input = crfHTML.createTextInput(null,cell1);
  488. break;
  489. }
  490. if (vType=="boolean"){
  491. input = crfHTML.createCheckbox(null,cell1);
  492. this.print("Creating checkbox");
  493. break;
  494. }
  495. break;
  496. }
  497. input.id=setup.getInputId(vName);
  498. this.print(fName+': adding element '+input.id);
  499. this.print(fName+': listing element '+crfHTML.getElement(input.id));
  500. //connect associated list
  501. this.generateSubQuery(input,setup,readonlyFlag);
  502. if (readonlyFlag) {
  503. this.print(fName+': exiting(readonlyFlag)');
  504. return;
  505. }
  506. }
  507. crfVisit.addSpecialFieldRows=
  508. function(tb,field,specFieldSetup,setup){
  509. //tb is the table, specFieldSetup is a row from the table where special fields are being setup
  510. //the first column is fieldUID, which is a colon joined amalgation of queryName:fieldName
  511. let fieldUID=specFieldSetup["fieldUID"];
  512. let x=fieldUID.split(':');
  513. let fieldName=x[1];
  514. let fName="[addSpecialFieldRow/"+fieldUID+"]";
  515. let q=variableList.parseVariables(specFieldSetup['actionParameters']);
  516. this.print(fName);
  517. let type=specFieldSetup['actionType'];
  518. this.print(fName+' type '+type);
  519. if (type=='textArea' || type=="textAreaFromVariableDefinition"){
  520. let row=tb.insertRow();
  521. let cell1=row.insertCell();
  522. cell1.colSpan="4";
  523. cell1.style.textAlign="justify";
  524. cell1.style.padding="10px";
  525. cell1.style.backgroundColor="#e0e0e0";
  526. cell1.innerText=q['description'];
  527. if (type!='textAreaFromVariableDefinition') return;
  528. let varName=q['varName'];
  529. //get the value. But sometimes and particularly in this case, there are two rows for the same query
  530. //one should rely on formSetup variable definition
  531. let value=setup.setVariables[varName];
  532. let code=q['pattern'];
  533. code=code.replace(varName,value);
  534. this.print(fName+' using ['+varName+'] '+value+' pattern '+q['pattern']+' code '+code);
  535. cell1.innerText=q[code];
  536. }
  537. //copyCrfEntry in populateSpecialField
  538. if (specFieldSetup['actionType']=='generationObject'){
  539. //only in EDIT mode!!
  540. let ro=setup.readonlyFlag(fieldName);
  541. if (ro) return;
  542. generateRegistration.set(this);
  543. q['setup']=setup;
  544. let gc=generateRegistration.getObject(q,setup.getInputId(fieldName));
  545. let that=this;
  546. let action=function(){that.doNothing();};
  547. if ('mailRecipient' in q){
  548. gc.callback=function(data){that.sendEmail(data,q['mailRecipient'],action,q['subject']);};
  549. }
  550. else
  551. gc.callback=function(data){that.doNothing();};
  552. if ("addData" in q){
  553. vars=q["addData"].split(',');
  554. gc.addData=new Array();
  555. for (let v in vars){
  556. let s=vars[v]
  557. //variable name can be written as A/B where A is the name in addData and B is the variable name in crfEntry
  558. //useful for mocking up crfId from daughter crf-s such as registration
  559. let sArray=s.split('/');
  560. let sTarget=sArray[0];
  561. let sSource=sArray[sArray.length-1];
  562. gc.addData[sTarget]=crfData.getCrfEntry()[sSource];
  563. this.print(fName+" addData ["+sTarget+"]: "+gc.addData[sTarget]);
  564. }
  565. }
  566. let row=tb.insertRow();
  567. let cell=crfHTML.createTblHeader(null,row);
  568. crfHTML.createTextNode("Automatic ID generator",null,cell);
  569. let cell1=row.insertCell();
  570. cell1.colSpan="3";
  571. let b=crfHTML.createButton(null,cell1);
  572. b.id="generateIdButton";
  573. b.onclick=function(){generateRegistration.execute(gc);};
  574. b.value="Generate ID";
  575. }
  576. if (specFieldSetup['actionType']=='multiChoiceButtonRow'){
  577. //need all options for the field
  578. if (!("lookup" in field)) {
  579. this.print(fieldUID+" only enabled for lookup fields");
  580. return;
  581. }
  582. let lookup=field["lookup"];
  583. let lObject=crfData.getLookup(lookup.queryName);
  584. let row=tb.insertRow();
  585. let cell=crfHTML.createTblHeader(null,row);
  586. let header="All variables";
  587. if ('header' in q){
  588. header=q['header'];
  589. header=header.replace(/_fieldCaption_/,field.shortCaption);
  590. header=header.replace(/_t_/,"\t");
  591. }
  592. crfHTML.createTextNode(header,null,cell);
  593. crfHTML.addStyle(cell,'center');
  594. crfHTML.addStyle(cell,'topLess');
  595. let cell1=row.insertCell();
  596. cell1.colSpan="3";
  597. for (let x in lObject.LUT){
  598. let b=crfHTML.createButton(null,cell1);
  599. b.id=fieldUID+':'+x;
  600. b.value=lObject.LUT[x];
  601. input=crfHTML.getElement(setup.getInputId(field.name));
  602. b.onclick=function(){crfHTML.updateSelect(input,cell1,x,b.value);}
  603. }
  604. }
  605. }
  606. crfVisit.populateFieldRow=
  607. function(entry,field,setup){
  608. this.populateField(entry,field,setup);
  609. this.populateSubQuery(entry,field,setup);
  610. this.populateSpecialFields(entry,field,setup);
  611. }
  612. crfVisit.populateSubQuery=
  613. function(entry,field,setup){
  614. let fName='[populateSubQuery/'+setup.queryName+':'+field.name+']';
  615. if (setup.isReview) return;
  616. if (!(setup.queryName in crfSetup.getAdditionalDataObject())){
  617. let msg=fName+': no additionalData entry for '+setup.queryName;
  618. msg+=' (probably a subquery)';
  619. this.print(msg);
  620. return;
  621. }
  622. //find if field is connected to a sub array
  623. //find queryName
  624. //
  625. let additionalData=crfSetup.getAdditionalData(setup.queryName);
  626. this.print(fName);
  627. //let flag=additionalData.showFlag;
  628. if (!("showFlag" in additionalData)) return;
  629. let eId=setup.getInputId(additionalData.showFlag);
  630. let id=setup.getInputId(field.name);
  631. if (eId!=id) {
  632. this.print(fName+": ignoring field "+id+"/"+eId);
  633. return;
  634. }
  635. this.print(fName+': id '+id);
  636. //hard to estimate readonlyFlag
  637. //
  638. let input=crfHTML.getElement(id);
  639. let eType=input.nodeName.toLowerCase();
  640. let readonlyFlag=eType!="select";
  641. this.setListVisibility(input,setup,readonlyFlag);
  642. }
  643. crfVisit.clearField=
  644. function(field,setup){
  645. let foo=new Object();
  646. this.populateField(foo,field,setup);
  647. }
  648. crfVisit.populateField=
  649. function(entry,field,setup){
  650. let vName=field.name;
  651. let fName='[populateFieldName/'+vName+']';
  652. let varValue="UNDEF";
  653. //if (vName in setup.filters) varValue=setup.filters[vName];
  654. if (vName in entry) varValue=entry[vName];
  655. //if part of the filter, set it to value
  656. if (vName in setup.filters) varValue=setup.filters[vName];
  657. let isLookup=("lookup" in field);
  658. this.print(fName+' v='+varValue+'/'+isLookup+' ['+
  659. setup.getInputId(field.name)+']');
  660. let vType=field.type;
  661. let id=setup.getInputId(vName);
  662. let input=crfHTML.getElement(id);
  663. //date
  664. if (vType=="date"){
  665. if (varValue=="UNDEF") varValue=new Date();
  666. else varValue=new Date(varValue);
  667. }
  668. //lookup for readonly
  669. if (isLookup && varValue!="UNDEF"){
  670. let lookup=field["lookup"];
  671. //get all values from config.formConfig.lookup[X]
  672. let lObject=crfData.getLookup(lookup.queryName);
  673. varValue=lObject.LUT[varValue];
  674. }
  675. this.print('Element: '+id+'/'+input);
  676. //figure out the element type
  677. let eType=input.nodeName.toLowerCase();
  678. this.print('Element type: '+eType);
  679. //change varValue for printing
  680. if (varValue=="UNDEF") varValue="";
  681. //HTMLTextArea, createElement(textArea)
  682. if (eType==="textarea"){
  683. input.value=varValue;
  684. return;
  685. }
  686. //Text, createTextNode
  687. if (eType==="#text"){
  688. input.nodeValue=varValue;
  689. return;
  690. }
  691. //HTMLLabelElement, createElement('label')
  692. if (eType==="label"){
  693. input.innerText=varValue;
  694. return;
  695. }
  696. //HTMLSelectElement, createElement('select')
  697. if (eType==="select"){
  698. input.selectedIndex=0;
  699. for (let i=0;i<input.options.length;i++){
  700. let v=input.options[i].text;
  701. if (v!=varValue) continue;
  702. input.selectedIndex=i;
  703. break;
  704. }
  705. return;
  706. }
  707. if (eType!="input"){
  708. this.print('Unknown type: '+eType+' encountered, igonring');
  709. return;
  710. }
  711. //HTMLInputElement
  712. let type=input.type;
  713. if (type=="date"){
  714. input.valueAsDate=varValue;
  715. return;
  716. }
  717. //string,float
  718. if (type=="text"){
  719. input.value=varValue;
  720. return;
  721. }
  722. //boolean
  723. if (type=="checkbox"){
  724. input.checked=varValue;
  725. return;
  726. }
  727. this.print('Unknown input type: '+type+'. Ignoring.');
  728. }
  729. crfVisit.populateSpecialFields=
  730. function(entry,field,setup){
  731. let fName='[populateSpecialFields]';
  732. let fieldUID=setup.queryName+':'+field.name;
  733. let specialFields=crfSetup.getEntryMap('specialFields:fieldUID');
  734. if (!(fieldUID in specialFields)) return;
  735. let specFieldSetup=specialFields[fieldUID];
  736. //q is not used by copyCrfEntry, keeping it here for future reference
  737. let q=variableList.parseVariables(specFieldSetup['actionParameters']);
  738. let type=specFieldSetup['actionType'];
  739. if (type=='copyCrfEntry'){
  740. let el=crfHTML.getElement(setup.getInputId(field.name));
  741. let varName=field.name;
  742. if ("varName" in q) varName=q["varName"];
  743. let id=crfData.getCrfEntry()[varName];
  744. el.value=id;
  745. this.print(fName+' specialFields ['+field.name+'] '+id+'/'+el.value);
  746. }
  747. }
  748. crfVisit.populateTable=
  749. function(listName,writeMode,setup){
  750. //function populateTable(formSetupEntry){
  751. //let listName=config.formConfig.queryMap[formSetupEntry['queryName']];
  752. //let accessMode=config.formConfig.operator+'Mode';
  753. //let writeMode=formSetupEntry[accessMode]=='EDIT';
  754. let fName='[populateTable/'+listName+']';
  755. //should contain formSetup key
  756. //data snapshot
  757. let fQuery=crfData.getQuerySnapshot(listName);
  758. let queryLayout=crfData.getQueryLayout(listName);
  759. //here I assume that listName was parsed during setDataLayout and setData
  760. //so that rows was set (even if they are empty)
  761. this.print(fName+"]: nrows "+fQuery.rows.length);
  762. let entry=this.selectEntry(fQuery.rows,setup);
  763. if (!entry) entry=new Object();
  764. let fields=queryLayout.fields;
  765. for (f in fields){
  766. let field=fields[f];
  767. //each field is a new row
  768. this.print(fName+": Adding field: "+f+'/'+field.name+' hidden: '+field.hidden+' type:'+field.type);
  769. if (field.hidden) continue;
  770. if (field.name=="crfRef") continue;
  771. if (field.name in setup.setVariables) continue;
  772. this.populateFieldRow(entry,field,setup);
  773. }
  774. }
  775. crfVisit.generateTable=
  776. function(listName,divName,additionalData,setup){
  777. let fName="[generateTable/"+listName+"]";
  778. this.print(fName);
  779. //is listName and setup.queryName a duplicate of the same value
  780. this.print(fName+': setup.queryName '+setup.queryName);
  781. //assume data is set in config.formConfig.dataQueries[data.queryName].rows;
  782. let populateData=true;
  783. if ("subTable" in setup){
  784. this.print(fName+" is subTable");
  785. populateData=false;
  786. }
  787. let entry=new Object();
  788. //data snapshot
  789. let fQuerySnapshot=crfData.getQuerySnapshot(listName);
  790. let queryLayout=crfData.getQueryLayout(listName);
  791. //here I assume that listName was parsed during setDataLayout and setData
  792. //so that rows was set (even if they are empty)
  793. this.print(fName+": Nrows "+fQuerySnapshot.rows.length);
  794. if (fQuerySnapshot.rows.length>0)
  795. entry=fQuerySnapshot.rows[0];
  796. if ("reviewTable" in setup){
  797. entry['reviewComment']='';
  798. delete entry["ModifiedBy"];
  799. }
  800. let tb=crfHTML.createTable(divName);
  801. tb.className="t2";
  802. //this are the fields (probably constant)
  803. let fields=queryLayout.fields;
  804. for (f in fields){
  805. let field=fields[f];
  806. let fieldUID=listName+":"+field.name;
  807. //each field is a new row
  808. this.print(fName+": Adding field: "+f+'/'+field.name+' ('+fieldUID+').');
  809. //unique name
  810. if (field.hidden) continue;
  811. if (field.name=="crfRef") continue;
  812. if (field.name in setup.setVariables) continue;
  813. this.addFieldRow(tb,field,setup,additionalData);
  814. if (populateData) this.populateFieldRow(entry,field,setup);
  815. let specialFields=crfSetup.getEntryMap('specialFields:fieldUID');
  816. if (fieldUID in specialFields){
  817. let specFieldSetup=specialFields[fieldUID];
  818. this.addSpecialFieldRows(tb,field,specFieldSetup,setup);
  819. }
  820. }
  821. //finish of if apply button is not required
  822. if (!("addApply" in setup)) {
  823. this.print(fName+"populateTable: done");
  824. return;
  825. }
  826. let row=tb.insertRow();
  827. let th=crfHTML.createTblHeader(null,row);
  828. th.innerHTML=setup.addApply;
  829. let cell=row.insertCell();
  830. //cell.setAttribute("colspan","2");
  831. let input=crfHTML.createButton(null,cell);
  832. input.value=setup.addApply;
  833. let cell1=row.insertCell();
  834. cell1.setAttribute("colspan","2");
  835. cell1.id=setup.getInputId("rerviewLastSave");
  836. cell1.innerHTML="No recent update";
  837. //saveReview is a generic name for saving content of the html page to a list entry
  838. let that=this;
  839. input.onclick=function(){that.saveReview(listName,cell1.id,setup)};
  840. }
  841. crfVisit.setEntryFromElement=
  842. function(entry,elementId, field){
  843. //set value to entry from element using representation (field) from labkey
  844. //
  845. //
  846. let fName='setEntryFromElement';
  847. let el=crfHTML.getElement(elementId);
  848. if (!el) {
  849. this.print(fName+" element: "+elementId+" not found");
  850. return;
  851. }
  852. this.print(fName+" element: "+elementId);
  853. let vName=field.name;
  854. let vType=field.type;
  855. let eType=el.nodeName.toLowerCase();
  856. if (eType==="select"){
  857. entry[vName]=el.options[el.selectedIndex].value;
  858. return;
  859. }
  860. if (eType==="td"){
  861. entry[vName]=el.innerText;
  862. return;
  863. }
  864. if (vType=="date"){
  865. let date=el.valueAsDate;
  866. if (!date) return;
  867. date.setUTCHours(12);
  868. entry[vName]=date.toString();
  869. this.print(fName+" setting date to "+entry[vName]);
  870. return;
  871. }
  872. if (vType=="string"){
  873. entry[vName]=el.value;
  874. if (vName.search('_file_')<0)
  875. return;
  876. //upload file
  877. let id1=elementId+'_file_';
  878. let input1=crfHTML.getElement(id1);
  879. this.print(fName+' attachment field: '+input1.value);
  880. //entry[vName]=el.files[0].stream();
  881. let ctx=new Object();
  882. ctx['dirName']='consent';
  883. ctx['ID']=entry['crfRef'];
  884. //should point to data container
  885. ctx['project']=getContainer('data');
  886. //need ID->crf!
  887. //assume crfRef will get set before this
  888. //element is encountered
  889. this.uploadFile(input1,ctx);
  890. let fv=el.value;
  891. let suf=fv.split('.').pop();
  892. entry[vName]=entry['crfRef']+'.'+suf;
  893. return;
  894. }
  895. if (vType=="float" || vType=="int"){
  896. entry[vName]=el.value;
  897. if (vName=="queryName") {
  898. this.print(fName+' parsing queryName: '+el.innerText);
  899. let qMapInverse=crfSetup.invertMap(crfSetup.getMap('inputLists'));
  900. entry[vName]=qMapInverse[el.innerText];
  901. //use queryMap lookup
  902. }
  903. return;
  904. }
  905. if (vType=="boolean"){
  906. entry[vName]=el.checked;
  907. return;
  908. }
  909. return;
  910. }
  911. crfVisit.selectEntry=
  912. function(fRows,setup){
  913. let fName='[selectEntry]';
  914. if (!("unique" in setup)) return null;
  915. if (fRows.length==0) return null;
  916. keys=Object.keys(setup.setVariables);
  917. if (keys.length==0)
  918. return fRows[0];
  919. for (let i=0;i<fRows.length;i++){
  920. for (let v in setup.setVariables){
  921. this.print(fName+' row '+i+' ['+v+'] '+fRows[i][v]+'/'+setup.setVariables[v]);
  922. if (fRows[i][v]==setup.setVariables[v]){
  923. this.print(fName+' using '+i);
  924. return fRows[i];
  925. }
  926. }
  927. }
  928. return null;
  929. }
  930. crfVisit.saveReview=
  931. function(queryName,elementId,setup){
  932. //loads any queryName
  933. let fName='[saveReview/'+queryName+']';
  934. this.print(fName+" elementId "+elementId);
  935. let unique=("unique" in setup);
  936. //data snapshot
  937. let fQuerySnapshot=crfData.getQuerySnapshot(queryName);
  938. let nRows=fQuerySnapshot.rows.length;
  939. //data layout
  940. let queryLayout=crfData.getQueryLayout(queryName);
  941. //determine mode based on entry uniqueness and presence of data
  942. let entry=this.selectEntry(fQuerySnapshot.rows,setup);
  943. let mode='update';
  944. if (!entry){
  945. entry=new Object();
  946. mode='insert';
  947. }
  948. this.print(fName+' unique '+unique+' mode '+mode+' nRows '+nRows);
  949. entry.crfRef=this.getCrfRefData();
  950. this.print(fName+" set crfRef="+entry.crfRef);
  951. let fields=queryLayout.fields;
  952. for (f in fields){
  953. let field=fields[f];
  954. this.print(fName+" saveReview field: "+field.name);
  955. if (field.hidden) continue;
  956. if (field.name in setup.setVariables){
  957. entry[field.name]=setup.setVariables[field.name];
  958. continue;
  959. }
  960. let vName=field.name;
  961. let vType=field.type;
  962. this.print(fName+" vType: "+vType);
  963. if (vName=="crfRef") continue;
  964. //need to save queryName for reviewComments
  965. let eId=setup.getInputId(vName);
  966. //copy values from form to entry
  967. this.setEntryFromElement(entry,eId,field,setup);
  968. //clear field value
  969. if (!unique) this.clearField(field,setup);
  970. }
  971. let that=this;
  972. let updateFlag=function(data){that.updateLastSavedFlag(data,setup,elementId)};
  973. let cPath=crfSetup.getContainer('data');
  974. let action=updateFlag;
  975. if (crfSetup.getSettings("updateRegistration")){
  976. let pars=variableList.parseVariables(crfSetup.getSettings("updateRegistration"));
  977. if (pars['query']==queryName){
  978. action=function(data){that.updateRegistration(updateFlag,data);}
  979. }
  980. }
  981. runQuery.modifyRows(mode,'lists',queryName,[entry],action,cPath);
  982. }
  983. crfVisit.updateLastSavedFlag=
  984. function(data,setup,elementId){
  985. let fName='[updateLastSavedFlag]';
  986. this.print(fName+" update last saved flag to "+elementId);
  987. let el=crfHTML.getElement(elementId);
  988. let dt=new Date();
  989. el.innerHTML="Last saved "+dt.toString();
  990. if (data.queryName=="reviewComments"){
  991. this.updateListDisplay(setup.divReviewListId,"reviewComments",setup.filters,true);
  992. }
  993. //refresh stored data!
  994. let writeMode=!setup.readonlyFlag();
  995. let that=this;
  996. let cb=function(){that.populateTable(data.queryName,writeMode,setup);};
  997. if ("unique" in setup)
  998. crfData.setData(crfData.getCrfRefForData(),cb);
  999. if ("masterQuery" in setup){
  1000. let ad=crfSetup.getAdditionalData(setup.masterQuery);
  1001. this.print('Updating list display: '+setup.queryName+'/'+ad.queryName);
  1002. this.updateListDisplay(ad.divQueryName,ad.queryName,ad.filters,false);
  1003. }
  1004. }
  1005. //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  1006. //generic form status switch statementes
  1007. crfVisit.changeFormStatusAndNotify=
  1008. function(actionName){
  1009. let fName='[changeStatusAndNotify]';
  1010. this.print(fName);
  1011. let targetStatus=crfSetup.getTargetStatus(actionName);
  1012. let targetRecipient=crfSetup.getTargetRecipient(actionName);
  1013. let actionSettings=crfSetup.getActionSettings(actionName);
  1014. let action=new Object();
  1015. action.name=actionName;
  1016. let finalStep=function(){that.redirect();};
  1017. if (variableList.hasVariable(actionSettings,"finalStep")){
  1018. this.print(fName+' adjusting finalStep');
  1019. //set to doNothing to remain on submit window
  1020. if (actionSettings.finalStep=="doNothing"){
  1021. finalStep=function(){that.doNothing();};
  1022. }
  1023. }
  1024. this.print(fName+' action '+actionName+' targetStatus '+targetStatus);
  1025. let that=this;
  1026. action.cb=function(data){that.sendEmail(data,targetRecipient,finalStep,actionName);}
  1027. this.updateFlag(targetStatus,action);//Approved
  1028. }
  1029. crfVisit.updateFlag=
  1030. function(flag,action){
  1031. let fName='[updateFlag]';
  1032. let entry=crfData.getCrfEntry();
  1033. entry.FormStatus=flag;
  1034. let uId=LABKEY.Security.currentUser.id;
  1035. entry[this.role]=uId;
  1036. this.print(fName+': Form: '+entry.Form);
  1037. this.print(fName+": set form status to "+entry.FormStatus);
  1038. let that=this;
  1039. let cb=function(data){that.completeWithFlag(data,action);};
  1040. runQuery.modifyRows('update','lists','crfEntry',[entry],cb,crfSetup.getContainer('data'));
  1041. }
  1042. crfVisit.completeWithFlag=
  1043. function(data,action){
  1044. let fName='[completeWithFlag]';
  1045. this.print(fName+': nrows '+data.rows.length);
  1046. let fentry=data.rows[0];
  1047. this.print(fName+': form status '+fentry.FormStatus);
  1048. this.print(fName+': form '+fentry.Form);
  1049. let crfStatus=crfData.createCrfStatus(fentry);
  1050. crfStatus.operator=this.role;
  1051. crfStatus.action=action.name;
  1052. let that=this;
  1053. let cb=function(){that.doNothing();};
  1054. if (action.cb) cb=action.cb;
  1055. runQuery.insertRows('lists','crfStatus',[crfStatus],cb,crfSetup.getContainer('data'));
  1056. }
  1057. //******************************************upload to database *********************
  1058. crfVisit.onDatabaseUpload=
  1059. function(){
  1060. let actionName='onDatabaseUpload';
  1061. let fName='['+actionName+']';
  1062. this.print(fName);
  1063. let pM=this.getIdManager();
  1064. let participantId=participantIdManager.getParticipantIdFromCrfEntry('STUDY');
  1065. let that=this;
  1066. let crfRefForData=crfData.getCrfRefForData();
  1067. //load lists and study data
  1068. //check what needs to be updated and upload
  1069. //a (reverse) sequence of functions
  1070. let completeUpload=function(){that.changeFormStatusAndNotify(actionName);};
  1071. let uploadData=function(){crfData.uploadData(participantId,crfRefForData,completeUpload);};
  1072. let loadStudy=function(){crfData.setData(crfRefForData,uploadData,'study');}
  1073. crfData.setData(crfRefForData,loadStudy,'lists');
  1074. }
  1075. //*************************update for further review *************************
  1076. crfVisit.onUpdateForReview=
  1077. function(){
  1078. let actionName='onUpdateForReview';
  1079. this.changeFormStatusAndNotify(actionName);
  1080. }
  1081. //************************************************ submit *******************************************
  1082. crfVisit.onSubmit=
  1083. function(){
  1084. //update list storage and change status
  1085. this.hideErr();
  1086. this.clearErr();
  1087. this.printErr("onSubmit");
  1088. let that=this;
  1089. let actionName='onSubmit';
  1090. let action=function(){that.verifyData(actionName);};
  1091. crfData.setData(crfData.getCrfRefForData(),action);
  1092. }
  1093. crfVisit.verifyData=
  1094. function(actionName){
  1095. let fName='[verifyData/'+actionName+']';
  1096. let qList=crfData.getActiveQueries();
  1097. let that=this;
  1098. let doNothing=function(data){that.doNothing();};
  1099. let pM=this.getIdManager();
  1100. let fieldName=pM.getCrfEntryFieldName(pM.getMode());
  1101. let setId=crfData.getCrfEntry()[fieldName];
  1102. this.print(fName+' crfEntry ['+fieldName+'] '+crfData.getCrfEntry()[fieldName]);
  1103. if (!setId){
  1104. this.printErr('Missing ID !');
  1105. return false;
  1106. }
  1107. for (let qId in qList){
  1108. let entry=qList[qId];
  1109. let q=entry['queryName'];
  1110. let qData=crfData.getQuerySnapshot(q);
  1111. if (q=="reviewComments") continue;
  1112. //copy snapshot to history
  1113. if (qData.rows.length==0){
  1114. this.print(fName+' no rows for '+q);
  1115. }
  1116. else
  1117. runQuery.insertRows('lists',q+'History',qData.rows,doNothing,this.getContainer('data'));
  1118. //if it doesn't have additionalData, it is a sub query
  1119. if (!(q in crfSetup.getAdditionalDataObject())){
  1120. continue;
  1121. }
  1122. if (qData.rows.length<1){
  1123. this.printErr('Missing entry for query '+q);
  1124. return false;
  1125. }
  1126. }
  1127. //this is necessary only for Generated to Generation completed step
  1128. //let actionSettings=crfSetup.getActionSettings(actionName);
  1129. //if (variableList.hasVariable(actionSettings,"updateRegistration")){
  1130. //if updateRegistrationFormId is set, only update when submit is used on that form
  1131. // if (variableList.hasVariable(actionSettings,"updateRegistrationFormId")){
  1132. // let formId=crfData.getCrfEntry()['Form'];
  1133. //if (actionSettings['updateRegistrationFormId']==formId)
  1134. // this.updateRegistration();
  1135. //}
  1136. //else
  1137. // this.updateRegistration();
  1138. //}
  1139. this.changeFormStatusAndNotify(actionName);
  1140. }
  1141. crfVisit.getEmail=
  1142. function(recipientCode){
  1143. this.print('getEmail w/'+recipientCode);
  1144. let recipients=new Array();
  1145. let typeTo=LABKEY.Message.recipientType.to;
  1146. let create=LABKEY.Message.createRecipient;
  1147. let userMap=crfSetup.getEntryMap('users');
  1148. let currentUser=userMap[LABKEY.Security.currentUser.id];
  1149. let currentSite=this.siteEntry;
  1150. let formCreator=userMap[crfData.getCrfEntry()['UserId']];
  1151. let userRows=crfSetup.getRows('users');
  1152. let parentUser=null;
  1153. if ("parentCrfData" in crfSetup){
  1154. let parentCrf=crfSetup.getRows('parentCrfData');
  1155. parentUser=userMap[parentCrf[0].UserId];
  1156. }
  1157. let recipientCategories=recipientCode.split(',');
  1158. for (let i=0;i<recipientCategories.length;i++){
  1159. let recipient=recipientCategories[i];
  1160. this.print('Checking '+recipient);
  1161. if (recipient=='crfEditor'){
  1162. this.print('Adding :'+formCreator.Email);
  1163. recipients.push(create(typeTo,formCreator.Email));
  1164. if (!parentUser) continue;
  1165. this.print('Adding :'+parentUser.Email);
  1166. recipients.push(create(typeTo,parentUser.Email));
  1167. continue;
  1168. }
  1169. //Monitor or Sponsor
  1170. let fList=recipient+'s';
  1171. let fRows=crfSetup.getRows(fList);
  1172. for (let i=0;i<fRows.length;i++){
  1173. this.print('Checking '+fRows[i].User+'/'+fRows[i].Site);
  1174. if (fRows[i].Site!=currentSite.siteNumber) continue;
  1175. let targetUser=userMap[fRows[i].User];
  1176. if (!targetUser) continue;
  1177. recipients.push(create(typeTo,targetUser.Email));
  1178. }
  1179. }
  1180. return recipients;
  1181. }
  1182. crfVisit.sendEmail=
  1183. function(data,recipient='crfEditor',cb=null,subj='Form submitted'){
  1184. this.print('sendEmail; recipient: '+recipient);
  1185. let that=this;
  1186. if (!cb)
  1187. cb=function(){that.redirect();};
  1188. let cvar='sendEmail';
  1189. let cval=crfSetup.getSettings(cvar);
  1190. if (cval){
  1191. this.print(cvar+' set to '+cval);
  1192. if (cval=='FALSE'){
  1193. this.print('Skipping sending emails');
  1194. cb();
  1195. return;
  1196. }
  1197. }
  1198. if (recipient==null){
  1199. this.print('Skipping sending emails w/ no recipients');
  1200. cb();
  1201. return;
  1202. }
  1203. this.print('send email '+data.rows.length);
  1204. let crf=data.rows[0]['entryId'];
  1205. let formId=data.rows[0]['Form'];
  1206. let link=LABKEY.ActionURL.getBaseURL();
  1207. link+=LABKEY.ActionURL.getContainer();
  1208. link+='/crf_tecant-visit.view?';
  1209. link+='entryId='+crf;
  1210. link+='&formId='+formId;
  1211. link+='&role='+recipient;
  1212. //debug
  1213. let recipients=this.getEmail(recipient);
  1214. //from crfManagers list
  1215. let typeHtml=LABKEY.Message.msgType.html;
  1216. let typePlain=LABKEY.Message.msgType.plain;
  1217. let msg1=LABKEY.Message.createMsgContent(typePlain,link);
  1218. //let cb=doNothing;
  1219. //let cb=redirect;
  1220. LABKEY.Message.sendMessage({
  1221. msgFrom:'labkey@fmf.uni-lj.si',
  1222. msgSubject:subj,
  1223. msgRecipients:recipients,
  1224. msgContent:[msg1],
  1225. success: cb
  1226. });
  1227. }
  1228. crfVisit.hideErr=
  1229. function(){
  1230. let el=crfHTML.getElement("errorDiv");
  1231. el.style.display="none";
  1232. }
  1233. crfVisit.clearErr=
  1234. function(){
  1235. let el=crfHTML.getElement("errorTxt");
  1236. el.value="";
  1237. }
  1238. crfVisit.showErr=
  1239. function(){
  1240. let el=crfHTML.getElement("errorDiv");
  1241. el.style.display="block";
  1242. }
  1243. crfVisit.printErr=
  1244. function(msg){
  1245. this.showErr();
  1246. el=crfHTML.getElement("errorTxt");
  1247. el.style.color="red";
  1248. el.value+="\n"+msg;
  1249. }
  1250. //**************************************************
  1251. //
  1252. crfVisit.onRemoveCRF=
  1253. function(){
  1254. let fName='[onRemoveCRF]';
  1255. let crfRef=this.crfRef;
  1256. let crfRefForData=crfData.getCrfRefForData();
  1257. this.print(fName+' starting loop');
  1258. let actionName='onRemoveCRF';
  1259. let that=this;
  1260. let notify=function(){that.changeFormStatusAndNotify(actionName);};
  1261. //let removeCrfEntry=function(){crfData.removeCrfEntry(notify);};
  1262. let removeData=function(){crfData.removeData(notify);};
  1263. let setStudyData=function(){crfData.setData(crfRefForData,removeData,'study');};
  1264. let action=setStudyData;
  1265. let actionSettings=crfSetup.getActionSettings(actionName);
  1266. if (variableList.hasVariable(actionSettings,'removeWithParentCrf')){
  1267. //if some query needs to be deleted with parent crf, insert this as an intermediate action
  1268. let q=actionSettings['removeWithParentCrf'];
  1269. let parentCrf=crfData.getCrfEntry()['parentCrf'];
  1270. if (parentCrf){
  1271. let setParentStudyData=function(){crfData.setDataForQuery(q,parentCrf,removeData,'study');};
  1272. let setStudyData1=function(){crfData.setData(crfRef,setParentStudyData);}
  1273. action=function(){crfData.setDataForQuery(q,parentCrf,setStudyData1);};
  1274. }
  1275. }
  1276. crfData.setData(crfRefForData,action);
  1277. }
  1278. crfVisit.redirect=
  1279. function(){
  1280. let formUrl="participantPortal";
  1281. let params=new Object();
  1282. params.name=formUrl;
  1283. params.role=this.role;
  1284. let crfEntry=crfData.getCrfEntry();
  1285. params.site=crfEntry['Site'];
  1286. let participantLabel=crfSetup.getParticipantLabel(crfEntry);
  1287. params['participantLabel']=participantLabel;
  1288. //params.pageId="CRF";
  1289. //points to crf container
  1290. let containerPath=crfSetup.getContainer('CRF');
  1291. // This changes the page after building the URL.
  1292. //Note that the wiki page destination name is set in params.
  1293. //let homeURL = LABKEY.ActionURL.buildURL("project", formUrl , containerPath, params);
  1294. let homeURL = LABKEY.ActionURL.buildURL("crf", formUrl , containerPath, params);
  1295. this.print("Redirecting to "+homeURL);
  1296. window.location = homeURL;
  1297. }
  1298. //master section, entry point from html files
  1299. crfVisit.generateMasterForm=
  1300. function(){
  1301. let that=this;
  1302. let action=function(){that.setFormConfig();}
  1303. this.init(action);
  1304. }
  1305. //helper function to set basic parameters on web page
  1306. //(fields defined in html file)
  1307. crfVisit.populateBasicData=
  1308. function(){
  1309. let staticData=new Object();
  1310. let titles=new Object();
  1311. staticData['version']='0.16.3'
  1312. titles['version']='Software version';
  1313. let varRows=crfSetup.getRows('crfStaticVariables');
  1314. for (let i=0;i<varRows.length;i++){
  1315. let vName=varRows[i].staticVariable;
  1316. let val=crfData.getCrfEntry()[vName];
  1317. if (val==undefined) continue;
  1318. staticData[vName]=val;
  1319. titles[vName]=varRows[i].Title;
  1320. }
  1321. staticData['investigatorName']=this.userEntry['DisplayName'];
  1322. titles['investigatorName']='Investigator';
  1323. staticData['email']=this.userEntry['Email'];
  1324. titles['email']='Email';
  1325. staticData['siteName']=this.siteEntry['siteName'];
  1326. titles['siteName']='Site';
  1327. staticData['sitePhone']=this.siteEntry['sitePhone'];
  1328. titles['sitePhone']='Telephone(site)';
  1329. for (f in staticData){
  1330. this.addStaticData(f,titles[f],staticData[f]);
  1331. }
  1332. let formId=crfData.getCrfEntry()['Form'];
  1333. let formEntry=crfSetup.getEntryMap('dataForms')[formId];
  1334. crfHTML.getElement('formTitle').innerText=formEntry['formName'];
  1335. }
  1336. crfVisit.addStaticData=
  1337. function(f,title,value){
  1338. let el=crfHTML.getElement(f);
  1339. //populate only
  1340. if (el!=undefined){
  1341. el.innerText=value;
  1342. return;
  1343. }
  1344. //add row to table if element cannot be found
  1345. let table=crfHTML.getElement('staticTable');
  1346. let row=table.insertRow();
  1347. let cell=row.insertCell();
  1348. cell.innerText=title;
  1349. let cell1=row.insertCell();
  1350. cell1.id=f;
  1351. cell1.style.fontWeight='bold';
  1352. //populate
  1353. cell1.innerText=value;
  1354. }
  1355. //come here after the layout is read from labkey page
  1356. //
  1357. crfVisit.generateErrorMsg=
  1358. function(msg){
  1359. let txt=crfHTML.createParagraph(msg,this.masterForm);
  1360. this.generateButton("submitDiv",'Exit','Exit','redirect');
  1361. }
  1362. crfVisit.checkPermissions=
  1363. function(){
  1364. //check if user has permission on the form
  1365. let userMap=crfSetup.getEntryMap('users');
  1366. let currentUser=userMap[LABKEY.Security.currentUser.id];
  1367. let currentSite=this.siteEntry;
  1368. let formCreator=userMap[crfData.getCrfEntry()['UserId']];
  1369. let formCreatorId=formCreator.UserId;
  1370. //get list of sites the user can work on
  1371. let fList=this.role+'s';
  1372. let fRows=crfSetup.getRows(fList);
  1373. let operatorSites=new Array();
  1374. for (let i=0;i<fRows.length;i++){
  1375. if (fRows[i].User!=currentUser.UserId) continue;
  1376. operatorSites.push(fRows[i].Site);
  1377. }
  1378. this.print('operator Site: '+operatorSites.length);
  1379. if (operatorSites.length==0){
  1380. let msg='User '+currentUser.DisplayName;
  1381. msg+=' is not a '+operator;
  1382. this.generateErrorMsg(msg);
  1383. return false;
  1384. }
  1385. //depending on operator mode, we should decide what is right
  1386. let operator=this.role;
  1387. if (this.role=='crfEditor'){
  1388. //editor can only edit its own forms
  1389. if (currentUser.UserId==formCreatorId){
  1390. return true;
  1391. }
  1392. //here we are if UserId and formCreatorId are not equal
  1393. let allowR=crfSetup.getSettings("allowFormReassignment");
  1394. //form reassignment is not allowed
  1395. if (!allowR){
  1396. let msg='User '+currentUser.DisplayName;
  1397. msg+=' has no permission on this form';
  1398. this.generateErrorMsg(msg);
  1399. return false;
  1400. }
  1401. //this is for allowed form reassignments
  1402. //site should still match
  1403. if (!operatorSites.includes(currentSite.siteNumber)){
  1404. let msg='User '+currentUser.DisplayName;
  1405. msg+=' has no permission for site '+currentSite.siteName;
  1406. this.generateErrorMsg(msg);
  1407. return false;
  1408. }
  1409. //re-assign form, leave a trace in crfStatus and change creator in crfEntry
  1410. let that=this;
  1411. let action=new Object();
  1412. action.name="formReassignement";
  1413. action.cb=function(){that.doNothing();}
  1414. crfData.getCrfEntry()['UserId']=currentUser.UserId;
  1415. let status=crfData.getCrfEntry()['FormStatus'];
  1416. this.updateFlag(status,action);
  1417. return true;
  1418. }
  1419. if (operator=='crfMonitor' || operator=='crfSponsor'){
  1420. //monitor can look at forms based on his site
  1421. //find monitor line
  1422. //implementation of currentSite in operatorSites
  1423. if (!operatorSites.includes(currentSite.siteNumber)){
  1424. let msg='User '+currentUser.DisplayName;
  1425. msg+=' is not a '+operator+' for site ';
  1426. msg+=currentSite.siteName+'('+currentSite.siteNumber+')';
  1427. msg+='/'+operatorSites.join(',');
  1428. this.generateErrorMsg(msg);
  1429. return false;
  1430. }
  1431. }
  1432. this.print('User '+currentUser.DisplayName+'/'+
  1433. currentSite['siteName']+
  1434. ' acting as '+this.role);
  1435. return true;
  1436. }
  1437. crfVisit.afterConfig=
  1438. function(){
  1439. let fName='[afterConfig]';
  1440. this.print(fName);
  1441. this.populateBasicData();
  1442. if (!this.checkPermissions()) return;
  1443. crfSetup.parseButtons();
  1444. let formStatus=crfSetup.getRows('formStatus')[0]['formStatus'];
  1445. //let functionArray=new Array();
  1446. this.print(fName+" generating buttons for formStatus \""+ formStatus+"\"");
  1447. let allButtonRows=crfSetup.getRows('crfButtons');
  1448. let buttonRows=new Array();
  1449. //specifying role=X in actionSettings will limit button to that role
  1450. for (let i=0;i<allButtonRows.length;i++){
  1451. let action=allButtonRows[i]['action'];
  1452. //filter on actionSettings
  1453. let as=crfSetup.getActionSettings[action];
  1454. if (variableList.hasVariable(as,'role')){
  1455. this.print('Role['+this.role+'/'+as['role']+'] limited for action '+action);
  1456. //mismatch skips addition of button to buttonRows
  1457. if (this.role!=as['role']) continue;
  1458. }
  1459. buttonRows.push(allButtonRows[i]);
  1460. }
  1461. for (let i=0;i<buttonRows.length;i++){
  1462. let bt=buttonRows[i];
  1463. //if (typeof window[bt.action]==="function"){
  1464. this.generateButton("submitDiv",bt.caption,bt.label,bt.action,null);
  1465. //}
  1466. //else{
  1467. // this.print('No match for function :'+bt.action+
  1468. // ' obj: '+window[bt.action]);
  1469. //}
  1470. }
  1471. this.print(fName+' buttons generated.');
  1472. //here we should get data. For now, just initialize objects that will hold data
  1473. let that=this;
  1474. let action=function(){that.afterDataLayout();};
  1475. let formId=crfData.getCrfEntry()['Form'];
  1476. crfData.setDataLayout(formId,this.role,action);//callback is afterDataLayout
  1477. }
  1478. crfVisit.afterDataLayout=
  1479. function(){
  1480. let that=this;
  1481. let action=function(){that.afterData();};
  1482. //let action=function(){that.doNothing();};
  1483. crfData.setData(crfData.getCrfRefForData(),action);//callback is afterData
  1484. }
  1485. crfVisit.updateRegistration=
  1486. function(cb=null,data){
  1487. //data is just inserted/updated registration row
  1488. let fName="[updateRegistration]";
  1489. this.print(fName);
  1490. let pM=this.getIdManager();
  1491. let idFieldName=pM.getCrfEntryFieldName('STUDY');
  1492. //have to reload query data
  1493. let regEntry=data.rows[0];
  1494. for (x in regEntry){
  1495. this.print(fName+" ["+x+"] "+regEntry[x]);
  1496. }
  1497. let studyId=data.rows[0][idFieldName];
  1498. if (!studyId) {
  1499. this.print(fName+" study id not set ("+idFieldName+'/'+studyId+")");
  1500. return; //study id not set
  1501. }
  1502. //set
  1503. pM.setParticipantIdToCrfEntry("STUDY",studyId);
  1504. pM.updateCrfEntry();
  1505. //this will only update crfEntry in memory, but not on LabKey,
  1506. //we are counting on updateFlag to follow updateRegistration
  1507. //update parentCRF as well, here we schedule update of data entry as well
  1508. if ("parentCrfData" in crfSetup){
  1509. let parentCrfEntry=crfSetup.getRows('parentCrfData')[0];
  1510. parentCrfEntry[idFieldName]=studyId;
  1511. let that=this;
  1512. let doNothing=function(){that.doNothing();};
  1513. let action={name:"updateRegistration",cb:doNothing};
  1514. let complete=function(data){that.completeWithFlag(data,action);};
  1515. runQuery.modifyRows('update','lists','crfEntry',[parentCrfEntry],complete,crfSetup.getContainer('CRF'));
  1516. }
  1517. if (cb) cb(data);
  1518. }
  1519. crfVisit.afterData=
  1520. function(){
  1521. let fName='afterData';
  1522. this.configureIdManager();
  1523. this.generateSections();
  1524. }
  1525. crfVisit.configureIdManager=
  1526. function(){
  1527. let fName='[configureIdManager]';
  1528. let idMode=this.formEntry['idMode'];
  1529. //set default value if no value is in the list (read value is null)
  1530. if (!idMode) idMode="STUDY:EDIT";
  1531. this.print(fName+': idMode '+idMode);
  1532. //add print to config so participantManager can use it
  1533. let pM=this.getIdManager();
  1534. //extend object
  1535. let that=this;
  1536. let action=new Object();
  1537. action.name='updateCrfEntry';
  1538. action.cb=function(){that.doNothing();};
  1539. let formStatus=crfData.getCrfEntry()['FormStatus'];
  1540. participantIdManager.updateCrfEntry=function(){that.updateFlag(formStatus,action);};
  1541. let idModeArray=idMode.split(':');
  1542. pM.setMode("STUDY");
  1543. if (idModeArray.includes("LOCAL")) {
  1544. pM.setMode("LOCAL");
  1545. }
  1546. //OK, but check if CRF or registration indicate that study id is already set
  1547. pM.verifyCrfStudyId();
  1548. //still local
  1549. if (pM.getMode()=='LOCAL'){
  1550. if (idModeArray.includes("READONLY")){
  1551. pM.setReadonly(pM.getMode());
  1552. let id=pM.getParticipantIdFromCrfEntry(pM.getMode());
  1553. pM.setLabelMode(pM.getMode(),id);
  1554. }
  1555. let localId=pM.getParticipantIdFromCrfEntry('LOCAL');
  1556. if (localId) pM.setLabelMode('LOCAL',localId);
  1557. else pM.setEditMode(pM.getMode());
  1558. pM.setReadonly('STUDY');
  1559. pM.setLabelMode('STUDY','NOT SET');
  1560. }
  1561. }
  1562. crfVisit.generateSections=
  1563. function(){
  1564. let accessMode=this.role+'Mode';
  1565. let formId=crfData.getCrfEntry()['Form'];
  1566. let rowsSetup=crfSetup.selectFormSetupRows(formId);
  1567. for (let i=0;i<rowsSetup.length;i++){
  1568. let entry=rowsSetup[i];
  1569. //debug
  1570. let queryName=crfSetup.getMap('inputLists')[entry['queryName']];
  1571. this.print(fName+" ["+queryName+"]: showFlag: "+entry["showFlag"]);
  1572. this.print(fName+" ["+queryName+"]: accessMode: "+entry[accessMode]);
  1573. const nData=crfData.getQuerySnapshot(queryName).rows.length;
  1574. this.print(fName+" ["+queryName+"]: nData: "+nData);
  1575. //skip sections
  1576. //also from fields
  1577. if (entry[accessMode]=="NONE") continue;
  1578. //section fits one dataset/list
  1579. this.generateSection(entry);
  1580. }
  1581. }
  1582. crfVisit.populateSection=
  1583. function(sectionId){
  1584. let fName='[populateSection/'+sectionId+']';
  1585. this.print(fName);
  1586. //old setting
  1587. let entry=crfSetup.findSetupRow(sectionId);
  1588. //ignore names without associated entry in formSetup
  1589. if (!entry){
  1590. this.print(fName+': no matching FormSetup entry found');
  1591. return;
  1592. }
  1593. //populate comes after generate, we should be pretty safe in taking
  1594. //already generated additionalData
  1595. let queryName=crfSetup.getMap('inputLists')[entry['queryName']];
  1596. if (!(queryName in crfSetup.getAdditionalDataObject())){
  1597. this.print(fName+': no additionalData generated for '+queryName);
  1598. return;
  1599. }
  1600. let additionalData=crfSetup.getAdditionalData(queryName);
  1601. this.print(fName+': using additionalData '+additionalData);
  1602. if ("isReview" in additionalData){
  1603. let action=function(){crfReviewSection.CB();};
  1604. crfReviewSection.generateSection(queryName,queryName,action);
  1605. return;
  1606. }
  1607. let accessMode=this.role+'Mode';
  1608. let aM=entry[accessMode];
  1609. this.print(fName+': accessMode '+aM);
  1610. if (aM!='GENERATE'){
  1611. let writeMode=entry[accessMode]=='EDIT';
  1612. this.print(fName+': mode='+writeMode);
  1613. let setup=this.getStoredSetup(sectionId);
  1614. this.populateTable(queryName,writeMode,setup);
  1615. return;
  1616. }
  1617. //deal with generate
  1618. //
  1619. //already available -> shift to READ mode
  1620. let divTable=sectionId+'Table';
  1621. let divObj=crfHTML.getElement(divTable);
  1622. let divRev=crfHTML.getElement(sectionId+'Review');
  1623. let divRLi=crfHTML.getElement(sectionId+'ReviewList');
  1624. let divGBu=crfHTML.getElement(sectionId+'GenerateButton');
  1625. this.print('div GBU: '+divGBu);
  1626. divObj.style.display="block";
  1627. divRev.style.display="block";
  1628. divRLi.style.display="block";
  1629. if (divGBu!=undefined) divGBu.style.display="none";
  1630. let nData=crfData.getQuerySnapshot(queryName).rows.length;
  1631. let setup=this.getSetup(sectionId,queryName,0);
  1632. this.print('['+queryName+']: nrows '+nData);
  1633. if (nData>0){
  1634. this.populateTable(queryName,0,setup);
  1635. return;
  1636. }
  1637. //hide table
  1638. divObj.style.display="none";
  1639. divRev.style.display="none";
  1640. divRLi.style.display="none";
  1641. if (divGBu!=undefined) divGBu.style.display="block";
  1642. //add buttons?
  1643. //is button already generated?
  1644. //populateTable(entry);
  1645. }
  1646. //******* generateQuery infrastructure *********************
  1647. crfVisit.onGenerateQuery=
  1648. function(queryName){
  1649. let fName='[onGenerateQuery]';
  1650. this.print(fName+' '+queryName);
  1651. //
  1652. let cfgRows=crfSetup.getRows('generateConfigData');
  1653. // //queryName to queryId?
  1654. let qMapInverse=crfSetup.invertMap(crfSetup.getMap('inputLists'));
  1655. let queryId=qMapInverse[queryName];
  1656. let cfgRow=crfSetup.getEntryMap('generateConfigData:queryId')[queryId];
  1657. if (!cfgRow){
  1658. this.print('generateConfig for queryName['+queryId+']='+queryName+' not found');
  1659. return;
  1660. }
  1661. //let formRows=crfSetup.selectFormSetupRows(cfgRow.formId);
  1662. //
  1663. // //check if all required datasets were at least saved
  1664. this.checkGenerationFields(cfgRow);
  1665. }
  1666. crfVisit.checkGenerationFields=
  1667. function(entry){
  1668. //entry is generateConfig row
  1669. let fName='[checkGenerationFields]';
  1670. let mailRecipient=entry.emailRecipient;
  1671. let qMap=crfSetup.getMap('inputLists');
  1672. let qName=qMap[entry['queryId']];
  1673. //list of queries that are part of Registration form
  1674. this.print(fName);
  1675. this.print(fName+' setRecipient: '+mailRecipient);
  1676. let formId=entry['formId'];
  1677. this.print(fName+" Checking form w/id "+formId);
  1678. let formRows=crfSetup.selectFormSetupRows(formId);
  1679. //registration rows
  1680. for (let i=0;i<formRows.length;i++){
  1681. let row=formRows[i];
  1682. let queryId=row.queryName;
  1683. if (queryId==entry.queryId) continue;
  1684. let fQuery=crfData.getQuerySnapshot(qMap[queryId]);
  1685. this.print('Checking '+qMap[queryId]+' nrows: '+fQuery.rows.length);
  1686. //this is to check whether sufficient data was provided for monitor
  1687. //to make an informed decision whether registration is in order
  1688. if (fQuery.rows.length==0){
  1689. this.generateError(qName,qMap[queryId]);
  1690. return;
  1691. }
  1692. }
  1693. this.generateMessage(qName,'Vailidation OK');
  1694. let that=this;
  1695. let cb=function(){that.prepareForm(entry);};
  1696. this.generateListEntry(entry.formId,qName,cb);
  1697. }
  1698. crfVisit.prepareForm=
  1699. function(entry){
  1700. //entry is generateConfig row
  1701. let fName="[prepareForm]";
  1702. let formId=entry['formId'];
  1703. //this.print(fName+' recipient '+mailRecipient);
  1704. //look for existing registration entry
  1705. let that=this;
  1706. let action=function(data){that.generateForm(data,entry);};
  1707. let formFilter=LABKEY.Filter.create('Form',formId);
  1708. let parentCrfFilter=LABKEY.Filter.create('parentCrf',this.crfRef);
  1709. let filters=[formFilter,parentCrfFilter];
  1710. runQuery.selectRows('lists','crfEntry',filters,action,crfSetup.getContainer('data'));
  1711. }
  1712. crfVisit.generateError=
  1713. function(queryName,fQueryName){
  1714. let elName=queryName+'GenerateButton'+'_reportField';
  1715. let el=crfHTML.getElement(elName);
  1716. el.innerText='Error: '+fQueryName+' was not set';
  1717. el.style.color='red';
  1718. }
  1719. crfVisit.generateMessage=
  1720. function(queryName,msg){
  1721. let elName=queryName+'GenerateButton'+'_reportField';
  1722. let el=crfHTML.getElement(elName);
  1723. el.innerText=msg;
  1724. el.style.color='green';
  1725. }
  1726. crfVisit.generateForm=
  1727. function(data,entry){
  1728. //entry is generateConfig entry
  1729. //data is a crfEntry row
  1730. let fName='[generateForm]';
  1731. const nData=data.rows.length;
  1732. let formId=entry['formId'];
  1733. let formEntry=crfSetup.getEntryMap('dataForms')[formId];
  1734. let formName=formEntry['formName'];
  1735. this.print(fName+' crfEntry ('+formName+'): '+nData+' rows');
  1736. //we have to generate masterQuery with parentCrf and crfRef
  1737. //and crfEntry with new entryId and parentCrf equal to crfRef
  1738. let queryName=crfSetup.getMap('inputLists')[entry['queryId']];
  1739. if (nData>0) {
  1740. this.generateMessage(queryName,formName+' already generated.');
  1741. return;
  1742. }
  1743. //use current crfEntry as base
  1744. let crfBase=crfData.getCrfEntry();
  1745. let idLabel=crfSetup.getParticipantLabel(crfBase);
  1746. //role will appear in crfStatus and will be validated agains crfCreator entry of the form
  1747. let roleAndSite='generate:'+crfBase.Site;
  1748. //have to overload crfEntry
  1749. // - parentCrf
  1750. // - formStatus
  1751. // - UserId (set to sponsor UserId)
  1752. //
  1753. // should provide mail recipient and/or modified cb
  1754. //
  1755. //
  1756. let crfEntryOverload=new Object();
  1757. //parentCrf
  1758. crfEntryOverload.parentCrf=crfBase.entryId;
  1759. //formStatus
  1760. crfEntryOverload.formStatus=1;//In progress
  1761. //checks for both field presence (if not in query, undefined) and field value (if not set, null)
  1762. this.print(fName+' setup status: '+entry.formStatus);
  1763. if (entry.formStatus){
  1764. crfEntryOverload.formStatus=entry.formStatus;
  1765. }
  1766. // UserId
  1767. //find sponsor for site
  1768. let site=crfBase.Site;
  1769. let crfSponsors=crfSetup.getRows('crfSponsors');
  1770. let userMap=crfSetup.getEntryMap('users');
  1771. let sponsorId=null;
  1772. for (let i=0;i<crfSponsors.length;i++){
  1773. //take first matching sponsor
  1774. if (crfSponsors[i].Site!=site) continue;
  1775. sponsorId=crfSponsors[i].User;
  1776. //finds first
  1777. break;
  1778. }
  1779. let sponsor=userMap[sponsorId];
  1780. this.print('Selecting '+sponsor.DisplayName+' as sponsor');
  1781. //different user than the original form...
  1782. //should be set to the study sponsor
  1783. crfEntryOverload.UserId=sponsor.UserId;
  1784. let mailRecipient=entry.mailRecipient;
  1785. let that=this;
  1786. let action=function(){that.doNothing();};
  1787. let cb=function(data,_crfEntry){that.sendEmail(data,mailRecipient,action,formName+' generated');}
  1788. formPortal.createForm(formId,roleAndSite,cb,idLabel,crfEntryOverload);
  1789. }
  1790. crfVisit.generateListEntry=
  1791. function(formId,queryName,cb){
  1792. //check if registration was already generated
  1793. let formRows=crfSetup.selectFormSetupRows(formId);
  1794. let nData=crfData.getQuerySnapshot(queryName).rows.length;
  1795. if (nData>0) return;
  1796. //create new list entry
  1797. let pM=this.getIdManager();
  1798. let e2=new Object();
  1799. e2.crfRef=this.getCrfRef();
  1800. e2.registrationStatus=0;
  1801. e2.submissionDate=new Date();
  1802. let idLabel=crfSetup.getParticipantLabel(crfData.getCrfEntry());
  1803. e2[crfSetup.getLocalIdLabel()]=crfSetup.getLocalId(idLabel);
  1804. e2[crfSetup.getStudyIdLabel()]=crfSetup.getStudyId(idLabel);
  1805. this.print('set values');
  1806. e2.site=crfData.getCrfEntry()['Site'];
  1807. runQuery.insertRows('lists',queryName,[e2],cb,crfSetup.getContainer('data'));
  1808. }
  1809. // ******************** end form generator (Registration) ********************
  1810. //jump to populate table/generate review, etc defined at the begining of the file
  1811. //entry point from generateMasterForm
  1812. crfVisit.setFormConfig=
  1813. function(){
  1814. let fName="[setFormConfig]";
  1815. let crfRef=this.crfRef;
  1816. let that=this;
  1817. let afterCrfEntry=function(){that.afterCrfEntry();};
  1818. let action=function(){crfData.setCrfEntry(crfRef,afterCrfEntry);};//afterCrfEntry
  1819. crfSetup.setContainers(action);
  1820. }
  1821. crfVisit.afterCrfEntry=
  1822. function(){
  1823. let fName='[afterCRFEntry]';
  1824. this.print(fName+" setting crfEntry (x) to "+crfData.getCrfEntry()["entryId"]);
  1825. //for empty records or those with parentCrf not set, parentCrf comes up as null
  1826. //nevertheless, with two equal signs, check against undefined also works
  1827. crfSetup.formStatus=crfData.getCrfEntry()['FormStatus'];
  1828. let parentCrf=crfData.getCrfEntry()['parentCrf'];
  1829. this.print(fName+' parentCrf set to '+parentCrf);
  1830. if (parentCrf) crfSetup.parentCrf=parentCrf;
  1831. let that=this;
  1832. let action=function(){that.parseSetup();};
  1833. crfSetup.parseSetup(action);
  1834. }
  1835. crfVisit.parseSetup=
  1836. function(){
  1837. //debug
  1838. let fName='[parseSetup]';
  1839. let varRows=crfSetup.getRows('crfStaticVariables');
  1840. let studyVars=crfSetup.getRows('studyData')[0];
  1841. for (let i=0;i<varRows.length;i++){
  1842. let vName=varRows[i].staticVariable;
  1843. this.print(fName+' '+vName+': '+studyVars[vName]);
  1844. }
  1845. //parse site
  1846. this.siteEntry=crfSetup.getEntryMap('siteData')[crfData.getCrfEntry()['Site']];
  1847. this.print("Setting site name to "+this.siteEntry['siteName']);
  1848. //study
  1849. this.print("XSetting participantField to "+studyVars["SubjectColumnName"]);
  1850. //parse user
  1851. this.userEntry=crfSetup.getEntryMap('users')[crfData.getCrfEntry()['UserId']];
  1852. this.print("Setting user to "+this.userEntry["DisplayName"]);
  1853. this.print('Setting operator to: '+this.role);
  1854. //point formId to point to form set in crfEntry
  1855. let formId=crfData.getCrfEntry()['Form'];
  1856. this.formEntry=crfSetup.getEntryMap('dataForms')[formId];
  1857. let accessModeColumn=this.role+'Status';
  1858. let targetStatus=this.formEntry[accessModeColumn];
  1859. let formStatus=crfData.getCrfEntry()['FormStatus'];
  1860. this.print(fName+' comparing status '+formStatus+'/'+targetStatus);
  1861. if (targetStatus!=formStatus){
  1862. let statusMap=crfSetup.getEntryMap('formStatusAll');
  1863. let targetEntry=statusMap[targetStatus];
  1864. let actualEntry=statusMap[formStatus];
  1865. alert('Form status ['+actualEntry.formStatus+'] not suitable to be operated by '+this.role+' targeting status ['+targetEntry.formStatus+']');
  1866. this.redirect();
  1867. }
  1868. crfSetup.setAdditionalData(this.crfRef,formId);
  1869. this.afterConfig();
  1870. }
  1871. crfVisit.uploadFile=
  1872. function(inputElement,context){
  1873. //context should have ID and dirName attributes;
  1874. //path will be dirName/ID/fieldName_ID.suf
  1875. //where suf is identical to localPath content picked from
  1876. //inputElement
  1877. this.print('uploadFile: '+inputElement.value+'/');
  1878. if (inputElement.type=="text") return;
  1879. this.print('uploadFile: '+inputElement.files+'/');
  1880. this.print('uploadFile: '+inputElement.files.length+'/');
  1881. if (inputElement.files.length>0){
  1882. let file=inputElement.files[0];
  1883. this.print('uploadFile: '+inputElement.value+'/'+file.size);
  1884. webdav.uploadFile(file,context);
  1885. }
  1886. }
  1887. crfVisit.printForm=
  1888. function(){
  1889. crfPrint.printForm();
  1890. }