crfVisit.js 101 KB

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