crfVisitNew.js 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302
  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. crfHTML.createTextNode("All options",null,cell);
  587. let cell1=row.insertCell();
  588. cell1.colSpan="3";
  589. for (let x in lObject.LUT){
  590. let b=crfHTML.createButton(null,cell1);
  591. b.id=fieldUID+':'+x;
  592. b.value=lObject.LUT[x];
  593. input=crfHTML.getElement(setup.getInputId(field.name));
  594. b.onclick=function(){crfHTML.updateSelect(input,cell1,x,b.value);}
  595. }
  596. }
  597. }
  598. crfVisit.populateFieldRow=
  599. function(entry,field,setup){
  600. this.populateField(entry,field,setup);
  601. this.populateSubQuery(entry,field,setup);
  602. this.populateSpecialFields(entry,field,setup);
  603. }
  604. crfVisit.populateSubQuery=
  605. function(entry,field,setup){
  606. let fName='[populateSubQuery/'+setup.queryName+':'+field.name+']';
  607. if (setup.isReview) return;
  608. if (!(setup.queryName in crfSetup.getAdditionalDataObject())){
  609. let msg=fName+': no additionalData entry for '+setup.queryName;
  610. msg+=' (probably a subquery)';
  611. this.print(msg);
  612. return;
  613. }
  614. //find if field is connected to a sub array
  615. //find queryName
  616. //
  617. let additionalData=crfSetup.getAdditionalData(setup.queryName);
  618. this.print(fName);
  619. //let flag=additionalData.showFlag;
  620. if (!("showFlag" in additionalData)) return;
  621. let eId=setup.getInputId(additionalData.showFlag);
  622. let id=setup.getInputId(field.name);
  623. if (eId!=id) {
  624. this.print(fName+": ignoring field "+id+"/"+eId);
  625. return;
  626. }
  627. this.print(fName+': id '+id);
  628. //hard to estimate readonlyFlag
  629. //
  630. let input=crfHTML.getElement(id);
  631. let eType=input.nodeName.toLowerCase();
  632. let readonlyFlag=eType!="select";
  633. this.setListVisibility(input,setup,readonlyFlag);
  634. }
  635. crfVisit.clearField=
  636. function(field,setup){
  637. let foo=new Object();
  638. this.populateField(foo,field,setup);
  639. }
  640. crfVisit.populateField=
  641. function(entry,field,setup){
  642. let vName=field.name;
  643. let fName='[populateFieldName/'+vName+']';
  644. let varValue="UNDEF";
  645. //if (vName in setup.filters) varValue=setup.filters[vName];
  646. if (vName in entry) varValue=entry[vName];
  647. //if part of the filter, set it to value
  648. if (vName in setup.filters) varValue=setup.filters[vName];
  649. let isLookup=("lookup" in field);
  650. this.print(fName+' v='+varValue+'/'+isLookup+' ['+
  651. setup.getInputId(field.name)+']');
  652. let vType=field.type;
  653. let id=setup.getInputId(vName);
  654. let input=crfHTML.getElement(id);
  655. //date
  656. if (vType=="date"){
  657. if (varValue=="UNDEF") varValue=new Date();
  658. else varValue=new Date(varValue);
  659. }
  660. //lookup for readonly
  661. if (isLookup && varValue!="UNDEF"){
  662. let lookup=field["lookup"];
  663. //get all values from config.formConfig.lookup[X]
  664. let lObject=crfData.getLookup(lookup.queryName);
  665. varValue=lObject.LUT[varValue];
  666. }
  667. this.print('Element: '+id+'/'+input);
  668. //figure out the element type
  669. let eType=input.nodeName.toLowerCase();
  670. this.print('Element type: '+eType);
  671. //change varValue for printing
  672. if (varValue=="UNDEF") varValue="";
  673. //HTMLTextArea, createElement(textArea)
  674. if (eType==="textarea"){
  675. input.value=varValue;
  676. return;
  677. }
  678. //Text, createTextNode
  679. if (eType==="#text"){
  680. input.nodeValue=varValue;
  681. return;
  682. }
  683. //HTMLLabelElement, createElement('label')
  684. if (eType==="label"){
  685. input.innerText=varValue;
  686. return;
  687. }
  688. //HTMLSelectElement, createElement('select')
  689. if (eType==="select"){
  690. input.selectedIndex=0;
  691. for (let i=0;i<input.options.length;i++){
  692. let v=input.options[i].text;
  693. if (v!=varValue) continue;
  694. input.selectedIndex=i;
  695. break;
  696. }
  697. return;
  698. }
  699. if (eType!="input"){
  700. this.print('Unknown type: '+eType+' encountered, igonring');
  701. return;
  702. }
  703. //HTMLInputElement
  704. let type=input.type;
  705. if (type=="date"){
  706. input.valueAsDate=varValue;
  707. return;
  708. }
  709. //string,float
  710. if (type=="text"){
  711. input.value=varValue;
  712. return;
  713. }
  714. //boolean
  715. if (type=="checkbox"){
  716. input.checked=varValue;
  717. return;
  718. }
  719. this.print('Unknown input type: '+type+'. Ignoring.');
  720. }
  721. crfVisit.populateSpecialFields=
  722. function(entry,field,setup){
  723. let fName='[populateSpecialFields]';
  724. let fieldUID=setup.queryName+':'+field.name;
  725. let specialFields=crfSetup.getEntryMap('specialFields:fieldUID');
  726. if (!(fieldUID in specialFields)) return;
  727. let specFieldSetup=specialFields[fieldUID];
  728. //q is not used by copyCrfEntry, keeping it here for future reference
  729. let q=variableList.parseVariables(specFieldSetup['actionParameters']);
  730. let type=specFieldSetup['actionType'];
  731. if (type=='copyCrfEntry'){
  732. let el=crfHTML.getElement(setup.getInputId(field.name));
  733. let varName=field.name;
  734. if ("varName" in q) varName=q["varName"];
  735. let id=crfData.getCrfEntry()[varName];
  736. el.value=id;
  737. this.print(fName+' specialFields ['+field.name+'] '+id+'/'+el.value);
  738. }
  739. }
  740. crfVisit.populateTable=
  741. function(listName,writeMode,setup){
  742. //function populateTable(formSetupEntry){
  743. //let listName=config.formConfig.queryMap[formSetupEntry['queryName']];
  744. //let accessMode=config.formConfig.operator+'Mode';
  745. //let writeMode=formSetupEntry[accessMode]=='EDIT';
  746. let fName='[populateTable/'+listName+']';
  747. //should contain formSetup key
  748. //data snapshot
  749. let fQuery=crfData.getQuerySnapshot(listName);
  750. let queryLayout=crfData.getQueryLayout(listName);
  751. //here I assume that listName was parsed during setDataLayout and setData
  752. //so that rows was set (even if they are empty)
  753. this.print(fName+"]: nrows "+fQuery.rows.length);
  754. let entry=this.selectEntry(fQuery.rows,setup);
  755. if (!entry) entry=new Object();
  756. let fields=queryLayout.fields;
  757. for (f in fields){
  758. let field=fields[f];
  759. //each field is a new row
  760. this.print(fName+": Adding field: "+f+'/'+field.name+' hidden: '+field.hidden+' type:'+field.type);
  761. if (field.hidden) continue;
  762. if (field.name=="crfRef") continue;
  763. if (field.name in setup.setVariables) continue;
  764. this.populateFieldRow(entry,field,setup);
  765. }
  766. }
  767. crfVisit.generateTable=
  768. function(listName,divName,additionalData,setup){
  769. let fName="[generateTable/"+listName+"]";
  770. this.print(fName);
  771. //is listName and setup.queryName a duplicate of the same value
  772. this.print(fName+': setup.queryName '+setup.queryName);
  773. //assume data is set in config.formConfig.dataQueries[data.queryName].rows;
  774. let populateData=true;
  775. if ("subTable" in setup){
  776. this.print(fName+" is subTable");
  777. populateData=false;
  778. }
  779. let entry=new Object();
  780. //data snapshot
  781. let fQuerySnapshot=crfData.getQuerySnapshot(listName);
  782. let queryLayout=crfData.getQueryLayout(listName);
  783. //here I assume that listName was parsed during setDataLayout and setData
  784. //so that rows was set (even if they are empty)
  785. this.print(fName+": Nrows "+fQuerySnapshot.rows.length);
  786. if (fQuerySnapshot.rows.length>0)
  787. entry=fQuerySnapshot.rows[0];
  788. if ("reviewTable" in setup){
  789. entry['reviewComment']='';
  790. delete entry["ModifiedBy"];
  791. }
  792. let tb=crfHTML.createTable(divName);
  793. tb.className="t2";
  794. //this are the fields (probably constant)
  795. let fields=queryLayout.fields;
  796. for (f in fields){
  797. let field=fields[f];
  798. let fieldUID=listName+":"+field.name;
  799. //each field is a new row
  800. this.print(fName+": Adding field: "+f+'/'+field.name+' ('+fieldUID+').');
  801. //unique name
  802. if (field.hidden) continue;
  803. if (field.name=="crfRef") continue;
  804. if (field.name in setup.setVariables) continue;
  805. this.addFieldRow(tb,field,setup,additionalData);
  806. if (populateData) this.populateFieldRow(entry,field,setup);
  807. let specialFields=crfSetup.getEntryMap('specialFields:fieldUID');
  808. if (fieldUID in specialFields){
  809. let specFieldSetup=specialFields[fieldUID];
  810. this.addSpecialFieldRows(tb,field,specFieldSetup,setup);
  811. }
  812. }
  813. //finish of if apply button is not required
  814. if (!("addApply" in setup)) {
  815. this.print(fName+"populateTable: done");
  816. return;
  817. }
  818. let row=tb.insertRow();
  819. let th=crfHTML.createTblHeader(null,row);
  820. th.innerHTML=setup.addApply;
  821. let cell=row.insertCell();
  822. //cell.setAttribute("colspan","2");
  823. let input=crfHTML.createButton(null,cell);
  824. input.value=setup.addApply;
  825. let cell1=row.insertCell();
  826. cell1.setAttribute("colspan","2");
  827. cell1.id=setup.getInputId("rerviewLastSave");
  828. cell1.innerHTML="No recent update";
  829. //saveReview is a generic name for saving content of the html page to a list entry
  830. let that=this;
  831. input.onclick=function(){that.saveReview(listName,cell1.id,setup)};
  832. }
  833. crfVisit.setEntryFromElement=
  834. function(entry,elementId, field){
  835. //set value to entry from element using representation (field) from labkey
  836. //
  837. //
  838. let fName='setEntryFromElement';
  839. let el=crfHTML.getElement(elementId);
  840. if (!el) {
  841. this.print(fName+" element: "+elementId+" not found");
  842. return;
  843. }
  844. this.print(fName+" element: "+elementId);
  845. let vName=field.name;
  846. let vType=field.type;
  847. let eType=el.nodeName.toLowerCase();
  848. if (eType==="select"){
  849. entry[vName]=el.options[el.selectedIndex].value;
  850. return;
  851. }
  852. if (eType==="td"){
  853. entry[vName]=el.innerText;
  854. return;
  855. }
  856. if (vType=="date"){
  857. let date=el.valueAsDate;
  858. if (!date) return;
  859. date.setUTCHours(12);
  860. entry[vName]=date.toString();
  861. this.print(fName+" setting date to "+entry[vName]);
  862. return;
  863. }
  864. if (vType=="string"){
  865. entry[vName]=el.value;
  866. if (vName.search('_file_')<0)
  867. return;
  868. //upload file
  869. let id1=elementId+'_file_';
  870. let input1=crfHTML.getElement(id1);
  871. this.print(fName+' attachment field: '+input1.value);
  872. //entry[vName]=el.files[0].stream();
  873. let ctx=new Object();
  874. ctx['dirName']='consent';
  875. ctx['ID']=entry['crfRef'];
  876. //should point to data container
  877. ctx['project']=getContainer('data');
  878. //need ID->crf!
  879. //assume crfRef will get set before this
  880. //element is encountered
  881. this.uploadFile(input1,ctx);
  882. let fv=el.value;
  883. let suf=fv.split('.').pop();
  884. entry[vName]=entry['crfRef']+'.'+suf;
  885. return;
  886. }
  887. if (vType=="float" || vType=="int"){
  888. entry[vName]=el.value;
  889. if (vName=="queryName") {
  890. this.print(fName+' parsing queryName: '+el.innerText);
  891. let qMapInverse=crfSetup.invertMap(crfSetup.getMap('inputLists'));
  892. entry[vName]=qMapInverse[el.innerText];
  893. //use queryMap lookup
  894. }
  895. return;
  896. }
  897. if (vType=="boolean"){
  898. entry[vName]=el.checked;
  899. return;
  900. }
  901. return;
  902. }
  903. crfVisit.selectEntry=
  904. function(fRows,setup){
  905. let fName='[selectEntry]';
  906. if (!("unique" in setup)) return null;
  907. if (fRows.length==0) return null;
  908. keys=Object.keys(setup.setVariables);
  909. if (keys.length==0)
  910. return fRows[0];
  911. for (let i=0;i<fRows.length;i++){
  912. for (let v in setup.setVariables){
  913. this.print(fName+' row '+i+' ['+v+'] '+fRows[i][v]+'/'+setup.setVariables[v]);
  914. if (fRows[i][v]==setup.setVariables[v]){
  915. this.print(fName+' using '+i);
  916. return fRows[i];
  917. }
  918. }
  919. }
  920. return null;
  921. }
  922. crfVisit.saveReview=
  923. function(queryName,elementId,setup){
  924. //loads any queryName
  925. let fName='[saveReview/'+queryName+']';
  926. this.print(fName+" elementId "+elementId);
  927. let unique=("unique" in setup);
  928. //data snapshot
  929. let fQuerySnapshot=crfData.getQuerySnapshot(queryName);
  930. let nRows=fQuerySnapshot.rows.length;
  931. //data layout
  932. let queryLayout=crfData.getQueryLayout(queryName);
  933. //determine mode based on entry uniqueness and presence of data
  934. let entry=this.selectEntry(fQuerySnapshot.rows,setup);
  935. let mode='update';
  936. if (!entry){
  937. entry=new Object();
  938. mode='insert';
  939. }
  940. this.print(fName+' unique '+unique+' mode '+mode+' nRows '+nRows);
  941. entry.crfRef=this.getCrfRefData();
  942. this.print(fName+" set crfRef="+entry.crfRef);
  943. let fields=queryLayout.fields;
  944. for (f in fields){
  945. let field=fields[f];
  946. this.print(fName+" saveReview field: "+field.name);
  947. if (field.hidden) continue;
  948. if (field.name in setup.setVariables){
  949. entry[field.name]=setup.setVariables[field.name];
  950. continue;
  951. }
  952. let vName=field.name;
  953. let vType=field.type;
  954. this.print(fName+" vType: "+vType);
  955. if (vName=="crfRef") continue;
  956. //need to save queryName for reviewComments
  957. let eId=setup.getInputId(vName);
  958. //copy values from form to entry
  959. this.setEntryFromElement(entry,eId,field,setup);
  960. //clear field value
  961. if (!unique) this.clearField(field,setup);
  962. }
  963. let that=this;
  964. let updateFlag=function(data){that.updateLastSavedFlag(data,setup,elementId)};
  965. let cPath=crfSetup.getContainer('data');
  966. let action=updateFlag;
  967. if (crfSetup.getSettings("updateRegistration")){
  968. let pars=variableList.parseVariables(crfSetup.getSettings("updateRegistration"));
  969. if (pars['query']==queryName){
  970. action=function(data){that.updateRegistration(updateFlag,data);}
  971. }
  972. }
  973. runQuery.modifyRows(mode,'lists',queryName,[entry],action,cPath);
  974. }
  975. crfVisit.updateLastSavedFlag=
  976. function(data,setup,elementId){
  977. let fName='[updateLastSavedFlag]';
  978. this.print(fName+" update last saved flag to "+elementId);
  979. let el=crfHTML.getElement(elementId);
  980. let dt=new Date();
  981. el.innerHTML="Last saved "+dt.toString();
  982. if (data.queryName=="reviewComments"){
  983. this.updateListDisplay(setup.divReviewListId,"reviewComments",setup.filters,true);
  984. }
  985. //refresh stored data!
  986. let writeMode=!setup.readonlyFlag();
  987. let that=this;
  988. let cb=function(){that.populateTable(data.queryName,writeMode,setup);};
  989. if ("unique" in setup)
  990. crfData.setData(crfData.getCrfRefForData(),cb);
  991. if ("masterQuery" in setup){
  992. let ad=crfSetup.getAdditionalData(setup.masterQuery);
  993. this.print('Updating list display: '+setup.queryName+'/'+ad.queryName);
  994. this.updateListDisplay(ad.divQueryName,ad.queryName,ad.filters,false);
  995. }
  996. }
  997. //>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
  998. //generic form status switch statementes
  999. crfVisit.changeFormStatusAndNotify=
  1000. function(actionName){
  1001. let fName='[changeStatusAndNotify]';
  1002. this.print(fName);
  1003. let targetStatus=crfSetup.getTargetStatus(actionName);
  1004. let targetRecipient=crfSetup.getTargetRecipient(actionName);
  1005. let actionSettings=crfSetup.getActionSettings(actionName);
  1006. let action=new Object();
  1007. action.name=actionName;
  1008. let finalStep=function(){that.redirect();};
  1009. if (variableList.hasVariable(actionSettings,"finalStep")){
  1010. this.print(fName+' adjusting finalStep');
  1011. //set to doNothing to remain on submit window
  1012. if (actionSettings.finalStep=="doNothing"){
  1013. finalStep=function(){that.doNothing();};
  1014. }
  1015. }
  1016. this.print(fName+' action '+actionName+' targetStatus '+targetStatus);
  1017. let that=this;
  1018. action.cb=function(data){that.sendEmail(data,targetRecipient,finalStep,actionName);}
  1019. this.updateFlag(targetStatus,action);//Approved
  1020. }
  1021. crfVisit.updateFlag=
  1022. function(flag,action){
  1023. let fName='[updateFlag]';
  1024. let entry=crfData.getCrfEntry();
  1025. entry.FormStatus=flag;
  1026. let uId=LABKEY.Security.currentUser.id;
  1027. entry[this.role]=uId;
  1028. this.print(fName+': Form: '+entry.Form);
  1029. this.print(fName+": set form status to "+entry.FormStatus);
  1030. let that=this;
  1031. let cb=function(data){that.completeWithFlag(data,action);};
  1032. runQuery.modifyRows('update','lists','crfEntry',[entry],cb,crfSetup.getContainer('data'));
  1033. }
  1034. crfVisit.completeWithFlag=
  1035. function(data,action){
  1036. let fName='[completeWithFlag]';
  1037. this.print(fName+': nrows '+data.rows.length);
  1038. let fentry=data.rows[0];
  1039. this.print(fName+': form status '+fentry.FormStatus);
  1040. this.print(fName+': form '+fentry.Form);
  1041. let crfStatus=crfData.createCrfStatus(fentry);
  1042. crfStatus.operator=this.role;
  1043. crfStatus.action=action.name;
  1044. let that=this;
  1045. let cb=function(){that.doNothing();};
  1046. if (action.cb) cb=action.cb;
  1047. runQuery.insertRows('lists','crfStatus',[crfStatus],cb,crfSetup.getContainer('data'));
  1048. }
  1049. //******************************************upload to database *********************
  1050. crfVisit.onDatabaseUpload=
  1051. function(){
  1052. let actionName='onDatabaseUpload';
  1053. let fName='['+actionName+']';
  1054. this.print(fName);
  1055. let pM=this.getIdManager();
  1056. let participantId=participantIdManager.getParticipantIdFromCrfEntry('STUDY');
  1057. let that=this;
  1058. let crfRefForData=crfData.getCrfRefForData();
  1059. //load lists and study data
  1060. //check what needs to be updated and upload
  1061. //a (reverse) sequence of functions
  1062. let completeUpload=function(){that.changeFormStatusAndNotify(actionName);};
  1063. let uploadData=function(){crfData.uploadData(participantId,crfRefForData,completeUpload);};
  1064. let loadStudy=function(){crfData.setData(crfRefForData,uploadData,'study');}
  1065. crfData.setData(crfRefForData,loadStudy,'lists');
  1066. }
  1067. //*************************update for further review *************************
  1068. crfVisit.onUpdateForReview=
  1069. function(){
  1070. let actionName='onUpdateForReview';
  1071. this.changeFormStatusAndNotify(actionName);
  1072. }
  1073. //************************************************ submit *******************************************
  1074. crfVisit.onSubmit=
  1075. function(){
  1076. //update list storage and change status
  1077. this.hideErr();
  1078. this.clearErr();
  1079. this.printErr("onSubmit");
  1080. let that=this;
  1081. let actionName='onSubmit';
  1082. let action=function(){that.verifyData(actionName);};
  1083. crfData.setData(crfData.getCrfRefForData(),action);
  1084. }
  1085. crfVisit.verifyData=
  1086. function(actionName){
  1087. let fName='[verifyData/'+actionName+']';
  1088. let qList=crfData.getActiveQueries();
  1089. let that=this;
  1090. let doNothing=function(data){that.doNothing();};
  1091. let pM=this.getIdManager();
  1092. let fieldName=pM.getCrfEntryFieldName(pM.getMode());
  1093. let setId=crfData.getCrfEntry()[fieldName];
  1094. this.print(fName+' crfEntry ['+fieldName+'] '+crfData.getCrfEntry()[fieldName]);
  1095. if (!setId){
  1096. this.printErr('Missing ID !');
  1097. return false;
  1098. }
  1099. for (let qId in qList){
  1100. let entry=qList[qId];
  1101. let q=entry['queryName'];
  1102. let qData=crfData.getQuerySnapshot(q);
  1103. if (q=="reviewComments") continue;
  1104. //copy snapshot to history
  1105. if (qData.rows.length==0){
  1106. this.print(fName+' no rows for '+q);
  1107. }
  1108. else
  1109. runQuery.insertRows('lists',q+'History',qData.rows,doNothing,this.getContainer('data'));
  1110. //if it doesn't have additionalData, it is a sub query
  1111. if (!(q in crfSetup.getAdditionalDataObject())){
  1112. continue;
  1113. }
  1114. if (qData.rows.length<1){
  1115. this.printErr('Missing entry for query '+q);
  1116. return false;
  1117. }
  1118. }
  1119. //this is necessary only for Generated to Generation completed step
  1120. //let actionSettings=crfSetup.getActionSettings(actionName);
  1121. //if (variableList.hasVariable(actionSettings,"updateRegistration")){
  1122. //if updateRegistrationFormId is set, only update when submit is used on that form
  1123. // if (variableList.hasVariable(actionSettings,"updateRegistrationFormId")){
  1124. // let formId=crfData.getCrfEntry()['Form'];
  1125. //if (actionSettings['updateRegistrationFormId']==formId)
  1126. // this.updateRegistration();
  1127. //}
  1128. //else
  1129. // this.updateRegistration();
  1130. //}
  1131. this.changeFormStatusAndNotify(actionName);
  1132. }
  1133. crfVisit.getEmail=
  1134. function(recipientCode){
  1135. this.print('getEmail w/'+recipientCode);
  1136. let recipients=new Array();
  1137. let typeTo=LABKEY.Message.recipientType.to;
  1138. let create=LABKEY.Message.createRecipient;
  1139. let userMap=crfSetup.getEntryMap('users');
  1140. let currentUser=userMap[LABKEY.Security.currentUser.id];
  1141. let currentSite=this.siteEntry;
  1142. let formCreator=userMap[crfData.getCrfEntry()['UserId']];
  1143. let userRows=crfSetup.getRows('users');
  1144. let parentUser=null;
  1145. if ("parentCrfData" in crfSetup){
  1146. let parentCrf=crfSetup.getRows('parentCrfData');
  1147. parentUser=userMap[parentCrf[0].UserId];
  1148. }
  1149. let recipientCategories=recipientCode.split(',');
  1150. for (let i=0;i<recipientCategories.length;i++){
  1151. let recipient=recipientCategories[i];
  1152. this.print('Checking '+recipient);
  1153. if (recipient=='crfEditor'){
  1154. this.print('Adding :'+formCreator.Email);
  1155. recipients.push(create(typeTo,formCreator.Email));
  1156. if (!parentUser) continue;
  1157. this.print('Adding :'+parentUser.Email);
  1158. recipients.push(create(typeTo,parentUser.Email));
  1159. continue;
  1160. }
  1161. //Monitor or Sponsor
  1162. let fList=recipient+'s';
  1163. let fRows=crfSetup.getRows(fList);
  1164. for (let i=0;i<fRows.length;i++){
  1165. this.print('Checking '+fRows[i].User+'/'+fRows[i].Site);
  1166. if (fRows[i].Site!=currentSite.siteNumber) continue;
  1167. let targetUser=userMap[fRows[i].User];
  1168. if (!targetUser) continue;
  1169. recipients.push(create(typeTo,targetUser.Email));
  1170. }
  1171. }
  1172. return recipients;
  1173. }
  1174. crfVisit.sendEmail=
  1175. function(data,recipient='crfEditor',cb=null,subj='Form submitted'){
  1176. this.print('sendEmail; recipient: '+recipient);
  1177. let that=this;
  1178. if (!cb)
  1179. cb=function(){that.redirect();};
  1180. let cvar='sendEmail';
  1181. let cval=crfSetup.getSettings(cvar);
  1182. if (cval){
  1183. this.print(cvar+' set to '+cval);
  1184. if (cval=='FALSE'){
  1185. this.print('Skipping sending emails');
  1186. cb();
  1187. return;
  1188. }
  1189. }
  1190. if (recipient==null){
  1191. this.print('Skipping sending emails w/ no recipients');
  1192. cb();
  1193. return;
  1194. }
  1195. this.print('send email '+data.rows.length);
  1196. let crf=data.rows[0]['entryId'];
  1197. let formId=data.rows[0]['Form'];
  1198. let link=LABKEY.ActionURL.getBaseURL();
  1199. link+=LABKEY.ActionURL.getContainer();
  1200. link+='/crf_tecant-visit.view?';
  1201. link+='entryId='+crf;
  1202. link+='&formId='+formId;
  1203. link+='&role='+recipient;
  1204. //debug
  1205. let recipients=this.getEmail(recipient);
  1206. //from crfManagers list
  1207. let typeHtml=LABKEY.Message.msgType.html;
  1208. let typePlain=LABKEY.Message.msgType.plain;
  1209. let msg1=LABKEY.Message.createMsgContent(typePlain,link);
  1210. //let cb=doNothing;
  1211. //let cb=redirect;
  1212. LABKEY.Message.sendMessage({
  1213. msgFrom:'labkey@fmf.uni-lj.si',
  1214. msgSubject:subj,
  1215. msgRecipients:recipients,
  1216. msgContent:[msg1],
  1217. success: cb
  1218. });
  1219. }
  1220. crfVisit.hideErr=
  1221. function(){
  1222. let el=crfHTML.getElement("errorDiv");
  1223. el.style.display="none";
  1224. }
  1225. crfVisit.clearErr=
  1226. function(){
  1227. let el=crfHTML.getElement("errorTxt");
  1228. el.value="";
  1229. }
  1230. crfVisit.showErr=
  1231. function(){
  1232. let el=crfHTML.getElement("errorDiv");
  1233. el.style.display="block";
  1234. }
  1235. crfVisit.printErr=
  1236. function(msg){
  1237. this.showErr();
  1238. el=crfHTML.getElement("errorTxt");
  1239. el.style.color="red";
  1240. el.value+="\n"+msg;
  1241. }
  1242. //**************************************************
  1243. //
  1244. crfVisit.onRemoveCRF=
  1245. function(){
  1246. let fName='[onRemoveCRF]';
  1247. let crfRef=this.crfRef;
  1248. let crfRefForData=crfData.getCrfRefForData();
  1249. this.print(fName+' starting loop');
  1250. let actionName='onRemoveCRF';
  1251. let that=this;
  1252. let notify=function(){that.changeFormStatusAndNotify(actionName);};
  1253. //let removeCrfEntry=function(){crfData.removeCrfEntry(notify);};
  1254. let removeData=function(){crfData.removeData(notify);};
  1255. let setStudyData=function(){crfData.setData(crfRefForData,removeData,'study');};
  1256. let action=setStudyData;
  1257. let actionSettings=crfSetup.getActionSettings(actionName);
  1258. if (variableList.hasVariable(actionSettings,'removeWithParentCrf')){
  1259. //if some query needs to be deleted with parent crf, insert this as an intermediate action
  1260. let q=actionSettings['removeWithParentCrf'];
  1261. let parentCrf=crfData.getCrfEntry()['parentCrf'];
  1262. if (parentCrf){
  1263. let setParentStudyData=function(){crfData.setDataForQuery(q,parentCrf,removeData,'study');};
  1264. let setStudyData1=function(){crfData.setData(crfRef,setParentStudyData);}
  1265. action=function(){crfData.setDataForQuery(q,parentCrf,setStudyData1);};
  1266. }
  1267. }
  1268. crfData.setData(crfRefForData,action);
  1269. }
  1270. crfVisit.redirect=
  1271. function(){
  1272. let formUrl="participantPortal";
  1273. let params=new Object();
  1274. params.name=formUrl;
  1275. params.role=this.role;
  1276. let crfEntry=crfData.getCrfEntry();
  1277. params.site=crfEntry['Site'];
  1278. let participantLabel=crfSetup.getParticipantLabel(crfEntry);
  1279. params['participantLabel']=participantLabel;
  1280. //params.pageId="CRF";
  1281. //points to crf container
  1282. let containerPath=crfSetup.getContainer('CRF');
  1283. // This changes the page after building the URL.
  1284. //Note that the wiki page destination name is set in params.
  1285. //let homeURL = LABKEY.ActionURL.buildURL("project", formUrl , containerPath, params);
  1286. let homeURL = LABKEY.ActionURL.buildURL("crf", formUrl , containerPath, params);
  1287. this.print("Redirecting to "+homeURL);
  1288. window.location = homeURL;
  1289. }
  1290. //master section, entry point from html files
  1291. crfVisit.generateMasterForm=
  1292. function(){
  1293. let that=this;
  1294. let action=function(){that.setFormConfig();}
  1295. this.init(action);
  1296. }
  1297. //helper function to set basic parameters on web page
  1298. //(fields defined in html file)
  1299. crfVisit.populateBasicData=
  1300. function(){
  1301. let staticData=new Object();
  1302. let titles=new Object();
  1303. staticData['version']='0.16.3'
  1304. titles['version']='Software version';
  1305. let varRows=crfSetup.getRows('crfStaticVariables');
  1306. for (let i=0;i<varRows.length;i++){
  1307. let vName=varRows[i].staticVariable;
  1308. let val=crfData.getCrfEntry()[vName];
  1309. if (val==undefined) continue;
  1310. staticData[vName]=val;
  1311. titles[vName]=varRows[i].Title;
  1312. }
  1313. staticData['investigatorName']=this.userEntry['DisplayName'];
  1314. titles['investigatorName']='Investigator';
  1315. staticData['email']=this.userEntry['Email'];
  1316. titles['email']='Email';
  1317. staticData['siteName']=this.siteEntry['siteName'];
  1318. titles['siteName']='Site';
  1319. staticData['sitePhone']=this.siteEntry['sitePhone'];
  1320. titles['sitePhone']='Telephone(site)';
  1321. for (f in staticData){
  1322. this.addStaticData(f,titles[f],staticData[f]);
  1323. }
  1324. let formId=crfData.getCrfEntry()['Form'];
  1325. let formEntry=crfSetup.getEntryMap('dataForms')[formId];
  1326. crfHTML.getElement('formTitle').innerText=formEntry['formName'];
  1327. }
  1328. crfVisit.addStaticData=
  1329. function(f,title,value){
  1330. let el=crfHTML.getElement(f);
  1331. //populate only
  1332. if (el!=undefined){
  1333. el.innerText=value;
  1334. return;
  1335. }
  1336. //add row to table if element cannot be found
  1337. let table=crfHTML.getElement('staticTable');
  1338. let row=table.insertRow();
  1339. let cell=row.insertCell();
  1340. cell.innerText=title;
  1341. let cell1=row.insertCell();
  1342. cell1.id=f;
  1343. cell1.style.fontWeight='bold';
  1344. //populate
  1345. cell1.innerText=value;
  1346. }
  1347. //come here after the layout is read from labkey page
  1348. //
  1349. crfVisit.generateErrorMsg=
  1350. function(msg){
  1351. let txt=crfHTML.createParagraph(msg,this.masterForm);
  1352. this.generateButton("submitDiv",'Exit','Exit','redirect');
  1353. }
  1354. crfVisit.checkPermissions=
  1355. function(){
  1356. //check if user has permission on the form
  1357. let userMap=crfSetup.getEntryMap('users');
  1358. let currentUser=userMap[LABKEY.Security.currentUser.id];
  1359. let currentSite=this.siteEntry;
  1360. let formCreator=userMap[crfData.getCrfEntry()['UserId']];
  1361. let formCreatorId=formCreator.UserId;
  1362. //get list of sites the user can work on
  1363. let fList=this.role+'s';
  1364. let fRows=crfSetup.getRows(fList);
  1365. let operatorSites=new Array();
  1366. for (let i=0;i<fRows.length;i++){
  1367. if (fRows[i].User!=currentUser.UserId) continue;
  1368. operatorSites.push(fRows[i].Site);
  1369. }
  1370. this.print('operator Site: '+operatorSites.length);
  1371. if (operatorSites.length==0){
  1372. let msg='User '+currentUser.DisplayName;
  1373. msg+=' is not a '+operator;
  1374. this.generateErrorMsg(msg);
  1375. return false;
  1376. }
  1377. //depending on operator mode, we should decide what is right
  1378. let operator=this.role;
  1379. if (this.role=='crfEditor'){
  1380. //editor can only edit its own forms
  1381. if (currentUser.UserId==formCreatorId){
  1382. return true;
  1383. }
  1384. //here we are if UserId and formCreatorId are not equal
  1385. let allowR=crfSetup.getSettings("allowFormReassignment");
  1386. //form reassignment is not allowed
  1387. if (!allowR){
  1388. let msg='User '+currentUser.DisplayName;
  1389. msg+=' has no permission on this form';
  1390. this.generateErrorMsg(msg);
  1391. return false;
  1392. }
  1393. //this is for allowed form reassignments
  1394. //site should still match
  1395. if (!operatorSites.includes(currentSite.siteNumber)){
  1396. let msg='User '+currentUser.DisplayName;
  1397. msg+=' has no permission for site '+currentSite.siteName;
  1398. this.generateErrorMsg(msg);
  1399. return false;
  1400. }
  1401. //re-assign form, leave a trace in crfStatus and change creator in crfEntry
  1402. let that=this;
  1403. let action=new Object();
  1404. action.name="formReassignement";
  1405. action.cb=function(){that.doNothing();}
  1406. crfData.getCrfEntry()['UserId']=currentUser.UserId;
  1407. let status=crfData.getCrfEntry()['FormStatus'];
  1408. this.updateFlag(status,action);
  1409. return true;
  1410. }
  1411. if (operator=='crfMonitor' || operator=='crfSponsor'){
  1412. //monitor can look at forms based on his site
  1413. //find monitor line
  1414. //implementation of currentSite in operatorSites
  1415. if (!operatorSites.includes(currentSite.siteNumber)){
  1416. let msg='User '+currentUser.DisplayName;
  1417. msg+=' is not a '+operator+' for site ';
  1418. msg+=currentSite.siteName+'('+currentSite.siteNumber+')';
  1419. msg+='/'+operatorSites.join(',');
  1420. this.generateErrorMsg(msg);
  1421. return false;
  1422. }
  1423. }
  1424. this.print('User '+currentUser.DisplayName+'/'+
  1425. currentSite['siteName']+
  1426. ' acting as '+this.role);
  1427. return true;
  1428. }
  1429. crfVisit.afterConfig=
  1430. function(){
  1431. let fName='[afterConfig]';
  1432. this.print(fName);
  1433. this.populateBasicData();
  1434. if (!this.checkPermissions()) return;
  1435. crfSetup.parseButtons();
  1436. let formStatus=crfSetup.getRows('formStatus')[0]['formStatus'];
  1437. //let functionArray=new Array();
  1438. this.print(fName+" generating buttons for formStatus \""+ formStatus+"\"");
  1439. let allButtonRows=crfSetup.getRows('crfButtons');
  1440. let buttonRows=new Array();
  1441. //specifying role=X in actionSettings will limit button to that role
  1442. for (let i=0;i<allButtonRows.length;i++){
  1443. let action=allButtonRows[i]['action'];
  1444. //filter on actionSettings
  1445. let as=crfSetup.getActionSettings[action];
  1446. if (variableList.hasVariable(as,'role')){
  1447. this.print('Role['+this.role+'/'+as['role']+'] limited for action '+action);
  1448. //mismatch skips addition of button to buttonRows
  1449. if (this.role!=as['role']) continue;
  1450. }
  1451. buttonRows.push(allButtonRows[i]);
  1452. }
  1453. for (let i=0;i<buttonRows.length;i++){
  1454. let bt=buttonRows[i];
  1455. //if (typeof window[bt.action]==="function"){
  1456. this.generateButton("submitDiv",bt.caption,bt.label,bt.action,null);
  1457. //}
  1458. //else{
  1459. // this.print('No match for function :'+bt.action+
  1460. // ' obj: '+window[bt.action]);
  1461. //}
  1462. }
  1463. this.print(fName+' buttons generated.');
  1464. //here we should get data. For now, just initialize objects that will hold data
  1465. let that=this;
  1466. let action=function(){that.afterDataLayout();};
  1467. let formId=crfData.getCrfEntry()['Form'];
  1468. crfData.setDataLayout(formId,this.role,action);//callback is afterDataLayout
  1469. }
  1470. crfVisit.afterDataLayout=
  1471. function(){
  1472. let that=this;
  1473. let action=function(){that.afterData();};
  1474. //let action=function(){that.doNothing();};
  1475. crfData.setData(crfData.getCrfRefForData(),action);//callback is afterData
  1476. }
  1477. crfVisit.updateRegistration=
  1478. function(cb=null,data){
  1479. //data is just inserted/updated registration row
  1480. let fName="[updateRegistration]";
  1481. this.print(fName);
  1482. let pM=this.getIdManager();
  1483. let idFieldName=pM.getCrfEntryFieldName('STUDY');
  1484. //have to reload query data
  1485. let regEntry=data.rows[0];
  1486. for (x in regEntry){
  1487. this.print(fName+" ["+x+"] "+regEntry[x]);
  1488. }
  1489. let studyId=data.rows[0][idFieldName];
  1490. if (!studyId) {
  1491. this.print(fName+" study id not set ("+idFieldName+'/'+studyId+")");
  1492. return; //study id not set
  1493. }
  1494. //set
  1495. pM.setParticipantIdToCrfEntry("STUDY",studyId);
  1496. pM.updateCrfEntry();
  1497. //this will only update crfEntry in memory, but not on LabKey,
  1498. //we are counting on updateFlag to follow updateRegistration
  1499. //update parentCRF as well, here we schedule update of data entry as well
  1500. if ("parentCrfData" in crfSetup){
  1501. let parentCrfEntry=crfSetup.getRows('parentCrfData')[0];
  1502. parentCrfEntry[idFieldName]=studyId;
  1503. let that=this;
  1504. let doNothing=function(){that.doNothing();};
  1505. let action={name:"updateRegistration",cb:doNothing};
  1506. let complete=function(data){that.completeWithFlag(data,action);};
  1507. runQuery.modifyRows('update','lists','crfEntry',[parentCrfEntry],complete,crfSetup.getContainer('CRF'));
  1508. }
  1509. if (cb) cb(data);
  1510. }
  1511. crfVisit.afterData=
  1512. function(){
  1513. let fName='afterData';
  1514. this.configureIdManager();
  1515. this.generateSections();
  1516. }
  1517. crfVisit.configureIdManager=
  1518. function(){
  1519. let fName='[configureIdManager]';
  1520. let idMode=this.formEntry['idMode'];
  1521. //set default value if no value is in the list (read value is null)
  1522. if (!idMode) idMode="STUDY:EDIT";
  1523. this.print(fName+': idMode '+idMode);
  1524. //add print to config so participantManager can use it
  1525. let pM=this.getIdManager();
  1526. //extend object
  1527. let that=this;
  1528. let action=new Object();
  1529. action.name='updateCrfEntry';
  1530. action.cb=function(){that.doNothing();};
  1531. let formStatus=crfData.getCrfEntry()['FormStatus'];
  1532. participantIdManager.updateCrfEntry=function(){that.updateFlag(formStatus,action);};
  1533. let idModeArray=idMode.split(':');
  1534. pM.setMode("STUDY");
  1535. if (idModeArray.includes("LOCAL")) {
  1536. pM.setMode("LOCAL");
  1537. }
  1538. //OK, but check if CRF or registration indicate that study id is already set
  1539. pM.verifyCrfStudyId();
  1540. //still local
  1541. if (pM.getMode()=='LOCAL'){
  1542. if (idModeArray.includes("READONLY")){
  1543. pM.setReadonly(pM.getMode());
  1544. let id=pM.getParticipantIdFromCrfEntry(pM.getMode());
  1545. pM.setLabelMode(pM.getMode(),id);
  1546. }
  1547. let localId=pM.getParticipantIdFromCrfEntry('LOCAL');
  1548. if (localId) pM.setLabelMode('LOCAL',localId);
  1549. else pM.setEditMode(pM.getMode());
  1550. pM.setReadonly('STUDY');
  1551. pM.setLabelMode('STUDY','NOT SET');
  1552. }
  1553. }
  1554. crfVisit.generateSections=
  1555. function(){
  1556. let accessMode=this.role+'Mode';
  1557. let formId=crfData.getCrfEntry()['Form'];
  1558. let rowsSetup=crfSetup.selectFormSetupRows(formId);
  1559. for (let i=0;i<rowsSetup.length;i++){
  1560. let entry=rowsSetup[i];
  1561. //debug
  1562. let queryName=crfSetup.getMap('inputLists')[entry['queryName']];
  1563. this.print(fName+" ["+queryName+"]: showFlag: "+entry["showFlag"]);
  1564. this.print(fName+" ["+queryName+"]: accessMode: "+entry[accessMode]);
  1565. const nData=crfData.getQuerySnapshot(queryName).rows.length;
  1566. this.print(fName+" ["+queryName+"]: nData: "+nData);
  1567. //skip sections
  1568. //also from fields
  1569. if (entry[accessMode]=="NONE") continue;
  1570. //section fits one dataset/list
  1571. this.generateSection(entry);
  1572. }
  1573. }
  1574. crfVisit.populateSection=
  1575. function(sectionId){
  1576. let fName='[populateSection/'+sectionId+']';
  1577. this.print(fName);
  1578. //old setting
  1579. let entry=crfSetup.findSetupRow(sectionId);
  1580. //ignore names without associated entry in formSetup
  1581. if (!entry){
  1582. this.print(fName+': no matching FormSetup entry found');
  1583. return;
  1584. }
  1585. //populate comes after generate, we should be pretty safe in taking
  1586. //already generated additionalData
  1587. let queryName=crfSetup.getMap('inputLists')[entry['queryName']];
  1588. if (!(queryName in crfSetup.getAdditionalDataObject())){
  1589. this.print(fName+': no additionalData generated for '+queryName);
  1590. return;
  1591. }
  1592. let additionalData=crfSetup.getAdditionalData(queryName);
  1593. this.print(fName+': using additionalData '+additionalData);
  1594. if ("isReview" in additionalData){
  1595. let action=function(){crfReviewSection.CB();};
  1596. crfReviewSection.generateSection(queryName,queryName,action);
  1597. return;
  1598. }
  1599. let accessMode=this.role+'Mode';
  1600. let aM=entry[accessMode];
  1601. this.print(fName+': accessMode '+aM);
  1602. if (aM!='GENERATE'){
  1603. let writeMode=entry[accessMode]=='EDIT';
  1604. this.print(fName+': mode='+writeMode);
  1605. let setup=this.getStoredSetup(sectionId);
  1606. this.populateTable(queryName,writeMode,setup);
  1607. return;
  1608. }
  1609. //deal with generate
  1610. //
  1611. //already available -> shift to READ mode
  1612. let divTable=sectionId+'Table';
  1613. let divObj=crfHTML.getElement(divTable);
  1614. let divRev=crfHTML.getElement(sectionId+'Review');
  1615. let divRLi=crfHTML.getElement(sectionId+'ReviewList');
  1616. let divGBu=crfHTML.getElement(sectionId+'GenerateButton');
  1617. this.print('div GBU: '+divGBu);
  1618. divObj.style.display="block";
  1619. divRev.style.display="block";
  1620. divRLi.style.display="block";
  1621. if (divGBu!=undefined) divGBu.style.display="none";
  1622. let nData=crfData.getQuerySnapshot(queryName).rows.length;
  1623. let setup=this.getSetup(sectionId,queryName,0);
  1624. this.print('['+queryName+']: nrows '+nData);
  1625. if (nData>0){
  1626. this.populateTable(queryName,0,setup);
  1627. return;
  1628. }
  1629. //hide table
  1630. divObj.style.display="none";
  1631. divRev.style.display="none";
  1632. divRLi.style.display="none";
  1633. if (divGBu!=undefined) divGBu.style.display="block";
  1634. //add buttons?
  1635. //is button already generated?
  1636. //populateTable(entry);
  1637. }
  1638. //******* generateQuery infrastructure *********************
  1639. crfVisit.onGenerateQuery=
  1640. function(queryName){
  1641. let fName='[onGenerateQuery]';
  1642. this.print(fName+' '+queryName);
  1643. //
  1644. let cfgRows=crfSetup.getRows('generateConfigData');
  1645. // //queryName to queryId?
  1646. let qMapInverse=crfSetup.invertMap(crfSetup.getMap('inputLists'));
  1647. let queryId=qMapInverse[queryName];
  1648. let cfgRow=crfSetup.getEntryMap('generateConfigData:queryId')[queryId];
  1649. if (!cfgRow){
  1650. this.print('generateConfig for queryName['+queryId+']='+queryName+' not found');
  1651. return;
  1652. }
  1653. //let formRows=crfSetup.selectFormSetupRows(cfgRow.formId);
  1654. //
  1655. // //check if all required datasets were at least saved
  1656. this.checkGenerationFields(cfgRow);
  1657. }
  1658. crfVisit.checkGenerationFields=
  1659. function(entry){
  1660. //entry is generateConfig row
  1661. let fName='[checkGenerationFields]';
  1662. let mailRecipient=entry.emailRecipient;
  1663. let qMap=crfSetup.getMap('inputLists');
  1664. let qName=qMap[entry['queryId']];
  1665. //list of queries that are part of Registration form
  1666. this.print(fName);
  1667. this.print(fName+' setRecipient: '+mailRecipient);
  1668. let formId=entry['formId'];
  1669. this.print(fName+" Checking form w/id "+formId);
  1670. let formRows=crfSetup.selectFormSetupRows(formId);
  1671. //registration rows
  1672. for (let i=0;i<formRows.length;i++){
  1673. let row=formRows[i];
  1674. let queryId=row.queryName;
  1675. if (queryId==entry.queryId) continue;
  1676. let fQuery=crfData.getQuerySnapshot(qMap[queryId]);
  1677. this.print('Checking '+qMap[queryId]+' nrows: '+fQuery.rows.length);
  1678. //this is to check whether sufficient data was provided for monitor
  1679. //to make an informed decision whether registration is in order
  1680. if (fQuery.rows.length==0){
  1681. this.generateError(qName,qMap[queryId]);
  1682. return;
  1683. }
  1684. }
  1685. this.generateMessage(qName,'Vailidation OK');
  1686. let that=this;
  1687. let cb=function(){that.prepareForm(entry);};
  1688. this.generateListEntry(entry.formId,qName,cb);
  1689. }
  1690. crfVisit.prepareForm=
  1691. function(entry){
  1692. //entry is generateConfig row
  1693. let fName="[prepareForm]";
  1694. let formId=entry['formId'];
  1695. //this.print(fName+' recipient '+mailRecipient);
  1696. //look for existing registration entry
  1697. let that=this;
  1698. let action=function(data){that.generateForm(data,entry);};
  1699. let formFilter=LABKEY.Filter.create('Form',formId);
  1700. let parentCrfFilter=LABKEY.Filter.create('parentCrf',this.crfRef);
  1701. let filters=[formFilter,parentCrfFilter];
  1702. runQuery.selectRows('lists','crfEntry',filters,action,crfSetup.getContainer('data'));
  1703. }
  1704. crfVisit.generateError=
  1705. function(queryName,fQueryName){
  1706. let elName=queryName+'GenerateButton'+'_reportField';
  1707. let el=crfHTML.getElement(elName);
  1708. el.innerText='Error: '+fQueryName+' was not set';
  1709. el.style.color='red';
  1710. }
  1711. crfVisit.generateMessage=
  1712. function(queryName,msg){
  1713. let elName=queryName+'GenerateButton'+'_reportField';
  1714. let el=crfHTML.getElement(elName);
  1715. el.innerText=msg;
  1716. el.style.color='green';
  1717. }
  1718. crfVisit.generateForm=
  1719. function(data,entry){
  1720. //entry is generateConfig entry
  1721. //data is a crfEntry row
  1722. let fName='[generateForm]';
  1723. const nData=data.rows.length;
  1724. let formId=entry['formId'];
  1725. let formEntry=crfSetup.getEntryMap('dataForms')[formId];
  1726. let formName=formEntry['formName'];
  1727. this.print(fName+' crfEntry ('+formName+'): '+nData+' rows');
  1728. //we have to generate masterQuery with parentCrf and crfRef
  1729. //and crfEntry with new entryId and parentCrf equal to crfRef
  1730. let queryName=crfSetup.getMap('inputLists')[entry['queryId']];
  1731. if (nData>0) {
  1732. this.generateMessage(queryName,formName+' already generated.');
  1733. return;
  1734. }
  1735. //use current crfEntry as base
  1736. let crfBase=crfData.getCrfEntry();
  1737. let idLabel=crfSetup.getParticipantLabel(crfBase);
  1738. //role will appear in crfStatus and will be validated agains crfCreator entry of the form
  1739. let roleAndSite='generate:'+crfBase.Site;
  1740. //have to overload crfEntry
  1741. // - parentCrf
  1742. // - formStatus
  1743. // - UserId (set to sponsor UserId)
  1744. //
  1745. // should provide mail recipient and/or modified cb
  1746. //
  1747. //
  1748. let crfEntryOverload=new Object();
  1749. //parentCrf
  1750. crfEntryOverload.parentCrf=crfBase.entryId;
  1751. //formStatus
  1752. crfEntryOverload.formStatus=1;//In progress
  1753. //checks for both field presence (if not in query, undefined) and field value (if not set, null)
  1754. this.print(fName+' setup status: '+entry.formStatus);
  1755. if (entry.formStatus){
  1756. crfEntryOverload.formStatus=entry.formStatus;
  1757. }
  1758. // UserId
  1759. //find sponsor for site
  1760. let site=crfBase.Site;
  1761. let crfSponsors=crfSetup.getRows('crfSponsors');
  1762. let userMap=crfSetup.getEntryMap('users');
  1763. let sponsorId=null;
  1764. for (let i=0;i<crfSponsors.length;i++){
  1765. //take first matching sponsor
  1766. if (crfSponsors[i].Site!=site) continue;
  1767. sponsorId=crfSponsors[i].User;
  1768. //finds first
  1769. break;
  1770. }
  1771. let sponsor=userMap[sponsorId];
  1772. this.print('Selecting '+sponsor.DisplayName+' as sponsor');
  1773. //different user than the original form...
  1774. //should be set to the study sponsor
  1775. crfEntryOverload.UserId=sponsor.UserId;
  1776. let mailRecipient=entry.mailRecipient;
  1777. let that=this;
  1778. let action=function(){that.doNothing();};
  1779. let cb=function(data,_crfEntry){that.sendEmail(data,mailRecipient,action,formName+' generated');}
  1780. formPortal.createForm(formId,roleAndSite,cb,idLabel,crfEntryOverload);
  1781. }
  1782. crfVisit.generateListEntry=
  1783. function(formId,queryName,cb){
  1784. //check if registration was already generated
  1785. let formRows=crfSetup.selectFormSetupRows(formId);
  1786. let nData=crfData.getQuerySnapshot(queryName).rows.length;
  1787. if (nData>0) return;
  1788. //create new list entry
  1789. let pM=this.getIdManager();
  1790. let e2=new Object();
  1791. e2.crfRef=this.getCrfRef();
  1792. e2.registrationStatus=0;
  1793. e2.submissionDate=new Date();
  1794. let idLabel=crfSetup.getParticipantLabel(crfData.getCrfEntry());
  1795. e2[crfSetup.getLocalIdLabel()]=crfSetup.getLocalId(idLabel);
  1796. e2[crfSetup.getStudyIdLabel()]=crfSetup.getStudyId(idLabel);
  1797. this.print('set values');
  1798. e2.site=crfData.getCrfEntry()['Site'];
  1799. runQuery.insertRows('lists',queryName,[e2],cb,crfSetup.getContainer('data'));
  1800. }
  1801. // ******************** end form generator (Registration) ********************
  1802. //jump to populate table/generate review, etc defined at the begining of the file
  1803. //entry point from generateMasterForm
  1804. crfVisit.setFormConfig=
  1805. function(){
  1806. let fName="[setFormConfig]";
  1807. let crfRef=this.crfRef;
  1808. let that=this;
  1809. let afterCrfEntry=function(){that.afterCrfEntry();};
  1810. let action=function(){crfData.setCrfEntry(crfRef,afterCrfEntry);};//afterCrfEntry
  1811. crfSetup.setContainers(action);
  1812. }
  1813. crfVisit.afterCrfEntry=
  1814. function(){
  1815. let fName='[afterCRFEntry]';
  1816. this.print(fName+" setting crfEntry (x) to "+crfData.getCrfEntry()["entryId"]);
  1817. //for empty records or those with parentCrf not set, parentCrf comes up as null
  1818. //nevertheless, with two equal signs, check against undefined also works
  1819. crfSetup.formStatus=crfData.getCrfEntry()['FormStatus'];
  1820. let parentCrf=crfData.getCrfEntry()['parentCrf'];
  1821. this.print(fName+' parentCrf set to '+parentCrf);
  1822. if (parentCrf) crfSetup.parentCrf=parentCrf;
  1823. let that=this;
  1824. let action=function(){that.parseSetup();};
  1825. crfSetup.parseSetup(action);
  1826. }
  1827. crfVisit.parseSetup=
  1828. function(){
  1829. //debug
  1830. let fName='[parseSetup]';
  1831. let varRows=crfSetup.getRows('crfStaticVariables');
  1832. let studyVars=crfSetup.getRows('studyData')[0];
  1833. for (let i=0;i<varRows.length;i++){
  1834. let vName=varRows[i].staticVariable;
  1835. this.print(fName+' '+vName+': '+studyVars[vName]);
  1836. }
  1837. //parse site
  1838. this.siteEntry=crfSetup.getEntryMap('siteData')[crfData.getCrfEntry()['Site']];
  1839. this.print("Setting site name to "+this.siteEntry['siteName']);
  1840. //study
  1841. this.print("XSetting participantField to "+studyVars["SubjectColumnName"]);
  1842. //parse user
  1843. this.userEntry=crfSetup.getEntryMap('users')[crfData.getCrfEntry()['UserId']];
  1844. this.print("Setting user to "+this.userEntry["DisplayName"]);
  1845. this.print('Setting operator to: '+this.role);
  1846. //point formId to point to form set in crfEntry
  1847. let formId=crfData.getCrfEntry()['Form'];
  1848. this.formEntry=crfSetup.getEntryMap('dataForms')[formId];
  1849. let accessModeColumn=this.role+'Status';
  1850. let targetStatus=this.formEntry[accessModeColumn];
  1851. let formStatus=crfData.getCrfEntry()['FormStatus'];
  1852. this.print(fName+' comparing status '+formStatus+'/'+targetStatus);
  1853. if (targetStatus!=formStatus){
  1854. let statusMap=crfSetup.getEntryMap('formStatusAll');
  1855. let targetEntry=statusMap[targetStatus];
  1856. let actualEntry=statusMap[formStatus];
  1857. alert('Form status ['+actualEntry.formStatus+'] not suitable to be operated by '+this.role+' targeting status ['+targetEntry.formStatus+']');
  1858. this.redirect();
  1859. }
  1860. crfSetup.setAdditionalData(this.crfRef,formId);
  1861. this.afterConfig();
  1862. }
  1863. crfVisit.uploadFile=
  1864. function(inputElement,context){
  1865. //context should have ID and dirName attributes;
  1866. //path will be dirName/ID/fieldName_ID.suf
  1867. //where suf is identical to localPath content picked from
  1868. //inputElement
  1869. this.print('uploadFile: '+inputElement.value+'/');
  1870. if (inputElement.type=="text") return;
  1871. this.print('uploadFile: '+inputElement.files+'/');
  1872. this.print('uploadFile: '+inputElement.files.length+'/');
  1873. if (inputElement.files.length>0){
  1874. let file=inputElement.files[0];
  1875. this.print('uploadFile: '+inputElement.value+'/'+file.size);
  1876. webdav.uploadFile(file,context);
  1877. }
  1878. }
  1879. crfVisit.printForm=
  1880. function(){
  1881. crfPrint.printForm();
  1882. }