crfVisit.js 100 KB

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