crfVisit.js 100 KB

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