crfVisit.js 99 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694
  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 row=tb.insertRow();
  794. let cell=config.document.createElement('th');
  795. cell.style.width='300px';
  796. row.appendChild(cell);
  797. let text = config.document.createTextNode(field.shortCaption);
  798. cell.appendChild(text);
  799. let input=null;
  800. let colSpan="3";
  801. let cell1=row.insertCell();
  802. cell1.colSpan=colSpan;
  803. let readonlyFlag=setup.readonlyFlag(vName);
  804. //set the html input object
  805. while (1){
  806. if (readonlyFlag){
  807. input=config.document.createElement('label');
  808. input.innerText='Loading';
  809. break;
  810. }
  811. //lookup
  812. if (isLookup){
  813. input = config.document.createElement("select");
  814. break;
  815. }
  816. //date
  817. if (vType=="date"){
  818. input = config.document.createElement("input");
  819. input.type="date";
  820. break;
  821. }
  822. //string
  823. if (vType=="string"){
  824. //we have to make sure UNDEF is carried to below
  825. //since we are adapting file to either show
  826. //current file or allow user to select a file
  827. //
  828. //TODO change this so one can always select file
  829. //but also show the selected file
  830. if(vName.search("reviewComment")>-1){
  831. input = config.document.createElement("textarea");
  832. input.cols="65";
  833. input.rows="5";
  834. break;
  835. }
  836. input=config.document.createElement('input');
  837. input.type="text";
  838. if (vName.search('_file_')<0) break;
  839. cell1.setAttribute('colspan',"1");
  840. let cell2=row.insertCell();
  841. cell2.setAttribute('colspan',"2");
  842. let input1=config.document.createElement('input');
  843. input1.type="file";
  844. input1.id=setup.getInputId(vName)+'_file_';
  845. cell2.appendChild(input1);
  846. break;
  847. }
  848. if (vType=="float"){
  849. input = config.document.createElement("input");
  850. input.type="text";
  851. break;
  852. }
  853. if (vType=="boolean"){
  854. input = config.document.createElement("input");
  855. input.type="checkbox";
  856. print("Creating checkbox");
  857. break;
  858. }
  859. break;
  860. }
  861. input.id=setup.getInputId(vName);
  862. cell1.appendChild(input);
  863. print(fName+': adding element '+input.id);
  864. print(fName+': listing element '+config.document.getElementById(input.id));
  865. //connect associated list
  866. generateSubQuery(input,setup,readonlyFlag);
  867. if (readonlyFlag) {
  868. print(fName+': exiting(readonlyFlag)');
  869. return;
  870. }
  871. if (!isLookup) {
  872. print(fName+': exiting (not lookup)');
  873. return;
  874. }
  875. let lookup=field["lookup"];
  876. //get all values from config.formConfig.lookup[X]
  877. let lObject=config.formConfig.lookup[lookup.queryName];
  878. //debug
  879. print(fName+": query: "+lookup.queryName);
  880. print(fName+": ElementId: "+input.id);
  881. print(fName+": No of options: " +lObject.LUT.length);
  882. print(fName+": Element: "+input);
  883. //set the lut value (input is text label) for readonly
  884. //clear existing fields from input
  885. for(let i = input.options.length; i >= 0; i--) {
  886. input.remove(i);
  887. }
  888. //create option -1
  889. let opt = config.document.createElement("option");
  890. opt.text = "<Select>";
  891. opt.value = -1;
  892. input.options[0] = opt;
  893. print(fName+": Adding <Select>");
  894. //add other, label them with LUT
  895. for (let v in lObject.LUT) {
  896. print(fName+': populating '+v+': '+lObject.LUT[v]);
  897. let opt = config.document.createElement("option");
  898. opt.text = lObject.LUT[v];
  899. opt.value = v;
  900. input.options[input.options.length] = opt;
  901. }
  902. input.selectedIndex=0;
  903. }
  904. function parseVariables(pars){
  905. let pA=pars.split(";");
  906. let q=new Object();
  907. for (let i=0;i<pA.length;i++){
  908. let vA=pA[i].split('=');
  909. q[vA[0]]=vA[1];
  910. }
  911. return q;
  912. }
  913. function addSpecialFieldRow(tb,specFieldSetup,setup){
  914. //tb is the table, specFieldSetup is a row from the table where special fields are being setup
  915. //the first column is fieldUID, which is a colon joined amalgation of queryName:fieldName
  916. let fieldUID=specFieldSetup["fieldUID"];
  917. let x=fieldUID.split(':');
  918. let fieldName=x[1];
  919. let fName="[addSpecialFieldRow/"+fieldUID+"]";
  920. let q=parseVariables(specFieldSetup['actionParameters']);
  921. print(fName);
  922. if (specFieldSetup['actionType']=='textArea'){
  923. let row=tb.insertRow();
  924. let cell1=row.insertCell();
  925. cell1.colSpan="4";
  926. cell1.style.textAlign="justify";
  927. cell1.style.padding="10px";
  928. cell1.style.backgroundColor="#e0e0e0";
  929. cell1.innerText=q['description'];
  930. return;
  931. }
  932. if (specFieldSetup['actionType']=='generationObject'){
  933. //only in EDIT mode!!
  934. let ro=setup.readonlyFlag(fieldName);
  935. if (ro) return;
  936. config.print=print;
  937. let gc=getGenerationObject(config,q,setup.getInputId(fieldName));
  938. let row=tb.insertRow();
  939. let cell=config.document.createElement('th');
  940. row.appendChild(cell);
  941. let text = config.document.createTextNode("Automatic ID generator");
  942. cell.appendChild(text);
  943. let cell1=row.insertCell();
  944. cell1.colSpan="3";
  945. let b=config.document.createElement("input");
  946. b.type="button";
  947. b.id="generateIdButton";
  948. b.onclick=function(){gc.execute();};
  949. b.value="Generate ID";
  950. cell1.appendChild(b);
  951. }
  952. }
  953. function populateFieldRow(entry,field,setup){
  954. populateField(entry,field,setup);
  955. populateSubQuery(entry,field,setup);
  956. }
  957. function populateSubQuery(entry,field,setup){
  958. let fName='[populateSubQuery/'+setup.queryName+':'+field.name+']';
  959. if (setup.isReview) return;
  960. if (!(setup.queryName in config.formConfig.additionalData)){
  961. let msg=fName+': no additionalData entry for '+setup.queryName;
  962. msg+=' (probably a subquery)';
  963. print(msg);
  964. return;
  965. }
  966. //find if field is connected to a sub array
  967. //find queryName
  968. //
  969. let additionalData=config.formConfig.additionalData[setup.queryName];
  970. print(fName);
  971. //let flag=additionalData.showFlag;
  972. if (!("showFlag" in additionalData)) return;
  973. let eId=setup.getInputId(additionalData.showFlag);
  974. let id=setup.getInputId(field.name);
  975. if (eId!=id) {
  976. print(fName+": ignoring field "+id+"/"+eId);
  977. return;
  978. }
  979. print(fName+': id '+id);
  980. //hard to estimate readonlyFlag
  981. //
  982. let input=config.document.getElementById(id);
  983. let eType=input.nodeName.toLowerCase();
  984. let readonlyFlag=eType!="select";
  985. setListVisibility(input,setup,readonlyFlag);
  986. }
  987. function populateField(entry,field,setup){
  988. let vName=field.name;
  989. let fName='[populateFieldName/'+vName+']';
  990. let varValue="UNDEF";
  991. //if (vName in setup.filters) varValue=setup.filters[vName];
  992. if (vName in entry) varValue=entry[vName];
  993. //if part of the filter, set it to value
  994. if (vName in setup.filters) varValue=setup.filters[vName];
  995. let isLookup=("lookup" in field);
  996. print(fName+' v='+varValue+'/'+isLookup+' ['+
  997. setup.getInputId(field.name)+']');
  998. let vType=field.type;
  999. let id=setup.getInputId(vName);
  1000. let input=config.document.getElementById(id);
  1001. //date
  1002. if (vType=="date"){
  1003. if (varValue==="UNDEF") varValue=new Date();
  1004. else varValue=new Date(varValue);
  1005. }
  1006. //lookup for readonly
  1007. if (isLookup && varValue!="UNDEF"){
  1008. let lookup=field["lookup"];
  1009. //get all values from config.formConfig.lookup[X]
  1010. let lObject=config.formConfig.lookup[lookup.queryName];
  1011. varValue=lObject.LUT[varValue];
  1012. }
  1013. print('Element: '+input);
  1014. //figure out the element type
  1015. let eType=input.nodeName.toLowerCase();
  1016. print('Element type: '+eType);
  1017. //change varValue for printing
  1018. if (varValue=="UNDEF") varValue="";
  1019. //HTMLTextArea, createElement(textArea)
  1020. if (eType==="textarea"){
  1021. input.value=varValue;
  1022. return;
  1023. }
  1024. //Text, createTextNode
  1025. if (eType==="#text"){
  1026. input.nodeValue=varValue;
  1027. return;
  1028. }
  1029. //HTMLLabelElement, createElement('label')
  1030. if (eType==="label"){
  1031. input.innerText=varValue;
  1032. return;
  1033. }
  1034. //HTMLSelectElement, createElement('select')
  1035. if (eType==="select"){
  1036. input.selectedIndex=0;
  1037. for (let i=0;i<input.options.length;i++){
  1038. let v=input.options[i].text;
  1039. if (v!=varValue) continue;
  1040. input.selectedIndex=i;
  1041. break;
  1042. }
  1043. return;
  1044. }
  1045. if (eType!="input"){
  1046. print('Unknown type: '+eType+' encountered, igonring');
  1047. return;
  1048. }
  1049. //HTMLInputElement
  1050. let type=input.type;
  1051. if (type=="date"){
  1052. input.valueAsDate=varValue;
  1053. return;
  1054. }
  1055. //string,float
  1056. if (type=="text"){
  1057. input.value=varValue;
  1058. return;
  1059. }
  1060. //boolean
  1061. if (type=="checkbox"){
  1062. input.checked=varValue;
  1063. return;
  1064. }
  1065. print('Unknown input type: '+type+'. Ignoring.');
  1066. }
  1067. function populateTable(listName,writeMode){
  1068. //function populateTable(formSetupEntry){
  1069. //let listName=config.formConfig.queryMap[formSetupEntry['queryName']];
  1070. //let accessMode=config.formConfig.operator+'Mode';
  1071. //let writeMode=formSetupEntry[accessMode]=='EDIT';
  1072. let fName='[populateTable/'+listName+']';
  1073. let setup=getSetup(listName,writeMode);
  1074. let entry=new Object();
  1075. //data snapshot
  1076. let fQuery=config.formConfig.dataQueries[listName];
  1077. //here I assume that listName was parsed during setDataLayout and setData
  1078. //so that rows was set (even if they are empty)
  1079. print(fName+"]: nrows "+fQuery.rows.length);
  1080. if (fQuery.rows.length>0)
  1081. entry=fQuery.rows[0];
  1082. let fields=fQuery.fields;
  1083. for (f in fields){
  1084. let field=fields[f];
  1085. //each field is a new row
  1086. print(fName+": Adding field: "+f+'/'+field.name+' hidden: '+field.hidden);
  1087. if (field.hidden) continue;
  1088. if (field.name=="crfRef") continue;
  1089. populateFieldRow(entry,field,setup);
  1090. }
  1091. }
  1092. function generateTable(listName,divName,additionalData,setup){
  1093. let debug=true;
  1094. let fName="[generateTable/"+listName+"]";
  1095. if (debug) print(fName);
  1096. //is listName and setup.queryName a duplicate of the same value
  1097. print(fName+': setup.queryName '+setup.queryName);
  1098. //assume data is set in config.formConfig.dataQueries[data.queryName].rows;
  1099. let entry=new Object();
  1100. //data snapshot
  1101. let fQuery=config.formConfig.dataQueries[listName];
  1102. //here I assume that listName was parsed during setDataLayout and setData
  1103. //so that rows was set (even if they are empty)
  1104. print(fName+": Nrows "+fQuery.rows.length);
  1105. if (fQuery.rows.length>0)
  1106. entry=fQuery.rows[0];
  1107. let tb=config.document.createElement('table');
  1108. tb.className="t2";
  1109. config.document.getElementById(divName).appendChild(tb);
  1110. //this are the fields (probably constant)
  1111. let fields=fQuery.fields;
  1112. for (f in fields){
  1113. let field=fields[f];
  1114. let fieldUID=listName+":"+field.name;
  1115. //each field is a new row
  1116. print(fName+": Adding field: "+f+'/'+field.name+' ('+fieldUID+').');
  1117. //unique name
  1118. if (field.hidden) continue;
  1119. if (field.name=="crfRef") continue;
  1120. addFieldRow(tb,field,setup,additionalData);
  1121. populateFieldRow(entry,field,setup);
  1122. if (fieldUID in config.formConfig["specialFields"]){
  1123. let specFieldSetup=config.formConfig["specialFields"][fieldUID];
  1124. addSpecialFieldRow(tb,specFieldSetup,setup);
  1125. }
  1126. }
  1127. //finish of if apply button is not required
  1128. if (!("addApply" in setup)) {
  1129. print(fName+"populateTable: done");
  1130. return;
  1131. }
  1132. let row=tb.insertRow();
  1133. let th=config.document.createElement('th');
  1134. row.appendChild(th);
  1135. th.innerHTML=setup.addApply;
  1136. let cell=row.insertCell();
  1137. //cell.setAttribute("colspan","2");
  1138. let input=config.document.createElement("input");
  1139. input.type="button";
  1140. input.value=setup.addApply;
  1141. cell.appendChild(input);
  1142. let cell1=row.insertCell();
  1143. cell1.setAttribute("colspan","2");
  1144. cell1.id=setup.getInputId("rerviewLastSave");
  1145. cell1.innerHTML="No recent update";
  1146. //saveReview is a generic name for saving content of the html page to a list entry
  1147. input.onclick=function(){saveReview(listName,cell1.id,setup)};
  1148. }
  1149. function saveReview(queryName,elementId,setup){
  1150. //loads any queryName
  1151. let debug=true;
  1152. if (debug) print("saveReview: elementId "+elementId+" queryName "+queryName);
  1153. let useInsert=false;
  1154. if (!("unique" in setup)) useInsert=true;
  1155. let fQuery=config.formConfig.dataQueries[queryName];
  1156. if (fQuery.rows.length==0) useInsert=true;
  1157. let entry=new Object();
  1158. if (!useInsert){
  1159. entry=fQuery.rows[0];
  1160. }
  1161. entry.crfRef=getCRFrefData();
  1162. if (debug) print("Set crfRef="+entry.crfRef);
  1163. //if ("queryName" in setup.filters) {
  1164. // entry.queryName=setup.filters["queryName"];
  1165. // if (debug) print("Setting queryName: "+entry.queryName);
  1166. //}
  1167. let fields=fQuery.fields;
  1168. for (f in fields){
  1169. let field=fields[f];
  1170. if (debug) print("saveReview field: "+field.name);
  1171. if (field.hidden) continue;
  1172. let vName=field.name;
  1173. let vType=field.type;
  1174. if (debug) print("vType: "+vType);
  1175. if (vName=="crfRef") continue;
  1176. //need to save queryName for reviewComments
  1177. let eId=setup.getInputId(vName);
  1178. let el=config.document.getElementById(eId);
  1179. if (!el) {
  1180. if (debug) print("saveReview element: "+eId+" not found");
  1181. continue;
  1182. }
  1183. if (debug) print("saveReview element: "+eId);
  1184. let eType=el.nodeName.toLowerCase();
  1185. if (eType==="select"){
  1186. entry[vName]=el.options[el.selectedIndex].value;
  1187. continue;
  1188. }
  1189. if (eType==="td"){
  1190. entry[vName]=el.innerText;
  1191. continue;
  1192. }
  1193. if (vType=="date"){
  1194. let date=el.valueAsDate;
  1195. if (date==="null") continue;
  1196. date.setUTCHours(12);
  1197. entry[vName]=date.toString();
  1198. print("Setting date to "+entry[vName]);
  1199. continue;
  1200. }
  1201. if (vType=="string"){
  1202. entry[vName]=el.value;
  1203. if (vName.search('_file_')<0)
  1204. continue;
  1205. //upload file
  1206. let id1=eId+'_file_';
  1207. let input1=config.document.getElementById(id1);
  1208. print('Attachment field: '+input1.value);
  1209. //entry[vName]=el.files[0].stream();
  1210. let ctx=new Object();
  1211. ctx['dirName']='consent';
  1212. ctx['ID']=entry['crfRef'];
  1213. //should point to data container
  1214. ctx['project']=getContainer('data');
  1215. //need ID->crf!
  1216. //assume crfRef will get set before this
  1217. //element is encountered
  1218. uploadFile(input1,ctx);
  1219. let fv=el.value;
  1220. let suf=fv.split('.').pop();
  1221. entry[vName]=entry['crfRef']+'.'+suf;
  1222. continue;
  1223. }
  1224. if (vType=="float" || vType=="int"){
  1225. entry[vName]=el.value;
  1226. if (vName=="queryName") {
  1227. print('Parsing queryName: '+el.innerText);
  1228. entry[vName]=config.formConfig.fields[el.innerText].queryId;
  1229. //use queryMap lookup
  1230. }
  1231. continue;
  1232. }
  1233. if (vType=="boolean"){
  1234. entry[vName]=el.checked;
  1235. continue;
  1236. }
  1237. }
  1238. let qconfig=new Object();
  1239. qconfig.rows=[entry];
  1240. //should point to data container
  1241. qconfig.containerPath=getContainer('data');
  1242. qconfig.schemaName='lists';
  1243. qconfig.queryName=queryName;
  1244. //only update comments
  1245. print("modifyRows: useInsert "+useInsert);
  1246. qconfig.success=function(data){updateLastSavedFlag(data,setup,elementId)};
  1247. if (!useInsert){
  1248. LABKEY.Query.updateRows(qconfig);
  1249. }
  1250. else{
  1251. LABKEY.Query.insertRows(qconfig);
  1252. }
  1253. }
  1254. function updateLastSavedFlag(data,setup,elementId){
  1255. let debug=true;
  1256. if (debug) print("Update last saved flag to "+elementId);
  1257. let el=config.document.getElementById(elementId);
  1258. let dt=new Date();
  1259. el.innerHTML="Last saved "+dt.toString();
  1260. if (data.queryName=="reviewComments"){
  1261. updateListDisplay(setup.divReviewListId,"reviewComments",setup.filters,true);
  1262. }
  1263. //refresh stored data!
  1264. let writeMode=!setup.readonlyFlag();
  1265. if ("unique" in setup)
  1266. setData(function (){populateTable(data.queryName,writeMode);});
  1267. if ("masterQuery" in setup){
  1268. let ad=config.formConfig.additionalData[setup.masterQuery];
  1269. print('Updating list display: '+setup.queryName+'/'+ad.queryName);
  1270. updateListDisplay(ad.divQueryName,ad.queryName,ad.filters,false);
  1271. }
  1272. }
  1273. //******************************************upload to database *********************
  1274. function onDatabaseUpload(){
  1275. let fName='[onDatabaseUpload]';
  1276. print(fName);
  1277. config.upload=new Object();
  1278. let fc=new Object();
  1279. let pM=getParticipantManagerObject(config);
  1280. fc.participantId=pM.getParticipantIdFromCrfEntry();
  1281. print(fName+' id '+fc.participantId);
  1282. afterParticipantId(fc);
  1283. }
  1284. function onDatabaseUpload1(){
  1285. let fName='[onDatabaseUpload]';
  1286. print(fName);
  1287. config.upload=new Object();
  1288. //figure out the participantId
  1289. let masterQueryId=config.formConfig.form["masterQuery"];
  1290. print(fName+': master query: '+masterQueryId);
  1291. let pidClass=new Object();
  1292. pidClass.afterId=afterParticipantId;
  1293. //use stored name of participantField
  1294. //for migrating data from lists to study
  1295. //this is to avoid conflicts in column assignments
  1296. //since datasets contain all fields of a list plus
  1297. //default fields of which participantId is one
  1298. pidClass.participantField=config.registrationParticipantIdField;
  1299. let qconfig=new Object();
  1300. qconfig.queryName=config.formConfig.queryMap[masterQueryId];
  1301. //queryMap holds mapping for queries in visit;
  1302. //masterQuery should be one of them, so this is safe.
  1303. qconfig.schemaName='lists';
  1304. qconfig.containerPath=getContainer('data');
  1305. qconfig.filterArray=[LABKEY.Filter.create('crfRef',getCRFref())];
  1306. qconfig.success=function(data){afterRegistration(data,pidClass);};
  1307. LABKEY.Query.selectRows(qconfig);
  1308. //waitForCompleteUpload(config);//
  1309. }
  1310. function afterRegistration(data,fc){
  1311. let fName='[afterRegistration/'+data.queryName+']';
  1312. print(fName+": rows:"+data.rows.length);
  1313. fc.registration=data;
  1314. let registrationData=fc.registration;
  1315. clearErr();
  1316. if (registrationData.rows.length!=1){
  1317. let msg=fName+": ERROR: Found "+registrationData.rows.length;
  1318. msg+=" registration entries for crfrefid "+getCRFref();
  1319. print(msg);
  1320. fc.afterId(fc);
  1321. return;
  1322. }
  1323. print(fName+'registration participant field: '+fc.participantField);
  1324. fc.participantId=registrationData.rows[0][fc.participantField];
  1325. //could be a lookup field (particularly for studies)
  1326. print('ID: '+fc.participantId);
  1327. let fields=registrationData.metaData.fields;
  1328. let field="NONE";
  1329. for (f in fields){
  1330. if (fields[f]["name"]==fc.participantField)
  1331. field=fields[f];
  1332. }
  1333. if ("lookup" in field){
  1334. let pid=fc.participantId;
  1335. print("Using lookup for participantId: "+pid);
  1336. let lookup=field["lookup"];
  1337. print("Lookup: ["+lookup.schemaName+','+lookup.queryName+']');
  1338. let qconfig=new Object();
  1339. //should point to data container
  1340. qconfig.containerPath=getContainer('data');
  1341. qconfig.schemaName=lookup.schemaName;
  1342. qconfig.queryName=lookup.queryName;
  1343. qconfig.filterArray=
  1344. [LABKEY.Filter.create(lookup.keyColumn,pid)];
  1345. qconfig.success=function(data){
  1346. afterRegistrationLookup(data,lookup.displayColumn,fc)};
  1347. LABKEY.Query.selectRows(qconfig);
  1348. }
  1349. else{
  1350. //afterParticipantId(configUpload);
  1351. fc.afterId(fc);
  1352. }
  1353. }
  1354. function afterRegistrationLookup(data,displayColumn,fc){
  1355. print("afterRegistrationLookup");
  1356. let entry=data.rows[0];
  1357. fc.participantId=entry[displayColumn];
  1358. print('Setting to '+fc.participantId);
  1359. fc.afterId(fc);
  1360. //afterParticipantId(configUpload);
  1361. }
  1362. function afterParticipantId(fc){
  1363. print("Setting participantId to "+fc.participantId);
  1364. config.upload.participantId=fc.participantId;
  1365. //another select rows to update all queries from setup
  1366. //just use registration for test
  1367. let formSetupRows=config.formConfig.formSetupRows;
  1368. config.upload.queries=new Array();
  1369. print("Form rows: "+formSetupRows.length);
  1370. for (let i=0;i<formSetupRows.length;i++){
  1371. let entry=formSetupRows[i];
  1372. //skip reviews
  1373. if (entry.showFlag=="REVIEW") continue;
  1374. //use lookup table to convert from id to name
  1375. let queryName=config.formConfig.queryMap[entry.queryName];
  1376. config.upload.queries.push({queryName:queryName,queryStatus:"QUEUED"});
  1377. print('form ['+i+']='+queryName+' '+entry.showFlag+'/'+entry.showQuery);
  1378. if (entry.showQuery=="NONE")
  1379. continue;
  1380. config.upload.queries.push({queryName:entry.showQuery,queryStatus:"QUEUED"});
  1381. }
  1382. //add reviews
  1383. config.upload.queries.push({queryName:"reviewComments",queryStatus:"QUEUED"});
  1384. config.upload.queryId=0;
  1385. copyToDataset();
  1386. }
  1387. function copyToDataset(){
  1388. let fName='[copyToDataset]: ';
  1389. print(fName+'['+config.upload.queryId+'/'+config.upload.queries.length+']');
  1390. //watch dog + scheduler
  1391. //
  1392. //watchdog part
  1393. if (config.upload.queryId==config.upload.queries.length) {
  1394. print(fName+'completing');
  1395. let targetStatus=config.formConfig.targetStatus['onDatabaseUpload'];
  1396. let targetRecipient=config.formConfig.targetRecipient['onDatabaseUpload'];
  1397. let action=new Object();
  1398. action.name='onDatabaseUpload';
  1399. action.cb=function(data){sendEmail(data,targetRecipient,redirect,'Form uploaded');}
  1400. updateFlag(targetStatus,action);//Approved
  1401. return;
  1402. }
  1403. //scheduler
  1404. let queryName=config.upload.queries[config.upload.queryId].queryName;
  1405. print("copyToDataset["+config.upload.queryId+"/"+
  1406. config.upload.queries.length+"]: "+queryName);
  1407. let qconfig=new Object();
  1408. qconfig.queryName=queryName;
  1409. qconfig.schemaName="lists";
  1410. qconfig.containerPath=getContainer('data');
  1411. qconfig.filterArray=[LABKEY.Filter.create('crfRef',getCRFref())];
  1412. qconfig.success=afterListData;
  1413. LABKEY.Query.selectRows(qconfig);
  1414. }
  1415. function afterListData(data){
  1416. let fName='[afterListData]: ';
  1417. let queryName=config.upload.queries[config.upload.queryId].queryName;
  1418. print(fName+" ["+queryName+"/list]: "+data.rows.length+" entries");
  1419. config.upload.queries[config.upload.queryId].listData=data;
  1420. let id=config.upload.participantId;
  1421. let qconfig=new Object();
  1422. qconfig.queryName=queryName;
  1423. qconfig.schemaName="study";
  1424. qconfig.containerPath=getContainer('data');
  1425. qconfig.filterArray=[LABKEY.Filter.create('crfRef',getCRFref())];
  1426. qconfig.filterArray.push(LABKEY.Filter.create('ParticipantId',id));
  1427. qconfig.success=afterStudyData;
  1428. LABKEY.Query.selectRows(qconfig);
  1429. }
  1430. function afterStudyData(data){
  1431. let fName='[afterStudyData]: ';
  1432. let queryObj=config.upload.queries[config.upload.queryId];
  1433. queryObj.studyData=data;
  1434. let msg=fName+"["+queryObj.queryName+"/study]: "+data.rows.length+" entries";
  1435. print(msg);
  1436. let listRows=queryObj.listData.rows;
  1437. //skip uploading an empty set
  1438. if (listRows.length==0){
  1439. printErr("List "+queryObj.queryName+" empty.");
  1440. queryObj.queryStatus="DONE";
  1441. config.upload.queryId+=1;
  1442. //back to watchdog
  1443. copyToDataset();
  1444. return;
  1445. }
  1446. let studyRows=queryObj.studyData.rows;
  1447. for (let i=0;i<studyRows.length;i++){
  1448. let entry=studyRows[i];
  1449. //
  1450. if (! (i<listRows.length) ) continue;
  1451. let entryList=listRows[i];
  1452. //keeps study only variables (ParticipantId, SequenceNum)
  1453. for (let f in entryList) {
  1454. entry[f]=entryList[f];
  1455. print(fName+"Copying ["+f+"]: "+entry[f]+"/"+entryList[f]);
  1456. }
  1457. }
  1458. print(fName+' copying completed');
  1459. if (studyRows.length>0) {
  1460. let qconfig=new Object();
  1461. qconfig.queryName=queryObj.queryName;
  1462. qconfig.schemaName="study";
  1463. qconfig.rows=studyRows;
  1464. qconfig.containerPath=getContainer('data');
  1465. qconfig.success=afterStudyUpload;
  1466. LABKEY.Query.updateRows(qconfig);
  1467. print(fName+'updateRows sent');
  1468. }
  1469. else{
  1470. let data=new Object();
  1471. data.rows=new Array();
  1472. afterStudyUpload(data);
  1473. }
  1474. }
  1475. function afterStudyUpload(data){
  1476. let fName='[afterStudyUpload] ';
  1477. print(fName);
  1478. //let participantField=config.participantField;
  1479. let participantField=config.formConfig.studyData["SubjectColumnName"];
  1480. print(fName+' participantField: '+participantField);
  1481. let queryObj=config.upload.queries[config.upload.queryId];
  1482. let queryName=queryObj.queryName;
  1483. printErr("Updated "+data.rows.length+" rows to "+queryName);
  1484. let studyRows=queryObj.studyData.rows;
  1485. let listRows=queryObj.listData.rows;
  1486. let rows=new Array();
  1487. //also updating existing rows, if they exist
  1488. for (let i=studyRows.length;i<listRows.length;i++){
  1489. let entry=listRows[i];
  1490. //make sure you have the participantField right
  1491. //
  1492. entry[participantField]=config.upload.participantId;
  1493. entry.crfRef=getCRFref();
  1494. entry.SequenceNum=getCRFref();
  1495. entry.SequenceNum=entry.SequenceNum % 1000000000;
  1496. if (listRows.length>1){
  1497. entry.SequenceNum+=i/100;
  1498. }
  1499. print( "Adding sequence number "+entry.SequenceNum);
  1500. rows.push(entry);
  1501. }
  1502. if (rows.length>0){
  1503. let qconfig=new Object();
  1504. qconfig.queryName=queryName;
  1505. qconfig.schemaName="study";
  1506. qconfig.containerPath=getContainer('data');
  1507. qconfig.success=afterListUpload;
  1508. qconfig.rows=rows;
  1509. LABKEY.Query.insertRows(qconfig);
  1510. }
  1511. else{
  1512. let data=new Object();
  1513. data.rows=rows;
  1514. afterListUpload(data);
  1515. }
  1516. }
  1517. function afterListUpload(data){
  1518. let queryObj=config.upload.queries[config.upload.queryId];
  1519. let queryName=queryObj.queryName;
  1520. printErr("Inserted "+data.rows.length+" rows to "+queryName);
  1521. queryObj.queryStatus="DONE";
  1522. config.upload.queryId+=1;
  1523. copyToDataset();
  1524. }
  1525. //*************************update for further review *************************
  1526. function onUpdateForReview(){
  1527. let targetStatus=config.formConfig.targetStatus['onUpdateForReview'];
  1528. let targetRecipient=config.formConfig.targetRecipient['onUpdateForReview'];
  1529. let action=new Object();
  1530. action.name='onUpdateForReview';
  1531. action.cb=function(data){sendEmail(data,targetRecipient,redirect,'Form updated for review');};
  1532. updateFlag(targetStatus,action);
  1533. }
  1534. function updateFlag(flag,action){
  1535. let fName='[updateFlag 1]';
  1536. let debug=true;
  1537. let entry=config.formConfig.crfEntry;
  1538. entry.FormStatus=flag;
  1539. let uId=config.formConfig.currentUser.UserId;
  1540. entry[config.formConfig.operator]=uId;
  1541. print(fName+': Form: '+entry.Form);
  1542. print(fName+": set form status to "+entry.FormStatus);
  1543. let qconfig=new Object();
  1544. qconfig.schemaName='lists';
  1545. qconfig.queryName='crfEntry';
  1546. qconfig.containerPath=getContainer('data');
  1547. qconfig.rows=[entry];
  1548. //qconfig.success=function(data){completeWithFlag(data,flag);}
  1549. qconfig.success=function(data){completeWithFlag(data,action);};
  1550. LABKEY.Query.updateRows(qconfig);
  1551. }
  1552. function completeWithFlag(data,action){
  1553. let fName='[completeWithFlag]';
  1554. print(fName+': nrows '+data.rows.length);
  1555. let fentry=data.rows[0];
  1556. print(fName+': form status '+fentry.FormStatus);
  1557. print(fName+': form '+fentry.Form);
  1558. let entry=new Object();
  1559. entry.entryId=getCRFref();
  1560. entry.submissionDate=new Date();
  1561. entry.FormStatus=fentry.FormStatus;
  1562. entry.User=config.formConfig.currentUser.UserId;
  1563. entry.Form=fentry.Form;
  1564. entry.operator=config.formConfig.operator;
  1565. entry.action=action.name;
  1566. let qconfig=new Object();
  1567. qconfig.schemaName='lists';
  1568. qconfig.queryName='crfStatus';
  1569. qconfig.containerPath=getContainer('data');
  1570. qconfig.rows=[entry];
  1571. //qconfig.success=function(data){completeWithFlag(data,flag);}
  1572. qconfig.success=action.cb;
  1573. LABKEY.Query.insertRows(qconfig);
  1574. }
  1575. //************************************************ submit *******************************************
  1576. function onSubmit(){
  1577. //update list storage and change status
  1578. let debug=true;
  1579. hideErr();
  1580. clearErr();
  1581. printErr("onSubmit");
  1582. setData(verifyData);
  1583. }
  1584. function verifyData(){
  1585. let queries=config.formConfig.dataQueries;
  1586. for (q in queries){
  1587. let qData=queries[q];
  1588. if (q=="reviewComments") continue;
  1589. //if it doesn't have additionalData, it is a sub query
  1590. if (!(q in config.formConfig.additionalData))
  1591. continue;
  1592. if (qData.rows.length<1){
  1593. printErr('Missing entry for query '+q);
  1594. return false;
  1595. }
  1596. }
  1597. let targetStatus=config.formConfig.targetStatus['onSubmit'];
  1598. let targetRecipient=config.formConfig.targetRecipient['onSubmit'];
  1599. print('verifyStatus: targetStatus: '+targetStatus);
  1600. let fName='verifyStatus';
  1601. //useful for debug
  1602. //let finalStep=doNothing;
  1603. //production mode
  1604. let finalStep=redirect;
  1605. let action=new Object();
  1606. action.name='onSubmit';
  1607. action.cb=function(data){sendEmail(data,targetRecipient,finalStep,'Form sumbitted');};
  1608. updateFlag(targetStatus,action);
  1609. }
  1610. function getEmail(recipientCode){
  1611. print('getEmail w/'+recipientCode);
  1612. let recipients=new Array();
  1613. let typeTo=LABKEY.Message.recipientType.to;
  1614. let create=LABKEY.Message.createRecipient;
  1615. let currentUser=config.formConfig.currentUser;
  1616. let formCreator=config.formConfig.formCreator;
  1617. let currentSite=config.formConfig.currentSite;
  1618. let userRows=config.formConfig.userRows;
  1619. let parentUser=undefined;
  1620. if ("parentCrfData" in config.formConfig){
  1621. let parentCrf=config.formConfig.parentCrfData;
  1622. parentUser=getUser(parentCrf.rows[0].UserId,'parentUser');
  1623. }
  1624. let recipientCategories=recipientCode.split(',');
  1625. for (let i=0;i<recipientCategories.length;i++){
  1626. let recipient=recipientCategories[i];
  1627. print('Checking '+recipient);
  1628. if (recipient=='crfEditor'){
  1629. print('Adding :'+formCreator.Email);
  1630. recipients.push(create(typeTo,formCreator.Email));
  1631. if (parentUser==undefined) continue;
  1632. print('Adding :'+parentUser.Email);
  1633. recipients.push(create(typeTo,parentUser.Email));
  1634. continue;
  1635. }
  1636. //Monitor or Sponsor
  1637. let fList=recipient+'s';
  1638. let fRows=config.formConfig[fList];
  1639. for (let i=0;i<fRows.length;i++){
  1640. print('Checking '+fRows[i].User+'/'+fRows[i].Site);
  1641. if (fRows[i].Site!=currentSite.siteNumber) continue;
  1642. for (let j=0;j<userRows.length;j++){
  1643. if (userRows[j].UserId!=fRows[i].User) continue;
  1644. print('Adding :'+userRows[j].Email);
  1645. recipients.push(create(typeTo,userRows[j].Email));
  1646. break;
  1647. }
  1648. }
  1649. }
  1650. return recipients;
  1651. }
  1652. function sendEmail(data,recipient='crfEditor',cb=redirect,subj='Form submitted'){
  1653. print('sendEmail; recipient: '+recipient);
  1654. let st=config.formConfig.settings;
  1655. let cvar='sendEmail';
  1656. if (cvar in st){
  1657. print(cvar+' set to '+st[cvar]);
  1658. if (st[cvar]=='FALSE'){
  1659. print('Skipping sending emails');
  1660. cb();
  1661. return;
  1662. }
  1663. }
  1664. if (recpient==null){
  1665. print('Skipping sending emails w/ no recipients');
  1666. cb();
  1667. return;
  1668. }
  1669. print('send email '+data.rows.length);
  1670. let crf=data.rows[0]['entryId'];
  1671. let formId=data.rows[0]['Form'];
  1672. let link=LABKEY.ActionURL.getBaseURL();
  1673. link+=LABKEY.ActionURL.getContainer();
  1674. link+='/crf_tecant-visit.view?';
  1675. link+='entryId='+crf;
  1676. link+='&formId='+formId;
  1677. link+='&role='+recipient;
  1678. //debug
  1679. let recipients=getEmail(recipient);
  1680. //from crfManagers list
  1681. let typeHtml=LABKEY.Message.msgType.html;
  1682. let typePlain=LABKEY.Message.msgType.plain;
  1683. let msg1=LABKEY.Message.createMsgContent(typePlain,link);
  1684. //let cb=doNothing;
  1685. //let cb=redirect;
  1686. LABKEY.Message.sendMessage({
  1687. msgFrom:'labkey@fmf.uni-lj.si',
  1688. msgSubject:subj,
  1689. msgRecipients:recipients,
  1690. msgContent:[msg1],
  1691. success: cb
  1692. });
  1693. }
  1694. function hideErr(){
  1695. let el=config.document.getElementById("errorDiv");
  1696. el.style.display="none";
  1697. }
  1698. function clearErr(){
  1699. let el=config.document.getElementById("errorTxt");
  1700. el.value="";
  1701. }
  1702. function showErr(){
  1703. let el=config.document.getElementById("errorDiv");
  1704. el.style.display="block";
  1705. }
  1706. function printErr(msg){
  1707. showErr();
  1708. el=config.document.getElementById("errorTxt");
  1709. el.style.color="red";
  1710. el.value+="\n"+msg;
  1711. }
  1712. //**************************************************
  1713. //
  1714. function onRemoveCRF(){
  1715. let debug=true;
  1716. if (debug){
  1717. print("Removing CRF");
  1718. }
  1719. let selectRows=new Object();
  1720. //points to data container
  1721. selectRows.containerPath=getContainer('config');
  1722. selectRows.schemaName="lists";
  1723. selectRows.queryName="inputLists";
  1724. selectRows.success=afterInputLists;
  1725. LABKEY.Query.selectRows(selectRows);
  1726. }
  1727. function afterInputLists(data){
  1728. let debug=true;
  1729. if (debug)
  1730. print("After input lists");
  1731. config.inputLists=data;
  1732. config.inputListsIterator=0;
  1733. removeCRFLoop();
  1734. }
  1735. function removeCRFLoop(){
  1736. let debug=true;
  1737. let i=config.inputListsIterator;
  1738. let iMax=config.inputLists.rows.length;
  1739. //in fact, we are adding two additional passages of the loop, one for
  1740. //crfEntry, the second for the same query, but using parentCrf as the
  1741. //selection variable
  1742. let iTotal=iMax+1;
  1743. //let iTotal=iMax+1;
  1744. if (debug)
  1745. print("removeCRFLoop ["+i+"/"+iMax+"]");
  1746. if (i>iTotal){
  1747. if (0) return;
  1748. redirect();
  1749. }
  1750. let queryName="crfEntry";
  1751. let idVar="entryId";
  1752. let idValue=getCRFref();
  1753. if (i<iMax){
  1754. //in all but crfEntry, variable is called crfRef
  1755. queryName=config.inputLists.rows[i].queryName;
  1756. idVar="crfRef";
  1757. }
  1758. //for i=iMax and i=iMax+1, query is crfEntry.
  1759. //delete also crfEntries where parentCrf is set to crf that we are deleting
  1760. if (i==iTotal){
  1761. idVar='parentCrf';
  1762. }
  1763. if (debug)
  1764. print("["+i+"/"+iMax+"] "+queryName+":"+idVar+'/'+idValue);
  1765. let selectRows=new Object();
  1766. //points to data container
  1767. selectRows.containerPath=getContainer('data');
  1768. selectRows.schemaName="lists";
  1769. selectRows.queryName=queryName;
  1770. selectRows.filterArray=[LABKEY.Filter.create(idVar,idValue)];
  1771. selectRows.success=removeListCRF;
  1772. selectRows.failure=skipListCRF;
  1773. LABKEY.Query.selectRows(selectRows);
  1774. }
  1775. function removeListCRF(data){
  1776. let debug=true;
  1777. if (debug)
  1778. print(data.queryName+": "+data.rows.length);
  1779. config.inputListsIterator+=1;
  1780. if (data.rows.length==0){
  1781. removeCRFLoop();
  1782. return;
  1783. }
  1784. let deleteRows=new Object();
  1785. //points to data container
  1786. deleteRows.containerPath=getContainer('data');
  1787. deleteRows.schemaName=data.schemaName;
  1788. deleteRows.queryName=data.queryName;
  1789. deleteRows.success=function(data){removeCRFLoop()};
  1790. deleteRows.rows=data.rows;
  1791. LABKEY.Query.deleteRows(deleteRows);
  1792. }
  1793. function skipListCRF(errorInfo){
  1794. let debug=true;
  1795. if (debug)
  1796. print("Error in removeCRF: "+errorInfo.exception);
  1797. config.inputListsIterator+=1;
  1798. removeCRFLoop();
  1799. }
  1800. function redirect(){
  1801. let debug=false;
  1802. let formUrl="begin";
  1803. let params=new Object();
  1804. params.name=formUrl;
  1805. params.pageId="CRF";
  1806. //points to crf container
  1807. let containerPath=getContainer('CRF');
  1808. // This changes the page after building the URL.
  1809. //Note that the wiki page destination name is set in params.
  1810. var homeURL = LABKEY.ActionURL.buildURL(
  1811. "project", formUrl , containerPath, params);
  1812. print("Redirecting to "+homeURL);
  1813. if (debug) return;
  1814. window.location = homeURL;
  1815. }
  1816. //printing section
  1817. function checkBlob(){
  1818. print("checkBlob: "+config.blob);
  1819. if (config.blob) {
  1820. clearInterval(config.blobInterval);
  1821. config.a.href = config.window.URL.createObjectURL(config.blob);
  1822. print("HREF: "+config.a.href);
  1823. config.a.download = 'test.pdf';
  1824. config.a.click();
  1825. config.window.URL.revokeObjectURL(config.a.href);
  1826. }
  1827. config.count=config.count+1;
  1828. print("Eval: "+config.count);
  1829. if (config.count>100){
  1830. clearInterval(config.blobInterval);
  1831. }
  1832. }
  1833. function printForm(){
  1834. config.doc=new PDFDocument();
  1835. //config.doc.end();
  1836. let stream = config.doc.pipe(blobStream()).on("finish",function(){
  1837. config.blob=stream.toBlob("application/pdf");});
  1838. print("BLob: "+config.blob);
  1839. config.a = config.document.createElement("a");
  1840. config.document.body.appendChild(config.a);
  1841. config.a.innerHTML="Download PDF";
  1842. config.a.style = "display: none";
  1843. config.count=0;
  1844. //run until blob is set
  1845. config.blobInterval=setInterval(checkBlob,1000);
  1846. //pick data from crfForm list
  1847. print("Printing form");
  1848. printHeader();
  1849. setData(formatPrintData);
  1850. }
  1851. function printHeader(){
  1852. config.doc.fontSize(25).text(config.formConfig.form['formName']);
  1853. config.doc.moveDown();
  1854. let crfEntry=config.formConfig.crfEntry;
  1855. let site=config.formConfig.currentSite;
  1856. let val=new Object();
  1857. let user=config.formConfig.user;
  1858. val['A']={o:crfEntry,f:'EudraCTNumber',t:'Eudra CT Number'};
  1859. val['B']={o:crfEntry,f:'StudyCoordinator',t:'Study Coordinator'};
  1860. val['C']={o:crfEntry,f:'StudySponsor',t:'Study Sponsor'};
  1861. val['D']={o:site,f:'siteName',t:'Site'};
  1862. val['E']={o:site,f:'sitePhone',t:'Phone'};
  1863. val['F']={o:user,f:'DisplayName',t:'Investigator'};
  1864. for (let f in val){
  1865. print('Printing for '+f);
  1866. let e=val[f];
  1867. let entry=new Object();
  1868. entry[f]=e.o[e.f];
  1869. printPDF(entry,
  1870. {name:f,caption:e.t,type:'string'},null);
  1871. }
  1872. config.doc.moveDown();
  1873. }
  1874. function formatPrintData(){
  1875. qS=config.formConfig.dataQueries;
  1876. for (let q in qS){
  1877. print('Setting up '+q);
  1878. let qData=qS[q];
  1879. print('Number of rows: '+qData.rows.length);
  1880. if (qData.rows.length>0){
  1881. config.doc.fontSize(20).text(qData.title);
  1882. }
  1883. for (let i=0;i<qData.rows.length;i++){
  1884. let entry=qData.rows[i];
  1885. for (let f in qData.fields){
  1886. let field=qData.fields[f];
  1887. let lookup=null;
  1888. if (field.lookup){
  1889. lookup=config.formConfig.lookup[field.lookup.queryName];
  1890. }
  1891. if (field.hidden) continue;
  1892. printPDF(entry,field,lookup);
  1893. }
  1894. }
  1895. config.doc.moveDown();
  1896. }
  1897. print("All done");
  1898. config.doc.end();
  1899. }
  1900. function printPDF(entry,field,lookup){
  1901. //object field should have a name, type, caption
  1902. //entry should have field.name
  1903. //lookup is null or has a lookup table LUT
  1904. //for value v of entry[field.name]
  1905. //
  1906. //the total width of a A4 page is 598 px,
  1907. //left margin is 72. With a right margin of 50,
  1908. //the total available with is 476 px.
  1909. let w=476;
  1910. let spacing=25;
  1911. let w1=(w-spacing)*0.5;
  1912. let fontSize=14;
  1913. print('printPDF: entry['+field.name+']='+entry[field.name]);
  1914. let v=entry[field.name];
  1915. if (lookup!=null){
  1916. v=lookup.LUT[v];
  1917. }
  1918. print('printPDF: field type:'+field.type);
  1919. if (field.type=="date"){
  1920. let d=new Date(v);
  1921. v=d.getDate()+'/'+(d.getMonth()+1)+'/'+d.getFullYear();
  1922. }
  1923. if (v===null) v=' / ';
  1924. if (v===undefined) v=' / ';
  1925. //measure text
  1926. let label=field.caption;
  1927. let opt={width:w1};
  1928. config.doc.fontSize(fontSize);
  1929. //for more eloquent display the height of the text
  1930. //can be measured prior to output
  1931. //use currentLineHeight to scale height
  1932. //let lineH=config.doc.currentLineHeight(1);
  1933. //let h=config.doc.heightOfString(label,opt)/lineH;
  1934. //print label
  1935. config.doc.font('Courier').text(label,opt);
  1936. //align last row of description w/ first row of value
  1937. config.doc.moveUp();
  1938. //store x value for later use
  1939. let tx=config.doc.x;
  1940. let ty=config.doc.y;
  1941. //shift for value output
  1942. config.doc.x+=w1+spacing;
  1943. config.doc.font('Courier-Bold').text(v,opt);
  1944. //restore x value
  1945. config.doc.x=tx;
  1946. }
  1947. //master section, entry point from html files
  1948. function generateMasterForm(){
  1949. generateDebugSection();
  1950. //read enviroment from lists disperesed on labkey
  1951. setFormConfig();
  1952. }
  1953. //helper function to set basic parameters on web page
  1954. //(fields defined in html file)
  1955. function populateBasicData(){
  1956. let staticData=new Object();
  1957. let titles=new Object();
  1958. staticData['version']=config.formConfig.softwareVersion;
  1959. titles['version']='Software version';
  1960. let varRows=config.formConfig['crfStaticVariables'].rows;
  1961. for (let i=0;i<varRows.length;i++){
  1962. let vName=varRows[i].staticVariable;
  1963. let val=config.formConfig.crfEntry[vName];
  1964. if (val==undefined) continue;
  1965. staticData[vName]=val;
  1966. titles[vName]=varRows[i].Title;
  1967. }
  1968. staticData['investigatorName']=config.formConfig.user['DisplayName'];
  1969. titles['investigatorName']='Investigator';
  1970. staticData['email']=config.formConfig.user['Email'];
  1971. titles['email']='Email';
  1972. staticData['siteName']=config.formConfig.currentSite['siteName'];
  1973. titles['siteName']='Site';
  1974. staticData['sitePhone']=config.formConfig.currentSite['sitePhone'];
  1975. titles['sitePhone']='Telephone(site)';
  1976. for (f in staticData){
  1977. addStaticData(f,titles[f],staticData[f]);
  1978. }
  1979. }
  1980. function addStaticData(f,title,value){
  1981. let el=config.document.getElementById(f);
  1982. //populate only
  1983. if (el!=undefined){
  1984. el.innerText=value;
  1985. return;
  1986. }
  1987. //add row to table if element cannot be found
  1988. let table=config.document.getElementById('staticTable');
  1989. let row=table.insertRow();
  1990. let cell=row.insertCell();
  1991. cell.innerText=title;
  1992. let cell1=row.insertCell();
  1993. cell1.id=f;
  1994. cell1.style.fontWeight='bold';
  1995. //populate
  1996. cell1.innerText=value;
  1997. }
  1998. //come here after the layout is read from labkey page
  1999. //
  2000. function generateErrorMsg(msg){
  2001. let txt=config.document.createElement('p');
  2002. txt.innerText=msg;
  2003. config.document.getElementById(config.masterForm).appendChild(txt);
  2004. generateButton("submitDiv",'Exit','Exit','redirect',redirect);
  2005. }
  2006. function getUser(id,field){
  2007. if (field in config.formConfig) return config.formConfig[field];
  2008. let uRows=config.formConfig.userRows;
  2009. for (let i=0;i<uRows.length;i++){
  2010. let userId=uRows[i].UserId;
  2011. if (userId!=id) continue;
  2012. config.formConfig[field]=uRows[i];
  2013. return config.formConfig[field];
  2014. }
  2015. return null;
  2016. }
  2017. function afterConfig(){
  2018. let debug=true;
  2019. if (debug)
  2020. print("afterConfig");
  2021. populateBasicData();
  2022. //check if user has permission on the form
  2023. let currentUser=getUser(LABKEY.Security.currentUser.id,'currentUser');
  2024. let currentSite=config.formConfig.currentSite;
  2025. let formCreator=getUser(config.formConfig.crfEntry.UserId,'formCreator');
  2026. let formCreatorId=formCreator.UserId;
  2027. //let formSite=config.formConfig.crfEntry.Site;
  2028. let fList=config.formConfig.operator+'s';
  2029. let fRows=config.formConfig[fList];
  2030. //let currentSiteId=-1;
  2031. //depending on operator mode, we should decide what is right
  2032. let operator=config.formConfig.operator;
  2033. if (operator=='crfEditor'){
  2034. //editor can only edit its own forms
  2035. if (currentUser.UserId!=formCreatorId){
  2036. let msg='User '+currentUser.DisplayName;
  2037. msg+=' has no permission on this form';
  2038. generateErrorMsg(msg);
  2039. return;
  2040. }
  2041. }
  2042. if (operator=='crfMonitor' || operator=='crfSponsor'){
  2043. //monitor can look at forms based on his site
  2044. //find monitor line
  2045. let operatorSites=new Array();
  2046. for (let i=0;i<fRows.length;i++){
  2047. if (fRows[i].User!=currentUser.UserId) continue;
  2048. operatorSites.push(fRows[i].Site);
  2049. }
  2050. print('operator Site: '+operatorSites.length);
  2051. if (operatorSites.length==0){
  2052. let msg='User '+currentUser.DisplayName;
  2053. msg+=' is not a '+operator;
  2054. generateErrorMsg(msg);
  2055. return;
  2056. }
  2057. let selectedSite=-1;
  2058. let siteCandidates="[";
  2059. for (let i=0;i<operatorSites.length;i++){
  2060. if (i>0) siteCandidates+=", ";
  2061. siteCandidates+=operatorSites[i];
  2062. if (operatorSites[i]!=currentSite.siteNumber) continue;
  2063. selectedSite=currentSite.siteNumber;
  2064. break;
  2065. }
  2066. siteCandidates+="]";
  2067. if (selectedSite==-1){
  2068. let msg='User '+currentUser.DisplayName;
  2069. msg+=' is not a '+operator+' for site ';
  2070. msg+=currentSite.siteName+'('+currentSite.siteNumber+')';
  2071. msg+='/'+siteCandidates;
  2072. generateErrorMsg(msg);
  2073. return;
  2074. }
  2075. }
  2076. print('User '+currentUser.DisplayName+'/'+
  2077. config.formConfig.currentSite['siteName']+
  2078. ' acting as '+config.formConfig.operator);
  2079. let rows=config.formConfig.crfButtons.rows;
  2080. config.formConfig.targetStatus=new Array();
  2081. config.formConfig.targetRecipient=new Array();
  2082. for (let i=0; i<rows.length; i++){
  2083. let action=rows[i].action;//String
  2084. let tstatus=rows[i].targetFormStatus;
  2085. let trecip=rows[i].targetRecipient;
  2086. config.formConfig.targetStatus[action]=tstatus;
  2087. config.formConfig.targetRecipient[action]=trecip;
  2088. }
  2089. let formStatus=config.formConfig.formStatus;
  2090. //let functionArray=new Array();
  2091. print("Generating buttons for formStatus \""+ formStatus+"\"");
  2092. let buttonRows=config.formConfig.crfButtons.rows;
  2093. for (let i=0;i<buttonRows.length;i++){
  2094. let bt=buttonRows[i];
  2095. if (typeof window[bt.action]==="function"){
  2096. generateButton("submitDiv",bt.caption,bt.label,bt.action,
  2097. window[bt.action]);
  2098. }
  2099. else{
  2100. print('No match for function :'+bt.action+
  2101. ' obj: '+window[bt.action]);
  2102. }
  2103. }
  2104. print('Here');
  2105. //here we should get data. For now, just initialize objects that will hold data
  2106. setDataLayout(afterDataLayout);//callback is afterDataLayout
  2107. }
  2108. function afterDataLayout(){
  2109. setData(afterData);//callback is afterData
  2110. }
  2111. function verifyCrfStudyId(pM){
  2112. //is studyId already set for the crf
  2113. let studyId=pM.getParticipantIdFromCrfEntry('STUDY');
  2114. if (!studyId) return;
  2115. pM.mode="STUDY";
  2116. pM.readOnly="TRUE";
  2117. }
  2118. function verifyRegistration(pM){
  2119. //if registration is in,
  2120. //then local id should not be changed any longer
  2121. let idFieldName=pM.getCrfEntryFieldName("STUDY");
  2122. let registrationQuery=config.formConfig.settings['registrationQuery'];
  2123. if (!registrationQuery) return; //LOCAL is OK
  2124. let fQuery=config.formConfig.dataQueries[registrationQuery];
  2125. if (!fQuery) return; //no registration query, then it should be ignored
  2126. if (fQuery.rows.length==0) return; //registration is empty
  2127. let studyId=fQuery.rows[0][idFieldName];
  2128. if (!studyId) return; //study id not set
  2129. //set
  2130. pM.mode="STUDY";
  2131. pM.readOnly="TRUE";
  2132. //set crf (this happens later, but probably before the form will be corrected)
  2133. pM.setParticipantIdToCrfEntry(studyId,"STUDY");
  2134. pM.updateCrfEntry();
  2135. }
  2136. function afterData(){
  2137. let fName='afterData';
  2138. //operatorBasedAccessMode
  2139. let accessMode=config.formConfig.operator+'Mode';
  2140. let rowsSetup=config.formConfig.formSetupRows;
  2141. let idMode=config.formConfig.form['idMode'];
  2142. //set default value if no value is in the list (read value is null)
  2143. if (!idMode) idMode="STUDY:EDIT";
  2144. print(fName+': idMode '+idMode);
  2145. //add print to config so participantManager can use it
  2146. config.print=print;
  2147. let pM=getParticipantManagerObject(config);
  2148. pM.updateCrfEntry=function(){updateFlag(config.formConfig.crfEntry['FormStatus'],doNothing);};
  2149. let idModeArray=idMode.split(':');
  2150. pM.mode="STUDY";
  2151. if (idModeArray.includes("LOCAL")) {
  2152. pM.mode="LOCAL";
  2153. //OK, but check if CRF or registration indicate that study id is already set
  2154. verifyCrfStudyId(pM);
  2155. verifyRegistration(pM);
  2156. }
  2157. if (idModeArray.includes("READONLY")){
  2158. pM.readOnly="TRUE";
  2159. }
  2160. let pId=pM.getParticipantIdFromCrfEntry();
  2161. if (!pId){
  2162. pM.setEditMode();
  2163. }
  2164. else{
  2165. let label=pId;
  2166. if (pM.mode=="STUDY"){
  2167. let loc=pM.getParticipantIdFromCrfEntry('LOCAL');
  2168. label=pId+':'+loc;
  2169. pM.readOnly="true";
  2170. }
  2171. pM.setLabelMode(label);
  2172. //in STUDY mode also change LOCAL ID from crfEntry
  2173. }
  2174. for (let i=0;i<rowsSetup.length;i++){
  2175. let entry=rowsSetup[i];
  2176. let queryName=config.formConfig.queryMap[entry['queryName']];
  2177. print(fName+" ["+queryName+"]: showFlag: "+entry["showFlag"]);
  2178. print(fName+" ["+queryName+"]: accessMode: "+entry[accessMode]);
  2179. const nData=config.formConfig.dataQueries[queryName].rows.length;
  2180. print(fName+" ["+queryName+"]: nData: "+nData);
  2181. //skip sections
  2182. //also from fields
  2183. if (entry[accessMode]=="NONE") continue;
  2184. //skip readonly empty records
  2185. //if (entry[accessMode]=="READ" && nData==0) continue;
  2186. //let additionalData=new Object();
  2187. //setAdditionalData(additionalData,entry);
  2188. //section fits one dataset/list
  2189. generateSection(entry);
  2190. //generateSection(queryName,entry["title"],entry[accessMode],
  2191. // additionalData);
  2192. }
  2193. }
  2194. function findSetupRow(queryName){
  2195. let rowsSetup=config.formConfig.formSetupRows;
  2196. for (let i=0;i<rowsSetup.length;i++){
  2197. let e=rowsSetup[i];
  2198. let queryName1=config.formConfig.queryMap[e['queryName']];
  2199. if (e.formName!=config.formId) continue;
  2200. if (queryName1!=queryName) continue;
  2201. return e;
  2202. }
  2203. return null;
  2204. }
  2205. function populateSection(queryName){
  2206. let fName='[populateSection/'+queryName+']';
  2207. print(fName);
  2208. let entry=findSetupRow(queryName);
  2209. //ignore names without associated entry in formSetup
  2210. if (entry==undefined){
  2211. print(fName+': no matching FormSetup entry found');
  2212. return;
  2213. }
  2214. //populate comes after generate, we should be pretty safe in taking
  2215. //already generated additionalData
  2216. if (!(queryName in config.formConfig.additionalData)){
  2217. print(fName+': no additionalData generated for '+queryName);
  2218. return;
  2219. }
  2220. let additionalData=config.formConfig.additionalData[queryName];
  2221. print(fName+': using additionalData '+additionalData);
  2222. if ("isReview" in additionalData){
  2223. generateReviewSection(queryName,queryName,generateReviewSectionCB);
  2224. return;
  2225. }
  2226. let accessMode=config.formConfig.operator+'Mode';
  2227. let aM=entry[accessMode];
  2228. print(fName+': accessMode '+aM);
  2229. if (aM!='GENERATE'){
  2230. let writeMode=entry[accessMode]=='EDIT';
  2231. print(fName+': mode='+writeMode);
  2232. populateTable(queryName,writeMode);
  2233. return;
  2234. }
  2235. //deal with generate
  2236. //
  2237. //already available -> shift to READ mode
  2238. let divTable=queryName+'Table';
  2239. let divObj=config.document.getElementById(divTable);
  2240. let divRev=config.document.getElementById(queryName+'Review');
  2241. let divRLi=config.document.getElementById(queryName+'ReviewList');
  2242. let divGBu=config.document.getElementById(queryName+'GenerateButton');
  2243. print('div GBU: '+divGBu);
  2244. divObj.style.display="block";
  2245. divRev.style.display="block";
  2246. divRLi.style.display="block";
  2247. if (divGBu!=undefined) divGBu.style.display="none";
  2248. let nData=config.formConfig.dataQueries[queryName].rows.length;
  2249. print('['+queryName+']: nrows '+nData);
  2250. if (nData>0){
  2251. populateTable(queryName,0);
  2252. return;
  2253. }
  2254. //hide table
  2255. divObj.style.display="none";
  2256. divRev.style.display="none";
  2257. divRLi.style.display="none";
  2258. if (divGBu!=undefined) divGBu.style.display="block";
  2259. //add buttons?
  2260. //is button already generated?
  2261. //populateTable(entry);
  2262. }
  2263. //******* generateQuery infrastructure *********************
  2264. function onGenerateQuery(queryName){
  2265. let fName='[onGenerateQuery]';
  2266. print(fName+' '+queryName);
  2267. //
  2268. let cfgRows=config.formConfig.generateConfigData.rows;
  2269. // //queryName to queryId?
  2270. let queryId=config.formConfig.fields[queryName].queryId;
  2271. let cfgRow=undefined;
  2272. for (let i=0;i<cfgRows.length;i++){
  2273. if (cfgRows[i].queryId!=queryId) continue;
  2274. cfgRow=cfgRows[i];
  2275. break;
  2276. }
  2277. if (cfgRow==undefined){
  2278. print('generateConfig for queryName['+queryId+']='+queryName+' not found');
  2279. return;
  2280. }
  2281. //add config to the list
  2282. if (!("generateConfig" in config.formConfig)){
  2283. config.formConfig.generateConfig=new Object();
  2284. }
  2285. config.formConfig.generateConfig[queryName]=cfgRow;
  2286. if (!("generateForm" in config.formConfig)){
  2287. config.formConfig.generateForm=new Object();
  2288. }
  2289. //
  2290. let formRows=config.formConfig.formRows;
  2291. let formId=cfgRow.formId;
  2292. for (let i=0;i<formRows.length;i++){
  2293. if (formRows[i].Key==formId) {
  2294. config.formConfig.generateForm[queryName]=formRows[i];
  2295. break;
  2296. }
  2297. }
  2298. //print('XcfgRow '+config.formConfig.generateForm[queryName]);
  2299. //
  2300. // //check if all required datasets were at least saved
  2301. checkGenerationFields(queryName);
  2302. }
  2303. function checkGenerationFields(queryName){
  2304. let fName='[checkGenerationFields]';
  2305. let genForm=config.formConfig.generateForm[queryName];
  2306. let genCfg=config.formConfig.generateConfig[queryName];
  2307. let mailRecipient=genCfg.emailRecipient;
  2308. //list of queries that are part of Registration form
  2309. print(fName);
  2310. print(fName+' setRecipient: '+mailRecipient);
  2311. let formId=genForm.Key;
  2312. print(fName+" Checking form w/id "+formId);
  2313. let selectGenerationRows=selectFormSetupRows(formId);
  2314. //registration rows
  2315. for (let i=0;i<selectGenerationRows.length;i++){
  2316. let row=selectGenerationRows[i];
  2317. let queryId=row.queryName;
  2318. let fQueryName=config.formConfig.queryMap[queryId];
  2319. if (fQueryName==queryName) continue;
  2320. let fQuery=config.formConfig.dataQueries[fQueryName];
  2321. print('Checking '+fQueryName+' nrows: '+fQuery.rows.length);
  2322. if (fQuery.rows.length==0){
  2323. generateError(queryName,fQueryName);
  2324. return;
  2325. }
  2326. }
  2327. generateMessage(queryName,'Vailidation OK');
  2328. print('callback: set recipient: '+mailRecipient);
  2329. let cb=function(){prepareForm(queryName,formId,mailRecipient);};
  2330. generateListEntry(formId,queryName,cb);
  2331. }
  2332. function prepareForm(queryName,formId,mailRecipient){
  2333. print('prepareForm: recipient '+mailRecipient);
  2334. //
  2335. // return;
  2336. //look for existing registration entry
  2337. let selectRows=new Object();
  2338. //inputLists should be in configuration container
  2339. selectRows.containerPath=getContainer('data');
  2340. selectRows.schemaName='lists';
  2341. selectRows.queryName='crfEntry';
  2342. selectRows.success=function(data){generateForm(data,queryName,mailRecipient);};
  2343. let formFilter=LABKEY.Filter.create('Form',formId);
  2344. let parentCrfFilter=LABKEY.Filter.create('parentCrf',getCRFref());
  2345. selectRows.filterArray=[formFilter,parentCrfFilter];
  2346. LABKEY.Query.selectRows(selectRows);
  2347. }
  2348. function generateError(queryName,fQueryName){
  2349. let elName=queryName+'GenerateButton'+'_reportField';
  2350. let el=config.document.getElementById(elName);
  2351. el.innerText='Error: '+fQueryName+' was not set';
  2352. el.style.color='red';
  2353. }
  2354. function generateMessage(queryName,msg){
  2355. let elName=queryName+'GenerateButton'+'_reportField';
  2356. let el=config.document.getElementById(elName);
  2357. el.innerText=msg;
  2358. el.style.color='green';
  2359. }
  2360. function generateForm(data,queryName,mailRecipient){
  2361. print('generateForm, recipient: '+mailRecipient);
  2362. //
  2363. const nData=data.rows.length;
  2364. print('Registration: '+nData+' rows');
  2365. let formRow=config.formConfig.generateForm[queryName];
  2366. //we have to generate masterQuery with parentCrf and crfRef
  2367. //and crfEntry with new entryId and parentCrf equal to crfRef
  2368. if (nData>0) {
  2369. generateMessage(queryName,'Registration already generated.');
  2370. return;
  2371. }
  2372. let formId=formRow.Key;
  2373. let formName=formRow.formName;
  2374. let crfBase=config.formConfig.crfEntry;
  2375. let crfEntry=new Object();
  2376. //add new reference
  2377. crfEntry.entryId=Date.now();
  2378. crfEntry.parentCrf=getCRFref();
  2379. crfEntry["Date"]=new Date();
  2380. crfEntry["View"]="[VIEW]";
  2381. crfEntry.formStatus=1;//In progress
  2382. //get local Id
  2383. let pM=getParticipantManagerObject(config);
  2384. crfEntry[pM.getCrfEntryFieldName()]=pM.getParticipantIdFromCrfEntry();
  2385. // //set other variables
  2386. //requires studyData as part of formConfig
  2387. // let studyData=config.formConfig.studyData;
  2388. print('Adding study: '+crfBase.EudraCTNumber);
  2389. crfEntry.EudraCTNumber=crfBase.EudraCTNumber;
  2390. crfEntry.StudyCoordinator=crfBase.StudyCoordinator;
  2391. crfEntry.StudySponsor=crfBase.StudySponsor;
  2392. crfEntry.RegulatoryNumber=crfBase.RegulatoryNumber;
  2393. //
  2394. // //find sponsor for site
  2395. let site=crfBase.Site;
  2396. let crfSponsors=config.formConfig.crfSponsors;
  2397. let users=config.formConfig.userRows;
  2398. for (let i=0;i<crfSponsors.length;i++){
  2399. //print('Checking for site '+crfSponsors[i].Site);
  2400. if (crfSponsors[i].Site!=site) continue;
  2401. config.formConfig.sponsorId=crfSponsors[i].User;
  2402. //print('Setting id '+config.formConfig.sponsorId);
  2403. //finds first
  2404. break;
  2405. }
  2406. for (let j=0;j<users.length;j++){
  2407. if (config.formConfig.sponsorId!=users[j].UserId) continue;
  2408. config.formConfig.sponsor=users[j];
  2409. //finds first (should be unique)
  2410. break;
  2411. }
  2412. print('Selecting '+config.formConfig.sponsor.DisplayName+' as sponsor');
  2413. //different user than the original form...
  2414. //should be set to the study sponsor
  2415. crfEntry.UserId=config.formConfig.sponsor.UserId;
  2416. crfEntry.Site=site;
  2417. // //set formId to one found through registration search
  2418. crfEntry.Form=formId;
  2419. ////
  2420. let qconfig=new Object();
  2421. qconfig.schemaName='lists';
  2422. qconfig.queryName='crfEntry';
  2423. qconfig.success=function(data){sendEmail(data,mailRecipient,doNothing,formName+' generated');}
  2424. qconfig.rows=[crfEntry];
  2425. LABKEY.Query.insertRows(qconfig);
  2426. }
  2427. //
  2428. function generateListEntry(formId,queryName,cb){
  2429. //check if registration was already generated
  2430. let formRows=config.formConfig.formRows;
  2431. let qForm=undefined;
  2432. for (let i=0;i<formRows.length;i++){
  2433. if (formRows[i].Key!=formId) continue;
  2434. qForm=formRows[i];
  2435. }
  2436. let nData=config.formConfig.dataQueries[queryName].rows.length
  2437. if (nData>0) return;
  2438. let pM=getParticipantManagerObject(config);
  2439. let e2=new Object();
  2440. e2.crfRef=getCRFref();
  2441. e2.registrationStatus=0;
  2442. e2.submissionDate=new Date();
  2443. e2[pM.getCrfEntryFieldName()]=pM.getParticipantIdFromCrfEntry();
  2444. print('set values');
  2445. let qconfig=new Object();
  2446. qconfig.containerPath=getContainer('data');
  2447. qconfig.schemaName='lists';
  2448. qconfig.queryName=queryName;
  2449. qconfig.success=cb;
  2450. qconfig.rows=[e2]
  2451. LABKEY.Query.insertRows(qconfig);
  2452. }
  2453. // ******************** end form generator (Registration) ********************
  2454. //jump to populate table/generate review, etc defined at the begining of the file
  2455. function setContainer(label,container){
  2456. if (!(config.formConfig.hasOwnProperty('container'))){
  2457. config.formConfig.container=new Array();
  2458. }
  2459. config.formConfig.container[label]=container;
  2460. }
  2461. function getContainer(label){
  2462. return config.formConfig.container[label];
  2463. }
  2464. //entry point from generateMasterForm
  2465. function setFormConfig(){
  2466. //add object to store form related data
  2467. config.formConfig=new Object();
  2468. config.formConfig.softwareVersion='T.15.18';
  2469. let debug=true;
  2470. if (debug)
  2471. print("generateMasterForm1");
  2472. //set containers for data and configuration
  2473. //TODO: set this from a query
  2474. //
  2475. setContainer('data',LABKEY.ActionURL.getContainer());
  2476. setContainer('config',LABKEY.ActionURL.getContainer());
  2477. setContainer('CRF',LABKEY.ActionURL.getContainer());
  2478. let selectRows=new Object();
  2479. //this is local data
  2480. selectRows.containerPath=getContainer('CRF');
  2481. selectRows.schemaName='lists';
  2482. selectRows.queryName='crfSettings';
  2483. //store form related data to this object
  2484. selectRows.success=afterSettings;
  2485. LABKEY.Query.selectRows(selectRows);
  2486. }
  2487. function convertToDictionary(rows){
  2488. let x=new Array();
  2489. for (let i=0;i<rows.length;i++){
  2490. let n=rows[i]['name'];
  2491. let v=rows[i]['value'];
  2492. x[n]=v;
  2493. }
  2494. return x;
  2495. }
  2496. function convertToAssociatedArray(rows,fieldName="name"){
  2497. let fName="[convertToAssociatedArray]";
  2498. let x=new Object();
  2499. for (let i=0;i<rows.length;i++){
  2500. let n=rows[i][fieldName];
  2501. x[n]=rows[i];
  2502. }
  2503. return x;
  2504. }
  2505. function afterSettings(data){
  2506. config.formConfig.settings=convertToDictionary(data.rows);
  2507. let st=config.formConfig.settings;
  2508. print('afterSettings');
  2509. for (let k in st){
  2510. print('\t'+k+'='+st[k]);
  2511. }
  2512. //if ('dataContainer' in st){
  2513. // setContainer('data',st['dataContainer']);
  2514. //}
  2515. let vname='configContainer';
  2516. if (vname in st){
  2517. setContainer('config',st[vname]);
  2518. }
  2519. print('Config: '+getContainer('config'));
  2520. print('Data: '+getContainer('data'));
  2521. let selectRows=new Object();
  2522. //this is local data
  2523. selectRows.containerPath=getContainer('data');
  2524. selectRows.schemaName='lists';
  2525. selectRows.queryName='crfEntry';
  2526. //use first-> we must first establish link to the rigth crf entry
  2527. selectRows.filterArray=[LABKEY.Filter.create('entryId',getCRFrefFirst())];
  2528. //store form related data to this object
  2529. selectRows.success=afterCRFEntry;
  2530. LABKEY.Query.selectRows(selectRows);
  2531. }
  2532. function afterCRFEntry(data){
  2533. config.formConfig.crfEntry=data.rows[0];
  2534. print("Setting crfEntry (x) to "+config.formConfig.crfEntry["entryId"]);
  2535. //for empty records or those with parentCrf not set, parentCrf comes up as null
  2536. //nevertheless, with two equal signs, check against undefined also works
  2537. print('parentCrf set to '+config.formConfig.crfEntry.parentCrf);
  2538. collectData();
  2539. }
  2540. function collectData(){
  2541. let targetObject=config.formConfig;
  2542. targetObject.print=print;
  2543. targetObject.getContainer=getContainer;
  2544. let queryArray=new Array();
  2545. //k
  2546. //site
  2547. queryArray.push(makeQuery(targetObject,'config','site','siteData',[]));
  2548. //users
  2549. queryArray.push(makeQuery(targetObject,'CRF','users','userData',[]));
  2550. queryArray[queryArray.length-1].schemaName='core';
  2551. //crfEditors
  2552. queryArray.push(makeQuery(targetObject,'config','crfEditors','crfEditorsData',[]));
  2553. //crfMonitors
  2554. queryArray.push(makeQuery(targetObject,'config','crfMonitors','crfMonitorsData',[]));
  2555. //crfSponsors
  2556. queryArray.push(makeQuery(targetObject,'config','crfSponsors','crfSponsorsData',[]));
  2557. //study static data
  2558. queryArray.push(
  2559. makeQuery(targetObject,'data','crfStaticVariables','crfStaticVariables',[]));
  2560. queryArray.push(makeQuery(targetObject,'data','specialFields','specialFieldsQuery',[]));
  2561. //study
  2562. queryArray.push(makeQuery(targetObject,'data','Study','studyDataAll1',[]));
  2563. let e=queryArray[queryArray.length-1];
  2564. //overload schema name
  2565. e.schemaName='study';
  2566. //make sure variables not part of default view are loaded
  2567. //here we should already have read crfStaticVariables table
  2568. e.columns="SubjectColumnName,EudraCTNumber,StudySponsor";
  2569. e.columns+=",StudyCoordinator,RegulatoryNumber";
  2570. //formStatus
  2571. let varLabel='sourceFormStatus';
  2572. let formStatus=config.formConfig.crfEntry['FormStatus'];
  2573. let formFilter=LABKEY.Filter.create('Key',formStatus);
  2574. queryArray.push(
  2575. makeQuery(targetObject,'config','FormStatus','formStatusData',[formFilter]));
  2576. //crfButtons
  2577. let statusFilter=LABKEY.Filter.create(varLabel,formStatus);
  2578. queryArray.push(
  2579. makeQuery(targetObject,'config','crfButtons','crfButtons',[statusFilter]));
  2580. //Forms
  2581. queryArray.push(makeQuery(targetObject,'config','Forms','formData',[]));
  2582. //FormSetup
  2583. queryArray.push(makeQuery(targetObject,'config','FormSetup','formSetup',[]));
  2584. //generateConfig
  2585. queryArray.push(
  2586. makeQuery(targetObject,'config','generateConfig','generateConfigData',[]));
  2587. //parentCrf
  2588. let parentCrf=config.formConfig.crfEntry['parentCrf'];
  2589. if (parentCrf!=undefined){
  2590. let crfFilter=LABKEY.Filter.create('entryId',parentCrf);
  2591. queryArray.push(makeQuery(targetObject,'data','crfEntry','parentCrfData',[crfFilter]));
  2592. }
  2593. print('running getDataFromQueries');
  2594. getDataFromQueries(queryArray,addStudyData);
  2595. }
  2596. function addStudyData(){
  2597. let fName='addStudyData';
  2598. //convert specialFields to array
  2599. let q=config.formConfig["specialFieldsQuery"].rows;
  2600. config.formConfig.specialFields=convertToAssociatedArray(q,"fieldUID");
  2601. print(fName);
  2602. let queryArray=new Array();
  2603. let targetObject=config.formConfig;
  2604. targetObject.print=print;
  2605. targetObject.getContainer=getContainer;
  2606. //study
  2607. queryArray.push(makeQuery(targetObject,'data','Study','studyDataAll',[]));
  2608. //queryArray.push(makeQuery('data','Study','studyDataAll',[]));
  2609. let e=queryArray[queryArray.length-1];
  2610. //overload schema name
  2611. e.schemaName='study';
  2612. //make sure variables not part of default view are loaded
  2613. //here we should already have read crfStaticVariables table
  2614. let staticVarRows=config.formConfig['crfStaticVariables'].rows;
  2615. let columnModel=""
  2616. for (let i=0;i<staticVarRows.length;i++){
  2617. if (i>0) columnModel+=',';
  2618. columnModel+=staticVarRows[i]['staticVariable'];
  2619. }
  2620. e.columns=columnModel;
  2621. //also collect ids already in study
  2622. //registrationQuery should be a dataset
  2623. let demoQuery=config.formConfig.settings['registrationQuery'];
  2624. queryArray.push(makeQuery(targetObject,'data',demoQuery,'registrationData',[]));
  2625. queryArray[queryArray.length-1].schemaName='study';
  2626. getDataFromQueries(queryArray,fcontinue);
  2627. }
  2628. function selectFormSetupRows(formId){
  2629. let formSetupRows=new Array();
  2630. let allRows=config.formConfig.formSetup.rows;
  2631. for (let i=0;i<allRows.length;i++){
  2632. let formEntry=allRows[i];
  2633. if (formEntry.formName==formId)
  2634. formSetupRows.push(formEntry);
  2635. }
  2636. return formSetupRows;
  2637. }
  2638. function fcontinue(){
  2639. //debug
  2640. let fName='[fcontinue]';
  2641. let varRows=config.formConfig['crfStaticVariables'].rows;
  2642. let studyVars=config.formConfig['studyDataAll'].rows[0];
  2643. for (let i=0;i<varRows.length;i++){
  2644. let vName=varRows[i].staticVariable;
  2645. print(fName+' '+vName+': '+studyVars[vName]);
  2646. }
  2647. //parse site
  2648. config.formConfig.siteRows=config.formConfig.siteData.rows;
  2649. let sRows=config.formConfig.siteRows;
  2650. for (let i=0;i<sRows.length;i++){
  2651. let siteId=sRows[i].siteNumber;
  2652. print('site '+siteId);
  2653. if (siteId==config.formConfig.crfEntry.Site){
  2654. config.formConfig.currentSite=sRows[i];
  2655. break;
  2656. }
  2657. }
  2658. //config.formConfig.site=data.rows[0];
  2659. print("Setting site name to "+config.formConfig.currentSite.siteName);
  2660. //study
  2661. config.formConfig.studyData=config.formConfig.studyDataAll.rows[0];
  2662. print("XSetting participantField to "+
  2663. config.formConfig.studyData["SubjectColumnName"]);
  2664. config.formConfig.crfEditors=config.formConfig.crfEditorsData.rows;
  2665. config.formConfig.crfMonitors=config.formConfig.crfMonitorsData.rows;
  2666. config.formConfig.crfSponsors=config.formConfig.crfSponsorsData.rows;
  2667. config.formConfig.userRows=config.formConfig.userData.rows;
  2668. let uRows=config.formConfig.userRows;
  2669. for (let i=0;i<uRows.length;i++){
  2670. let userId=uRows[i].UserId;
  2671. if (userId==config.formConfig.crfEntry.UserId){
  2672. config.formConfig.user=uRows[i];
  2673. break;
  2674. }
  2675. }
  2676. //config.formConfig.user=data.rows[0];
  2677. print("Setting user to "+config.formConfig.user["DisplayName"]);
  2678. let fsRows=config.formConfig.formStatusData.rows;
  2679. config.formConfig.formStatus=fsRows[0].formStatus;
  2680. config.formConfig.operator=config.role;
  2681. //config.formConfig.operator=fsRows[0].operator;
  2682. print('Setting operator to: '+config.formConfig.operator);
  2683. config.formConfig.formRows=config.formConfig.formData.rows;
  2684. let formRows=config.formConfig.formRows;
  2685. //filter out the current form
  2686. for (let i=0;i<formRows.length;i++){
  2687. if (formRows[i].Key==config.formId){
  2688. config.formConfig.form=formRows[i];
  2689. break;
  2690. }
  2691. }
  2692. config.formConfig.formSetupRows=selectFormSetupRows(config.formId);
  2693. print("Number of datasets for form ["+config.formId+"]: "+
  2694. config.formConfig.formSetupRows.length);
  2695. let fields=config.formConfig.formSetup.metaData.fields;
  2696. //get the lookup for queryName column
  2697. let formQueryName='queryName';
  2698. let field="NONE";
  2699. for (f in fields){
  2700. if (fields[f]['name']!=formQueryName) continue;
  2701. field=fields[f];
  2702. break;
  2703. }
  2704. let lookup=field.lookup;
  2705. print("Getting dataset names from "+lookup.queryName);
  2706. let selectRows=new Object();
  2707. //inputLists should be in configuration container
  2708. selectRows.containerPath=getContainer('config');
  2709. selectRows.schemaName=lookup.schemaName;
  2710. selectRows.queryName=lookup.queryName;
  2711. selectRows.success=afterFormDatasets;
  2712. LABKEY.Query.selectRows(selectRows);
  2713. }
  2714. function afterFormDatasets(data){
  2715. print('afterFormDatasets: '+data.rows.length);
  2716. config.formConfig.formDatasets=data;//inputLists
  2717. config.formConfig.fields=new Object();
  2718. config.formConfig.queryMap=new Object();
  2719. config.formConfig.additionalData=new Object();
  2720. let rows=config.formConfig.formSetupRows;
  2721. //should skip report only rows
  2722. for (let i=0;i<rows.length;i++){
  2723. let entry=rows[i];
  2724. let reviewField=(entry['showFlag']=='REVIEW');
  2725. //is the operator set yet?
  2726. let accessMode=config.formConfig.operator+'Mode';
  2727. let skipField=(entry[accessMode]=="NONE");
  2728. let queryId=entry['queryName'];
  2729. let lookupRows=config.formConfig.formDatasets.rows;
  2730. print('QueryID['+i+']='+queryId);
  2731. let dentry;
  2732. for (let j=0;j<lookupRows.length;j++){
  2733. if (queryId!=lookupRows[j]['Key']) continue;
  2734. dentry=lookupRows[j];
  2735. break;
  2736. }
  2737. let qName=dentry['queryName'];
  2738. //update list of dataset formConfig is observing (fields/queryMap)
  2739. while (1){
  2740. //review contains no data
  2741. if (reviewField) break;
  2742. if (skipField) break;
  2743. //already in fields
  2744. if (qName in config.formConfig.fields) break;
  2745. config.formConfig.fields[qName]=new Object();
  2746. break;
  2747. }
  2748. while(1){
  2749. //already done
  2750. if (queryId in config.formConfig.queryMap) break;
  2751. config.formConfig.queryMap[queryId]=qName;
  2752. break;
  2753. }
  2754. if (reviewField) continue;
  2755. if (skipField) continue;
  2756. //only do this for real lists
  2757. let field=config.formConfig.fields[qName];
  2758. field.title=entry['title'];
  2759. field.queryId=queryId;
  2760. }
  2761. print("List of datasets in form : ");
  2762. for (f in config.formConfig.fields){
  2763. let field=config.formConfig.fields[f];
  2764. print("\t"+f+" ID: "+field.queryId+' title '+field.title);
  2765. }
  2766. afterConfig();
  2767. }
  2768. //>>>>>>>>>>>>>>>>>new>>>>>>>>>>>>
  2769. function setDataLayout(cb){
  2770. let rowsSetup=config.formConfig.formSetupRows;
  2771. config.formConfig.dataQueries=new Object();
  2772. let dS=config.formConfig.dataQueries;//reference only
  2773. let qMap=config.formConfig.queryMap;
  2774. config.formConfig.lookup=new Object();
  2775. for (let i=0;i<rowsSetup.length;i++){
  2776. let entry=rowsSetup[i];
  2777. //skip review rows
  2778. if (entry['showFlag']=='REVIEW')
  2779. continue;
  2780. let queryId=entry['queryName'];
  2781. let queryName=qMap[entry['queryName']];
  2782. dS[queryName]=new Object();
  2783. dS[queryName].title=entry['title'];
  2784. if (entry['showQuery']!="NONE"){
  2785. let sqName=entry['showQuery'];
  2786. dS[sqName]=new Object();
  2787. dS[sqName].title=findTitle(sqName);
  2788. }
  2789. }
  2790. //always add reviews
  2791. //
  2792. config.formConfig.dataQueries['reviewComments']=new Object();
  2793. //perhaps we will need queryId, but this is stuff for later
  2794. for (q in config.formConfig.dataQueries){
  2795. //callback will be a watchdog and will complete only
  2796. //when all data will be gathered
  2797. let dq=config.formConfig.dataQueries[q];
  2798. dq.collectingLayout="INITIALIZED";
  2799. let selectRows=new Object();
  2800. selectRows.queryName=q;
  2801. selectRows.schemaName='lists';
  2802. selectRows.containerPath=getContainer('data');
  2803. //we are only interested in metadata
  2804. selectRows.success=function(data){afterDatasets(data,cb);}
  2805. LABKEY.Query.selectRows(selectRows);
  2806. }
  2807. }
  2808. function findTitle(queryName){
  2809. //find by name from formDatasets
  2810. //and set associated title as title
  2811. let rows=config.formConfig.formDatasets.rows;
  2812. for (let i=0;i<rows.length;i++){
  2813. let entry=rows[i];
  2814. if (entry['queryName']!=queryName) continue;
  2815. return entry['title'];
  2816. }
  2817. return "NONE";
  2818. }
  2819. //this happens after the for loop, so all dataQueries objects are set
  2820. function afterDatasets(data,cb){
  2821. let qobject=config.formConfig.dataQueries[data.queryName];
  2822. print("Inspecting layout for "+data.queryName+" "+qobject);
  2823. qobject.fields=data.metaData.fields;
  2824. qobject.collectingLayout="STARTED";
  2825. //qobject.started="TRUE";
  2826. qobject.lookup=new Object();//keep track of objects
  2827. let i=0;
  2828. for (let f in qobject.fields){
  2829. //anything else is simple but lookup
  2830. let field=qobject.fields[f];
  2831. if (!("lookup" in field)) continue;
  2832. qobject.lookup[f]="PENDING";
  2833. print("Adding pending lookup for field "+f);
  2834. if (field.lookup.queryName in config.formConfig.lookup){
  2835. qobject.lookup[f]="DONE";
  2836. continue;
  2837. }
  2838. print("Setting up query for field "+f);
  2839. config.formConfig.lookup[field.lookup.queryName]=new Object();
  2840. let lObject=config.formConfig.lookup[field.lookup.queryName];
  2841. lObject.keyColumn=field.lookup.keyColumn;
  2842. lObject.displayColumn=field.lookup.displayColumn;
  2843. let selectRows=new Object();
  2844. selectRows.schemaName=field.lookup.schemaName;
  2845. selectRows.queryName=field.lookup.queryName;
  2846. selectRows.containerPath=getContainer('data');
  2847. if ("containerPath" in field.lookup){
  2848. selectRows.containerPath=field.lookup.containerPath;
  2849. }
  2850. selectRows.columns=field.lookup.keyColumn+","+
  2851. field.lookup.displayColumn;
  2852. //wait for all lookups to return
  2853. selectRows.success=function(data){addLookup(data,qobject,f,cb);};
  2854. print("Sending query: ["+
  2855. field.lookup.queryName+"] "+
  2856. field.lookup.keyColumn+'/'+
  2857. field.lookup.displayColumn);
  2858. LABKEY.Query.selectRows(selectRows);
  2859. i+=1;
  2860. }
  2861. if (i==0){
  2862. print("No lookups for "+data.queryName);
  2863. qobject.collectingLayout="FINISHED";
  2864. }
  2865. //check if done (both here and in lookup
  2866. //this only passes if no lookups are anywhere in the dataset assembly
  2867. if (!dataLayoutSet()) return;
  2868. cb();
  2869. }
  2870. function addLookup(data,qobject,f,cb){
  2871. print("Adding lookup "+data.queryName+' '+qobject+' '+f);
  2872. let lObject=config.formConfig.lookup[data.queryName];
  2873. lObject.LUT=new Array();//key to value
  2874. lObject.ValToKey=new Array();//value to key
  2875. let key=lObject.keyColumn;
  2876. let val=lObject.displayColumn;
  2877. for (let i=0;i<data.rows.length;i++){
  2878. lObject.LUT[data.rows[i][key]]=data.rows[i][val];
  2879. lObject.ValToKey[data.rows[i][val]]=data.rows[i][key];
  2880. }
  2881. qobject.lookup[f]="DONE";
  2882. if (!dataLayoutSet()) return;
  2883. cb();
  2884. }
  2885. function dataLayoutSet(){
  2886. print("Checking layout completeness");
  2887. let dq=config.formConfig.dataQueries;
  2888. for (f in dq){
  2889. print("["+f+"]: "+dq[f].collectingLayout);
  2890. if (dq[f].collectingLayout=="INITIALIZED")
  2891. return 0;
  2892. if (dq[f].collectingLayout=="FINISHED")
  2893. continue; //OK
  2894. let qobject=dq[f];
  2895. for (q in qobject.lookup){
  2896. if (qobject.lookup[q]=="DONE") {
  2897. print("["+f+"/"+q+"]: DONE");
  2898. continue;//OK
  2899. }
  2900. print("["+f+"/"+q+"]: "+qobject.lookup[q]);
  2901. return 0;
  2902. }
  2903. dq[f].collectingLayout="FINISHED";
  2904. }
  2905. print("Success");
  2906. return 1;
  2907. }
  2908. function setData(cb){
  2909. fName='[setData]';
  2910. //print(fName+': cb '+cb);
  2911. let crfMatch=getCRFref();
  2912. let parentCrf=config.formConfig.crfEntry['parentCrf'];
  2913. if (parentCrf!=undefined) crfMatch=parentCrf;
  2914. print(fName+' form crf ['+getCRFref()+'] matching for crfRef='+crfMatch);
  2915. //collect data and execute callback cb for queries in cb.queryList
  2916. for (q in config.formConfig.dataQueries){
  2917. let fQuery=config.formConfig.dataQueries[q];
  2918. fQuery.collectingData="STARTED";
  2919. let selectRows=new Object();
  2920. selectRows.containerPath=getContainer('data');
  2921. selectRows.queryName=q;
  2922. selectRows.schemaName='lists';
  2923. selectRows.filterArray=[
  2924. LABKEY.Filter.create("crfRef",crfMatch)
  2925. ];
  2926. selectRows.success=function(data){assembleData(data,cb);};
  2927. LABKEY.Query.selectRows(selectRows);
  2928. }
  2929. }
  2930. function assembleData(data,cb){
  2931. let fName='[assembleData/'+data.queryName+']';
  2932. let fQuery=config.formConfig.dataQueries[data.queryName];
  2933. fQuery.rows=data.rows;
  2934. fQuery.collectingData="FINISHED";
  2935. print(fName+': adding data');
  2936. for (q in config.formConfig.dataQueries){
  2937. let dq=config.formConfig.dataQueries[q];
  2938. //print("assembleData ["+q+"]: "+dq.collectingData);
  2939. if (dq.collectingData=="STARTED") return;
  2940. }
  2941. print(fName+': completing');
  2942. cb();
  2943. }
  2944. function uploadFile(inputElement,context){
  2945. //context should have ID and dirName attributes;
  2946. //path will be dirName/ID/fieldName_ID.suf
  2947. //where suf is identical to localPath content picked from
  2948. //inputElement
  2949. print('uploadFile: '+inputElement.value+'/');
  2950. if (inputElement.type=="text") return;
  2951. print('uploadFile: '+inputElement.files+'/');
  2952. print('uploadFile: '+inputElement.files.length+'/');
  2953. if (inputElement.files.length>0){
  2954. let file=inputElement.files[0];
  2955. print('uploadFile: '+inputElement.value+'/'+file.size);
  2956. }
  2957. let url=LABKEY.ActionURL.getBaseURL();
  2958. url+='_webdav';
  2959. url+=LABKEY.ActionURL.getContainer();
  2960. url+='/@files';
  2961. url+='/'+context['dirName'];
  2962. print('uploadFile url: '+url);
  2963. let uploadConfig=new Object();
  2964. uploadConfig.inputElement=inputElement;
  2965. uploadConfig.context=context;
  2966. uploadConfig.url=url;
  2967. uploadConfig.success=afterBaseDir;
  2968. uploadConfig.failure=tryMakeDir;
  2969. webdavCheck(uploadConfig);
  2970. }
  2971. function afterBaseDir(cfg){
  2972. print('afterBaseDir');
  2973. cfg.url+='/'+cfg.context['ID'];
  2974. cfg.success=afterIDDir;
  2975. cfg.failure=tryMakeDir;
  2976. webdavCheck(cfg);
  2977. }
  2978. function afterIDDir(cfg){
  2979. print('afterIDDir');
  2980. if (cfg.inputElement.files.length==0){
  2981. print('No files found');
  2982. return;
  2983. }
  2984. let file=cfg.inputElement.files[0];
  2985. print('Uploading '+file.name);
  2986. let suf=file.name.split('.').pop();
  2987. cfg.url+='/'+cfg.context['ID']+'.'+suf;
  2988. cfg.success=afterUpload;
  2989. cfg.failure=onFailure;
  2990. cfg.data=file;
  2991. webdavPut(cfg);
  2992. }
  2993. function afterUpload(cfg){
  2994. print('afterUpload');
  2995. }
  2996. function tryMakeDir(cfg){
  2997. print('tryMakeDir '+cfg.url);
  2998. cfg.failure=onFailure;
  2999. webdavMakeDir(cfg);
  3000. }
  3001. function request(cfg,verb,data){
  3002. print('request['+verb+'] '+cfg.url);
  3003. let connRequest=new XMLHttpRequest();
  3004. connRequest.addEventListener("loadend",
  3005. function(){checkResponse(connRequest,cfg);});
  3006. connRequest.open(verb, cfg.url);
  3007. connRequest.send(data);
  3008. //print('request['+verb+'] sent');
  3009. }
  3010. function checkResponse(xrq,cfg){
  3011. //print('checkResponse: readyState '+xrq.readyState);
  3012. //print('checkResponse: status '+xrq.status);
  3013. if (xrq.status<400) {
  3014. //client errors 400-499
  3015. //server errors 500-599
  3016. cfg.success(cfg);
  3017. return;
  3018. }
  3019. cfg.status=xrq.status;
  3020. cfg.failure(cfg);
  3021. }
  3022. function webdavMakeDir(cfg){ request(cfg,'MKCOL',null);}
  3023. function webdavCheck(cfg) { request(cfg,'GET',null);}
  3024. function webdavPut(cfg) { request(cfg,'PUT',cfg.data);}
  3025. function onFailure(cfg){
  3026. print('request failed with status='+cfg.status);
  3027. }