crfVisit.js 104 KB

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