crfVisit.js 90 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263
  1. const config=new Object();
  2. function clear(){
  3. let el=config.document.getElementById(config.debugId);
  4. if (el===null) {
  5. //alert("Debug section not initialized");
  6. return;
  7. }
  8. config.document.getElementById(config.debugId).value="";
  9. }
  10. function print(msg){
  11. let el=config.document.getElementById(config.debugId);
  12. if (el===null) {
  13. //alert("Debug section not initialized. Message: "+msg);
  14. return;
  15. }
  16. el.value+="\n"+msg;
  17. }
  18. //harmonize signature
  19. //(schema,query,row,action=cvDoNothing,container=null
  20. function cvInsertRows(schema,query,rows,action=null,container=null,failure=null){
  21. cvModifyRows('insert',schema,query,rows,action,container);
  22. }
  23. function cvDeleteRows(schema,query,rows,action=null,container=null,failure=null){
  24. cvModifyRows('delete',schema,query,rows,action,container);
  25. }
  26. function cvModifyRows(mode,schema,query,rows,action=null,container=null,failure=null){
  27. //insert rows to container/schema/query and return with action
  28. let fName="[cvModifyRows/"+mode+"]";
  29. print(fName+' '+schema+'/'+query);
  30. let qconfig=new Object();
  31. qconfig.schemaName=schema;
  32. qconfig.queryName=query;
  33. if (container) qconfig.containerPath=container;
  34. if (!rows) {
  35. print(fName+' rows '+rows);
  36. return;
  37. }
  38. qconfig.rows=rows;
  39. qconfig.success=function(data){;};
  40. if (action) qconfig.success=action;
  41. if (mode=='insert') LABKEY.Query.insertRows(qconfig);
  42. if (mode=='update') LABKEY.Query.updateRows(qconfig);
  43. if (mode=='delete') LABKEY.Query.deleteRows(qconfig);
  44. print(fName+" done");
  45. }
  46. function cvSelectRows(schema,query,filters=[],action=null, container=null, failure=null, columns=null){
  47. let fName="[cvSelectRows]";
  48. print(fName+' '+schema+' '+query+' '+container);
  49. let qconfig=new Object();
  50. qconfig.schemaName=schema;
  51. qconfig.queryName=query;
  52. if (container) qconfig.containerPath=container;
  53. qconfig.filterArray=filters;
  54. qconfig.success=function(data){;};
  55. if (action) qconfig.success=action;
  56. if (failure) qconfig.failure=failure;
  57. if (columns) qconfig.columns=columns;
  58. LABKEY.Query.selectRows(qconfig);
  59. print(fName+" done");
  60. }
  61. function createCrfStatus(crfEntry){
  62. let crfStatus=new Object();
  63. crfStatus.entryId=crfEntry.entryId;
  64. crfStatus.submissionDate=new Date();
  65. crfStatus.FormStatus=crfEntry.FormStatus;
  66. crfStatus.User=crfEntry.UserId;
  67. crfStatus.Form=crfEntry.Form;
  68. return crfStatus;
  69. }
  70. function getCRFrefFirst(){
  71. //crfRef is part of html call and gets stored in the page
  72. return config.document.getElementById(config.crfRefId).innerHTML;
  73. }
  74. function getCRFref(){
  75. //'crfRefId'
  76. return config.formConfig.crfEntry['entryId'];
  77. }
  78. function getCRFrefData(){
  79. let parentCrf=config.formConfig.crfEntry['parentCrf'];
  80. if (parentCrf!=undefined) return parentCrf;
  81. return getCRFref();
  82. }
  83. function onFailure(errorInfo, options, responseObj){
  84. if (errorInfo && errorInfo.exception)
  85. alert("Failure: " + errorInfo.exception);
  86. else
  87. alert("Failure: " + responseObj.statusText);
  88. }
  89. function doNothing(){
  90. print('doNothing called');
  91. }
  92. function createQueryObject(){
  93. //create object ready for makeQuery
  94. let x=new Object();
  95. x.print=print;
  96. x.getContainer=getContainer;
  97. return x;
  98. }
  99. function getSnapshotObject(){
  100. if (!("dataQueriesSnapshot" in config.formConfig))
  101. config.formConfig.dataQueriesSnapshot=createQueryObject();
  102. return config.formConfig.dataQueriesSnapshot;
  103. }
  104. function getQuerySnapshot(queryName){
  105. //check whether queryName is in snapshotObject?
  106. return getSnapshotObject()[queryName];
  107. }
  108. function getLayoutObject(){
  109. if (!("dataQueriesLayout" in config.formConfig))
  110. config.formConfig.dataQueriesLayout=createQueryObject();
  111. return config.formConfig.dataQueriesLayout;
  112. }
  113. function getQueryLayout(queryName){
  114. //check whether queryName is in snapshotObject?
  115. return getLayoutObject()[queryName];
  116. }
  117. function getLookupObject(){
  118. if (!("lookup" in config.formConfig))
  119. config.formConfig.lookup=createQueryObject();
  120. return config.formConfig.lookup;
  121. }
  122. function getLookup(queryName){
  123. let x=getLookupObject();
  124. if (queryName in x) return x[queryName];
  125. return null;
  126. }
  127. function getQueryList(){
  128. if (!("queryList" in config.formConfig))
  129. config.formConfig.queryList=new Object();
  130. return config.formConfig.queryList;
  131. }
  132. function generateDebugSection(){
  133. //let debug=true;
  134. //if (debug) print("generateDebugSection "+sectionName);
  135. let formName=config.debugDiv;
  136. let sectionName="debugSection";
  137. let sectionTitle="Debug Messages";
  138. let tb=config.document.createElement('table');
  139. tb.className='t2';
  140. let row=tb.insertRow();
  141. let cell=config.document.createElement('th');
  142. row.appendChild(cell);
  143. cell.setAttribute("colspan","4");
  144. cell.style.fontSize="20px";
  145. cell.style.textAlign="center";
  146. let cellData=config.document.createTextNode(sectionTitle);
  147. cell.appendChild(cellData);
  148. cell=row.insertCell();
  149. let input=config.document.createElement("input");
  150. input.type="button";
  151. input.id="toggle"+sectionName+"VisbilityButton";
  152. input.onclick=function(){toggleVisibility(sectionName,input.id)};
  153. cell.appendChild(input);
  154. config.document.getElementById(formName).appendChild(tb);
  155. let div=config.document.createElement('div');
  156. div.id=sectionName;
  157. config.document.getElementById(formName).appendChild(div);
  158. //start open (for debug)
  159. //input.value="Hide";
  160. //div.style.display="block";
  161. //start hidden (for production)
  162. input.value="Show";
  163. div.style.display="none";
  164. let debugArea=config.document.createElement('textarea');
  165. debugArea.rows=10;
  166. debugArea.cols=95;
  167. debugArea.id=config.debugId;
  168. div.appendChild(debugArea);
  169. //print('ver: 0.10');
  170. }
  171. function getAdditionalData(formSetupEntry){
  172. //return information on additional data associated with the form
  173. //additionalData is a sub-list with multiple entries per patient/visit
  174. //argument is the row of the formSetup setup list
  175. let queryName=config.formConfig.queryMap[formSetupEntry['queryName']];
  176. let fName='[getAdditionalData/'+queryName+']';
  177. print(fName);
  178. //additionalData holds a reference to all queries already parsed
  179. //this helps in reducing number of calls to the database (I assume)
  180. if (queryName in config.formConfig.additionalData){
  181. print(fName+': Returning preset value');
  182. return config.formConfig.additionalData[queryName];
  183. }
  184. //first time we see this query, so we have to do the setup
  185. print(fName+': generating');
  186. config.formConfig.additionalData[queryName]=new Object();
  187. //takes address, so further changes will be to the newly created object
  188. //in fact, ad is just a short alias of the long variable name on the right
  189. let ad=config.formConfig.additionalData[queryName];
  190. //no additional data
  191. if (formSetupEntry["showFlag"]==="NONE") {
  192. print(fName+": empty");
  193. return ad;
  194. }
  195. //use showFlag to setup report section of the CRF list
  196. if (formSetupEntry["showFlag"]==="REVIEW") {
  197. //abuse additionalData to signal different segment
  198. print(fName+": generateReport");
  199. ad.isReview=true;
  200. return ad;
  201. }
  202. //setup the additionalData memory object
  203. print(fName+': setting values');
  204. ad.showFlag=formSetupEntry["showFlag"];
  205. ad.showFlagValue=formSetupEntry["showFlagValue"];
  206. ad.queryName=formSetupEntry["showQuery"];
  207. //for data queries, limit to present CRF only
  208. ad.filters=new Object();
  209. ad.filters['crfRef']=getCRFref();
  210. //compose a long debug message
  211. let msg=fName+": flag "+ad.showFlag;
  212. msg+=" value "+ad.showFlagValue;
  213. msg+=" query "+ad.queryName;
  214. print(msg);
  215. return ad;
  216. }
  217. function fullAccessSetup(listName){
  218. //generate setup object whcih should contain fields:
  219. //readonlyFlag - whether the dataset is writeable
  220. //filters - selection fields that allow creation of LABKEY.Filter.create()
  221. //getInputId - formating of unique ids for html elements
  222. //addApply - whether a submit/Save button is generated
  223. //unique - whether entries in list are unique
  224. let debug=true;
  225. if (debug) print("fullAccessSetup");
  226. let setup=new Object();
  227. setup.queryName=listName;
  228. setup.readonlyFlag=function(vName){return false};
  229. setup.filters=new Object();
  230. setup.filters['crfRef']=getCRFref();
  231. setup.getInputId=function(vName){return listName+"_"+vName;}
  232. setup.addApply="Save";
  233. setup.isReview=false;
  234. return setup;
  235. }
  236. function readonlySetup(listName){
  237. //see definition of setup object above
  238. let debug=true;
  239. if (debug) print("readonlySetup");
  240. let setup=new Object();
  241. setup.queryName=listName;
  242. setup.readonlyFlag=function(vName){return true};
  243. setup.filters=new Object();
  244. setup.filters['crfRef']=getCRFref();
  245. setup.getInputId=function(vName){return listName+'_'+vName;}
  246. setup.isReview=false;
  247. return setup;
  248. }
  249. function getSetup(listName,writeAccess=true){
  250. //change to section granulated permission of type EDIT, COMMENT, READ
  251. //let formStatus=config.formConfig.formStatus;
  252. //equivalent to READ
  253. if (!writeAccess)
  254. //if (formStatus=="Submitted")
  255. return readonlySetup(listName);
  256. //if (formStatus=="Approved")
  257. // return readonlySetup(listName);
  258. return fullAccessSetup(listName);
  259. }
  260. function generateSection(formSetupEntry){
  261. let listName=config.formConfig.queryMap[formSetupEntry['queryName']];
  262. let fName='[generateSection/'+listName+']';
  263. let sectionTitle=formSetupEntry['title'];
  264. let accessModeColumn=config.formConfig.operator+'Mode';
  265. let accessMode=formSetupEntry[accessModeColumn];
  266. //this will fix it for later use as well
  267. let additionalData=getAdditionalData(formSetupEntry);
  268. print(fName);
  269. let formName=config.masterForm;//this is HTML designator of area on page
  270. let debug=true;
  271. let tb=config.document.createElement('table');
  272. tb.className='t2';
  273. let row=tb.insertRow();
  274. let cell=config.document.createElement('th');
  275. row.appendChild(cell);
  276. cell.setAttribute("colspan","4");
  277. cell.style.fontSize="20px";
  278. cell.style.textAlign="center";
  279. let cellData=config.document.createTextNode(sectionTitle);
  280. cell.appendChild(cellData);
  281. cell=row.insertCell();
  282. let input=config.document.createElement("input");
  283. input.type="button";
  284. input.value="Show";
  285. input.id="toggle"+listName+"VisbilityButton";
  286. input.onclick=function(){toggleVisibility(listName,input.id)};
  287. cell.appendChild(input);
  288. config.document.getElementById(formName).appendChild(tb);
  289. let div=config.document.createElement('div');
  290. div.id=listName;
  291. div.style.display="none";
  292. config.document.getElementById(formName).appendChild(div);
  293. let divTable=config.document.createElement('div');
  294. divTable.id=listName+"Table";
  295. div.appendChild(divTable);
  296. if ("showFlag" in additionalData) {
  297. additionalData.divName=listName+"SubDiv";
  298. additionalData.divQueryName=listName+"SubDivList";
  299. let div1=config.document.createElement('div');
  300. div1.id=additionalData.divName;
  301. div1.style.display="none";
  302. div.appendChild(div1);
  303. let div2=config.document.createElement('div');
  304. div2.id=additionalData.divQueryName;
  305. div1.appendChild(div2);
  306. }
  307. if (debug) print("generate master table");
  308. let writeMode=accessMode=="EDIT";
  309. let setup=getSetup(listName,writeMode);
  310. if ("isReview" in additionalData){
  311. generateReviewSection(listName,div.id,generateReviewSectionCB);
  312. return;
  313. }
  314. //master table is unique per visit
  315. setup.unique=true;
  316. generateTable(listName,divTable.id,additionalData,setup);
  317. if (debug) print("generate master table: done");
  318. let generateSubTable=true;
  319. //generateSubTable equivalent to read/write access to section
  320. if (accessMode != "EDIT")
  321. generateSubTable=false;
  322. if (! ("showFlag" in additionalData) ) generateSubTable=false;
  323. if (generateSubTable){
  324. let qName=additionalData.queryName;
  325. let dName=additionalData.divName;
  326. let xsetup=fullAccessSetup(qName);
  327. //only set master query for additionalData
  328. xsetup.masterQuery=listName;
  329. //if (readonly) setup=readonlySetup(config);
  330. xsetup.subTable=true;
  331. generateTable(qName,dName,additionalData,xsetup);
  332. //generateTable(formSetupEntry,qName,dName,additionalData,setup);
  333. }
  334. print("generate review");
  335. let divReviewList=config.document.createElement('div');
  336. divReviewList.id=listName+"ReviewList";
  337. div.appendChild(divReviewList);
  338. let divReview=config.document.createElement('div');
  339. divReview.id=listName+"Review";
  340. div.appendChild(divReview);
  341. //assume we already have listId (content of config.setupQueryName is listId)
  342. //we need listName also
  343. //qconfig.queryName=config.setupQueryName;
  344. generateReview(divReview.id,divReviewList.id,listName,accessMode);
  345. if (accessMode!='GENERATE') return;
  346. print('Adding generate button');
  347. //add generateButton
  348. let divGenerateButton=config.document.createElement('div');
  349. divGenerateButton.id=listName+'GenerateButton';
  350. div.appendChild(divGenerateButton);
  351. print('Adding generate button completed to here');
  352. let cb=function(){onGenerateQuery(listName);};
  353. generateButton(divGenerateButton.id,'Generate','Generate '+listName,'XX',cb);
  354. print('Adding generate button completed');
  355. }
  356. //>>>>reviewSection associated routines
  357. function parseResponseXML(){
  358. //print(config.config,'Status:' +this.status);
  359. print('Status:'+this.status);
  360. if (this.status!=200) return;
  361. config.loadFileConfig.json=JSON.parse(this.responseText);
  362. config.loadFileConfig.cb();
  363. }
  364. function loadFile(){
  365. print('YY: '+config.loadFileConfig.url);
  366. let connRequest=new XMLHttpRequest();
  367. connRequest.addEventListener("loadend",parseResponseXML);
  368. //function(e){parseResponseXML(e,config);});
  369. connRequest.open("GET", config.loadFileConfig.url);
  370. connRequest.send();
  371. }
  372. function getBasePath(){
  373. let server=LABKEY.ActionURL.getBaseURL();
  374. let basePath=server+"_webdav";
  375. basePath+=LABKEY.ActionURL.getContainer();
  376. return basePath;
  377. }
  378. function generateErrorMessage(id,listName,msg){
  379. print('generateErrorMessage:');
  380. let eid=listName+"_errorMsg";
  381. let el=config.document.getElementById(eid);
  382. if (el===null){
  383. el=config.document.createElement("p");
  384. config.document.getElementById(id).appendChild(el);
  385. }
  386. el.innerHTML=msg;
  387. }
  388. function clearErrorMessage(listName){
  389. let eid=listName+"_errorMsg";
  390. let el=config.document.getElementById(eid);
  391. if (el===null) return;
  392. el.remove();
  393. }
  394. function generateReview(divReviewId,divReviewListId, listName, accessMode){
  395. let listId=config.formConfig.fields[listName].queryId;
  396. //listId is a number->should it be queryName?
  397. let debug=true;
  398. if (debug) print("Generate review for: "+listId+'/'+listName);
  399. let reviewSetup=new Object();
  400. reviewSetup.readonlyFlag=function(vName){
  401. if (vName=="queryName") return true;
  402. if (vName=="queryname") return true;
  403. if (vName=="ModifiedBy") return true;
  404. return false;};
  405. reviewSetup.addApply="Add Review";
  406. reviewSetup.reviewTable=true;
  407. let generateTableFlag=true;
  408. let formStatus=config.formConfig.formStatus;
  409. //COMMENTS allowed or not
  410. //three levels of access: EDIT, COMMENT, READ
  411. if (accessMode == "READ"){
  412. //if (formStatus == "Approved" ){
  413. delete reviewSetup.addApply;
  414. reviewSetup.readonlyFlag=function(vName){return false;}
  415. generateTableFlag=false;
  416. }
  417. reviewSetup.filters=new Object();
  418. reviewSetup.filters["crfRef"]=getCRFref();
  419. if (config.formConfig.crfEntry.parentCrf){
  420. reviewSetup.filters["crfRef"]=getCRFref()+";"+config.formConfig.crfEntry.parentCrf;
  421. }
  422. reviewSetup.filters["queryName"]=listId;//entry in reviewComments list is queryname, all in small caps
  423. //needs listName, in argument
  424. reviewSetup.getInputId=function(vName){return listName+"_add"+vName};
  425. reviewSetup.divReviewListId=divReviewListId;
  426. reviewSetup.isReview=true;
  427. if (debug) {
  428. let msg="Review: divId: "+divReviewId;
  429. msg+=" inputId: "+reviewSetup.getInputId;
  430. print(msg);
  431. }
  432. updateListDisplay(divReviewListId,"reviewComments",reviewSetup.filters,true);
  433. if (! generateTableFlag) return;
  434. generateTable("reviewComments",divReviewId,new Object(),reviewSetup);
  435. }
  436. //>>>>>>>>>>trigger visibility of additional lists
  437. function setListVisibility(input,setup,readonlyFlag){
  438. let debug=true;
  439. let fName="[setListVisibility/"+setup.queryName+"]";
  440. print(fName);
  441. let additionalData=config.formConfig.additionalData[setup.queryName];
  442. let x = config.document.getElementById(additionalData.divName);
  443. if (debug) print(fName+": Div: "+x);
  444. x.style.display="none";
  445. let sText;
  446. if (readonlyFlag) sText=input.innerText;
  447. else sText=input.options[input.selectedIndex].text;
  448. if (debug) print(fName+": Selected option text: "+sText);
  449. if (sText == additionalData.showFlagValue){
  450. let filters=new Object();
  451. if ("filters" in additionalData) filters=additionalData.filters;
  452. x.style.display = "block";
  453. updateListDisplay(additionalData.divQueryName,
  454. additionalData.queryName,filters,readonlyFlag);
  455. }
  456. }
  457. //>>have list refresh when data is added (not optimal yet)
  458. //
  459. function isFilterList(v){
  460. if (typeof(v)!='string') return false;
  461. if (v.search(';')==-1) return false;
  462. return true;
  463. }
  464. function updateListDisplay(divName,queryName,filters,readonlyFlag){
  465. //use Labkey.QueryWebPart to show list
  466. let debug=true;
  467. let fName="[updateListDisplay]";
  468. if (debug)
  469. print(fName+": UpdateListDisplay: Query - "+queryName
  470. +" div - "+divName);
  471. if (divName=="NONE") return;
  472. let crfRef=getCRFref();
  473. let div=config.document.getElementById(divName);
  474. if (debug)
  475. print(fName+": generating WebPart: "+queryName);
  476. var qconfig=new Object();
  477. qconfig.renderTo=divName;
  478. //point to data container
  479. qconfig.containerPath=getContainer('data');
  480. qconfig.schemaName='lists';
  481. qconfig.queryName=queryName;
  482. qconfig.buttonBarPosition='top';
  483. qconfig.filters=[];
  484. for (f in filters){
  485. let fType=LABKEY.Filter.Types.EQUAL;
  486. print(fName+' filter ['+f+'] '+filters[f]+'/'+typeof(filters[f])+' ['+fType+']');
  487. if (isFilterList(filters[f])){
  488. fType=LABKEY.Filter.Types.IN;
  489. }
  490. qconfig.filters.push(LABKEY.Filter.create(f, filters[f],fType));
  491. }
  492. qconfig.success=updateSuccess;
  493. qconfig.failure=updateFailure;
  494. //show only print button
  495. if (readonlyFlag){
  496. qconfig.buttonBar=new Object();
  497. qconfig.buttonBar.items=["print"];
  498. }
  499. LABKEY.QueryWebPart(qconfig);
  500. }
  501. function updateSuccess(data){
  502. print("Update success");
  503. }
  504. function updateFailure(data){
  505. print("Update failed");
  506. }
  507. //TODO: this should trigger a data refresh on section, ie populateData(field)
  508. function toggleVisibility(divName,buttonName){
  509. let fName='[toggleVisibility/'+divName+']';
  510. print(fName);
  511. let x = config.document.getElementById(divName);
  512. if (x.style.display === "none") {
  513. //exclude non data sections (like debug)...
  514. print(fName+': issuing setData(populateSection)');
  515. x.style.display = "block";
  516. config.document.getElementById(buttonName).value="Hide";
  517. let cb=function(){populateSection(divName);};
  518. setData(cb);
  519. } else {
  520. x.style.display = "none";
  521. config.document.getElementById(buttonName).value="Show";
  522. }
  523. }
  524. function generateButton(divName,caption,label,callbackLabel,callback){
  525. let debug=true;
  526. if (debug) print("generateButtonX");
  527. let tb=config.document.createElement('table');
  528. tb.className="t2";
  529. let r1=tb.insertRow();
  530. th=config.document.createElement('th');
  531. r1.appendChild(th);
  532. th.innerHTML=caption;
  533. //*!*
  534. let c2=r1.insertCell();
  535. let i1=config.document.createElement("input");
  536. i1.type="button";
  537. i1.value=label;
  538. i1.style.fontSize="20px";
  539. i1.onclick=callback;
  540. i1.id='button_'+callbackLabel;
  541. c2.appendChild(i1);
  542. let c1=r1.insertCell();
  543. c1.setAttribute("colspan","1");
  544. //this is only for saveReview?
  545. c1.id=divName+'_reportField';
  546. //c1.id=config.submitReportId;
  547. let el=config.document.getElementById(divName);
  548. if (debug) print("generateButton: element["+divName+"]: "+el);
  549. el.appendChild(tb);
  550. }
  551. function generateSubQuery(input, setup, readonlyFlag){
  552. let fName="[generateSubQuery]";
  553. if (setup.isReview) return;
  554. if (!(setup.queryName in config.formConfig.additionalData)){
  555. print(fName+': no additionalData entry (probably a subquery)');
  556. return;
  557. }
  558. let additionalData=config.formConfig.additionalData[setup.queryName];
  559. if (!("showFlag" in additionalData))
  560. return;
  561. print(fName);
  562. let expId=setup.getInputId(additionalData.showFlag);
  563. if (expId!=input.id) {
  564. print(fName+": ignoring field "+input.id+"/"+expId);
  565. return;
  566. }
  567. print(fName+": Setting onChange to "+input.id);
  568. if (!readonlyFlag)
  569. input.onchange=function(){setListVisibility(input,setup,readonlyFlag)};
  570. }
  571. //>>populate fields
  572. //
  573. //
  574. //split to field generation and field population
  575. //
  576. function addFieldRow(tb,field,setup,additionalData){
  577. let fName="[addFieldRow/"+setup.queryName+':'+field.name+']';
  578. let vName=field.name;
  579. let vType=field.type;
  580. let isLookup=("lookup" in field);
  581. print(fName+": ["+vName+"/"+vType+'/'+isLookup+"]");
  582. let row=tb.insertRow();
  583. let cell=config.document.createElement('th');
  584. cell.style.width='300px';
  585. row.appendChild(cell);
  586. let text = config.document.createTextNode(field.shortCaption);
  587. cell.appendChild(text);
  588. let input=null;
  589. let colSpan="3";
  590. let cell1=row.insertCell();
  591. cell1.colSpan=colSpan;
  592. let readonlyFlag=setup.readonlyFlag(vName);
  593. //set the html input object
  594. while (1){
  595. if (readonlyFlag){
  596. input=config.document.createElement('label');
  597. input.innerText='Loading';
  598. break;
  599. }
  600. //lookup
  601. if (isLookup){
  602. input = config.document.createElement("select");
  603. break;
  604. }
  605. //date
  606. if (vType=="date"){
  607. input = config.document.createElement("input");
  608. input.type="date";
  609. break;
  610. }
  611. //string
  612. if (vType=="string"){
  613. //we have to make sure UNDEF is carried to below
  614. //since we are adapting file to either show
  615. //current file or allow user to select a file
  616. //
  617. //TODO change this so one can always select file
  618. //but also show the selected file
  619. if(vName.search("reviewComment")>-1){
  620. input = config.document.createElement("textarea");
  621. input.cols="65";
  622. input.rows="5";
  623. break;
  624. }
  625. input=config.document.createElement('input');
  626. input.type="text";
  627. if (vName.search('_file_')<0) break;
  628. cell1.setAttribute('colspan',"1");
  629. let cell2=row.insertCell();
  630. cell2.setAttribute('colspan',"2");
  631. let input1=config.document.createElement('input');
  632. input1.type="file";
  633. input1.id=setup.getInputId(vName)+'_file_';
  634. cell2.appendChild(input1);
  635. break;
  636. }
  637. if (vType=="float"){
  638. input = config.document.createElement("input");
  639. input.type="text";
  640. break;
  641. }
  642. if (vType=="boolean"){
  643. input = config.document.createElement("input");
  644. input.type="checkbox";
  645. print("Creating checkbox");
  646. break;
  647. }
  648. break;
  649. }
  650. input.id=setup.getInputId(vName);
  651. cell1.appendChild(input);
  652. print(fName+': adding element '+input.id);
  653. print(fName+': listing element '+config.document.getElementById(input.id));
  654. //connect associated list
  655. generateSubQuery(input,setup,readonlyFlag);
  656. if (readonlyFlag) {
  657. print(fName+': exiting(readonlyFlag)');
  658. return;
  659. }
  660. if (!isLookup) {
  661. print(fName+': exiting (not lookup)');
  662. return;
  663. }
  664. let lookup=field["lookup"];
  665. //get all values from config.formConfig.lookup[X]
  666. let lObject=config.formConfig.lookup[lookup.queryName];
  667. //debug
  668. print(fName+": query: "+lookup.queryName);
  669. print(fName+": ElementId: "+input.id);
  670. print(fName+": No of options: " +lObject.LUT.length);
  671. print(fName+": Element: "+input);
  672. //set the lut value (input is text label) for readonly
  673. //clear existing fields from input
  674. for(let i = input.options.length; i >= 0; i--) {
  675. input.remove(i);
  676. }
  677. //create option -1
  678. let opt = config.document.createElement("option");
  679. opt.text = "<Select>";
  680. opt.value = -1;
  681. input.options[0] = opt;
  682. print(fName+": Adding <Select>");
  683. //add other, label them with LUT
  684. for (let v in lObject.LUT) {
  685. print(fName+': populating '+v+': '+lObject.LUT[v]);
  686. let opt = config.document.createElement("option");
  687. opt.text = lObject.LUT[v];
  688. opt.value = v;
  689. input.options[input.options.length] = opt;
  690. }
  691. input.selectedIndex=0;
  692. }
  693. function parseVariables(pars){
  694. let pA=pars.split(";");
  695. let q=new Object();
  696. for (let i=0;i<pA.length;i++){
  697. let vA=pA[i].split('=');
  698. q[vA[0]]=vA[vA.length-1];
  699. }
  700. return q;
  701. }
  702. function printVariables(q){
  703. let fName="[printVariables]";
  704. for (let x in q){
  705. print(fName+" ["+x+"] "+q[x]);
  706. }
  707. }
  708. function hasVariable(q,varName){
  709. if (q && varName in q)
  710. return true;
  711. return false;
  712. }
  713. function addSpecialFieldRow(tb,specFieldSetup,setup){
  714. //tb is the table, specFieldSetup is a row from the table where special fields are being setup
  715. //the first column is fieldUID, which is a colon joined amalgation of queryName:fieldName
  716. let fieldUID=specFieldSetup["fieldUID"];
  717. let x=fieldUID.split(':');
  718. let fieldName=x[1];
  719. let fName="[addSpecialFieldRow/"+fieldUID+"]";
  720. let q=parseVariables(specFieldSetup['actionParameters']);
  721. print(fName);
  722. if (specFieldSetup['actionType']=='textArea'){
  723. let row=tb.insertRow();
  724. let cell1=row.insertCell();
  725. cell1.colSpan="4";
  726. cell1.style.textAlign="justify";
  727. cell1.style.padding="10px";
  728. cell1.style.backgroundColor="#e0e0e0";
  729. cell1.innerText=q['description'];
  730. return;
  731. }
  732. if (specFieldSetup['actionType']=='generationObject'){
  733. //only in EDIT mode!!
  734. let ro=setup.readonlyFlag(fieldName);
  735. if (ro) return;
  736. config.print=print;
  737. let gc=getGenerationObject(config,q,setup.getInputId(fieldName));
  738. if ('mailRecipient' in q){
  739. gc.callback=function(data){sendEmail(data,q['mailRecipient'],doNothing,q['subject']);};
  740. }
  741. if ("addData" in q){
  742. vars=q["addData"].split(',');
  743. gc.addData=new Array();
  744. for (let v in vars){
  745. let s=vars[v]
  746. //variable name can be written as A/B where A is the name in addData and B is the variable name in crfEntry
  747. //useful for mocking up crfId from daughter crf-s such as registration
  748. let sArray=s.split('/');
  749. let sTarget=sArray[0];
  750. let sSource=sArray[sArray.length-1];
  751. gc.addData[sTarget]=config.formConfig.crfEntry[sSource];
  752. print(fName+" addData ["+sTarget+"]: "+gc.addData[sTarget]);
  753. }
  754. }
  755. let row=tb.insertRow();
  756. let cell=config.document.createElement('th');
  757. row.appendChild(cell);
  758. let text = config.document.createTextNode("Automatic ID generator");
  759. cell.appendChild(text);
  760. let cell1=row.insertCell();
  761. cell1.colSpan="3";
  762. let b=config.document.createElement("input");
  763. b.type="button";
  764. b.id="generateIdButton";
  765. b.onclick=function(){gc.execute();};
  766. b.value="Generate ID";
  767. cell1.appendChild(b);
  768. }
  769. }
  770. function populateFieldRow(entry,field,setup){
  771. populateField(entry,field,setup);
  772. populateSubQuery(entry,field,setup);
  773. }
  774. function populateSubQuery(entry,field,setup){
  775. let fName='[populateSubQuery/'+setup.queryName+':'+field.name+']';
  776. if (setup.isReview) return;
  777. if (!(setup.queryName in config.formConfig.additionalData)){
  778. let msg=fName+': no additionalData entry for '+setup.queryName;
  779. msg+=' (probably a subquery)';
  780. print(msg);
  781. return;
  782. }
  783. //find if field is connected to a sub array
  784. //find queryName
  785. //
  786. let additionalData=config.formConfig.additionalData[setup.queryName];
  787. print(fName);
  788. //let flag=additionalData.showFlag;
  789. if (!("showFlag" in additionalData)) return;
  790. let eId=setup.getInputId(additionalData.showFlag);
  791. let id=setup.getInputId(field.name);
  792. if (eId!=id) {
  793. print(fName+": ignoring field "+id+"/"+eId);
  794. return;
  795. }
  796. print(fName+': id '+id);
  797. //hard to estimate readonlyFlag
  798. //
  799. let input=config.document.getElementById(id);
  800. let eType=input.nodeName.toLowerCase();
  801. let readonlyFlag=eType!="select";
  802. setListVisibility(input,setup,readonlyFlag);
  803. }
  804. function populateField(entry,field,setup){
  805. let vName=field.name;
  806. let fName='[populateFieldName/'+vName+']';
  807. let varValue="UNDEF";
  808. //if (vName in setup.filters) varValue=setup.filters[vName];
  809. if (vName in entry) varValue=entry[vName];
  810. //if part of the filter, set it to value
  811. if (vName in setup.filters) varValue=setup.filters[vName];
  812. let isLookup=("lookup" in field);
  813. print(fName+' v='+varValue+'/'+isLookup+' ['+
  814. setup.getInputId(field.name)+']');
  815. let vType=field.type;
  816. let id=setup.getInputId(vName);
  817. let input=config.document.getElementById(id);
  818. //date
  819. if (vType=="date"){
  820. if (varValue=="UNDEF") varValue=new Date();
  821. else varValue=new Date(varValue);
  822. }
  823. //lookup for readonly
  824. if (isLookup && varValue!="UNDEF"){
  825. let lookup=field["lookup"];
  826. //get all values from config.formConfig.lookup[X]
  827. let lObject=config.formConfig.lookup[lookup.queryName];
  828. varValue=lObject.LUT[varValue];
  829. }
  830. print('Element: '+input);
  831. //figure out the element type
  832. let eType=input.nodeName.toLowerCase();
  833. print('Element type: '+eType);
  834. //change varValue for printing
  835. if (varValue=="UNDEF") varValue="";
  836. //HTMLTextArea, createElement(textArea)
  837. if (eType==="textarea"){
  838. input.value=varValue;
  839. return;
  840. }
  841. //Text, createTextNode
  842. if (eType==="#text"){
  843. input.nodeValue=varValue;
  844. return;
  845. }
  846. //HTMLLabelElement, createElement('label')
  847. if (eType==="label"){
  848. input.innerText=varValue;
  849. return;
  850. }
  851. //HTMLSelectElement, createElement('select')
  852. if (eType==="select"){
  853. input.selectedIndex=0;
  854. for (let i=0;i<input.options.length;i++){
  855. let v=input.options[i].text;
  856. if (v!=varValue) continue;
  857. input.selectedIndex=i;
  858. break;
  859. }
  860. return;
  861. }
  862. if (eType!="input"){
  863. print('Unknown type: '+eType+' encountered, igonring');
  864. return;
  865. }
  866. //HTMLInputElement
  867. let type=input.type;
  868. if (type=="date"){
  869. input.valueAsDate=varValue;
  870. return;
  871. }
  872. //string,float
  873. if (type=="text"){
  874. input.value=varValue;
  875. return;
  876. }
  877. //boolean
  878. if (type=="checkbox"){
  879. input.checked=varValue;
  880. return;
  881. }
  882. print('Unknown input type: '+type+'. Ignoring.');
  883. }
  884. function populateTable(listName,writeMode){
  885. //function populateTable(formSetupEntry){
  886. //let listName=config.formConfig.queryMap[formSetupEntry['queryName']];
  887. //let accessMode=config.formConfig.operator+'Mode';
  888. //let writeMode=formSetupEntry[accessMode]=='EDIT';
  889. let fName='[populateTable/'+listName+']';
  890. let setup=getSetup(listName,writeMode);
  891. let entry=new Object();
  892. //data snapshot
  893. let fQuery=getQuerySnapshot(listName);
  894. let queryLayout=getQueryLayout(listName);
  895. //here I assume that listName was parsed during setDataLayout and setData
  896. //so that rows was set (even if they are empty)
  897. print(fName+"]: nrows "+fQuery.rows.length);
  898. if (fQuery.rows.length>0)
  899. entry=fQuery.rows[0];
  900. let fields=queryLayout.fields;
  901. for (f in fields){
  902. let field=fields[f];
  903. //each field is a new row
  904. print(fName+": Adding field: "+f+'/'+field.name+' hidden: '+field.hidden+' type:'+field.type);
  905. if (field.hidden) continue;
  906. if (field.name=="crfRef") continue;
  907. populateFieldRow(entry,field,setup);
  908. }
  909. }
  910. function generateTable(listName,divName,additionalData,setup){
  911. let debug=true;
  912. let fName="[generateTable/"+listName+"]";
  913. if (debug) print(fName);
  914. //is listName and setup.queryName a duplicate of the same value
  915. print(fName+': setup.queryName '+setup.queryName);
  916. //assume data is set in config.formConfig.dataQueries[data.queryName].rows;
  917. let populateData=true;
  918. if ("subTable" in setup){
  919. print(fName+" is subTable");
  920. populateData=false;
  921. }
  922. let entry=new Object();
  923. //data snapshot
  924. let fQuerySnapshot=getQuerySnapshot(listName);
  925. let queryLayout=getQueryLayout(listName);
  926. //here I assume that listName was parsed during setDataLayout and setData
  927. //so that rows was set (even if they are empty)
  928. print(fName+": Nrows "+fQuerySnapshot.rows.length);
  929. if (fQuerySnapshot.rows.length>0)
  930. entry=fQuerySnapshot.rows[0];
  931. if ("reviewTable" in setup){
  932. entry['reviewComment']='';
  933. delete entry["ModifiedBy"];
  934. }
  935. let tb=config.document.createElement('table');
  936. tb.className="t2";
  937. config.document.getElementById(divName).appendChild(tb);
  938. //this are the fields (probably constant)
  939. let fields=queryLayout.fields;
  940. for (f in fields){
  941. let field=fields[f];
  942. let fieldUID=listName+":"+field.name;
  943. //each field is a new row
  944. print(fName+": Adding field: "+f+'/'+field.name+' ('+fieldUID+').');
  945. //unique name
  946. if (field.hidden) continue;
  947. if (field.name=="crfRef") continue;
  948. addFieldRow(tb,field,setup,additionalData);
  949. if (populateData) populateFieldRow(entry,field,setup);
  950. if (fieldUID in config.formConfig["specialFields"]){
  951. let specFieldSetup=config.formConfig["specialFields"][fieldUID];
  952. addSpecialFieldRow(tb,specFieldSetup,setup);
  953. }
  954. }
  955. //finish of if apply button is not required
  956. if (!("addApply" in setup)) {
  957. print(fName+"populateTable: done");
  958. return;
  959. }
  960. let row=tb.insertRow();
  961. let th=config.document.createElement('th');
  962. row.appendChild(th);
  963. th.innerHTML=setup.addApply;
  964. let cell=row.insertCell();
  965. //cell.setAttribute("colspan","2");
  966. let input=config.document.createElement("input");
  967. input.type="button";
  968. input.value=setup.addApply;
  969. cell.appendChild(input);
  970. let cell1=row.insertCell();
  971. cell1.setAttribute("colspan","2");
  972. cell1.id=setup.getInputId("rerviewLastSave");
  973. cell1.innerHTML="No recent update";
  974. //saveReview is a generic name for saving content of the html page to a list entry
  975. input.onclick=function(){saveReview(listName,cell1.id,setup)};
  976. }
  977. function setEntryFromElement(entry,elementId, field){
  978. //set value to entry from element using representation (field) from labkey
  979. //
  980. //
  981. let fName='setEntryFromElement';
  982. let el=config.document.getElementById(elementId);
  983. if (!el) {
  984. print(fName+" element: "+elementId+" not found");
  985. return;
  986. }
  987. print(fName+" element: "+elementId);
  988. let vName=field.name;
  989. let vType=field.type;
  990. let eType=el.nodeName.toLowerCase();
  991. if (eType==="select"){
  992. entry[vName]=el.options[el.selectedIndex].value;
  993. return;
  994. }
  995. if (eType==="td"){
  996. entry[vName]=el.innerText;
  997. return;
  998. }
  999. if (vType=="date"){
  1000. let date=el.valueAsDate;
  1001. if (date==="null") return;
  1002. date.setUTCHours(12);
  1003. entry[vName]=date.toString();
  1004. print(fName+" setting date to "+entry[vName]);
  1005. return;
  1006. }
  1007. if (vType=="string"){
  1008. entry[vName]=el.value;
  1009. if (vName.search('_file_')<0)
  1010. return;
  1011. //upload file
  1012. let id1=elementId+'_file_';
  1013. let input1=config.document.getElementById(id1);
  1014. print(fName+' attachment field: '+input1.value);
  1015. //entry[vName]=el.files[0].stream();
  1016. let ctx=new Object();
  1017. ctx['dirName']='consent';
  1018. ctx['ID']=entry['crfRef'];
  1019. //should point to data container
  1020. ctx['project']=getContainer('data');
  1021. //need ID->crf!
  1022. //assume crfRef will get set before this
  1023. //element is encountered
  1024. uploadFile(input1,ctx);
  1025. let fv=el.value;
  1026. let suf=fv.split('.').pop();
  1027. entry[vName]=entry['crfRef']+'.'+suf;
  1028. return;
  1029. }
  1030. if (vType=="float" || vType=="int"){
  1031. entry[vName]=el.value;
  1032. if (vName=="queryName") {
  1033. print(fName+' parsing queryName: '+el.innerText);
  1034. entry[vName]=config.formConfig.fields[el.innerText].queryId;
  1035. //use queryMap lookup
  1036. }
  1037. return;
  1038. }
  1039. if (vType=="boolean"){
  1040. entry[vName]=el.checked;
  1041. return;
  1042. }
  1043. return;
  1044. }
  1045. function saveReview(queryName,elementId,setup){
  1046. //loads any queryName
  1047. let debug=true;
  1048. let fName='[saveReview/'+queryName+']';
  1049. print(fName+" elementId "+elementId);
  1050. let mode='update';
  1051. let unique=("unique" in setup);
  1052. if (!unique) mode='insert';
  1053. //data snapshot
  1054. let fQuerySnapshot=getQuerySnapshot(queryName);
  1055. let queryLayout=getQueryLayout(queryName);
  1056. if (fQuerySnapshot.rows.length==0) useInsert=true;
  1057. let entry=new Object();
  1058. if (unique){
  1059. entry=fQuerySnapshot.rows[0];
  1060. }
  1061. entry.crfRef=getCRFrefData();
  1062. if (debug) print("Set crfRef="+entry.crfRef);
  1063. //if ("queryName" in setup.filters) {
  1064. // entry.queryName=setup.filters["queryName"];
  1065. // if (debug) print("Setting queryName: "+entry.queryName);
  1066. //}
  1067. let fields=queryLayout.fields;
  1068. for (f in fields){
  1069. let field=fields[f];
  1070. if (debug) print("saveReview field: "+field.name);
  1071. if (field.hidden) continue;
  1072. let vName=field.name;
  1073. let vType=field.type;
  1074. if (debug) print("vType: "+vType);
  1075. if (vName=="crfRef") continue;
  1076. //need to save queryName for reviewComments
  1077. let eId=setup.getInputId(vName);
  1078. //copy values from form to entry
  1079. setEntryFromElement(entry,eId,field);
  1080. if (!unique){
  1081. let foo=Object();
  1082. //reset the field value
  1083. populateField(foo,field,setup);
  1084. }
  1085. }
  1086. let action=function(data){updateLastSavedFlag(data,setup,elementId)};
  1087. print(fName+" mode "+mode);
  1088. cvModifyRows(mode,'lists',queryName,[entry],action,getContainer('data'));
  1089. }
  1090. function updateLastSavedFlag(data,setup,elementId){
  1091. let debug=true;
  1092. if (debug) print("Update last saved flag to "+elementId);
  1093. let el=config.document.getElementById(elementId);
  1094. let dt=new Date();
  1095. el.innerHTML="Last saved "+dt.toString();
  1096. if (data.queryName=="reviewComments"){
  1097. updateListDisplay(setup.divReviewListId,"reviewComments",setup.filters,true);
  1098. }
  1099. //refresh stored data!
  1100. let writeMode=!setup.readonlyFlag();
  1101. if ("unique" in setup)
  1102. setData(function (){populateTable(data.queryName,writeMode);});
  1103. if ("masterQuery" in setup){
  1104. let ad=config.formConfig.additionalData[setup.masterQuery];
  1105. print('Updating list display: '+setup.queryName+'/'+ad.queryName);
  1106. updateListDisplay(ad.divQueryName,ad.queryName,ad.filters,false);
  1107. }
  1108. }
  1109. //******************************************upload to database *********************
  1110. function onDatabaseUpload(){
  1111. let fName='[onDatabaseUpload]';
  1112. print(fName);
  1113. config.upload=new Object();
  1114. let fc=new Object();
  1115. let pM=getParticipantManagerObject(config);
  1116. fc.participantId=pM.getParticipantIdFromCrfEntry();
  1117. print(fName+' id '+fc.participantId);
  1118. afterParticipantId(fc);
  1119. }
  1120. function afterParticipantId(fc){
  1121. print("Setting participantId to "+fc.participantId);
  1122. config.upload.participantId=fc.participantId;
  1123. //another select rows to update all queries from setup
  1124. //just use registration for test
  1125. let formSetupRows=config.formConfig.formSetupRows;
  1126. config.upload.queries=new Array();
  1127. print("Form rows: "+formSetupRows.length);
  1128. for (let i=0;i<formSetupRows.length;i++){
  1129. let entry=formSetupRows[i];
  1130. //skip reviews
  1131. if (entry.showFlag=="REVIEW") continue;
  1132. //use lookup table to convert from id to name
  1133. let queryName=config.formConfig.queryMap[entry.queryName];
  1134. config.upload.queries.push({queryName:queryName,queryStatus:"QUEUED"});
  1135. print('form ['+i+']='+queryName+' '+entry.showFlag+'/'+entry.showQuery);
  1136. if (entry.showQuery=="NONE")
  1137. continue;
  1138. config.upload.queries.push({queryName:entry.showQuery,queryStatus:"QUEUED"});
  1139. }
  1140. //add reviews
  1141. config.upload.queries.push({queryName:"reviewComments",queryStatus:"QUEUED"});
  1142. config.upload.queryId=0;
  1143. copyToDataset();
  1144. }
  1145. function copyToDataset(){
  1146. let fName='[copyToDataset]: ';
  1147. print(fName+'['+config.upload.queryId+'/'+config.upload.queries.length+']');
  1148. //watch dog + scheduler
  1149. //
  1150. //watchdog part
  1151. if (config.upload.queryId==config.upload.queries.length) {
  1152. print(fName+'completing');
  1153. let targetStatus=config.formConfig.targetStatus['onDatabaseUpload'];
  1154. let targetRecipient=config.formConfig.targetRecipient['onDatabaseUpload'];
  1155. let action=new Object();
  1156. action.name='onDatabaseUpload';
  1157. action.cb=function(data){sendEmail(data,targetRecipient,redirect,'Form uploaded');}
  1158. updateFlag(targetStatus,action);//Approved
  1159. return;
  1160. }
  1161. //scheduler
  1162. let queryName=config.upload.queries[config.upload.queryId].queryName;
  1163. print("copyToDataset["+config.upload.queryId+"/"+
  1164. config.upload.queries.length+"]: "+queryName);
  1165. let filters=[LABKEY.Filter.create('crfRef',getCRFref())];
  1166. cvSelectRows('lists',queryName,filters,afterListData,getContainer('data'));
  1167. }
  1168. function afterListData(data){
  1169. let fName='[afterListData]: ';
  1170. let queryName=config.upload.queries[config.upload.queryId].queryName;
  1171. print(fName+" ["+queryName+"/list]: "+data.rows.length+" entries");
  1172. config.upload.queries[config.upload.queryId].listData=data;
  1173. let id=config.upload.participantId;
  1174. let filters=[LABKEY.Filter.create('crfRef',getCRFref()),LABKEY.Filter.create('ParticipantId',id)];
  1175. cvSelectRows('study',queryName,filters,afterStudyData,getContainer('data'));
  1176. }
  1177. function afterStudyData(data){
  1178. let fName='[afterStudyData]: ';
  1179. let queryObj=config.upload.queries[config.upload.queryId];
  1180. queryObj.studyData=data;
  1181. let msg=fName+"["+queryObj.queryName+"/study]: "+data.rows.length+" entries";
  1182. print(msg);
  1183. let listRows=queryObj.listData.rows;
  1184. //skip uploading an empty set
  1185. if (listRows.length==0){
  1186. printErr("List "+queryObj.queryName+" empty.");
  1187. queryObj.queryStatus="DONE";
  1188. config.upload.queryId+=1;
  1189. //back to watchdog
  1190. copyToDataset();
  1191. return;
  1192. }
  1193. let studyRows=queryObj.studyData.rows;
  1194. for (let i=0;i<studyRows.length;i++){
  1195. let entry=studyRows[i];
  1196. //
  1197. if (! (i<listRows.length) ) continue;
  1198. let entryList=listRows[i];
  1199. //keeps study only variables (ParticipantId, SequenceNum)
  1200. for (let f in entryList) {
  1201. entry[f]=entryList[f];
  1202. print(fName+"Copying ["+f+"]: "+entry[f]+"/"+entryList[f]);
  1203. }
  1204. }
  1205. print(fName+' copying completed');
  1206. if (studyRows.length>0) {
  1207. cvModifyRows('update','study',queryObj.queryName,studyRows,afterStudyUpload,getContainer('data'));
  1208. print(fName+'updateRows sent');
  1209. }
  1210. else{
  1211. let data=new Object();
  1212. data.rows=new Array();
  1213. afterStudyUpload(data);
  1214. }
  1215. }
  1216. function afterStudyUpload(data){
  1217. let fName='[afterStudyUpload] ';
  1218. print(fName);
  1219. //let participantField=config.participantField;
  1220. let participantField=config.formConfig.studyData["SubjectColumnName"];
  1221. print(fName+' participantField: '+participantField);
  1222. let queryObj=config.upload.queries[config.upload.queryId];
  1223. let queryName=queryObj.queryName;
  1224. printErr("Updated "+data.rows.length+" rows to "+queryName);
  1225. let studyRows=queryObj.studyData.rows;
  1226. let listRows=queryObj.listData.rows;
  1227. let rows=new Array();
  1228. //also updating existing rows, if they exist
  1229. for (let i=studyRows.length;i<listRows.length;i++){
  1230. let entry=listRows[i];
  1231. //make sure you have the participantField right
  1232. //
  1233. entry[participantField]=config.upload.participantId;
  1234. entry.crfRef=getCRFref();
  1235. entry.SequenceNum=getCRFref();
  1236. entry.SequenceNum=entry.SequenceNum % 1000000000;
  1237. if (listRows.length>1){
  1238. entry.SequenceNum+=i/100;
  1239. }
  1240. print( "Adding sequence number "+entry.SequenceNum);
  1241. rows.push(entry);
  1242. }
  1243. if (rows.length>0){
  1244. cvInsertRows('study',queryName,rows,afterListUpload,getContainer('data'));
  1245. }
  1246. else{
  1247. let data=new Object();
  1248. data.rows=rows;
  1249. afterListUpload(data);
  1250. }
  1251. }
  1252. function afterListUpload(data){
  1253. let queryObj=config.upload.queries[config.upload.queryId];
  1254. let queryName=queryObj.queryName;
  1255. printErr("Inserted "+data.rows.length+" rows to "+queryName);
  1256. queryObj.queryStatus="DONE";
  1257. config.upload.queryId+=1;
  1258. copyToDataset();
  1259. }
  1260. //*************************update for further review *************************
  1261. function onUpdateForReview(){
  1262. let targetStatus=config.formConfig.targetStatus['onUpdateForReview'];
  1263. let targetRecipient=config.formConfig.targetRecipient['onUpdateForReview'];
  1264. let action=new Object();
  1265. action.name='onUpdateForReview';
  1266. action.cb=function(data){sendEmail(data,targetRecipient,redirect,'Form updated for review');};
  1267. updateFlag(targetStatus,action);
  1268. }
  1269. function updateFlag(flag,action){
  1270. let fName='[updateFlag 1]';
  1271. let debug=true;
  1272. let entry=config.formConfig.crfEntry;
  1273. entry.FormStatus=flag;
  1274. let uId=config.formConfig.currentUser.UserId;
  1275. entry[config.formConfig.operator]=uId;
  1276. print(fName+': Form: '+entry.Form);
  1277. print(fName+": set form status to "+entry.FormStatus);
  1278. let cb=function(data){completeWithFlag(data,action);};
  1279. cvModifyRows('update','lists','crfEntry',[entry],cb,getContainer('data'));
  1280. }
  1281. function completeWithFlag(data,action){
  1282. let fName='[completeWithFlag]';
  1283. print(fName+': nrows '+data.rows.length);
  1284. let fentry=data.rows[0];
  1285. print(fName+': form status '+fentry.FormStatus);
  1286. print(fName+': form '+fentry.Form);
  1287. let crfStatus=createCrfStatus(fentry);
  1288. crfStatus.operator=config.formConfig.operator;
  1289. crfStatus.action=action.name;
  1290. cvInsertRows('lists','crfStatus',[crfStatus],action.cb,getContainer('data'));
  1291. }
  1292. //************************************************ submit *******************************************
  1293. function onSubmit(){
  1294. //update list storage and change status
  1295. hideErr();
  1296. clearErr();
  1297. printErr("onSubmit");
  1298. setData(verifyData);
  1299. }
  1300. function verifyData(){
  1301. let fName='[verifyData]';
  1302. let qList=getQueryList();
  1303. for (q in qList){
  1304. let qData=getQuerySnapshot(q);
  1305. if (q=="reviewComments") continue;
  1306. //copy snapshot to history
  1307. if (qData.rows.length==0){
  1308. print(fName+' no rows for '+q);
  1309. }
  1310. else
  1311. cvInsertRows('lists',q+'History',qData.rows,doNothing,getContainer('data'));
  1312. //if it doesn't have additionalData, it is a sub query
  1313. if (!(q in config.formConfig.additionalData)){
  1314. continue;
  1315. }
  1316. if (qData.rows.length<1){
  1317. printErr('Missing entry for query '+q);
  1318. return false;
  1319. }
  1320. }
  1321. //this is necessary only for Generated to Generation completed step
  1322. let actionSettings=config.formConfig.actionSettings['onSubmit'];
  1323. if (hasVariable(actionSettings,"updateRegistration")){
  1324. updateRegistration();
  1325. }
  1326. let targetStatus=config.formConfig.targetStatus['onSubmit'];
  1327. let targetRecipient=config.formConfig.targetRecipient['onSubmit'];
  1328. print(fName+' targetStatus: '+targetStatus);
  1329. let finalStep=redirect;
  1330. if (hasVariable(actionSettings,"finalStep")){
  1331. //set to doNothing to remain on submit window
  1332. if (actionSettings.finalStep=="doNothing"){
  1333. finalStep=doNothing;
  1334. }
  1335. }
  1336. let action=new Object();
  1337. action.name='onSubmit';
  1338. action.cb=function(data){sendEmail(data,targetRecipient,finalStep,'Form sumbitted');};
  1339. updateFlag(targetStatus,action);
  1340. }
  1341. function getEmail(recipientCode){
  1342. print('getEmail w/'+recipientCode);
  1343. let recipients=new Array();
  1344. let typeTo=LABKEY.Message.recipientType.to;
  1345. let create=LABKEY.Message.createRecipient;
  1346. let currentUser=config.formConfig.currentUser;
  1347. let formCreator=config.formConfig.formCreator;
  1348. let currentSite=config.formConfig.currentSite;
  1349. let userRows=config.formConfig.userRows;
  1350. let parentUser=undefined;
  1351. if ("parentCrfData" in config.formConfig){
  1352. let parentCrf=config.formConfig.parentCrfData;
  1353. parentUser=getUser(parentCrf.rows[0].UserId,'parentUser');
  1354. }
  1355. let recipientCategories=recipientCode.split(',');
  1356. for (let i=0;i<recipientCategories.length;i++){
  1357. let recipient=recipientCategories[i];
  1358. print('Checking '+recipient);
  1359. if (recipient=='crfEditor'){
  1360. print('Adding :'+formCreator.Email);
  1361. recipients.push(create(typeTo,formCreator.Email));
  1362. if (parentUser==undefined) continue;
  1363. print('Adding :'+parentUser.Email);
  1364. recipients.push(create(typeTo,parentUser.Email));
  1365. continue;
  1366. }
  1367. //Monitor or Sponsor
  1368. let fList=recipient+'s';
  1369. let fRows=config.formConfig[fList];
  1370. for (let i=0;i<fRows.length;i++){
  1371. print('Checking '+fRows[i].User+'/'+fRows[i].Site);
  1372. if (fRows[i].Site!=currentSite.siteNumber) continue;
  1373. for (let j=0;j<userRows.length;j++){
  1374. if (userRows[j].UserId!=fRows[i].User) continue;
  1375. print('Adding :'+userRows[j].Email);
  1376. recipients.push(create(typeTo,userRows[j].Email));
  1377. break;
  1378. }
  1379. }
  1380. }
  1381. return recipients;
  1382. }
  1383. function sendEmail(data,recipient='crfEditor',cb=redirect,subj='Form submitted'){
  1384. print('sendEmail; recipient: '+recipient);
  1385. let st=config.formConfig.settings;
  1386. let cvar='sendEmail';
  1387. if (cvar in st){
  1388. print(cvar+' set to '+st[cvar]);
  1389. if (st[cvar]=='FALSE'){
  1390. print('Skipping sending emails');
  1391. cb();
  1392. return;
  1393. }
  1394. }
  1395. if (recipient==null){
  1396. print('Skipping sending emails w/ no recipients');
  1397. cb();
  1398. return;
  1399. }
  1400. print('send email '+data.rows.length);
  1401. let crf=data.rows[0]['entryId'];
  1402. let formId=data.rows[0]['Form'];
  1403. let link=LABKEY.ActionURL.getBaseURL();
  1404. link+=LABKEY.ActionURL.getContainer();
  1405. link+='/crf_tecant-visit.view?';
  1406. link+='entryId='+crf;
  1407. link+='&formId='+formId;
  1408. link+='&role='+recipient;
  1409. //debug
  1410. let recipients=getEmail(recipient);
  1411. //from crfManagers list
  1412. let typeHtml=LABKEY.Message.msgType.html;
  1413. let typePlain=LABKEY.Message.msgType.plain;
  1414. let msg1=LABKEY.Message.createMsgContent(typePlain,link);
  1415. //let cb=doNothing;
  1416. //let cb=redirect;
  1417. LABKEY.Message.sendMessage({
  1418. msgFrom:'labkey@fmf.uni-lj.si',
  1419. msgSubject:subj,
  1420. msgRecipients:recipients,
  1421. msgContent:[msg1],
  1422. success: cb
  1423. });
  1424. }
  1425. function hideErr(){
  1426. let el=config.document.getElementById("errorDiv");
  1427. el.style.display="none";
  1428. }
  1429. function clearErr(){
  1430. let el=config.document.getElementById("errorTxt");
  1431. el.value="";
  1432. }
  1433. function showErr(){
  1434. let el=config.document.getElementById("errorDiv");
  1435. el.style.display="block";
  1436. }
  1437. function printErr(msg){
  1438. showErr();
  1439. el=config.document.getElementById("errorTxt");
  1440. el.style.color="red";
  1441. el.value+="\n"+msg;
  1442. }
  1443. //**************************************************
  1444. //
  1445. function onRemoveCRF(){
  1446. let fName='[onRemoveCRF]';
  1447. config.inputListsIterator=0;
  1448. print(fName+' starting loop');
  1449. //let rd=function(data){redirect();};
  1450. //let cb=function(){cvInsertRows('lists','crfStatus',[crfStatus],rd,getContainer('data'));};
  1451. let cb=function(){removeCrfEntries(redirect);};
  1452. removeCRFLoop(cb);
  1453. }
  1454. function removeCRFLoop(cb){
  1455. let fName='[removeCRFLoop()]';
  1456. let debug=true;
  1457. let i=config.inputListsIterator;
  1458. let iMax=config.formConfig.inputLists.rows.length;
  1459. //in fact, we are adding two additional passages of the loop, one for
  1460. //crfEntry, the second for the same query, but using parentCrf as the
  1461. //selection variable
  1462. //let iTotal=iMax+1;
  1463. //let iTotal=iMax+1;
  1464. //
  1465. let actionSettings=config.formConfig.actionSettings['onRemoveCRF'];
  1466. let queryNameDeleteWithParentCrf='NONE';
  1467. if (hasVariable(actionSettings,'removeWithParentCrf')){
  1468. queryNameDeleteWithParentCrf=actionSettings['removeWithParentCrf'];
  1469. }
  1470. print(fName+" ["+i+"/"+iMax+"]");
  1471. if (!(i<iMax)){
  1472. if (0) return;
  1473. cb();
  1474. }
  1475. //in all but crfEntry, variable is called crfRef
  1476. let queryName=config.formConfig.inputLists.rows[i].queryName;
  1477. let idVar="crfRef";
  1478. let idValue=config.formConfig.crfEntry['entryId'];
  1479. //delete also crfEntries where parentCrf is set to crf that we are deleting
  1480. if (queryNameDeleteWithParentCrf==queryName){
  1481. idValue=config.formConfig.crfEntry['parentCrf'];
  1482. }
  1483. print(fName+" ["+i+"/"+iMax+"] "+queryName+":"+idVar+'/'+idValue);
  1484. let filters=[LABKEY.Filter.create(idVar,idValue)];
  1485. let action=function(data){removeListCRF(data,cb);};
  1486. let failure=function(errorInfo){skipListCRF(errorInfo,cb);};
  1487. cvSelectRows('lists',queryName,filters,action,getContainer('data'),failure);
  1488. //selectRows.failure=skipListCRF;
  1489. }
  1490. function removeListCRF(data,cb){
  1491. let fName="[removeListCRF]";
  1492. print(fName+" "+data.queryName+": "+data.rows.length);
  1493. config.inputListsIterator+=1;
  1494. if (data.rows.length==0){
  1495. removeCRFLoop(cb);
  1496. return;
  1497. }
  1498. let action=function(data){removeCRFLoop(cb)};
  1499. cvDeleteRows(data.schemaName,data.queryName,data.rows,action,getContainer('data'));
  1500. }
  1501. function skipListCRF(errorInfo,cb){
  1502. let fName='[skipListCRF]';
  1503. print(fName+" error in removeCRF: "+errorInfo.exception);
  1504. config.inputListsIterator+=1;
  1505. removeCRFLoop(cb);
  1506. }
  1507. function removeCrfEntries(cb){
  1508. let queryName="crfEntry";
  1509. let idVar="entryId";
  1510. let crfRef=getCRFref();
  1511. let filters=[LABKEY.Filter.create('entryId',crfRef)];
  1512. let action=function(data){deleteAndUpdateCrfStatus(data,null);}
  1513. cvSelectRows('lists',queryName,filters,action,getContainer('CRF'));
  1514. let action1=function(data){deleteAndUpdateCrfStatus(data,cb);}
  1515. let filters1=[LABKEY.Filter.create('parentCrf',crfRef)];
  1516. cvSelectRows('lists',queryName,filters1,action1,getContainer('CRF'));
  1517. }
  1518. function deleteAndUpdateCrfStatus(data,cb){
  1519. let fName='[deleteAndUpdateCrfStatus]';
  1520. let rows=data.rows;
  1521. let stack=new Array();
  1522. stack.push(cb);
  1523. for (let i=0;i<rows.length;i++){
  1524. //generate crfStatus entry out of crfEntry
  1525. let crfStatus=createCrfStatus(rows[i]);
  1526. crfStatus.action='onRemoveCRF';
  1527. crfStatus.FormStatus=config.formConfig.targetStatus[crfStatus.action];
  1528. print(fName+' status '+crfStatus.FormStatus);
  1529. crfStatus.operator=config.formConfig.operator;
  1530. let k=stack.length-1;
  1531. stack.push(function(){cvInsertRows('lists','crfStatus',[crfStatus],stack[k],getContainer('CRF'));});
  1532. let k1=k+1;
  1533. stack.push(function(){cvDeleteRows('lists','crfEntry',[rows[i]],stack[k1],getContainer('CRF'));});
  1534. }
  1535. //execute the whole stack
  1536. let m=stack.length-1;
  1537. stack[m]();
  1538. }
  1539. function redirect(){
  1540. let debug=false;
  1541. let formUrl="begin";
  1542. let params=new Object();
  1543. params.name=formUrl;
  1544. params.pageId="CRF";
  1545. //points to crf container
  1546. let containerPath=getContainer('CRF');
  1547. // This changes the page after building the URL.
  1548. //Note that the wiki page destination name is set in params.
  1549. var homeURL = LABKEY.ActionURL.buildURL(
  1550. "project", formUrl , containerPath, params);
  1551. print("Redirecting to "+homeURL);
  1552. if (debug) return;
  1553. window.location = homeURL;
  1554. }
  1555. //master section, entry point from html files
  1556. function generateMasterForm(){
  1557. generateDebugSection();
  1558. //read enviroment from lists disperesed on labkey
  1559. setFormConfig();
  1560. }
  1561. //helper function to set basic parameters on web page
  1562. //(fields defined in html file)
  1563. function populateBasicData(){
  1564. let staticData=new Object();
  1565. let titles=new Object();
  1566. staticData['version']=config.formConfig.softwareVersion;
  1567. titles['version']='Software version';
  1568. let varRows=config.formConfig['crfStaticVariables'].rows;
  1569. for (let i=0;i<varRows.length;i++){
  1570. let vName=varRows[i].staticVariable;
  1571. let val=config.formConfig.crfEntry[vName];
  1572. if (val==undefined) continue;
  1573. staticData[vName]=val;
  1574. titles[vName]=varRows[i].Title;
  1575. }
  1576. staticData['investigatorName']=config.formConfig.user['DisplayName'];
  1577. titles['investigatorName']='Investigator';
  1578. staticData['email']=config.formConfig.user['Email'];
  1579. titles['email']='Email';
  1580. staticData['siteName']=config.formConfig.currentSite['siteName'];
  1581. titles['siteName']='Site';
  1582. staticData['sitePhone']=config.formConfig.currentSite['sitePhone'];
  1583. titles['sitePhone']='Telephone(site)';
  1584. for (f in staticData){
  1585. addStaticData(f,titles[f],staticData[f]);
  1586. }
  1587. }
  1588. function addStaticData(f,title,value){
  1589. let el=config.document.getElementById(f);
  1590. //populate only
  1591. if (el!=undefined){
  1592. el.innerText=value;
  1593. return;
  1594. }
  1595. //add row to table if element cannot be found
  1596. let table=config.document.getElementById('staticTable');
  1597. let row=table.insertRow();
  1598. let cell=row.insertCell();
  1599. cell.innerText=title;
  1600. let cell1=row.insertCell();
  1601. cell1.id=f;
  1602. cell1.style.fontWeight='bold';
  1603. //populate
  1604. cell1.innerText=value;
  1605. }
  1606. //come here after the layout is read from labkey page
  1607. //
  1608. function generateErrorMsg(msg){
  1609. let txt=config.document.createElement('p');
  1610. txt.innerText=msg;
  1611. config.document.getElementById(config.masterForm).appendChild(txt);
  1612. generateButton("submitDiv",'Exit','Exit','redirect',redirect);
  1613. }
  1614. function getUser(id,field){
  1615. if (field in config.formConfig) return config.formConfig[field];
  1616. let uRows=config.formConfig.userRows;
  1617. for (let i=0;i<uRows.length;i++){
  1618. let userId=uRows[i].UserId;
  1619. if (userId!=id) continue;
  1620. config.formConfig[field]=uRows[i];
  1621. return config.formConfig[field];
  1622. }
  1623. return null;
  1624. }
  1625. function afterConfig(){
  1626. let debug=true;
  1627. if (debug)
  1628. print("afterConfig");
  1629. populateBasicData();
  1630. //check if user has permission on the form
  1631. let currentUser=getUser(LABKEY.Security.currentUser.id,'currentUser');
  1632. let currentSite=config.formConfig.currentSite;
  1633. let formCreator=getUser(config.formConfig.crfEntry.UserId,'formCreator');
  1634. let formCreatorId=formCreator.UserId;
  1635. //let formSite=config.formConfig.crfEntry.Site;
  1636. let fList=config.formConfig.operator+'s';
  1637. let fRows=config.formConfig[fList];
  1638. //let currentSiteId=-1;
  1639. //depending on operator mode, we should decide what is right
  1640. let operator=config.formConfig.operator;
  1641. if (operator=='crfEditor'){
  1642. //editor can only edit its own forms
  1643. if (currentUser.UserId!=formCreatorId){
  1644. let msg='User '+currentUser.DisplayName;
  1645. msg+=' has no permission on this form';
  1646. generateErrorMsg(msg);
  1647. return;
  1648. }
  1649. }
  1650. if (operator=='crfMonitor' || operator=='crfSponsor'){
  1651. //monitor can look at forms based on his site
  1652. //find monitor line
  1653. let operatorSites=new Array();
  1654. for (let i=0;i<fRows.length;i++){
  1655. if (fRows[i].User!=currentUser.UserId) continue;
  1656. operatorSites.push(fRows[i].Site);
  1657. }
  1658. print('operator Site: '+operatorSites.length);
  1659. if (operatorSites.length==0){
  1660. let msg='User '+currentUser.DisplayName;
  1661. msg+=' is not a '+operator;
  1662. generateErrorMsg(msg);
  1663. return;
  1664. }
  1665. let selectedSite=-1;
  1666. let siteCandidates="[";
  1667. for (let i=0;i<operatorSites.length;i++){
  1668. if (i>0) siteCandidates+=", ";
  1669. siteCandidates+=operatorSites[i];
  1670. if (operatorSites[i]!=currentSite.siteNumber) continue;
  1671. selectedSite=currentSite.siteNumber;
  1672. break;
  1673. }
  1674. siteCandidates+="]";
  1675. if (selectedSite==-1){
  1676. let msg='User '+currentUser.DisplayName;
  1677. msg+=' is not a '+operator+' for site ';
  1678. msg+=currentSite.siteName+'('+currentSite.siteNumber+')';
  1679. msg+='/'+siteCandidates;
  1680. generateErrorMsg(msg);
  1681. return;
  1682. }
  1683. }
  1684. print('User '+currentUser.DisplayName+'/'+
  1685. config.formConfig.currentSite['siteName']+
  1686. ' acting as '+config.formConfig.operator);
  1687. let rows=config.formConfig.crfButtons.rows;
  1688. config.formConfig.targetStatus=new Array();
  1689. config.formConfig.targetRecipient=new Array();
  1690. config.formConfig.actionSettings=new Array();
  1691. for (let i=0; i<rows.length; i++){
  1692. let action=rows[i].action;//String
  1693. let tstatus=rows[i].targetFormStatus;
  1694. let trecip=rows[i].targetRecipient;
  1695. config.formConfig.targetStatus[action]=tstatus;
  1696. config.formConfig.targetRecipient[action]=trecip;
  1697. //allow for settings to be promoted with each action (and potentially parsed and acted upon)
  1698. config.formConfig.actionSettings[action]=undefined;
  1699. let aSet=rows[i].actionSettings;
  1700. if (aSet){
  1701. config.formConfig.actionSettings[action]=parseVariables(aSet);
  1702. printVariables(config.formConfig.actionSettings[action]);
  1703. }
  1704. }
  1705. let formStatus=config.formConfig.formStatus;
  1706. //let functionArray=new Array();
  1707. print("Generating buttons for formStatus \""+ formStatus+"\"");
  1708. let allButtonRows=config.formConfig.crfButtons.rows;
  1709. let buttonRows=new Array();
  1710. //specifying role=X in actionSettings will limit button to that role
  1711. for (let i=0;i<allButtonRows.length;i++){
  1712. let action=allButtonRows[i]['action'];
  1713. //filter on actionSettings
  1714. let as=config.formConfig.actionSettings[action];
  1715. if (hasVariable(as,'role')){
  1716. print('Role['+config.formConfig.operator+'/'+as['role']+'] limited for action '+action);
  1717. //mismatch skips addition of button to buttonRows
  1718. if (config.formConfig.operator!=as['role']) continue;
  1719. }
  1720. buttonRows.push(allButtonRows[i]);
  1721. }
  1722. for (let i=0;i<buttonRows.length;i++){
  1723. let bt=buttonRows[i];
  1724. if (typeof window[bt.action]==="function"){
  1725. generateButton("submitDiv",bt.caption,bt.label,bt.action,
  1726. window[bt.action]);
  1727. }
  1728. else{
  1729. print('No match for function :'+bt.action+
  1730. ' obj: '+window[bt.action]);
  1731. }
  1732. }
  1733. print('Here');
  1734. //here we should get data. For now, just initialize objects that will hold data
  1735. setDataLayout(afterDataLayout);//callback is afterDataLayout
  1736. }
  1737. function afterDataLayout(){
  1738. setData(afterData);//callback is afterData
  1739. }
  1740. function verifyCrfStudyId(pM){
  1741. //is studyId already set for the crf
  1742. let studyId=pM.getParticipantIdFromCrfEntry('STUDY');
  1743. if (!studyId) return;
  1744. pM.mode="STUDY";
  1745. pM.readOnly="TRUE";
  1746. }
  1747. function verifyRegistration(pM){
  1748. //if registration is in,
  1749. //then local id should not be changed any longer
  1750. let idFieldName=pM.getCrfEntryFieldName("STUDY");
  1751. //let registrationQuery=config.formConfig.settings['registrationQuery'];
  1752. //if (!registrationQuery) return; //LOCAL is OK
  1753. //let fQuery=config.formConfig.dataQueries[registrationQuery];
  1754. //if (!fQuery) return; //no registration query, then it should be ignored
  1755. let fQuery=config.formConfig.registrationData;
  1756. if (fQuery.rows.length==0) return; //registration is empty
  1757. let studyId=fQuery.rows[0][idFieldName];
  1758. if (!studyId) return; //study id not set
  1759. //set
  1760. pM.mode="STUDY";
  1761. pM.readOnly="TRUE";
  1762. //set crf (this happens later, but probably before the form will be corrected)
  1763. pM.setParticipantIdToCrfEntry(studyId,"STUDY");
  1764. pM.updateCrfEntry();
  1765. }
  1766. function updateRegistration(){
  1767. let fName="[updateRegistration]";
  1768. print(fName);
  1769. let pM=getParticipantManagerObject(config);
  1770. let idFieldName=pM.getCrfEntryFieldName("STUDY");
  1771. //have to reload query data
  1772. let regQueryPars=parseVariables(config.formConfig.settings['registrationQuery']);
  1773. let regQuery=regQueryPars['query'];
  1774. let fQuery=getQuerySnapshot(regQuery);
  1775. if (fQuery.rows.length==0) {
  1776. print(fName+" registration is empty");
  1777. return; //registration is empty
  1778. }
  1779. let regEntry=fQuery.rows[0];
  1780. for (x in regEntry){
  1781. print(fName+" ["+x+"] "+regEntry[x]);
  1782. }
  1783. let studyId=fQuery.rows[0][idFieldName];
  1784. if (!studyId) {
  1785. print(fName+" study id not set ("+idFieldName+'/'+studyId+")");
  1786. return; //study id not set
  1787. }
  1788. //set
  1789. pM.setParticipantIdToCrfEntry(studyId,"STUDY");
  1790. //this will only update crfEntry in memory, but not on LabKey,
  1791. //we are counting on updateFlag to follow updateRegistration
  1792. //update parentCRF as well, here we schedule update of data entry as well
  1793. if ("parentCrfData" in config.formConfig){
  1794. let parentCrfEntry=config.formConfig.parentCrfData.rows[0];
  1795. parentCrfEntry[idFieldName]=studyId;
  1796. let cb=function(data){completeWithFlag(data,doNothing);};
  1797. cvModifyRows('update','lists','crfEntry',[parentCrfEntry],cb,getContainer('CRF'));
  1798. }
  1799. }
  1800. function afterData(){
  1801. let fName='afterData';
  1802. //operatorBasedAccessMode
  1803. let accessMode=config.formConfig.operator+'Mode';
  1804. let rowsSetup=config.formConfig.formSetupRows;
  1805. let idMode=config.formConfig.form['idMode'];
  1806. //set default value if no value is in the list (read value is null)
  1807. if (!idMode) idMode="STUDY:EDIT";
  1808. print(fName+': idMode '+idMode);
  1809. //add print to config so participantManager can use it
  1810. config.print=print;
  1811. let pM=getParticipantManagerObject(config);
  1812. pM.updateCrfEntry=function(){updateFlag(config.formConfig.crfEntry['FormStatus'],doNothing);};
  1813. let idModeArray=idMode.split(':');
  1814. pM.mode="STUDY";
  1815. if (idModeArray.includes("LOCAL")) {
  1816. pM.mode="LOCAL";
  1817. //OK, but check if CRF or registration indicate that study id is already set
  1818. verifyCrfStudyId(pM);
  1819. //study id should already be set by updateRegistration
  1820. //verifyRegistration(pM);
  1821. }
  1822. if (idModeArray.includes("READONLY")){
  1823. pM.readOnly="TRUE";
  1824. }
  1825. let pId=pM.getParticipantIdFromCrfEntry();
  1826. if (!pId){
  1827. pM.setEditMode();
  1828. }
  1829. else{
  1830. let label=pId;
  1831. if (pM.mode=="STUDY"){
  1832. let loc=pM.getParticipantIdFromCrfEntry('LOCAL');
  1833. label=pId+':'+loc;
  1834. pM.readOnly="true";
  1835. }
  1836. pM.setLabelMode(label);
  1837. //in STUDY mode also change LOCAL ID from crfEntry
  1838. }
  1839. for (let i=0;i<rowsSetup.length;i++){
  1840. let entry=rowsSetup[i];
  1841. let queryName=config.formConfig.queryMap[entry['queryName']];
  1842. print(fName+" ["+queryName+"]: showFlag: "+entry["showFlag"]);
  1843. print(fName+" ["+queryName+"]: accessMode: "+entry[accessMode]);
  1844. const nData=getQuerySnapshot(queryName).rows.length;
  1845. print(fName+" ["+queryName+"]: nData: "+nData);
  1846. //skip sections
  1847. //also from fields
  1848. if (entry[accessMode]=="NONE") continue;
  1849. //skip readonly empty records
  1850. //if (entry[accessMode]=="READ" && nData==0) continue;
  1851. //let additionalData=new Object();
  1852. //setAdditionalData(additionalData,entry);
  1853. //section fits one dataset/list
  1854. generateSection(entry);
  1855. //generateSection(queryName,entry["title"],entry[accessMode],
  1856. // additionalData);
  1857. }
  1858. }
  1859. function findSetupRow(queryName,formId){
  1860. let rowsSetup=config.formConfig.formSetupRows;
  1861. for (let i=0;i<rowsSetup.length;i++){
  1862. let e=rowsSetup[i];
  1863. let queryName1=config.formConfig.queryMap[e['queryName']];
  1864. if (e.formName!=formId) continue;
  1865. if (queryName1!=queryName) continue;
  1866. return e;
  1867. }
  1868. return null;
  1869. }
  1870. function populateSection(queryName){
  1871. let fName='[populateSection/'+queryName+']';
  1872. print(fName);
  1873. //old setting
  1874. let formId=config.formId;
  1875. //new setting
  1876. formId=config.formConfig.formId;
  1877. let entry=findSetupRow(queryName,formId);
  1878. //ignore names without associated entry in formSetup
  1879. if (entry==undefined){
  1880. print(fName+': no matching FormSetup entry found');
  1881. return;
  1882. }
  1883. //populate comes after generate, we should be pretty safe in taking
  1884. //already generated additionalData
  1885. if (!(queryName in config.formConfig.additionalData)){
  1886. print(fName+': no additionalData generated for '+queryName);
  1887. return;
  1888. }
  1889. let additionalData=config.formConfig.additionalData[queryName];
  1890. print(fName+': using additionalData '+additionalData);
  1891. if ("isReview" in additionalData){
  1892. generateReviewSection(queryName,queryName,generateReviewSectionCB);
  1893. return;
  1894. }
  1895. let accessMode=config.formConfig.operator+'Mode';
  1896. let aM=entry[accessMode];
  1897. print(fName+': accessMode '+aM);
  1898. if (aM!='GENERATE'){
  1899. let writeMode=entry[accessMode]=='EDIT';
  1900. print(fName+': mode='+writeMode);
  1901. populateTable(queryName,writeMode);
  1902. return;
  1903. }
  1904. //deal with generate
  1905. //
  1906. //already available -> shift to READ mode
  1907. let divTable=queryName+'Table';
  1908. let divObj=config.document.getElementById(divTable);
  1909. let divRev=config.document.getElementById(queryName+'Review');
  1910. let divRLi=config.document.getElementById(queryName+'ReviewList');
  1911. let divGBu=config.document.getElementById(queryName+'GenerateButton');
  1912. print('div GBU: '+divGBu);
  1913. divObj.style.display="block";
  1914. divRev.style.display="block";
  1915. divRLi.style.display="block";
  1916. if (divGBu!=undefined) divGBu.style.display="none";
  1917. let nData=getQuerySnapshot(queryName).rows.length;
  1918. print('['+queryName+']: nrows '+nData);
  1919. if (nData>0){
  1920. populateTable(queryName,0);
  1921. return;
  1922. }
  1923. //hide table
  1924. divObj.style.display="none";
  1925. divRev.style.display="none";
  1926. divRLi.style.display="none";
  1927. if (divGBu!=undefined) divGBu.style.display="block";
  1928. //add buttons?
  1929. //is button already generated?
  1930. //populateTable(entry);
  1931. }
  1932. //******* generateQuery infrastructure *********************
  1933. function onGenerateQuery(queryName){
  1934. let fName='[onGenerateQuery]';
  1935. print(fName+' '+queryName);
  1936. //
  1937. let cfgRows=config.formConfig.generateConfigData.rows;
  1938. // //queryName to queryId?
  1939. let queryId=config.formConfig.fields[queryName].queryId;
  1940. let cfgRow=undefined;
  1941. for (let i=0;i<cfgRows.length;i++){
  1942. if (cfgRows[i].queryId!=queryId) continue;
  1943. cfgRow=cfgRows[i];
  1944. break;
  1945. }
  1946. if (cfgRow==undefined){
  1947. print('generateConfig for queryName['+queryId+']='+queryName+' not found');
  1948. return;
  1949. }
  1950. //add config to the list
  1951. if (!("generateConfig" in config.formConfig)){
  1952. config.formConfig.generateConfig=new Object();
  1953. }
  1954. config.formConfig.generateConfig[queryName]=cfgRow;
  1955. if (!("generateForm" in config.formConfig)){
  1956. config.formConfig.generateForm=new Object();
  1957. }
  1958. //
  1959. let formRows=config.formConfig.formRows;
  1960. let formId=cfgRow.formId;
  1961. for (let i=0;i<formRows.length;i++){
  1962. if (formRows[i].Key==formId) {
  1963. config.formConfig.generateForm[queryName]=formRows[i];
  1964. break;
  1965. }
  1966. }
  1967. //print('XcfgRow '+config.formConfig.generateForm[queryName]);
  1968. //
  1969. // //check if all required datasets were at least saved
  1970. checkGenerationFields(queryName);
  1971. }
  1972. function checkGenerationFields(queryName){
  1973. let fName='[checkGenerationFields]';
  1974. let genForm=config.formConfig.generateForm[queryName];
  1975. let genCfg=config.formConfig.generateConfig[queryName];
  1976. let mailRecipient=genCfg.emailRecipient;
  1977. //list of queries that are part of Registration form
  1978. print(fName);
  1979. print(fName+' setRecipient: '+mailRecipient);
  1980. let formId=genForm.Key;
  1981. print(fName+" Checking form w/id "+formId);
  1982. let selectGenerationRows=selectFormSetupRows(formId);
  1983. //registration rows
  1984. for (let i=0;i<selectGenerationRows.length;i++){
  1985. let row=selectGenerationRows[i];
  1986. let queryId=row.queryName;
  1987. let fQueryName=config.formConfig.queryMap[queryId];
  1988. if (fQueryName==queryName) continue;
  1989. let fQuery=getQuerySnapshot(fQueryName);
  1990. print('Checking '+fQueryName+' nrows: '+fQuery.rows.length);
  1991. if (fQuery.rows.length==0){
  1992. generateError(queryName,fQueryName);
  1993. return;
  1994. }
  1995. }
  1996. generateMessage(queryName,'Vailidation OK');
  1997. print('callback: set recipient: '+mailRecipient);
  1998. let cb=function(){prepareForm(queryName,formId,mailRecipient);};
  1999. generateListEntry(formId,queryName,cb);
  2000. }
  2001. function prepareForm(queryName,formId,mailRecipient){
  2002. let fName="[prepareForm]";
  2003. print(fName+' recipient '+mailRecipient);
  2004. //look for existing registration entry
  2005. let action=function(data){generateForm(data,queryName,mailRecipient);};
  2006. let formFilter=LABKEY.Filter.create('Form',formId);
  2007. let parentCrfFilter=LABKEY.Filter.create('parentCrf',getCRFref());
  2008. let filters=[formFilter,parentCrfFilter];
  2009. cvSelectRows('lists','crfEntry',filters,action,getContainer('data'));
  2010. }
  2011. function generateError(queryName,fQueryName){
  2012. let elName=queryName+'GenerateButton'+'_reportField';
  2013. let el=config.document.getElementById(elName);
  2014. el.innerText='Error: '+fQueryName+' was not set';
  2015. el.style.color='red';
  2016. }
  2017. function generateMessage(queryName,msg){
  2018. let elName=queryName+'GenerateButton'+'_reportField';
  2019. let el=config.document.getElementById(elName);
  2020. el.innerText=msg;
  2021. el.style.color='green';
  2022. }
  2023. function generateForm(data,queryName,mailRecipient){
  2024. let fName='[generateForm]';
  2025. print(fName+' recipient: '+mailRecipient);
  2026. //
  2027. const nData=data.rows.length;
  2028. print(fName+' Registration: '+nData+' rows');
  2029. let formRow=config.formConfig.generateForm[queryName];
  2030. let formCfg=config.formConfig.generateConfig[queryName];
  2031. //we have to generate masterQuery with parentCrf and crfRef
  2032. //and crfEntry with new entryId and parentCrf equal to crfRef
  2033. if (nData>0) {
  2034. generateMessage(queryName,'Registration already generated.');
  2035. return;
  2036. }
  2037. let formId=formRow.Key;
  2038. let formName=formRow.formName;
  2039. let crfBase=config.formConfig.crfEntry;
  2040. let crfEntry=new Object();
  2041. //add new reference
  2042. crfEntry.entryId=Date.now();
  2043. crfEntry.parentCrf=getCRFref();
  2044. crfEntry["Date"]=new Date();
  2045. crfEntry["View"]="[VIEW]";
  2046. crfEntry.formStatus=1;//In progress
  2047. //checks for both field presence (if not in query, undefined) and field value (if not set, null)
  2048. print(fName+' setup status: '+formCfg.formStatus);
  2049. if (formCfg.formStatus){
  2050. crfEntry.formStatus=formCfg.formStatus;
  2051. }
  2052. //get local Id
  2053. let pM=getParticipantManagerObject(config);
  2054. crfEntry[pM.getCrfEntryFieldName()]=pM.getParticipantIdFromCrfEntry();
  2055. // //set other variables
  2056. //requires studyData as part of formConfig
  2057. // let studyData=config.formConfig.studyData;
  2058. print('Adding study: '+crfBase.EudraCTNumber);
  2059. crfEntry.EudraCTNumber=crfBase.EudraCTNumber;
  2060. crfEntry.StudyCoordinator=crfBase.StudyCoordinator;
  2061. crfEntry.StudySponsor=crfBase.StudySponsor;
  2062. crfEntry.RegulatoryNumber=crfBase.RegulatoryNumber;
  2063. //
  2064. // //find sponsor for site
  2065. let site=crfBase.Site;
  2066. let crfSponsors=config.formConfig.crfSponsors;
  2067. let users=config.formConfig.userRows;
  2068. for (let i=0;i<crfSponsors.length;i++){
  2069. //print('Checking for site '+crfSponsors[i].Site);
  2070. if (crfSponsors[i].Site!=site) continue;
  2071. config.formConfig.sponsorId=crfSponsors[i].User;
  2072. //print('Setting id '+config.formConfig.sponsorId);
  2073. //finds first
  2074. break;
  2075. }
  2076. for (let j=0;j<users.length;j++){
  2077. if (config.formConfig.sponsorId!=users[j].UserId) continue;
  2078. config.formConfig.sponsor=users[j];
  2079. //finds first (should be unique)
  2080. break;
  2081. }
  2082. print('Selecting '+config.formConfig.sponsor.DisplayName+' as sponsor');
  2083. //different user than the original form...
  2084. //should be set to the study sponsor
  2085. crfEntry.UserId=config.formConfig.sponsor.UserId;
  2086. crfEntry.Site=site;
  2087. // //set formId to one found through registration search
  2088. crfEntry.Form=formId;
  2089. ////
  2090. let crfStatus=createCrfStatus(crfEntry);
  2091. crfStatus.operator=config.formConfig.operator;
  2092. crfStatus.action='generateForm';
  2093. let cb=function(data){sendEmail(data,mailRecipient,doNothing,formName+' generated');}
  2094. let pass=function(data){cvInsertRows('lists','crfStatus',[crfStatus],cb,getContainer('data'));};
  2095. cvInsertRows('lists','crfEntry',[crfEntry],pass,getContainer('data'));
  2096. }
  2097. //
  2098. function generateListEntry(formId,queryName,cb){
  2099. //check if registration was already generated
  2100. let formRows=config.formConfig.formRows;
  2101. let qForm=undefined;
  2102. for (let i=0;i<formRows.length;i++){
  2103. if (formRows[i].Key!=formId) continue;
  2104. qForm=formRows[i];
  2105. }
  2106. let nData=getQuerySnapshot()[queryName].rows.length;
  2107. if (nData>0) return;
  2108. //create new list entry
  2109. let pM=getParticipantManagerObject(config);
  2110. let e2=new Object();
  2111. e2.crfRef=getCRFref();
  2112. e2.registrationStatus=0;
  2113. e2.submissionDate=new Date();
  2114. e2[pM.getCrfEntryFieldName()]=pM.getParticipantIdFromCrfEntry();
  2115. print('set values');
  2116. cvInsertRows('lists',queryName,[e2],cb,getContainer('data'));
  2117. }
  2118. // ******************** end form generator (Registration) ********************
  2119. //jump to populate table/generate review, etc defined at the begining of the file
  2120. function setContainer(label,container){
  2121. if (!(config.formConfig.hasOwnProperty('container'))){
  2122. config.formConfig.container=new Array();
  2123. }
  2124. config.formConfig.container[label]=container;
  2125. }
  2126. function getContainer(label){
  2127. return config.formConfig.container[label];
  2128. }
  2129. //entry point from generateMasterForm
  2130. function setFormConfig(){
  2131. //add object to store form related data
  2132. config.formConfig=new Object();
  2133. config.formConfig.softwareVersion='T.15.68';
  2134. let debug=true;
  2135. if (debug)
  2136. print("generateMasterForm1");
  2137. //set containers for data and configuration
  2138. //TODO: set this from a query
  2139. //
  2140. setContainer('data',LABKEY.ActionURL.getContainer());
  2141. setContainer('config',LABKEY.ActionURL.getContainer());
  2142. setContainer('CRF',LABKEY.ActionURL.getContainer());
  2143. //this is local data
  2144. cvSelectRows('lists','crfSettings',[],afterSettings,getContainer('CRF'));
  2145. //store form related data to this object
  2146. }
  2147. function convertToDictionary(rows){
  2148. let x=new Array();
  2149. for (let i=0;i<rows.length;i++){
  2150. let n=rows[i]['name'];
  2151. let v=rows[i]['value'];
  2152. x[n]=v;
  2153. }
  2154. return x;
  2155. }
  2156. function convertToAssociatedArray(rows,fieldName="name"){
  2157. let fName="[convertToAssociatedArray]";
  2158. let x=new Object();
  2159. for (let i=0;i<rows.length;i++){
  2160. let n=rows[i][fieldName];
  2161. x[n]=rows[i];
  2162. }
  2163. return x;
  2164. }
  2165. function afterSettings(data){
  2166. config.formConfig.settings=convertToDictionary(data.rows);
  2167. let st=config.formConfig.settings;
  2168. print('afterSettings');
  2169. for (let k in st){
  2170. print('\t'+k+'='+st[k]);
  2171. }
  2172. //if ('dataContainer' in st){
  2173. // setContainer('data',st['dataContainer']);
  2174. //}
  2175. let vname='configContainer';
  2176. if (vname in st){
  2177. setContainer('config',st[vname]);
  2178. }
  2179. print('Config: '+getContainer('config'));
  2180. print('Data: '+getContainer('data'));
  2181. //use first-> we must first establish link to the rigth crf entry
  2182. let filters=[LABKEY.Filter.create('entryId',getCRFrefFirst())];
  2183. cvSelectRows('lists','crfEntry',filters,afterCRFEntry,getContainer('data'));
  2184. }
  2185. function afterCRFEntry(data){
  2186. config.formConfig.crfEntry=data.rows[0];
  2187. print("Setting crfEntry (x) to "+config.formConfig.crfEntry["entryId"]);
  2188. //for empty records or those with parentCrf not set, parentCrf comes up as null
  2189. //nevertheless, with two equal signs, check against undefined also works
  2190. print('parentCrf set to '+config.formConfig.crfEntry.parentCrf);
  2191. collectData();
  2192. }
  2193. function collectData(){
  2194. let targetObject=config.formConfig;
  2195. targetObject.print=print;
  2196. targetObject.getContainer=getContainer;
  2197. let queryArray=new Array();
  2198. //k
  2199. //site
  2200. queryArray.push(makeQuery(targetObject,'config','site','siteData',[]));
  2201. //users
  2202. queryArray.push(makeQuery(targetObject,'CRF','users','userData',[]));
  2203. queryArray[queryArray.length-1].schemaName='core';
  2204. //crfEditors
  2205. queryArray.push(makeQuery(targetObject,'config','crfEditors','crfEditorsData',[]));
  2206. //crfMonitors
  2207. queryArray.push(makeQuery(targetObject,'config','crfMonitors','crfMonitorsData',[]));
  2208. //crfSponsors
  2209. queryArray.push(makeQuery(targetObject,'config','crfSponsors','crfSponsorsData',[]));
  2210. //study static data
  2211. queryArray.push(
  2212. makeQuery(targetObject,'data','crfStaticVariables','crfStaticVariables',[]));
  2213. queryArray.push(makeQuery(targetObject,'data','specialFields','specialFieldsQuery',[]));
  2214. //study
  2215. queryArray.push(makeQuery(targetObject,'data','Study','studyDataAll1',[]));
  2216. let e=queryArray[queryArray.length-1];
  2217. //overload schema name
  2218. e.schemaName='study';
  2219. //make sure variables not part of default view are loaded
  2220. //here we should already have read crfStaticVariables table
  2221. e.columns="SubjectColumnName,EudraCTNumber,StudySponsor";
  2222. e.columns+=",StudyCoordinator,RegulatoryNumber";
  2223. //formStatus
  2224. let varLabel='sourceFormStatus';
  2225. let formStatus=config.formConfig.crfEntry['FormStatus'];
  2226. let formFilter=LABKEY.Filter.create('Key',formStatus);
  2227. queryArray.push(
  2228. makeQuery(targetObject,'config','FormStatus','formStatusData',[formFilter]));
  2229. //crfButtons
  2230. let statusFilter=LABKEY.Filter.create(varLabel,formStatus);
  2231. queryArray.push(
  2232. makeQuery(targetObject,'config','crfButtons','crfButtons',[statusFilter]));
  2233. //Forms
  2234. queryArray.push(makeQuery(targetObject,'config','Forms','formData',[]));
  2235. //FormSetup
  2236. queryArray.push(makeQuery(targetObject,'config','FormSetup','formSetup',[]));
  2237. //generateConfig
  2238. queryArray.push(
  2239. makeQuery(targetObject,'config','generateConfig','generateConfigData',[]));
  2240. //inputLists
  2241. queryArray.push(
  2242. makeQuery(targetObject,'config','inputLists','inputLists',[]));
  2243. //parentCrf
  2244. let parentCrf=config.formConfig.crfEntry['parentCrf'];
  2245. if (parentCrf!=undefined){
  2246. let crfFilter=LABKEY.Filter.create('entryId',parentCrf);
  2247. queryArray.push(makeQuery(targetObject,'data','crfEntry','parentCrfData',[crfFilter]));
  2248. }
  2249. print('running getDataFromQueries');
  2250. getDataFromQueries(queryArray,addStudyData);
  2251. }
  2252. function addStudyData(){
  2253. let fName='addStudyData';
  2254. //convert specialFields to array
  2255. let q=config.formConfig["specialFieldsQuery"].rows;
  2256. config.formConfig.specialFields=convertToAssociatedArray(q,"fieldUID");
  2257. print(fName);
  2258. let queryArray=new Array();
  2259. let targetObject=config.formConfig;
  2260. targetObject.print=print;
  2261. targetObject.getContainer=getContainer;
  2262. //study
  2263. queryArray.push(makeQuery(targetObject,'data','Study','studyDataAll',[]));
  2264. //queryArray.push(makeQuery('data','Study','studyDataAll',[]));
  2265. let e=queryArray[queryArray.length-1];
  2266. //overload schema name
  2267. e.schemaName='study';
  2268. //make sure variables not part of default view are loaded
  2269. //here we should already have read crfStaticVariables table
  2270. let staticVarRows=config.formConfig['crfStaticVariables'].rows;
  2271. let columnModel=""
  2272. for (let i=0;i<staticVarRows.length;i++){
  2273. if (i>0) columnModel+=',';
  2274. columnModel+=staticVarRows[i]['staticVariable'];
  2275. }
  2276. e.columns=columnModel;
  2277. //also collect ids already in study
  2278. //registrationQuery should be a dataset
  2279. //since monitors can review late, it might be profitable to use lists
  2280. //rather than study
  2281. let regQueryPars=parseVariables(config.formConfig.settings['registrationQuery']);
  2282. let regQuery=regQueryPars['query'];
  2283. let regSchema='study';
  2284. if ('schema' in regQueryPars){
  2285. regSchema=regQueryPars['schema'];
  2286. }
  2287. queryArray.push(makeQuery(targetObject,'data',regQuery,'registrationData',[]));
  2288. queryArray[queryArray.length-1].schemaName=regSchema;
  2289. getDataFromQueries(queryArray,fcontinue);
  2290. }
  2291. function selectFormSetupRows(formId){
  2292. let formSetupRows=new Array();
  2293. let allRows=config.formConfig.formSetup.rows;
  2294. for (let i=0;i<allRows.length;i++){
  2295. let formEntry=allRows[i];
  2296. if (formEntry.formName==formId)
  2297. formSetupRows.push(formEntry);
  2298. }
  2299. return formSetupRows;
  2300. }
  2301. function fcontinue(){
  2302. //debug
  2303. let fName='[fcontinue]';
  2304. let varRows=config.formConfig['crfStaticVariables'].rows;
  2305. let studyVars=config.formConfig['studyDataAll'].rows[0];
  2306. for (let i=0;i<varRows.length;i++){
  2307. let vName=varRows[i].staticVariable;
  2308. print(fName+' '+vName+': '+studyVars[vName]);
  2309. }
  2310. //parse site
  2311. config.formConfig.siteRows=config.formConfig.siteData.rows;
  2312. let sRows=config.formConfig.siteRows;
  2313. for (let i=0;i<sRows.length;i++){
  2314. let siteId=sRows[i].siteNumber;
  2315. print('site '+siteId);
  2316. if (siteId==config.formConfig.crfEntry.Site){
  2317. config.formConfig.currentSite=sRows[i];
  2318. break;
  2319. }
  2320. }
  2321. //config.formConfig.site=data.rows[0];
  2322. print("Setting site name to "+config.formConfig.currentSite.siteName);
  2323. //study
  2324. config.formConfig.studyData=config.formConfig.studyDataAll.rows[0];
  2325. print("XSetting participantField to "+
  2326. config.formConfig.studyData["SubjectColumnName"]);
  2327. config.formConfig.crfEditors=config.formConfig.crfEditorsData.rows;
  2328. config.formConfig.crfMonitors=config.formConfig.crfMonitorsData.rows;
  2329. config.formConfig.crfSponsors=config.formConfig.crfSponsorsData.rows;
  2330. config.formConfig.userRows=config.formConfig.userData.rows;
  2331. let uRows=config.formConfig.userRows;
  2332. for (let i=0;i<uRows.length;i++){
  2333. let userId=uRows[i].UserId;
  2334. if (userId==config.formConfig.crfEntry.UserId){
  2335. config.formConfig.user=uRows[i];
  2336. break;
  2337. }
  2338. }
  2339. //config.formConfig.user=data.rows[0];
  2340. print("Setting user to "+config.formConfig.user["DisplayName"]);
  2341. let fsRows=config.formConfig.formStatusData.rows;
  2342. config.formConfig.formStatus=fsRows[0].formStatus;
  2343. config.formConfig.operator=config.role;
  2344. //config.formConfig.operator=fsRows[0].operator;
  2345. print('Setting operator to: '+config.formConfig.operator);
  2346. config.formConfig.formRows=config.formConfig.formData.rows;
  2347. //point formId to point to form set in crfEntry
  2348. config.formConfig.formId=config.formConfig.crfEntry['Form'];
  2349. //old setting, set from URL in visit.html
  2350. let formId=config.formId;
  2351. //new setting, set from crfEntry
  2352. formId=config.formConfig.formId;
  2353. let formRows=config.formConfig.formRows;
  2354. //filter out the current form
  2355. for (let i=0;i<formRows.length;i++){
  2356. if (formRows[i].Key==formId){
  2357. config.formConfig.form=formRows[i];
  2358. break;
  2359. }
  2360. }
  2361. config.formConfig.formSetupRows=selectFormSetupRows(formId);
  2362. print("Number of datasets for form ["+formId+"]: "+
  2363. config.formConfig.formSetupRows.length);
  2364. let fields=config.formConfig.formSetup.metaData.fields;
  2365. //get the lookup for queryName column
  2366. let formQueryName='queryName';
  2367. let field="NONE";
  2368. for (f in fields){
  2369. if (fields[f]['name']!=formQueryName) continue;
  2370. field=fields[f];
  2371. break;
  2372. }
  2373. let lookup=field.lookup;
  2374. print("Getting dataset names from "+lookup.queryName);
  2375. //inputLists should be in configuration container
  2376. cvSelectRows(lookup.schemaName,lookup.queryName,[],afterFormDatasets,getContainer('config'));
  2377. }
  2378. function afterFormDatasets(data){
  2379. print('afterFormDatasets: '+data.rows.length);
  2380. config.formConfig.formDatasets=data;//inputLists
  2381. config.formConfig.fields=new Object();
  2382. config.formConfig.queryMap=new Object();
  2383. config.formConfig.additionalData=new Object();
  2384. let rows=config.formConfig.formSetupRows;
  2385. //should skip report only rows
  2386. for (let i=0;i<rows.length;i++){
  2387. let entry=rows[i];
  2388. let reviewField=(entry['showFlag']=='REVIEW');
  2389. //is the operator set yet?
  2390. let accessMode=config.formConfig.operator+'Mode';
  2391. let skipField=(entry[accessMode]=="NONE");
  2392. let queryId=entry['queryName'];
  2393. let lookupRows=config.formConfig.formDatasets.rows;
  2394. print('QueryID['+i+']='+queryId);
  2395. let dentry;
  2396. for (let j=0;j<lookupRows.length;j++){
  2397. if (queryId!=lookupRows[j]['Key']) continue;
  2398. dentry=lookupRows[j];
  2399. break;
  2400. }
  2401. let qName=dentry['queryName'];
  2402. //update list of dataset formConfig is observing (fields/queryMap)
  2403. while (1){
  2404. //review contains no data
  2405. if (reviewField) break;
  2406. if (skipField) break;
  2407. //already in fields
  2408. if (qName in config.formConfig.fields) break;
  2409. config.formConfig.fields[qName]=new Object();
  2410. break;
  2411. }
  2412. while(1){
  2413. //already done
  2414. if (queryId in config.formConfig.queryMap) break;
  2415. config.formConfig.queryMap[queryId]=qName;
  2416. break;
  2417. }
  2418. if (reviewField) continue;
  2419. if (skipField) continue;
  2420. //only do this for real lists
  2421. let field=config.formConfig.fields[qName];
  2422. field.title=entry['title'];
  2423. field.queryId=queryId;
  2424. }
  2425. print("List of datasets in form : ");
  2426. for (f in config.formConfig.fields){
  2427. let field=config.formConfig.fields[f];
  2428. print("\t"+f+" ID: "+field.queryId+' title '+field.title);
  2429. }
  2430. afterConfig();
  2431. }
  2432. //>>>>>>>>>>>>>>>>>new>>>>>>>>>>>>
  2433. function setDataLayout(cb){
  2434. let fName='[setDataLayout]';
  2435. print(fName);
  2436. let rowsSetup=config.formConfig.formSetupRows;
  2437. let queryArray=new Array();
  2438. let dS=getLayoutObject();//reference only
  2439. let qList=getQueryList();
  2440. let qMap=config.formConfig.queryMap;
  2441. //config.formConfig.lookup=new Object();
  2442. for (let i=0;i<rowsSetup.length;i++){
  2443. let entry=rowsSetup[i];
  2444. //skip review rows
  2445. if (entry['showFlag']=='REVIEW')
  2446. continue;
  2447. let queryId=entry['queryName'];
  2448. let q=qMap[queryId];
  2449. queryArray.push(makeQuery(dS,'data',q,q,[]));
  2450. qList[q]=0;
  2451. print(fName+' adding '+q);
  2452. if (entry['showQuery']!="NONE"){
  2453. let sq=entry['showQuery'];
  2454. queryArray.push(makeQuery(dS,'data',sq,sq,[]));
  2455. qList[sq]=0;
  2456. print(fName+' adding '+sq);
  2457. }
  2458. }
  2459. //always add reviews
  2460. let q='reviewComments';
  2461. queryArray.push(makeQuery(dS,'data',q,q,[]));
  2462. qList[q]=0;
  2463. let action=function(){processLayout(cb);};
  2464. getDataFromQueries(queryArray,action);
  2465. }
  2466. function findTitle(queryName){
  2467. //find by name from formDatasets
  2468. //and set associated title as title
  2469. let rows=config.formConfig.formDatasets.rows;
  2470. for (let i=0;i<rows.length;i++){
  2471. let entry=rows[i];
  2472. if (entry['queryName']!=queryName) continue;
  2473. return entry['title'];
  2474. }
  2475. return "NONE";
  2476. }
  2477. //this happens after the for loop, so all dataQueries objects are set
  2478. function processLayout(cb){
  2479. let fName='[processLayout]';
  2480. let qList=getQueryList();
  2481. //for layouts
  2482. let queryArray=new Array();
  2483. let targetObject=getLookupObject();
  2484. let lookupSet=new Object();
  2485. for (let q in qList){
  2486. let qobject=getQueryLayout(q);
  2487. print(fName+" inspecting layout for "+q+" "+qobject);
  2488. qobject.fields=qobject.metaData.fields;
  2489. qobject.title=findTitle(q);
  2490. //check for lookups
  2491. for (let f in qobject.fields){
  2492. //anything else is simple but lookup
  2493. let field=qobject.fields[f];
  2494. if (!("lookup" in field)) continue;
  2495. let lookup=field.lookup;
  2496. let qObject=getLookup(lookup.queryName);
  2497. if (qObject) continue;
  2498. //add to list
  2499. let qName=lookup.queryName;
  2500. let qCode=qName+':'+lookup.keyColumn+':'+lookup.displayColumn;
  2501. let e=makeQuery(targetObject,'data',qName,qCode,[]);
  2502. //adjust minor settings
  2503. if (lookup.containerPath) e.containerPath=lookup.containerPath;
  2504. e.schemaName=lookup.schemaName;
  2505. e.columns=lookup.keyColumn+','+lookup.displayColumn;
  2506. lookupSet[qCode]=e;
  2507. print(fName+' inserting '+qCode);
  2508. }
  2509. }
  2510. for (let x in lookupSet){
  2511. queryArray.push(lookupSet[x]);
  2512. print(fName+' adding '+x);
  2513. for (let v in lookupSet[x]){
  2514. print(fName+' value ['+v+'] '+lookupSet[x][v]);
  2515. }
  2516. }
  2517. //print(fName+' print '+targetObject.print);
  2518. let action=function(){processLookup(cb);};
  2519. print(fName+' getDataFromQueries');
  2520. getDataFromQueries(queryArray,action);
  2521. print(fName+' getDataFromQueries done');
  2522. }
  2523. function processLookup(cb){
  2524. let fName="[processLookup]";
  2525. let obj=getLookupObject();
  2526. for (let q in obj){
  2527. print(fName+" "+q);
  2528. let a=q.split(':');
  2529. if (a.length<3) continue;
  2530. let lookupName=a[0];
  2531. let key=a[1];
  2532. let val=a[2];
  2533. obj[lookupName]=new Object();
  2534. print(fName+' adding ['+lookupName+'] '+key+'/'+val);
  2535. let lObject=obj[lookupName];
  2536. lObject.LUT=new Array();//key to value
  2537. lObject.ValToKey=new Array();//value to key
  2538. lObject.keyColumn=key
  2539. lObject.displayColumn=val;
  2540. let qRows=obj[q].rows;
  2541. for (let i=0;i<qRows.length;i++){
  2542. let r=qRows[i];
  2543. print(fName+' LUT ['+r[key]+'] '+r[val]);
  2544. lObject.LUT[r[key]]=r[val];
  2545. lObject.ValToKey[r[val]]=r[key];
  2546. }
  2547. }
  2548. cb();
  2549. }
  2550. function setData(cb){
  2551. fName='[setData]';
  2552. let crfMatch=getCRFref();
  2553. let parentCrf=config.formConfig.crfEntry['parentCrf'];
  2554. if (parentCrf!=undefined) crfMatch=parentCrf;
  2555. print(fName+' form crf ['+getCRFref()+'] matching for crfRef='+crfMatch);
  2556. let queryArray=new Array();
  2557. let targetObject=getSnapshotObject();
  2558. //collect data and execute callback cb for queries in cb.queryList
  2559. let qList=getQueryList();
  2560. for (q in qList){
  2561. let filters=[LABKEY.Filter.create("crfRef",crfMatch)];
  2562. queryArray.push(makeQuery(targetObject,'data',q,q,filters));
  2563. }
  2564. getDataFromQueries(queryArray,cb);
  2565. }
  2566. function uploadFile(inputElement,context){
  2567. //context should have ID and dirName attributes;
  2568. //path will be dirName/ID/fieldName_ID.suf
  2569. //where suf is identical to localPath content picked from
  2570. //inputElement
  2571. print('uploadFile: '+inputElement.value+'/');
  2572. if (inputElement.type=="text") return;
  2573. print('uploadFile: '+inputElement.files+'/');
  2574. print('uploadFile: '+inputElement.files.length+'/');
  2575. if (inputElement.files.length>0){
  2576. let file=inputElement.files[0];
  2577. print('uploadFile: '+inputElement.value+'/'+file.size);
  2578. }
  2579. let url=LABKEY.ActionURL.getBaseURL();
  2580. url+='_webdav';
  2581. url+=LABKEY.ActionURL.getContainer();
  2582. url+='/@files';
  2583. url+='/'+context['dirName'];
  2584. print('uploadFile url: '+url);
  2585. let uploadConfig=new Object();
  2586. uploadConfig.inputElement=inputElement;
  2587. uploadConfig.context=context;
  2588. uploadConfig.url=url;
  2589. uploadConfig.success=afterBaseDir;
  2590. uploadConfig.failure=tryMakeDir;
  2591. webdavCheck(uploadConfig);
  2592. }
  2593. function afterBaseDir(cfg){
  2594. print('afterBaseDir');
  2595. cfg.url+='/'+cfg.context['ID'];
  2596. cfg.success=afterIDDir;
  2597. cfg.failure=tryMakeDir;
  2598. webdavCheck(cfg);
  2599. }
  2600. function afterIDDir(cfg){
  2601. print('afterIDDir');
  2602. if (cfg.inputElement.files.length==0){
  2603. print('No files found');
  2604. return;
  2605. }
  2606. let file=cfg.inputElement.files[0];
  2607. print('Uploading '+file.name);
  2608. let suf=file.name.split('.').pop();
  2609. cfg.url+='/'+cfg.context['ID']+'.'+suf;
  2610. cfg.success=afterUpload;
  2611. cfg.failure=onFailure;
  2612. cfg.data=file;
  2613. webdavPut(cfg);
  2614. }
  2615. function afterUpload(cfg){
  2616. print('afterUpload');
  2617. }
  2618. function tryMakeDir(cfg){
  2619. print('tryMakeDir '+cfg.url);
  2620. cfg.failure=onFailure;
  2621. webdavMakeDir(cfg);
  2622. }
  2623. function request(cfg,verb,data){
  2624. print('request['+verb+'] '+cfg.url);
  2625. let connRequest=new XMLHttpRequest();
  2626. connRequest.addEventListener("loadend",
  2627. function(){checkResponse(connRequest,cfg);});
  2628. connRequest.open(verb, cfg.url);
  2629. connRequest.send(data);
  2630. //print('request['+verb+'] sent');
  2631. }
  2632. function checkResponse(xrq,cfg){
  2633. //print('checkResponse: readyState '+xrq.readyState);
  2634. //print('checkResponse: status '+xrq.status);
  2635. if (xrq.status<400) {
  2636. //client errors 400-499
  2637. //server errors 500-599
  2638. cfg.success(cfg);
  2639. return;
  2640. }
  2641. cfg.status=xrq.status;
  2642. cfg.failure(cfg);
  2643. }
  2644. function webdavMakeDir(cfg){ request(cfg,'MKCOL',null);}
  2645. function webdavCheck(cfg) { request(cfg,'GET',null);}
  2646. function webdavPut(cfg) { request(cfg,'PUT',cfg.data);}
  2647. function onFailure(cfg){
  2648. print('request failed with status='+cfg.status);
  2649. }