crfVisit.js 95 KB

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