crfVisit.js 97 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620
  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. let fc=new Object();
  1239. let pM=getParticipantManagerObject(config);
  1240. fc.participantId=pM.getParticipantIdFromCrfEntry();
  1241. print(fName+' id '+fc.participantId);
  1242. afterParticipantId(fc);
  1243. }
  1244. function onDatabaseUpload1(){
  1245. let fName='[onDatabaseUpload]';
  1246. print(fName);
  1247. config.upload=new Object();
  1248. //figure out the participantId
  1249. let masterQueryId=config.formConfig.form["masterQuery"];
  1250. print(fName+': master query: '+masterQueryId);
  1251. let pidClass=new Object();
  1252. pidClass.afterId=afterParticipantId;
  1253. //use stored name of participantField
  1254. //for migrating data from lists to study
  1255. //this is to avoid conflicts in column assignments
  1256. //since datasets contain all fields of a list plus
  1257. //default fields of which participantId is one
  1258. pidClass.participantField=config.registrationParticipantIdField;
  1259. let qconfig=new Object();
  1260. qconfig.queryName=config.formConfig.queryMap[masterQueryId];
  1261. //queryMap holds mapping for queries in visit;
  1262. //masterQuery should be one of them, so this is safe.
  1263. qconfig.schemaName='lists';
  1264. qconfig.containerPath=getContainer('data');
  1265. qconfig.filterArray=[LABKEY.Filter.create('crfRef',getCRFref())];
  1266. qconfig.success=function(data){afterRegistration(data,pidClass);};
  1267. LABKEY.Query.selectRows(qconfig);
  1268. //waitForCompleteUpload(config);//
  1269. }
  1270. function afterRegistration(data,fc){
  1271. let fName='[afterRegistration/'+data.queryName+']';
  1272. print(fName+": rows:"+data.rows.length);
  1273. fc.registration=data;
  1274. let registrationData=fc.registration;
  1275. clearErr();
  1276. if (registrationData.rows.length!=1){
  1277. let msg=fName+": ERROR: Found "+registrationData.rows.length;
  1278. msg+=" registration entries for crfrefid "+getCRFref();
  1279. print(msg);
  1280. fc.afterId(fc);
  1281. return;
  1282. }
  1283. print(fName+'registration participant field: '+fc.participantField);
  1284. fc.participantId=registrationData.rows[0][fc.participantField];
  1285. //could be a lookup field (particularly for studies)
  1286. print('ID: '+fc.participantId);
  1287. let fields=registrationData.metaData.fields;
  1288. let field="NONE";
  1289. for (f in fields){
  1290. if (fields[f]["name"]==fc.participantField)
  1291. field=fields[f];
  1292. }
  1293. if ("lookup" in field){
  1294. let pid=fc.participantId;
  1295. print("Using lookup for participantId: "+pid);
  1296. let lookup=field["lookup"];
  1297. print("Lookup: ["+lookup.schemaName+','+lookup.queryName+']');
  1298. let qconfig=new Object();
  1299. //should point to data container
  1300. qconfig.containerPath=getContainer('data');
  1301. qconfig.schemaName=lookup.schemaName;
  1302. qconfig.queryName=lookup.queryName;
  1303. qconfig.filterArray=
  1304. [LABKEY.Filter.create(lookup.keyColumn,pid)];
  1305. qconfig.success=function(data){
  1306. afterRegistrationLookup(data,lookup.displayColumn,fc)};
  1307. LABKEY.Query.selectRows(qconfig);
  1308. }
  1309. else{
  1310. //afterParticipantId(configUpload);
  1311. fc.afterId(fc);
  1312. }
  1313. }
  1314. function afterRegistrationLookup(data,displayColumn,fc){
  1315. print("afterRegistrationLookup");
  1316. let entry=data.rows[0];
  1317. fc.participantId=entry[displayColumn];
  1318. print('Setting to '+fc.participantId);
  1319. fc.afterId(fc);
  1320. //afterParticipantId(configUpload);
  1321. }
  1322. function afterParticipantId(fc){
  1323. print("Setting participantId to "+fc.participantId);
  1324. config.upload.participantId=fc.participantId;
  1325. //another select rows to update all queries from setup
  1326. //just use registration for test
  1327. let formSetupRows=config.formConfig.formSetupRows;
  1328. config.upload.queries=new Array();
  1329. print("Form rows: "+formSetupRows.length);
  1330. for (let i=0;i<formSetupRows.length;i++){
  1331. let entry=formSetupRows[i];
  1332. //skip reviews
  1333. if (entry.showFlag=="REVIEW") continue;
  1334. //use lookup table to convert from id to name
  1335. let queryName=config.formConfig.queryMap[entry.queryName];
  1336. config.upload.queries.push({queryName:queryName,queryStatus:"QUEUED"});
  1337. print('form ['+i+']='+queryName+' '+entry.showFlag+'/'+entry.showQuery);
  1338. if (entry.showQuery=="NONE")
  1339. continue;
  1340. config.upload.queries.push({queryName:entry.showQuery,queryStatus:"QUEUED"});
  1341. }
  1342. //add reviews
  1343. config.upload.queries.push({queryName:"reviewComments",queryStatus:"QUEUED"});
  1344. config.upload.queryId=0;
  1345. copyToDataset();
  1346. }
  1347. function copyToDataset(){
  1348. let fName='[copyToDataset]: ';
  1349. print(fName+'['+config.upload.queryId+'/'+config.upload.queries.length+']');
  1350. //watch dog + scheduler
  1351. //
  1352. //watchdog part
  1353. if (config.upload.queryId==config.upload.queries.length) {
  1354. print(fName+'completing');
  1355. let targetStatus=config.formConfig.targetStatus['onDatabaseUpload'];
  1356. let targetRecipient=config.formConfig.targetRecipient['onDatabaseUpload'];
  1357. let action=new Object();
  1358. action.name='onDatabaseUpload';
  1359. action.cb=function(data){sendEmail(data,targetRecipient,redirect,'Form uploaded');}
  1360. updateFlag(targetStatus,action);//Approved
  1361. return;
  1362. }
  1363. //scheduler
  1364. let queryName=config.upload.queries[config.upload.queryId].queryName;
  1365. print("copyToDataset["+config.upload.queryId+"/"+
  1366. config.upload.queries.length+"]: "+queryName);
  1367. let qconfig=new Object();
  1368. qconfig.queryName=queryName;
  1369. qconfig.schemaName="lists";
  1370. qconfig.containerPath=getContainer('data');
  1371. qconfig.filterArray=[LABKEY.Filter.create('crfRef',getCRFref())];
  1372. qconfig.success=afterListData;
  1373. LABKEY.Query.selectRows(qconfig);
  1374. }
  1375. function afterListData(data){
  1376. let fName='[afterListData]: ';
  1377. let queryName=config.upload.queries[config.upload.queryId].queryName;
  1378. print(fName+" ["+queryName+"/list]: "+data.rows.length+" entries");
  1379. config.upload.queries[config.upload.queryId].listData=data;
  1380. let id=config.upload.participantId;
  1381. let qconfig=new Object();
  1382. qconfig.queryName=queryName;
  1383. qconfig.schemaName="study";
  1384. qconfig.containerPath=getContainer('data');
  1385. qconfig.filterArray=[LABKEY.Filter.create('crfRef',getCRFref())];
  1386. qconfig.filterArray.push(LABKEY.Filter.create('ParticipantId',id));
  1387. qconfig.success=afterStudyData;
  1388. LABKEY.Query.selectRows(qconfig);
  1389. }
  1390. function afterStudyData(data){
  1391. let fName='[afterStudyData]: ';
  1392. let queryObj=config.upload.queries[config.upload.queryId];
  1393. queryObj.studyData=data;
  1394. let msg=fName+"["+queryObj.queryName+"/study]: "+data.rows.length+" entries";
  1395. print(msg);
  1396. let listRows=queryObj.listData.rows;
  1397. //skip uploading an empty set
  1398. if (listRows.length==0){
  1399. printErr("List "+queryObj.queryName+" empty.");
  1400. queryObj.queryStatus="DONE";
  1401. config.upload.queryId+=1;
  1402. //back to watchdog
  1403. copyToDataset();
  1404. return;
  1405. }
  1406. let studyRows=queryObj.studyData.rows;
  1407. for (let i=0;i<studyRows.length;i++){
  1408. let entry=studyRows[i];
  1409. //
  1410. if (! (i<listRows.length) ) continue;
  1411. let entryList=listRows[i];
  1412. //keeps study only variables (ParticipantId, SequenceNum)
  1413. for (let f in entryList) {
  1414. entry[f]=entryList[f];
  1415. print(fName+"Copying ["+f+"]: "+entry[f]+"/"+entryList[f]);
  1416. }
  1417. }
  1418. print(fName+' copying completed');
  1419. if (studyRows.length>0) {
  1420. let qconfig=new Object();
  1421. qconfig.queryName=queryObj.queryName;
  1422. qconfig.schemaName="study";
  1423. qconfig.rows=studyRows;
  1424. qconfig.containerPath=getContainer('data');
  1425. qconfig.success=afterStudyUpload;
  1426. LABKEY.Query.updateRows(qconfig);
  1427. print(fName+'updateRows sent');
  1428. }
  1429. else{
  1430. let data=new Object();
  1431. data.rows=new Array();
  1432. afterStudyUpload(data);
  1433. }
  1434. }
  1435. function afterStudyUpload(data){
  1436. let fName='[afterStudyUpload] ';
  1437. print(fName);
  1438. //let participantField=config.participantField;
  1439. let participantField=config.formConfig.studyData["SubjectColumnName"];
  1440. print(fName+' participantField: '+participantField);
  1441. let queryObj=config.upload.queries[config.upload.queryId];
  1442. let queryName=queryObj.queryName;
  1443. printErr("Updated "+data.rows.length+" rows to "+queryName);
  1444. let studyRows=queryObj.studyData.rows;
  1445. let listRows=queryObj.listData.rows;
  1446. let rows=new Array();
  1447. //also updating existing rows, if they exist
  1448. for (let i=studyRows.length;i<listRows.length;i++){
  1449. let entry=listRows[i];
  1450. //make sure you have the participantField right
  1451. //
  1452. entry[participantField]=config.upload.participantId;
  1453. entry.crfRef=getCRFref();
  1454. entry.SequenceNum=getCRFref();
  1455. entry.SequenceNum=entry.SequenceNum % 1000000000;
  1456. if (listRows.length>1){
  1457. entry.SequenceNum+=i/100;
  1458. }
  1459. print( "Adding sequence number "+entry.SequenceNum);
  1460. rows.push(entry);
  1461. }
  1462. if (rows.length>0){
  1463. let qconfig=new Object();
  1464. qconfig.queryName=queryName;
  1465. qconfig.schemaName="study";
  1466. qconfig.containerPath=getContainer('data');
  1467. qconfig.success=afterListUpload;
  1468. qconfig.rows=rows;
  1469. LABKEY.Query.insertRows(qconfig);
  1470. }
  1471. else{
  1472. let data=new Object();
  1473. data.rows=rows;
  1474. afterListUpload(data);
  1475. }
  1476. }
  1477. function afterListUpload(data){
  1478. let queryObj=config.upload.queries[config.upload.queryId];
  1479. let queryName=queryObj.queryName;
  1480. printErr("Inserted "+data.rows.length+" rows to "+queryName);
  1481. queryObj.queryStatus="DONE";
  1482. config.upload.queryId+=1;
  1483. copyToDataset();
  1484. }
  1485. //*************************update for further review *************************
  1486. function onUpdateForReview(){
  1487. let targetStatus=config.formConfig.targetStatus['onUpdateForReview'];
  1488. let targetRecipient=config.formConfig.targetRecipient['onUpdateForReview'];
  1489. let action=new Object();
  1490. action.name='onUpdateForReview';
  1491. action.cb=function(data){sendEmail(data,targetRecipient,redirect,'Form updated for review');};
  1492. updateFlag(targetStatus,action);
  1493. }
  1494. function updateFlag(flag,action){
  1495. let fName='[updateFlag 1]';
  1496. let debug=true;
  1497. let entry=config.formConfig.crfEntry;
  1498. entry.FormStatus=flag;
  1499. let uId=config.formConfig.currentUser.UserId;
  1500. entry[config.formConfig.operator]=uId;
  1501. print(fName+': Form: '+entry.Form);
  1502. print(fName+": set form status to "+entry.FormStatus);
  1503. let qconfig=new Object();
  1504. qconfig.schemaName='lists';
  1505. qconfig.queryName='crfEntry';
  1506. qconfig.containerPath=getContainer('data');
  1507. qconfig.rows=[entry];
  1508. //qconfig.success=function(data){completeWithFlag(data,flag);}
  1509. qconfig.success=function(data){completeWithFlag(data,action);};
  1510. LABKEY.Query.updateRows(qconfig);
  1511. }
  1512. function completeWithFlag(data,action){
  1513. let fName='[completeWithFlag]';
  1514. print(fName+': nrows '+data.rows.length);
  1515. let fentry=data.rows[0];
  1516. print(fName+': form status '+fentry.FormStatus);
  1517. print(fName+': form '+fentry.Form);
  1518. let entry=new Object();
  1519. entry.entryId=getCRFref();
  1520. entry.submissionDate=new Date();
  1521. entry.FormStatus=fentry.FormStatus;
  1522. entry.User=config.formConfig.currentUser.UserId;
  1523. entry.Form=fentry.Form;
  1524. entry.operator=config.formConfig.operator;
  1525. entry.action=action.name;
  1526. let qconfig=new Object();
  1527. qconfig.schemaName='lists';
  1528. qconfig.queryName='crfStatus';
  1529. qconfig.containerPath=getContainer('data');
  1530. qconfig.rows=[entry];
  1531. //qconfig.success=function(data){completeWithFlag(data,flag);}
  1532. qconfig.success=action.cb;
  1533. LABKEY.Query.insertRows(qconfig);
  1534. }
  1535. //************************************************ submit *******************************************
  1536. function onSubmit(){
  1537. //update list storage and change status
  1538. let debug=true;
  1539. hideErr();
  1540. clearErr();
  1541. printErr("onSubmit");
  1542. setData(verifyData);
  1543. }
  1544. function verifyData(){
  1545. let queries=config.formConfig.dataQueries;
  1546. for (q in queries){
  1547. let qData=queries[q];
  1548. if (q=="reviewComments") continue;
  1549. //if it doesn't have additionalData, it is a sub query
  1550. if (!(q in config.formConfig.additionalData))
  1551. continue;
  1552. if (qData.rows.length<1){
  1553. printErr('Missing entry for query '+q);
  1554. return false;
  1555. }
  1556. }
  1557. let targetStatus=config.formConfig.targetStatus['onSubmit'];
  1558. let targetRecipient=config.formConfig.targetRecipient['onSubmit'];
  1559. print('verifyStatus: targetStatus: '+targetStatus);
  1560. let fName='verifyStatus';
  1561. //useful for debug
  1562. //let finalStep=doNothing;
  1563. //production mode
  1564. let finalStep=redirect;
  1565. let action=new Object();
  1566. action.name='onSubmit';
  1567. action.cb=function(data){sendEmail(data,targetRecipient,finalStep,'Form sumbitted');};
  1568. updateFlag(targetStatus,action);
  1569. }
  1570. function getEmail(recipientCode){
  1571. print('getEmail w/'+recipientCode);
  1572. let recipients=new Array();
  1573. let typeTo=LABKEY.Message.recipientType.to;
  1574. let create=LABKEY.Message.createRecipient;
  1575. let currentUser=config.formConfig.currentUser;
  1576. let formCreator=config.formConfig.formCreator;
  1577. let currentSite=config.formConfig.currentSite;
  1578. let userRows=config.formConfig.userRows;
  1579. let parentUser=undefined;
  1580. if ("parentCrfData" in config.formConfig){
  1581. let parentCrf=config.formConfig.parentCrfData;
  1582. parentUser=getUser(parentCrf.rows[0].UserId,'parentUser');
  1583. }
  1584. let recipientCategories=recipientCode.split(',');
  1585. for (let i=0;i<recipientCategories.length;i++){
  1586. let recipient=recipientCategories[i];
  1587. print('Checking '+recipient);
  1588. if (recipient=='crfEditor'){
  1589. print('Adding :'+formCreator.Email);
  1590. recipients.push(create(typeTo,formCreator.Email));
  1591. if (parentUser==undefined) continue;
  1592. print('Adding :'+parentUser.Email);
  1593. recipients.push(create(typeTo,parentUser.Email));
  1594. continue;
  1595. }
  1596. //Monitor or Sponsor
  1597. let fList=recipient+'s';
  1598. let fRows=config.formConfig[fList];
  1599. for (let i=0;i<fRows.length;i++){
  1600. print('Checking '+fRows[i].User+'/'+fRows[i].Site);
  1601. if (fRows[i].Site!=currentSite.siteNumber) continue;
  1602. for (let j=0;j<userRows.length;j++){
  1603. if (userRows[j].UserId!=fRows[i].User) continue;
  1604. print('Adding :'+userRows[j].Email);
  1605. recipients.push(create(typeTo,userRows[j].Email));
  1606. break;
  1607. }
  1608. }
  1609. }
  1610. return recipients;
  1611. }
  1612. function sendEmail(data,recipient='crfEditor',cb=redirect,subj='Form submitted'){
  1613. print('sendEmail; recipient: '+recipient);
  1614. let st=config.formConfig.settings;
  1615. let cvar='sendEmail';
  1616. if (cvar in st){
  1617. print(cvar+' set to '+st[cvar]);
  1618. if (st[cvar]=='FALSE'){
  1619. print('Skipping sending emails');
  1620. redirect();
  1621. return;
  1622. }
  1623. }
  1624. print('send email '+data.rows.length);
  1625. let crf=data.rows[0]['entryId'];
  1626. let formId=data.rows[0]['Form'];
  1627. let link=LABKEY.ActionURL.getBaseURL();
  1628. link+=LABKEY.ActionURL.getContainer();
  1629. link+='/crf-visit.view?';
  1630. link+='entryId='+crf;
  1631. link+='&formId='+formId;
  1632. link+='&role='+recipient;
  1633. //debug
  1634. let recipients=getEmail(recipient);
  1635. //from crfManagers list
  1636. let typeHtml=LABKEY.Message.msgType.html;
  1637. let typePlain=LABKEY.Message.msgType.plain;
  1638. let msg1=LABKEY.Message.createMsgContent(typePlain,link);
  1639. //let cb=doNothing;
  1640. //let cb=redirect;
  1641. LABKEY.Message.sendMessage({
  1642. msgFrom:'labkey@fmf.uni-lj.si',
  1643. msgSubject:subj,
  1644. msgRecipients:recipients,
  1645. msgContent:[msg1],
  1646. success: cb
  1647. });
  1648. }
  1649. function hideErr(){
  1650. let el=config.document.getElementById("errorDiv");
  1651. el.style.display="none";
  1652. }
  1653. function clearErr(){
  1654. let el=config.document.getElementById("errorTxt");
  1655. el.value="";
  1656. }
  1657. function showErr(){
  1658. let el=config.document.getElementById("errorDiv");
  1659. el.style.display="block";
  1660. }
  1661. function printErr(msg){
  1662. showErr();
  1663. el=config.document.getElementById("errorTxt");
  1664. el.style.color="red";
  1665. el.value+="\n"+msg;
  1666. }
  1667. //**************************************************
  1668. //
  1669. function onRemoveCRF(){
  1670. let debug=true;
  1671. if (debug){
  1672. print("Removing CRF");
  1673. }
  1674. let selectRows=new Object();
  1675. //points to data container
  1676. selectRows.containerPath=getContainer('config');
  1677. selectRows.schemaName="lists";
  1678. selectRows.queryName="inputLists";
  1679. selectRows.success=afterInputLists;
  1680. LABKEY.Query.selectRows(selectRows);
  1681. }
  1682. function afterInputLists(data){
  1683. let debug=true;
  1684. if (debug)
  1685. print("After input lists");
  1686. config.inputLists=data;
  1687. config.inputListsIterator=0;
  1688. removeCRFLoop();
  1689. }
  1690. function removeCRFLoop(){
  1691. let debug=true;
  1692. let i=config.inputListsIterator;
  1693. let iMax=config.inputLists.rows.length;
  1694. //in fact, we are adding two additional passages of the loop, one for
  1695. //crfEntry, the second for the same query, but using parentCrf as the
  1696. //selection variable
  1697. let iTotal=iMax+1;
  1698. //let iTotal=iMax+1;
  1699. if (debug)
  1700. print("removeCRFLoop ["+i+"/"+iMax+"]");
  1701. if (i>iTotal){
  1702. if (0) return;
  1703. redirect();
  1704. }
  1705. let queryName="crfEntry";
  1706. let idVar="entryId";
  1707. let idValue=getCRFref();
  1708. if (i<iMax){
  1709. //in all but crfEntry, variable is called crfRef
  1710. queryName=config.inputLists.rows[i].queryName;
  1711. idVar="crfRef";
  1712. }
  1713. //for i=iMax and i=iMax+1, query is crfEntry.
  1714. //delete also crfEntries where parentCrf is set to crf that we are deleting
  1715. if (i==iTotal){
  1716. idVar='parentCrf';
  1717. }
  1718. if (debug)
  1719. print("["+i+"/"+iMax+"] "+queryName+":"+idVar+'/'+idValue);
  1720. let selectRows=new Object();
  1721. //points to data container
  1722. selectRows.containerPath=getContainer('data');
  1723. selectRows.schemaName="lists";
  1724. selectRows.queryName=queryName;
  1725. selectRows.filterArray=[LABKEY.Filter.create(idVar,idValue)];
  1726. selectRows.success=removeListCRF;
  1727. selectRows.failure=skipListCRF;
  1728. LABKEY.Query.selectRows(selectRows);
  1729. }
  1730. function removeListCRF(data){
  1731. let debug=true;
  1732. if (debug)
  1733. print(data.queryName+": "+data.rows.length);
  1734. config.inputListsIterator+=1;
  1735. if (data.rows.length==0){
  1736. removeCRFLoop();
  1737. return;
  1738. }
  1739. let deleteRows=new Object();
  1740. //points to data container
  1741. deleteRows.containerPath=getContainer('data');
  1742. deleteRows.schemaName=data.schemaName;
  1743. deleteRows.queryName=data.queryName;
  1744. deleteRows.success=function(data){removeCRFLoop()};
  1745. deleteRows.rows=data.rows;
  1746. LABKEY.Query.deleteRows(deleteRows);
  1747. }
  1748. function skipListCRF(errorInfo){
  1749. let debug=true;
  1750. if (debug)
  1751. print("Error in removeCRF: "+errorInfo.exception);
  1752. config.inputListsIterator+=1;
  1753. removeCRFLoop();
  1754. }
  1755. function redirect(){
  1756. let debug=false;
  1757. let formUrl="begin";
  1758. let params=new Object();
  1759. params.name=formUrl;
  1760. params.pageId="CRF";
  1761. //points to crf container
  1762. let containerPath=getContainer('CRF');
  1763. // This changes the page after building the URL.
  1764. //Note that the wiki page destination name is set in params.
  1765. var homeURL = LABKEY.ActionURL.buildURL(
  1766. "project", formUrl , containerPath, params);
  1767. print("Redirecting to "+homeURL);
  1768. if (debug) return;
  1769. window.location = homeURL;
  1770. }
  1771. //printing section
  1772. function checkBlob(){
  1773. print("checkBlob: "+config.blob);
  1774. if (config.blob) {
  1775. clearInterval(config.blobInterval);
  1776. config.a.href = config.window.URL.createObjectURL(config.blob);
  1777. print("HREF: "+config.a.href);
  1778. config.a.download = 'test.pdf';
  1779. config.a.click();
  1780. config.window.URL.revokeObjectURL(config.a.href);
  1781. }
  1782. config.count=config.count+1;
  1783. print("Eval: "+config.count);
  1784. if (config.count>100){
  1785. clearInterval(config.blobInterval);
  1786. }
  1787. }
  1788. function printForm(){
  1789. config.doc=new PDFDocument();
  1790. //config.doc.end();
  1791. let stream = config.doc.pipe(blobStream()).on("finish",function(){
  1792. config.blob=stream.toBlob("application/pdf");});
  1793. print("BLob: "+config.blob);
  1794. config.a = config.document.createElement("a");
  1795. config.document.body.appendChild(config.a);
  1796. config.a.innerHTML="Download PDF";
  1797. config.a.style = "display: none";
  1798. config.count=0;
  1799. //run until blob is set
  1800. config.blobInterval=setInterval(checkBlob,1000);
  1801. //pick data from crfForm list
  1802. print("Printing form");
  1803. printHeader();
  1804. setData(formatPrintData);
  1805. }
  1806. function printHeader(){
  1807. config.doc.fontSize(25).text(config.formConfig.form['formName']);
  1808. config.doc.moveDown();
  1809. let crfEntry=config.formConfig.crfEntry;
  1810. let site=config.formConfig.currentSite;
  1811. let val=new Object();
  1812. let user=config.formConfig.user;
  1813. val['A']={o:crfEntry,f:'EudraCTNumber',t:'Eudra CT Number'};
  1814. val['B']={o:crfEntry,f:'StudyCoordinator',t:'Study Coordinator'};
  1815. val['C']={o:crfEntry,f:'StudySponsor',t:'Study Sponsor'};
  1816. val['D']={o:site,f:'siteName',t:'Site'};
  1817. val['E']={o:site,f:'sitePhone',t:'Phone'};
  1818. val['F']={o:user,f:'DisplayName',t:'Investigator'};
  1819. for (let f in val){
  1820. print('Printing for '+f);
  1821. let e=val[f];
  1822. let entry=new Object();
  1823. entry[f]=e.o[e.f];
  1824. printPDF(entry,
  1825. {name:f,caption:e.t,type:'string'},null);
  1826. }
  1827. config.doc.moveDown();
  1828. }
  1829. function formatPrintData(){
  1830. qS=config.formConfig.dataQueries;
  1831. for (let q in qS){
  1832. print('Setting up '+q);
  1833. let qData=qS[q];
  1834. print('Number of rows: '+qData.rows.length);
  1835. if (qData.rows.length>0){
  1836. config.doc.fontSize(20).text(qData.title);
  1837. }
  1838. for (let i=0;i<qData.rows.length;i++){
  1839. let entry=qData.rows[i];
  1840. for (let f in qData.fields){
  1841. let field=qData.fields[f];
  1842. let lookup=null;
  1843. if (field.lookup){
  1844. lookup=config.formConfig.lookup[field.lookup.queryName];
  1845. }
  1846. if (field.hidden) continue;
  1847. printPDF(entry,field,lookup);
  1848. }
  1849. }
  1850. config.doc.moveDown();
  1851. }
  1852. print("All done");
  1853. config.doc.end();
  1854. }
  1855. function printPDF(entry,field,lookup){
  1856. //object field should have a name, type, caption
  1857. //entry should have field.name
  1858. //lookup is null or has a lookup table LUT
  1859. //for value v of entry[field.name]
  1860. //
  1861. //the total width of a A4 page is 598 px,
  1862. //left margin is 72. With a right margin of 50,
  1863. //the total available with is 476 px.
  1864. let w=476;
  1865. let spacing=25;
  1866. let w1=(w-spacing)*0.5;
  1867. let fontSize=14;
  1868. print('printPDF: entry['+field.name+']='+entry[field.name]);
  1869. let v=entry[field.name];
  1870. if (lookup!=null){
  1871. v=lookup.LUT[v];
  1872. }
  1873. print('printPDF: field type:'+field.type);
  1874. if (field.type=="date"){
  1875. let d=new Date(v);
  1876. v=d.getDate()+'/'+(d.getMonth()+1)+'/'+d.getFullYear();
  1877. }
  1878. if (v===null) v=' / ';
  1879. if (v===undefined) v=' / ';
  1880. //measure text
  1881. let label=field.caption;
  1882. let opt={width:w1};
  1883. config.doc.fontSize(fontSize);
  1884. //for more eloquent display the height of the text
  1885. //can be measured prior to output
  1886. //use currentLineHeight to scale height
  1887. //let lineH=config.doc.currentLineHeight(1);
  1888. //let h=config.doc.heightOfString(label,opt)/lineH;
  1889. //print label
  1890. config.doc.font('Courier').text(label,opt);
  1891. //align last row of description w/ first row of value
  1892. config.doc.moveUp();
  1893. //store x value for later use
  1894. let tx=config.doc.x;
  1895. let ty=config.doc.y;
  1896. //shift for value output
  1897. config.doc.x+=w1+spacing;
  1898. config.doc.font('Courier-Bold').text(v,opt);
  1899. //restore x value
  1900. config.doc.x=tx;
  1901. }
  1902. //master section, entry point from html files
  1903. function generateMasterForm(){
  1904. generateDebugSection();
  1905. //read enviroment from lists disperesed on labkey
  1906. setFormConfig();
  1907. }
  1908. //helper function to set basic parameters on web page
  1909. //(fields defined in html file)
  1910. function populateBasicData(){
  1911. let staticData=new Object();
  1912. let titles=new Object();
  1913. staticData['version']=config.formConfig.softwareVersion;
  1914. titles['version']='Software version';
  1915. let varRows=config.formConfig['crfStaticVariables'].rows;
  1916. for (let i=0;i<varRows.length;i++){
  1917. let vName=varRows[i].staticVariable;
  1918. let val=config.formConfig.crfEntry[vName];
  1919. if (val==undefined) continue;
  1920. staticData[vName]=val;
  1921. titles[vName]=varRows[i].Title;
  1922. }
  1923. staticData['investigatorName']=config.formConfig.user['DisplayName'];
  1924. titles['investigatorName']='Investigator';
  1925. staticData['email']=config.formConfig.user['Email'];
  1926. titles['email']='Email';
  1927. staticData['siteName']=config.formConfig.currentSite['siteName'];
  1928. titles['siteName']='Site';
  1929. staticData['sitePhone']=config.formConfig.currentSite['sitePhone'];
  1930. titles['sitePhone']='Telephone(site)';
  1931. for (f in staticData){
  1932. addStaticData(f,titles[f],staticData[f]);
  1933. }
  1934. }
  1935. function addStaticData(f,title,value){
  1936. let el=config.document.getElementById(f);
  1937. //populate only
  1938. if (el!=undefined){
  1939. el.innerText=value;
  1940. return;
  1941. }
  1942. //add row to table if element cannot be found
  1943. let table=config.document.getElementById('staticTable');
  1944. let row=table.insertRow();
  1945. let cell=row.insertCell();
  1946. cell.innerText=title;
  1947. let cell1=row.insertCell();
  1948. cell1.id=f;
  1949. cell1.style.fontWeight='bold';
  1950. //populate
  1951. cell1.innerText=value;
  1952. }
  1953. //come here after the layout is read from labkey page
  1954. //
  1955. function generateErrorMsg(msg){
  1956. let txt=config.document.createElement('p');
  1957. txt.innerText=msg;
  1958. config.document.getElementById(config.masterForm).appendChild(txt);
  1959. generateButton("submitDiv",'Exit','Exit','redirect',redirect);
  1960. }
  1961. function getUser(id,field){
  1962. if (field in config.formConfig) return config.formConfig[field];
  1963. let uRows=config.formConfig.userRows;
  1964. for (let i=0;i<uRows.length;i++){
  1965. let userId=uRows[i].UserId;
  1966. if (userId!=id) continue;
  1967. config.formConfig[field]=uRows[i];
  1968. return config.formConfig[field];
  1969. }
  1970. return null;
  1971. }
  1972. function afterConfig(){
  1973. let debug=true;
  1974. if (debug)
  1975. print("afterConfig");
  1976. populateBasicData();
  1977. //check if user has permission on the form
  1978. let currentUser=getUser(LABKEY.Security.currentUser.id,'currentUser');
  1979. let currentSite=config.formConfig.currentSite;
  1980. let formCreator=getUser(config.formConfig.crfEntry.UserId,'formCreator');
  1981. let formCreatorId=formCreator.UserId;
  1982. //let formSite=config.formConfig.crfEntry.Site;
  1983. let fList=config.formConfig.operator+'s';
  1984. let fRows=config.formConfig[fList];
  1985. //let currentSiteId=-1;
  1986. //depending on operator mode, we should decide what is right
  1987. let operator=config.formConfig.operator;
  1988. if (operator=='crfEditor'){
  1989. //editor can only edit its own forms
  1990. if (currentUser.UserId!=formCreatorId){
  1991. let msg='User '+currentUser.DisplayName;
  1992. msg+=' has no permission on this form';
  1993. generateErrorMsg(msg);
  1994. return;
  1995. }
  1996. }
  1997. if (operator=='crfMonitor' || operator=='crfSponsor'){
  1998. //monitor can look at forms based on his site
  1999. //find monitor line
  2000. let operatorSites=new Array();
  2001. for (let i=0;i<fRows.length;i++){
  2002. if (fRows[i].User!=currentUser.UserId) continue;
  2003. operatorSites.push(fRows[i].Site);
  2004. }
  2005. print('operator Site: '+operatorSites.length);
  2006. if (operatorSites.length==0){
  2007. let msg='User '+currentUser.DisplayName;
  2008. msg+=' is not a '+operator;
  2009. generateErrorMsg(msg);
  2010. return;
  2011. }
  2012. let selectedSite=-1;
  2013. let siteCandidates="[";
  2014. for (let i=0;i<operatorSites.length;i++){
  2015. if (i>0) siteCandidates+=", ";
  2016. siteCandidates+=operatorSites[i];
  2017. if (operatorSites[i]!=currentSite.siteNumber) continue;
  2018. selectedSite=currentSite.siteNumber;
  2019. break;
  2020. }
  2021. siteCandidates+="]";
  2022. if (selectedSite==-1){
  2023. let msg='User '+currentUser.DisplayName;
  2024. msg+=' is not a '+operator+' for site ';
  2025. msg+=currentSite.siteName+'('+currentSite.siteNumber+')';
  2026. msg+='/'+siteCandidates;
  2027. generateErrorMsg(msg);
  2028. return;
  2029. }
  2030. }
  2031. print('User '+currentUser.DisplayName+'/'+
  2032. config.formConfig.currentSite['siteName']+
  2033. ' acting as '+config.formConfig.operator);
  2034. let rows=config.formConfig.crfButtons.rows;
  2035. config.formConfig.targetStatus=new Array();
  2036. config.formConfig.targetRecipient=new Array();
  2037. for (let i=0; i<rows.length; i++){
  2038. let action=rows[i].action;//String
  2039. let tstatus=rows[i].targetFormStatus;
  2040. let trecip=rows[i].targetRecipient;
  2041. config.formConfig.targetStatus[action]=tstatus;
  2042. config.formConfig.targetRecipient[action]=trecip;
  2043. }
  2044. let formStatus=config.formConfig.formStatus;
  2045. //let functionArray=new Array();
  2046. print("Generating buttons for formStatus \""+ formStatus+"\"");
  2047. let buttonRows=config.formConfig.crfButtons.rows;
  2048. for (let i=0;i<buttonRows.length;i++){
  2049. let bt=buttonRows[i];
  2050. if (typeof window[bt.action]==="function"){
  2051. generateButton("submitDiv",bt.caption,bt.label,bt.action,
  2052. window[bt.action]);
  2053. }
  2054. else{
  2055. print('No match for function :'+bt.action+
  2056. ' obj: '+window[bt.action]);
  2057. }
  2058. }
  2059. print('Here');
  2060. //here we should get data. For now, just initialize objects that will hold data
  2061. setDataLayout(afterDataLayout);//callback is afterDataLayout
  2062. }
  2063. function afterDataLayout(){
  2064. setData(afterData);//callback is afterData
  2065. }
  2066. function verifyCrfStudyId(pM){
  2067. //is studyId already set for the crf
  2068. let studyId=pM.getParticipantIdFromCrfEntry('STUDY');
  2069. if (!studyId) return;
  2070. pM.mode="STUDY";
  2071. pM.readOnly="TRUE";
  2072. }
  2073. function verifyRegistration(pM){
  2074. //if registration is in,
  2075. //then local id should not be changed any longer
  2076. let idFieldName=pM.getCrfEntryFieldName("STUDY");
  2077. let registrationQuery=config.formConfig.settings['registrationQuery'];
  2078. if (!registrationQuery) return; //LOCAL is OK
  2079. let fQuery=config.formConfig.dataQueries[registrationQuery];
  2080. if (!fQuery) return; //no registration query, then it should be ignored
  2081. if (fQuery.rows.length==0) return; //registration is empty
  2082. let studyId=fQuery.rows[0][idFieldName];
  2083. if (!studyId) return; //study id not set
  2084. //set
  2085. pM.mode="STUDY";
  2086. pM.readOnly="TRUE";
  2087. //set crf (this happens later, but probably before the form will be corrected)
  2088. pM.setParticipantIdToCrfEntry(studyId,"STUDY");
  2089. pM.updateCrfEntry();
  2090. }
  2091. function afterData(){
  2092. let fName='afterData';
  2093. //operatorBasedAccessMode
  2094. let accessMode=config.formConfig.operator+'Mode';
  2095. let rowsSetup=config.formConfig.formSetupRows;
  2096. let idMode=config.formConfig.form['idMode'];
  2097. //set default value if no value is in the list (read value is null)
  2098. if (!idMode) idMode="STUDY:EDIT";
  2099. print(fName+': idMode '+idMode);
  2100. //add print to config so participantManager can use it
  2101. config.print=print;
  2102. let pM=getParticipantManagerObject(config);
  2103. pM.updateCrfEntry=function(){updateFlag(config.formConfig.crfEntry['FormStatus'],doNothing);};
  2104. let idModeArray=idMode.split(':');
  2105. pM.mode="STUDY";
  2106. if (idModeArray.includes("LOCAL")) {
  2107. pM.mode="LOCAL";
  2108. //OK, but check if CRF or registration indicate that study id is already set
  2109. verifyCrfStudyId(pM);
  2110. verifyRegistration(pM);
  2111. }
  2112. if (idModeArray.includes("READONLY")){
  2113. pM.readOnly="TRUE";
  2114. }
  2115. let pId=pM.getParticipantIdFromCrfEntry();
  2116. if (!pId){
  2117. pM.setEditMode();
  2118. }
  2119. else{
  2120. let label=pId;
  2121. if (pM.mode=="STUDY"){
  2122. let loc=pM.getParticipantIdFromCrfEntry('LOCAL');
  2123. label=pId+':'+loc;
  2124. pM.readOnly="true";
  2125. }
  2126. pM.setLabelMode(label);
  2127. //in STUDY mode also change LOCAL ID from crfEntry
  2128. }
  2129. for (let i=0;i<rowsSetup.length;i++){
  2130. let entry=rowsSetup[i];
  2131. let queryName=config.formConfig.queryMap[entry['queryName']];
  2132. print(fName+" ["+queryName+"]: showFlag: "+entry["showFlag"]);
  2133. print(fName+" ["+queryName+"]: accessMode: "+entry[accessMode]);
  2134. const nData=config.formConfig.dataQueries[queryName].rows.length;
  2135. print(fName+" ["+queryName+"]: nData: "+nData);
  2136. //skip sections
  2137. //also from fields
  2138. if (entry[accessMode]=="NONE") continue;
  2139. //skip readonly empty records
  2140. //if (entry[accessMode]=="READ" && nData==0) continue;
  2141. //let additionalData=new Object();
  2142. //setAdditionalData(additionalData,entry);
  2143. //section fits one dataset/list
  2144. generateSection(entry);
  2145. //generateSection(queryName,entry["title"],entry[accessMode],
  2146. // additionalData);
  2147. }
  2148. }
  2149. function findSetupRow(queryName){
  2150. let rowsSetup=config.formConfig.formSetupRows;
  2151. for (let i=0;i<rowsSetup.length;i++){
  2152. let e=rowsSetup[i];
  2153. let queryName1=config.formConfig.queryMap[e['queryName']];
  2154. if (e.formName!=config.formId) continue;
  2155. if (queryName1!=queryName) continue;
  2156. return e;
  2157. }
  2158. return null;
  2159. }
  2160. function populateSection(queryName){
  2161. let fName='[populateSection/'+queryName+']';
  2162. print(fName);
  2163. let entry=findSetupRow(queryName);
  2164. //ignore names without associated entry in formSetup
  2165. if (entry==undefined){
  2166. print(fName+': no matching FormSetup entry found');
  2167. return;
  2168. }
  2169. //populate comes after generate, we should be pretty safe in taking
  2170. //already generated additionalData
  2171. if (!(queryName in config.formConfig.additionalData)){
  2172. print(fName+': no additionalData generated for '+queryName);
  2173. return;
  2174. }
  2175. let additionalData=config.formConfig.additionalData[queryName];
  2176. print(fName+': using additionalData '+additionalData);
  2177. if ("isReview" in additionalData){
  2178. generateReviewSection(queryName,queryName,generateReviewSectionCB);
  2179. return;
  2180. }
  2181. let accessMode=config.formConfig.operator+'Mode';
  2182. let aM=entry[accessMode];
  2183. print(fName+': accessMode '+aM);
  2184. if (aM!='GENERATE'){
  2185. let writeMode=entry[accessMode]=='EDIT';
  2186. print(fName+': mode='+writeMode);
  2187. populateTable(queryName,writeMode);
  2188. return;
  2189. }
  2190. //deal with generate
  2191. //
  2192. //already available -> shift to READ mode
  2193. let divTable=queryName+'Table';
  2194. let divObj=config.document.getElementById(divTable);
  2195. let divRev=config.document.getElementById(queryName+'Review');
  2196. let divRLi=config.document.getElementById(queryName+'ReviewList');
  2197. let divGBu=config.document.getElementById(queryName+'GenerateButton');
  2198. print('div GBU: '+divGBu);
  2199. divObj.style.display="block";
  2200. divRev.style.display="block";
  2201. divRLi.style.display="block";
  2202. if (divGBu!=undefined) divGBu.style.display="none";
  2203. let nData=config.formConfig.dataQueries[queryName].rows.length;
  2204. print('['+queryName+']: nrows '+nData);
  2205. if (nData>0){
  2206. populateTable(queryName,0);
  2207. return;
  2208. }
  2209. //hide table
  2210. divObj.style.display="none";
  2211. divRev.style.display="none";
  2212. divRLi.style.display="none";
  2213. if (divGBu!=undefined) divGBu.style.display="block";
  2214. //add buttons?
  2215. //is button already generated?
  2216. //populateTable(entry);
  2217. }
  2218. //******* generateQuery infrastructure *********************
  2219. function onGenerateQuery(queryName){
  2220. let fName='[onGenerateQuery]';
  2221. print(fName+' '+queryName);
  2222. //
  2223. let cfgRows=config.formConfig.generateConfigData.rows;
  2224. // //queryName to queryId?
  2225. let queryId=config.formConfig.fields[queryName].queryId;
  2226. let cfgRow=undefined;
  2227. for (let i=0;i<cfgRows.length;i++){
  2228. if (cfgRows[i].queryId!=queryId) continue;
  2229. cfgRow=cfgRows[i];
  2230. break;
  2231. }
  2232. if (cfgRow==undefined){
  2233. print('generateConfig for queryName['+queryId+']='+queryName+' not found');
  2234. return;
  2235. }
  2236. //add config to the list
  2237. if (!("generateConfig" in config.formConfig)){
  2238. config.formConfig.generateConfig=new Object();
  2239. }
  2240. config.formConfig.generateConfig[queryName]=cfgRow;
  2241. if (!("generateForm" in config.formConfig)){
  2242. config.formConfig.generateForm=new Object();
  2243. }
  2244. //
  2245. let formRows=config.formConfig.formRows;
  2246. let formId=cfgRow.formId;
  2247. for (let i=0;i<formRows.length;i++){
  2248. if (formRows[i].Key==formId) {
  2249. config.formConfig.generateForm[queryName]=formRows[i];
  2250. break;
  2251. }
  2252. }
  2253. //print('XcfgRow '+config.formConfig.generateForm[queryName]);
  2254. //
  2255. // //check if all required datasets were at least saved
  2256. checkGenerationFields(queryName);
  2257. }
  2258. function checkGenerationFields(queryName){
  2259. let fName='[checkGenerationFields]';
  2260. let genForm=config.formConfig.generateForm[queryName];
  2261. let genCfg=config.formConfig.generateConfig[queryName];
  2262. let mailRecipient=genCfg.emailRecipient;
  2263. //list of queries that are part of Registration form
  2264. print(fName);
  2265. print(fName+' setRecipient: '+mailRecipient);
  2266. let formId=genForm.Key;
  2267. print(fName+" Checking form w/id "+formId);
  2268. let selectGenerationRows=selectFormSetupRows(formId);
  2269. //registration rows
  2270. for (let i=0;i<selectGenerationRows.length;i++){
  2271. let row=selectGenerationRows[i];
  2272. let queryId=row.queryName;
  2273. let fQueryName=config.formConfig.queryMap[queryId];
  2274. if (fQueryName==queryName) continue;
  2275. let fQuery=config.formConfig.dataQueries[fQueryName];
  2276. print('Checking '+fQueryName+' nrows: '+fQuery.rows.length);
  2277. if (fQuery.rows.length==0){
  2278. generateError(queryName,fQueryName);
  2279. return;
  2280. }
  2281. }
  2282. generateMessage(queryName,'Vailidation OK');
  2283. print('callback: set recipient: '+mailRecipient);
  2284. let cb=function(){prepareForm(queryName,formId,mailRecipient);};
  2285. generateListEntry(formId,queryName,cb);
  2286. }
  2287. function prepareForm(queryName,formId,mailRecipient){
  2288. print('prepareForm: recipient '+mailRecipient);
  2289. //
  2290. // return;
  2291. //look for existing registration entry
  2292. let selectRows=new Object();
  2293. //inputLists should be in configuration container
  2294. selectRows.containerPath=getContainer('data');
  2295. selectRows.schemaName='lists';
  2296. selectRows.queryName='crfEntry';
  2297. selectRows.success=function(data){generateForm(data,queryName,mailRecipient);};
  2298. let formFilter=LABKEY.Filter.create('Form',formId);
  2299. let parentCrfFilter=LABKEY.Filter.create('parentCrf',getCRFref());
  2300. selectRows.filterArray=[formFilter,parentCrfFilter];
  2301. LABKEY.Query.selectRows(selectRows);
  2302. }
  2303. function generateError(queryName,fQueryName){
  2304. let elName=queryName+'GenerateButton'+'_reportField';
  2305. let el=config.document.getElementById(elName);
  2306. el.innerText='Error: '+fQueryName+' was not set';
  2307. el.style.color='red';
  2308. }
  2309. function generateMessage(queryName,msg){
  2310. let elName=queryName+'GenerateButton'+'_reportField';
  2311. let el=config.document.getElementById(elName);
  2312. el.innerText=msg;
  2313. el.style.color='green';
  2314. }
  2315. function generateForm(data,queryName,mailRecipient){
  2316. print('generateForm, recipient: '+mailRecipient);
  2317. //
  2318. const nData=data.rows.length;
  2319. print('Registration: '+nData+' rows');
  2320. let formRow=config.formConfig.generateForm[queryName];
  2321. //we have to generate masterQuery with parentCrf and crfRef
  2322. //and crfEntry with new entryId and parentCrf equal to crfRef
  2323. if (nData>0) {
  2324. generateMessage(queryName,'Registration already generated.');
  2325. return;
  2326. }
  2327. let formId=formRow.Key;
  2328. let formName=formRow.formName;
  2329. let crfBase=config.formConfig.crfEntry;
  2330. let crfEntry=new Object();
  2331. //add new reference
  2332. crfEntry.entryId=Date.now();
  2333. crfEntry.parentCrf=getCRFref();
  2334. crfEntry["Date"]=new Date();
  2335. crfEntry["View"]="[VIEW]";
  2336. crfEntry.formStatus=1;//In progress
  2337. //get local Id
  2338. let pM=getParticipantManagerObject(config);
  2339. crfEntry[pM.getCrfEntryFieldName()]=pM.getParticipantIdFromCrfEntry();
  2340. // //set other variables
  2341. //requires studyData as part of formConfig
  2342. // let studyData=config.formConfig.studyData;
  2343. print('Adding study: '+crfBase.EudraCTNumber);
  2344. crfEntry.EudraCTNumber=crfBase.EudraCTNumber;
  2345. crfEntry.StudyCoordinator=crfBase.StudyCoordinator;
  2346. crfEntry.StudySponsor=crfBase.StudySponsor;
  2347. crfEntry.RegulatoryNumber=crfBase.RegulatoryNumber;
  2348. //
  2349. // //find sponsor for site
  2350. let site=crfBase.Site;
  2351. let crfSponsors=config.formConfig.crfSponsors;
  2352. let users=config.formConfig.userRows;
  2353. for (let i=0;i<crfSponsors.length;i++){
  2354. //print('Checking for site '+crfSponsors[i].Site);
  2355. if (crfSponsors[i].Site!=site) continue;
  2356. config.formConfig.sponsorId=crfSponsors[i].User;
  2357. //print('Setting id '+config.formConfig.sponsorId);
  2358. //finds first
  2359. break;
  2360. }
  2361. for (let j=0;j<users.length;j++){
  2362. if (config.formConfig.sponsorId!=users[j].UserId) continue;
  2363. config.formConfig.sponsor=users[j];
  2364. //finds first (should be unique)
  2365. break;
  2366. }
  2367. print('Selecting '+config.formConfig.sponsor.DisplayName+' as sponsor');
  2368. //different user than the original form...
  2369. //should be set to the study sponsor
  2370. crfEntry.UserId=config.formConfig.sponsor.UserId;
  2371. crfEntry.Site=site;
  2372. // //set formId to one found through registration search
  2373. crfEntry.Form=formId;
  2374. ////
  2375. let qconfig=new Object();
  2376. qconfig.schemaName='lists';
  2377. qconfig.queryName='crfEntry';
  2378. qconfig.success=function(data){sendEmail(data,mailRecipient,doNothing,formName+' generated');}
  2379. qconfig.rows=[crfEntry];
  2380. LABKEY.Query.insertRows(qconfig);
  2381. }
  2382. //
  2383. function generateListEntry(formId,queryName,cb){
  2384. //check if registration was already generated
  2385. let formRows=config.formConfig.formRows;
  2386. let qForm=undefined;
  2387. for (let i=0;i<formRows.length;i++){
  2388. if (formRows[i].Key!=formId) continue;
  2389. qForm=formRows[i];
  2390. }
  2391. let nData=config.formConfig.dataQueries[queryName].rows.length
  2392. if (nData>0) return;
  2393. let pM=getParticipantManagerObject(config);
  2394. let e2=new Object();
  2395. e2.crfRef=getCRFref();
  2396. e2.registrationStatus=0;
  2397. e2.submissionDate=new Date();
  2398. e2[pM.getCrfEntryFieldName()]=pM.getParticipantIdFromCrfEntry();
  2399. print('set values');
  2400. let qconfig=new Object();
  2401. qconfig.containerPath=getContainer('data');
  2402. qconfig.schemaName='lists';
  2403. qconfig.queryName=queryName;
  2404. qconfig.success=cb;
  2405. qconfig.rows=[e2]
  2406. LABKEY.Query.insertRows(qconfig);
  2407. }
  2408. // ******************** end form generator (Registration) ********************
  2409. //jump to populate table/generate review, etc defined at the begining of the file
  2410. function setContainer(label,container){
  2411. if (!(config.formConfig.hasOwnProperty('container'))){
  2412. config.formConfig.container=new Array();
  2413. }
  2414. config.formConfig.container[label]=container;
  2415. }
  2416. function getContainer(label){
  2417. return config.formConfig.container[label];
  2418. }
  2419. //entry point from generateMasterForm
  2420. function setFormConfig(){
  2421. //add object to store form related data
  2422. config.formConfig=new Object();
  2423. config.formConfig.softwareVersion='0.15.10';
  2424. let debug=true;
  2425. if (debug)
  2426. print("generateMasterForm1");
  2427. //set containers for data and configuration
  2428. //TODO: set this from a query
  2429. //
  2430. setContainer('data',LABKEY.ActionURL.getContainer());
  2431. setContainer('config',LABKEY.ActionURL.getContainer());
  2432. setContainer('CRF',LABKEY.ActionURL.getContainer());
  2433. let selectRows=new Object();
  2434. //this is local data
  2435. selectRows.containerPath=getContainer('CRF');
  2436. selectRows.schemaName='lists';
  2437. selectRows.queryName='crfSettings';
  2438. //store form related data to this object
  2439. selectRows.success=afterSettings;
  2440. LABKEY.Query.selectRows(selectRows);
  2441. }
  2442. function afterSettings(data){
  2443. config.formConfig.settings=new Array();
  2444. for (let i=0;i<data.rows.length;i++){
  2445. let n=data.rows[i]['name'];
  2446. let v=data.rows[i]['value'];
  2447. config.formConfig.settings[n]=v;
  2448. }
  2449. let st=config.formConfig.settings;
  2450. print('afterSettings');
  2451. for (let k in st){
  2452. print('\t'+k+'='+st[k]);
  2453. }
  2454. //if ('dataContainer' in st){
  2455. // setContainer('data',st['dataContainer']);
  2456. //}
  2457. let vname='configContainer';
  2458. if (vname in st){
  2459. setContainer('config',st[vname]);
  2460. }
  2461. print('Config: '+getContainer('config'));
  2462. print('Data: '+getContainer('data'));
  2463. let selectRows=new Object();
  2464. //this is local data
  2465. selectRows.containerPath=getContainer('data');
  2466. selectRows.schemaName='lists';
  2467. selectRows.queryName='crfEntry';
  2468. //use first-> we must first establish link to the rigth crf entry
  2469. selectRows.filterArray=[LABKEY.Filter.create('entryId',getCRFrefFirst())];
  2470. //store form related data to this object
  2471. selectRows.success=afterCRFEntry;
  2472. LABKEY.Query.selectRows(selectRows);
  2473. }
  2474. function afterCRFEntry(data){
  2475. config.formConfig.crfEntry=data.rows[0];
  2476. print("Setting crfEntry (x) to "+config.formConfig.crfEntry["entryId"]);
  2477. //for empty records or those with parentCrf not set, parentCrf comes up as null
  2478. //nevertheless, with two equal signs, check against undefined also works
  2479. print('parentCrf set to '+config.formConfig.crfEntry.parentCrf);
  2480. collectData();
  2481. }
  2482. function collectData(){
  2483. let targetObject=config.formConfig;
  2484. targetObject.print=print;
  2485. targetObject.getContainer=getContainer;
  2486. let queryArray=new Array();
  2487. //k
  2488. //site
  2489. queryArray.push(makeQuery(targetObject,'config','site','siteData',[]));
  2490. //users
  2491. queryArray.push(makeQuery(targetObject,'CRF','users','userData',[]));
  2492. queryArray[queryArray.length-1].schemaName='core';
  2493. //crfEditors
  2494. queryArray.push(makeQuery(targetObject,'config','crfEditors','crfEditorsData',[]));
  2495. //crfMonitors
  2496. queryArray.push(makeQuery(targetObject,'config','crfMonitors','crfMonitorsData',[]));
  2497. //crfSponsors
  2498. queryArray.push(makeQuery(targetObject,'config','crfSponsors','crfSponsorsData',[]));
  2499. //study static data
  2500. queryArray.push(
  2501. makeQuery(targetObject,'data','crfStaticVariables','crfStaticVariables',[]));
  2502. queryArray.push(makeQuery(targetObject,'data','variableDetails','variableDetails',[]));
  2503. //study
  2504. queryArray.push(makeQuery(targetObject,'data','Study','studyDataAll1',[]));
  2505. let e=queryArray[queryArray.length-1];
  2506. //overload schema name
  2507. e.schemaName='study';
  2508. //make sure variables not part of default view are loaded
  2509. //here we should already have read crfStaticVariables table
  2510. e.columns="SubjectColumnName,EudraCTNumber,StudySponsor";
  2511. e.columns+=",StudyCoordinator,RegulatoryNumber";
  2512. //formStatus
  2513. let varLabel='sourceFormStatus';
  2514. let formStatus=config.formConfig.crfEntry['FormStatus'];
  2515. let formFilter=LABKEY.Filter.create('Key',formStatus);
  2516. queryArray.push(
  2517. makeQuery(targetObject,'config','FormStatus','formStatusData',[formFilter]));
  2518. //crfButtons
  2519. let statusFilter=LABKEY.Filter.create(varLabel,formStatus);
  2520. queryArray.push(
  2521. makeQuery(targetObject,'config','crfButtons','crfButtons',[statusFilter]));
  2522. //Forms
  2523. queryArray.push(makeQuery(targetObject,'config','Forms','formData',[]));
  2524. //FormSetup
  2525. queryArray.push(makeQuery(targetObject,'config','FormSetup','formSetup',[]));
  2526. //generateConfig
  2527. queryArray.push(
  2528. makeQuery(targetObject,'config','generateConfig','generateConfigData',[]));
  2529. //parentCrf
  2530. let parentCrf=config.formConfig.crfEntry['parentCrf'];
  2531. if (parentCrf!=undefined){
  2532. let crfFilter=LABKEY.Filter.create('entryId',parentCrf);
  2533. queryArray.push(makeQuery(targetObject,'data','crfEntry','parentCrfData',[crfFilter]));
  2534. }
  2535. print('running getDataFromQueries');
  2536. getDataFromQueries(queryArray,addStudyData);
  2537. }
  2538. function addStudyData(){
  2539. let queryArray=new Array();
  2540. let targetObject=config.formConfig;
  2541. targetObject.print=print;
  2542. targetObject.getContainer=getContainer;
  2543. //study
  2544. queryArray.push(makeQuery(targetObject,'data','Study','studyDataAll',[]));
  2545. //queryArray.push(makeQuery('data','Study','studyDataAll',[]));
  2546. let e=queryArray[queryArray.length-1];
  2547. //overload schema name
  2548. e.schemaName='study';
  2549. //make sure variables not part of default view are loaded
  2550. //here we should already have read crfStaticVariables table
  2551. let staticVarRows=config.formConfig['crfStaticVariables'].rows;
  2552. let columnModel=""
  2553. for (let i=0;i<staticVarRows.length;i++){
  2554. if (i>0) columnModel+=',';
  2555. columnModel+=staticVarRows[i]['staticVariable'];
  2556. }
  2557. e.columns=columnModel;
  2558. //also collect ids already in study
  2559. let demoQuery=config.formConfig.settings['registrationQuery'];
  2560. queryArray.push(makeQuery(targetObject,'data',demoQuery,'registrationData',[]));
  2561. queryArray[queryArray.length-1].schemaName='study';
  2562. getDataFromQueries(queryArray,fcontinue);
  2563. }
  2564. function selectFormSetupRows(formId){
  2565. let formSetupRows=new Array();
  2566. let allRows=config.formConfig.formSetup.rows;
  2567. for (let i=0;i<allRows.length;i++){
  2568. let formEntry=allRows[i];
  2569. if (formEntry.formName==formId)
  2570. formSetupRows.push(formEntry);
  2571. }
  2572. return formSetupRows;
  2573. }
  2574. function fcontinue(){
  2575. //debug
  2576. let fName='[fcontinue]';
  2577. let varRows=config.formConfig['crfStaticVariables'].rows;
  2578. let studyVars=config.formConfig['studyDataAll'].rows[0];
  2579. for (let i=0;i<varRows.length;i++){
  2580. let vName=varRows[i].staticVariable;
  2581. print(fName+' '+vName+': '+studyVars[vName]);
  2582. }
  2583. //parse site
  2584. config.formConfig.siteRows=config.formConfig.siteData.rows;
  2585. let sRows=config.formConfig.siteRows;
  2586. for (let i=0;i<sRows.length;i++){
  2587. let siteId=sRows[i].siteNumber;
  2588. print('site '+siteId);
  2589. if (siteId==config.formConfig.crfEntry.Site){
  2590. config.formConfig.currentSite=sRows[i];
  2591. break;
  2592. }
  2593. }
  2594. //config.formConfig.site=data.rows[0];
  2595. print("Setting site name to "+config.formConfig.currentSite.siteName);
  2596. //study
  2597. config.formConfig.studyData=config.formConfig.studyDataAll.rows[0];
  2598. print("XSetting participantField to "+
  2599. config.formConfig.studyData["SubjectColumnName"]);
  2600. config.formConfig.crfEditors=config.formConfig.crfEditorsData.rows;
  2601. config.formConfig.crfMonitors=config.formConfig.crfMonitorsData.rows;
  2602. config.formConfig.crfSponsors=config.formConfig.crfSponsorsData.rows;
  2603. config.formConfig.userRows=config.formConfig.userData.rows;
  2604. let uRows=config.formConfig.userRows;
  2605. for (let i=0;i<uRows.length;i++){
  2606. let userId=uRows[i].UserId;
  2607. if (userId==config.formConfig.crfEntry.UserId){
  2608. config.formConfig.user=uRows[i];
  2609. break;
  2610. }
  2611. }
  2612. //config.formConfig.user=data.rows[0];
  2613. print("Setting user to "+config.formConfig.user["DisplayName"]);
  2614. let fsRows=config.formConfig.formStatusData.rows;
  2615. config.formConfig.formStatus=fsRows[0].formStatus;
  2616. config.formConfig.operator=config.role;
  2617. //config.formConfig.operator=fsRows[0].operator;
  2618. print('Setting operator to: '+config.formConfig.operator);
  2619. config.formConfig.formRows=config.formConfig.formData.rows;
  2620. let formRows=config.formConfig.formRows;
  2621. //filter out the current form
  2622. for (let i=0;i<formRows.length;i++){
  2623. if (formRows[i].Key==config.formId){
  2624. config.formConfig.form=formRows[i];
  2625. break;
  2626. }
  2627. }
  2628. config.formConfig.formSetupRows=selectFormSetupRows(config.formId);
  2629. print("Number of datasets for form ["+config.formId+"]: "+
  2630. config.formConfig.formSetupRows.length);
  2631. let fields=config.formConfig.formSetup.metaData.fields;
  2632. //get the lookup for queryName column
  2633. let formQueryName='queryName';
  2634. let field="NONE";
  2635. for (f in fields){
  2636. if (fields[f]['name']!=formQueryName) continue;
  2637. field=fields[f];
  2638. break;
  2639. }
  2640. let lookup=field.lookup;
  2641. print("Getting dataset names from "+lookup.queryName);
  2642. let selectRows=new Object();
  2643. //inputLists should be in configuration container
  2644. selectRows.containerPath=getContainer('config');
  2645. selectRows.schemaName=lookup.schemaName;
  2646. selectRows.queryName=lookup.queryName;
  2647. selectRows.success=afterFormDatasets;
  2648. LABKEY.Query.selectRows(selectRows);
  2649. }
  2650. function afterFormDatasets(data){
  2651. print('afterFormDatasets: '+data.rows.length);
  2652. config.formConfig.formDatasets=data;//inputLists
  2653. config.formConfig.fields=new Object();
  2654. config.formConfig.queryMap=new Object();
  2655. config.formConfig.additionalData=new Object();
  2656. let rows=config.formConfig.formSetupRows;
  2657. //should skip report only rows
  2658. for (let i=0;i<rows.length;i++){
  2659. let entry=rows[i];
  2660. let reviewField=(entry['showFlag']=='REVIEW');
  2661. //is the operator set yet?
  2662. let accessMode=config.formConfig.operator+'Mode';
  2663. let skipField=(entry[accessMode]=="NONE");
  2664. let queryId=entry['queryName'];
  2665. let lookupRows=config.formConfig.formDatasets.rows;
  2666. print('QueryID['+i+']='+queryId);
  2667. let dentry;
  2668. for (let j=0;j<lookupRows.length;j++){
  2669. if (queryId!=lookupRows[j]['Key']) continue;
  2670. dentry=lookupRows[j];
  2671. break;
  2672. }
  2673. let qName=dentry['queryName'];
  2674. //update list of dataset formConfig is observing (fields/queryMap)
  2675. while (1){
  2676. //review contains no data
  2677. if (reviewField) break;
  2678. if (skipField) break;
  2679. //already in fields
  2680. if (qName in config.formConfig.fields) break;
  2681. config.formConfig.fields[qName]=new Object();
  2682. break;
  2683. }
  2684. while(1){
  2685. //already done
  2686. if (queryId in config.formConfig.queryMap) break;
  2687. config.formConfig.queryMap[queryId]=qName;
  2688. break;
  2689. }
  2690. if (reviewField) continue;
  2691. if (skipField) continue;
  2692. //only do this for real lists
  2693. let field=config.formConfig.fields[qName];
  2694. field.title=entry['title'];
  2695. field.queryId=queryId;
  2696. }
  2697. print("List of datasets in form : ");
  2698. for (f in config.formConfig.fields){
  2699. let field=config.formConfig.fields[f];
  2700. print("\t"+f+" ID: "+field.queryId+' title '+field.title);
  2701. }
  2702. afterConfig();
  2703. }
  2704. //>>>>>>>>>>>>>>>>>new>>>>>>>>>>>>
  2705. function setDataLayout(cb){
  2706. let rowsSetup=config.formConfig.formSetupRows;
  2707. config.formConfig.dataQueries=new Object();
  2708. let dS=config.formConfig.dataQueries;//reference only
  2709. let qMap=config.formConfig.queryMap;
  2710. config.formConfig.lookup=new Object();
  2711. for (let i=0;i<rowsSetup.length;i++){
  2712. let entry=rowsSetup[i];
  2713. //skip review rows
  2714. if (entry['showFlag']=='REVIEW')
  2715. continue;
  2716. let queryId=entry['queryName'];
  2717. let queryName=qMap[entry['queryName']];
  2718. dS[queryName]=new Object();
  2719. dS[queryName].title=entry['title'];
  2720. if (entry['showQuery']!="NONE"){
  2721. let sqName=entry['showQuery'];
  2722. dS[sqName]=new Object();
  2723. dS[sqName].title=findTitle(sqName);
  2724. }
  2725. }
  2726. //always add reviews
  2727. //
  2728. config.formConfig.dataQueries['reviewComments']=new Object();
  2729. //perhaps we will need queryId, but this is stuff for later
  2730. for (q in config.formConfig.dataQueries){
  2731. //callback will be a watchdog and will complete only
  2732. //when all data will be gathered
  2733. let dq=config.formConfig.dataQueries[q];
  2734. dq.collectingLayout="INITIALIZED";
  2735. let selectRows=new Object();
  2736. selectRows.queryName=q;
  2737. selectRows.schemaName='lists';
  2738. selectRows.containerPath=getContainer('data');
  2739. //we are only interested in metadata
  2740. selectRows.success=function(data){afterDatasets(data,cb);}
  2741. LABKEY.Query.selectRows(selectRows);
  2742. }
  2743. }
  2744. function findTitle(queryName){
  2745. //find by name from formDatasets
  2746. //and set associated title as title
  2747. let rows=config.formConfig.formDatasets.rows;
  2748. for (let i=0;i<rows.length;i++){
  2749. let entry=rows[i];
  2750. if (entry['queryName']!=queryName) continue;
  2751. return entry['title'];
  2752. }
  2753. return "NONE";
  2754. }
  2755. //this happens after the for loop, so all dataQueries objects are set
  2756. function afterDatasets(data,cb){
  2757. let qobject=config.formConfig.dataQueries[data.queryName];
  2758. print("Inspecting layout for "+data.queryName+" "+qobject);
  2759. qobject.fields=data.metaData.fields;
  2760. qobject.collectingLayout="STARTED";
  2761. //qobject.started="TRUE";
  2762. qobject.lookup=new Object();//keep track of objects
  2763. let i=0;
  2764. for (let f in qobject.fields){
  2765. //anything else is simple but lookup
  2766. let field=qobject.fields[f];
  2767. if (!("lookup" in field)) continue;
  2768. qobject.lookup[f]="PENDING";
  2769. print("Adding pending lookup for field "+f);
  2770. if (field.lookup.queryName in config.formConfig.lookup){
  2771. qobject.lookup[f]="DONE";
  2772. continue;
  2773. }
  2774. print("Setting up query for field "+f);
  2775. config.formConfig.lookup[field.lookup.queryName]=new Object();
  2776. let lObject=config.formConfig.lookup[field.lookup.queryName];
  2777. lObject.keyColumn=field.lookup.keyColumn;
  2778. lObject.displayColumn=field.lookup.displayColumn;
  2779. let selectRows=new Object();
  2780. selectRows.schemaName=field.lookup.schemaName;
  2781. selectRows.queryName=field.lookup.queryName;
  2782. selectRows.containerPath=getContainer('data');
  2783. if ("containerPath" in field.lookup){
  2784. selectRows.containerPath=field.lookup.containerPath;
  2785. }
  2786. selectRows.columns=field.lookup.keyColumn+","+
  2787. field.lookup.displayColumn;
  2788. //wait for all lookups to return
  2789. selectRows.success=function(data){addLookup(data,qobject,f,cb);};
  2790. print("Sending query: ["+
  2791. field.lookup.queryName+"] "+
  2792. field.lookup.keyColumn+'/'+
  2793. field.lookup.displayColumn);
  2794. LABKEY.Query.selectRows(selectRows);
  2795. i+=1;
  2796. }
  2797. if (i==0){
  2798. print("No lookups for "+data.queryName);
  2799. qobject.collectingLayout="FINISHED";
  2800. }
  2801. //check if done (both here and in lookup
  2802. //this only passes if no lookups are anywhere in the dataset assembly
  2803. if (!dataLayoutSet()) return;
  2804. cb();
  2805. }
  2806. function addLookup(data,qobject,f,cb){
  2807. print("Adding lookup "+data.queryName+' '+qobject+' '+f);
  2808. let lObject=config.formConfig.lookup[data.queryName];
  2809. lObject.LUT=new Array();//key to value
  2810. lObject.ValToKey=new Array();//value to key
  2811. let key=lObject.keyColumn;
  2812. let val=lObject.displayColumn;
  2813. for (let i=0;i<data.rows.length;i++){
  2814. lObject.LUT[data.rows[i][key]]=data.rows[i][val];
  2815. lObject.ValToKey[data.rows[i][val]]=data.rows[i][key];
  2816. }
  2817. qobject.lookup[f]="DONE";
  2818. if (!dataLayoutSet()) return;
  2819. cb();
  2820. }
  2821. function dataLayoutSet(){
  2822. print("Checking layout completeness");
  2823. let dq=config.formConfig.dataQueries;
  2824. for (f in dq){
  2825. print("["+f+"]: "+dq[f].collectingLayout);
  2826. if (dq[f].collectingLayout=="INITIALIZED")
  2827. return 0;
  2828. if (dq[f].collectingLayout=="FINISHED")
  2829. continue; //OK
  2830. let qobject=dq[f];
  2831. for (q in qobject.lookup){
  2832. if (qobject.lookup[q]=="DONE") {
  2833. print("["+f+"/"+q+"]: DONE");
  2834. continue;//OK
  2835. }
  2836. print("["+f+"/"+q+"]: "+qobject.lookup[q]);
  2837. return 0;
  2838. }
  2839. dq[f].collectingLayout="FINISHED";
  2840. }
  2841. print("Success");
  2842. return 1;
  2843. }
  2844. function setData(cb){
  2845. fName='[setData]';
  2846. //print(fName+': cb '+cb);
  2847. let crfMatch=getCRFref();
  2848. let parentCrf=config.formConfig.crfEntry['parentCrf'];
  2849. if (parentCrf!=undefined) crfMatch=parentCrf;
  2850. print(fName+' form crf ['+getCRFref()+'] matching for crfRef='+crfMatch);
  2851. //collect data and execute callback cb for queries in cb.queryList
  2852. for (q in config.formConfig.dataQueries){
  2853. let fQuery=config.formConfig.dataQueries[q];
  2854. fQuery.collectingData="STARTED";
  2855. let selectRows=new Object();
  2856. selectRows.containerPath=getContainer('data');
  2857. selectRows.queryName=q;
  2858. selectRows.schemaName='lists';
  2859. selectRows.filterArray=[
  2860. LABKEY.Filter.create("crfRef",crfMatch)
  2861. ];
  2862. selectRows.success=function(data){assembleData(data,cb);};
  2863. LABKEY.Query.selectRows(selectRows);
  2864. }
  2865. }
  2866. function assembleData(data,cb){
  2867. let fName='[assembleData/'+data.queryName+']';
  2868. let fQuery=config.formConfig.dataQueries[data.queryName];
  2869. fQuery.rows=data.rows;
  2870. fQuery.collectingData="FINISHED";
  2871. print(fName+': adding data');
  2872. for (q in config.formConfig.dataQueries){
  2873. let dq=config.formConfig.dataQueries[q];
  2874. //print("assembleData ["+q+"]: "+dq.collectingData);
  2875. if (dq.collectingData=="STARTED") return;
  2876. }
  2877. print(fName+': completing');
  2878. cb();
  2879. }
  2880. function uploadFile(inputElement,context){
  2881. //context should have ID and dirName attributes;
  2882. //path will be dirName/ID/fieldName_ID.suf
  2883. //where suf is identical to localPath content picked from
  2884. //inputElement
  2885. print('uploadFile: '+inputElement.value+'/');
  2886. if (inputElement.type=="text") return;
  2887. print('uploadFile: '+inputElement.files+'/');
  2888. print('uploadFile: '+inputElement.files.length+'/');
  2889. if (inputElement.files.length>0){
  2890. let file=inputElement.files[0];
  2891. print('uploadFile: '+inputElement.value+'/'+file.size);
  2892. }
  2893. let url=LABKEY.ActionURL.getBaseURL();
  2894. url+='_webdav';
  2895. url+=LABKEY.ActionURL.getContainer();
  2896. url+='/@files';
  2897. url+='/'+context['dirName'];
  2898. print('uploadFile url: '+url);
  2899. let uploadConfig=new Object();
  2900. uploadConfig.inputElement=inputElement;
  2901. uploadConfig.context=context;
  2902. uploadConfig.url=url;
  2903. uploadConfig.success=afterBaseDir;
  2904. uploadConfig.failure=tryMakeDir;
  2905. webdavCheck(uploadConfig);
  2906. }
  2907. function afterBaseDir(cfg){
  2908. print('afterBaseDir');
  2909. cfg.url+='/'+cfg.context['ID'];
  2910. cfg.success=afterIDDir;
  2911. cfg.failure=tryMakeDir;
  2912. webdavCheck(cfg);
  2913. }
  2914. function afterIDDir(cfg){
  2915. print('afterIDDir');
  2916. if (cfg.inputElement.files.length==0){
  2917. print('No files found');
  2918. return;
  2919. }
  2920. let file=cfg.inputElement.files[0];
  2921. print('Uploading '+file.name);
  2922. let suf=file.name.split('.').pop();
  2923. cfg.url+='/'+cfg.context['ID']+'.'+suf;
  2924. cfg.success=afterUpload;
  2925. cfg.failure=onFailure;
  2926. cfg.data=file;
  2927. webdavPut(cfg);
  2928. }
  2929. function afterUpload(cfg){
  2930. print('afterUpload');
  2931. }
  2932. function tryMakeDir(cfg){
  2933. print('tryMakeDir '+cfg.url);
  2934. cfg.failure=onFailure;
  2935. webdavMakeDir(cfg);
  2936. }
  2937. function request(cfg,verb,data){
  2938. print('request['+verb+'] '+cfg.url);
  2939. let connRequest=new XMLHttpRequest();
  2940. connRequest.addEventListener("loadend",
  2941. function(){checkResponse(connRequest,cfg);});
  2942. connRequest.open(verb, cfg.url);
  2943. connRequest.send(data);
  2944. //print('request['+verb+'] sent');
  2945. }
  2946. function checkResponse(xrq,cfg){
  2947. //print('checkResponse: readyState '+xrq.readyState);
  2948. //print('checkResponse: status '+xrq.status);
  2949. if (xrq.status<400) {
  2950. //client errors 400-499
  2951. //server errors 500-599
  2952. cfg.success(cfg);
  2953. return;
  2954. }
  2955. cfg.status=xrq.status;
  2956. cfg.failure(cfg);
  2957. }
  2958. function webdavMakeDir(cfg){ request(cfg,'MKCOL',null);}
  2959. function webdavCheck(cfg) { request(cfg,'GET',null);}
  2960. function webdavPut(cfg) { request(cfg,'PUT',cfg.data);}
  2961. function onFailure(cfg){
  2962. print('request failed with status='+cfg.status);
  2963. }