crfVisit.js 99 KB

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