crfVisit.js 105 KB

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