Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

requestController copy 3.php 95KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523
  1. <?php
  2. class requestController extends mainController {
  3. function __construct() {
  4. parent::__construct();
  5. //To change for every Controllers
  6. $this->viewDir = 'Request';
  7. //$this->allow = [];
  8. define('MAX_ATTACH_TITLE_LENGTH', 30);
  9. }
  10. //List the requests
  11. public function index() {
  12. if(!$this->checkPermissions([ADMIN_ROLE_ID, MODERATOR_ROLE_ID, APPLICANT_ROLE_ID, REFERRER_ROLE_ID, GUEST_ROLE_ID])) {
  13. return $this->redirect('login', 'permissionDenied');
  14. }
  15. $this->controllerName = 'request';
  16. $this->actionName = 'index';
  17. $hr = new HandleRequest();
  18. $this->view->logList = $hr->getActivityLogList();
  19. //Scopes: "my" | "center" | "moderations" | "reports (referral)"
  20. $this->view->scope = $this->getPost('scope', 'my');
  21. $this->view->userHasClinicalCenters = true;
  22. $this->view->baseUri = 'requests/'.time().'/'.$this->view->scope;
  23. $this->view->currentPage = $this->getPost('pageNumb', 1);
  24. //$this->view->orderField = $this->getPost('orderField', 'created_at');
  25. $this->view->orderField = $this->getPost('orderField', 'request_status_number');
  26. $this->view->orderDir = $this->getPost('orderDir', 'asc');
  27. //$this->view->orderDir = $this->getPost('orderDir', 'desc');
  28. $this->view->statusSelectList = $hr->requestStatusLabels;
  29. //Robot (teleconsulti automatici)
  30. $robot_path = null;
  31. $this->view->robot_id = -1;
  32. if (file_exists(PUBLIC_HTML.'sportellocura-aosga-api/robot-id.txt')) {
  33. $robot_path = PUBLIC_HTML.'sportellocura-aosga-api/robot-id.txt';
  34. } else {
  35. if (file_exists(PUBLIC_HTML.'sportellocura-api/robot-id.txt')) {
  36. $robot_path = PUBLIC_HTML.'sportellocura-api/robot-id.txt';
  37. }
  38. }
  39. if (!is_null($robot_path)) {
  40. $this->view->robot_id = (int)file_get_contents($robot_path);
  41. }
  42. $userClinicalCenters = [];
  43. $userCcRole = 0;
  44. switch ($this->view->scope) {
  45. case 'my':
  46. $userCcRole = APPLICANT_ROLE_ID;
  47. break;
  48. case 'center':
  49. $userCcRole = APPLICANT_ROLE_ID;
  50. break;
  51. case 'moderations':
  52. $userCcRole = MODERATOR_ROLE_ID;
  53. break;
  54. case 'reports':
  55. $userCcRole = REFERRER_ROLE_ID;
  56. break;
  57. case 'center-guest':
  58. $userCcRole = GUEST_ROLE_ID;
  59. break;
  60. }
  61. $hr->setActivityLog($this->user->getUserId(), 'REQ_LISTED', ['userId'=>$this->user->getUserId(), 'scope'=>$this->view->scope]);
  62. if ($userCcRole > 0) {
  63. $userClinicalCenters = $this->getUserClinicalCenters($this->user->getUserId(), $userCcRole); //In mainController()
  64. }
  65. $this->view->ccSelectList = $userClinicalCenters;
  66. //Populate the Medical specialties list and the requester list for the column filter
  67. $ccIdList = [];
  68. $ccIdListString = '';
  69. $this->view->msSelectList = [];
  70. $this->view->requesterSelectList = [];
  71. foreach($userClinicalCenters as $ccId => $ccInfo) {
  72. $ccIdList[] = $ccId;
  73. }
  74. if (!empty($ccIdList)) {
  75. $ccIdListString = implode(',', $ccIdList);
  76. $this->view->debug = $ccIdListString;
  77. $msResults = $this->db
  78. ->where('ccmst.center_id IN('.$ccIdListString.')')
  79. ->where('ums.status', 1)
  80. ->join('users_medical_specialties ums', 'ums.id=ccmst.specialty_id', 'INNER')
  81. ->groupBy('ccmst.specialty_id')
  82. ->get('clinical_center_medical_specialties_to ccmst', null, ['ccmst.specialty_id', 'ums.description']);
  83. if (is_array($msResults) && !empty($msResults)) {
  84. foreach($msResults as $item) {
  85. $msSelectList[$item['specialty_id']] = _($item['description']);
  86. }
  87. //Sorting based on translated descriptions
  88. asort($msSelectList);
  89. //Medical specialties list
  90. $this->view->msSelectList = $msSelectList;
  91. }
  92. //Requester list
  93. $requestersResult = $this->db
  94. ->where('ucct.center_id IN('.$ccIdListString.')')
  95. ->where('ucct.role_id', APPLICANT_ROLE_ID)
  96. ->where('u.status', 1)
  97. ->where('u.trashed', 0)
  98. ->join('users u', 'u.id=ucct.user_id', 'INNER')
  99. ->groupBy('ucct.user_id')
  100. ->orderBy('u.surname', 'ASC')
  101. ->get('users_clinical_centers_to ucct', null, ['u.id', 'u.name', 'u.surname']);
  102. if (is_array($requestersResult) && !empty($requestersResult)) {
  103. foreach($requestersResult as $item) {
  104. $name = ucwords(strtolower($item['name']));
  105. $surname = ucwords(strtolower($item['surname']));
  106. $this->view->requesterSelectList[$item['id']] = $this->helper->setDottedFullname($name, $surname, false);
  107. }
  108. }
  109. //$this->view->debug = $this->view->requesterSelectList;
  110. }
  111. $this->view->ccStringList = '';
  112. $userCcList = [];
  113. $ccStringList = [];
  114. $this->view->referrals = [];
  115. $this->view->specialties = [];
  116. $searchData = $this->getPost('searchData', []);
  117. parse_str($searchData, $this->view->strOutput);
  118. //Default value
  119. $obscure = false;
  120. //Select the Clinical Center ID to anonymize
  121. $anonymCenters = [];
  122. foreach($userClinicalCenters as $uCC) {
  123. if (isset($uCC['anonymize']) && (int)$uCC['anonymize'] > 0) {
  124. $anonymCenters[$uCC['id']] = true;
  125. }
  126. }
  127. $this->view->anonymCenters = $anonymCenters;
  128. //Show user's requests
  129. if ($this->view->scope == 'my') {
  130. $this->actionTitle = _('My Requests');
  131. if ($this->user->is(APPLICANT_ROLE_ID)) {
  132. $this->db->where('user_id', $this->user->getUserId());
  133. }
  134. } else if ($this->view->scope == 'center' || $this->view->scope == 'moderations') {
  135. if ($this->view->scope == 'moderations' && $this->user->is(MODERATOR_ROLE_ID)) {
  136. $userClinicalCenters = $this->getUserClinicalCenters($this->user->getUserId(), MODERATOR_ROLE_ID);
  137. }
  138. $this->actionTitle = _('Center(s) Requests');
  139. if (is_array($userClinicalCenters) && !empty($userClinicalCenters)) {
  140. foreach($userClinicalCenters as $ccItem) {
  141. $userCcList[] = $ccItem['id'];
  142. $ccStringList[] = $ccItem['description'];
  143. }
  144. }
  145. $this->db->where('r.request_visibility', 'all');
  146. $this->db->where('r.group_id', $this->userGroupId);
  147. if ($this->user->is([MODERATOR_ROLE_ID])) {
  148. $this->db->where("r.request_status IN('draft', 'pending', 'opened', 'referted', 'reopened', '! referted')");
  149. } else {
  150. $this->db->where("r.request_status IN('pending', 'opened', 'referted', 'reopened', '! referted')");
  151. }
  152. if (!empty($userCcList)) {
  153. $userCcListString = implode(',', $userCcList);
  154. $this->db->where("cc.id IN($userCcListString)");
  155. $this->view->ccStringList = implode(', ', $ccStringList);
  156. } else {
  157. $this->db->where('cc.id', -1); //Force no results
  158. $this->view->userHasClinicalCenters = false;
  159. }
  160. } else if ($this->view->scope == 'reports') {
  161. $this->actionTitle = _('My Requests');
  162. if (is_array($userClinicalCenters) && !empty($userClinicalCenters)) {
  163. foreach($userClinicalCenters as $ccItem) {
  164. $ccStringList[] = $ccItem['description'];
  165. }
  166. }
  167. $this->view->ccStringList = implode(', ', $ccStringList);
  168. $this->db->where('r.request_visibility', 'all');
  169. $this->db->where('r.group_id', $this->userGroupId);
  170. $this->db->where("r.request_status IN('opened', 'referted', 'reopened', '! referted')");
  171. $this->db->where('rere.user_id', $this->user->getUserId());
  172. $this->db->join('requests_recipients rere', 'rere.request_id=r.id', 'INNER');
  173. } else if ($this->view->scope == 'center-guest') {
  174. $this->actionTitle = _('Requests');
  175. if (is_array($userClinicalCenters) && !empty($userClinicalCenters)) {
  176. foreach($userClinicalCenters as $ccItem) {
  177. $userCcList[] = $ccItem['id'];
  178. $ccStringList[] = $ccItem['description'];
  179. }
  180. }
  181. $this->db->where('r.request_visibility', 'all');
  182. $this->db->where('r.group_id', $this->userGroupId);
  183. $this->db->where("r.request_status IN('opened', 'referted', 'reopened', '! referted')");
  184. if (!empty($userCcList)) {
  185. $userCcListString = implode(',', $userCcList);
  186. $this->db->where("cc.id IN($userCcListString)");
  187. $this->view->ccStringList = implode(', ', $ccStringList);
  188. } else {
  189. $this->db->where('cc.id', -1); //Force no results
  190. $this->view->userHasClinicalCenters = false;
  191. }
  192. }
  193. //if (!empty($this->view->strOutput)) {
  194. /*$searchRequester = isset($this->view->strOutput['search']['requester']) ? (int)$this->view->strOutput['search']['requester'] : 0;
  195. $searchStatus = isset($this->view->strOutput['search']['status']) ? $this->view->strOutput['search']['status'] : '';
  196. $seachMs = isset($this->view->strOutput['search']['ms']) ? (int)$this->view->strOutput['search']['ms'] : 0;
  197. $seachCc = isset($this->view->strOutput['search']['cc']) ? (int)$this->view->strOutput['search']['cc'] : 0;*/
  198. // SET INFO MAX REQUESTS
  199. $this->view->getTotRequests = $this->db->totalCount;
  200. $this->view->getMaxRequests = $this->db->MaxAddRequests;
  201. $has_pdf = -1;
  202. if (isset($this->view->strOutput['search']['has_pdf'])) {
  203. $this->session->deleteSession('reqHasPdf');
  204. $has_pdf = $this->view->strOutput['search']['has_pdf'];
  205. $this->session->refreshSession('reqHasPdf', (int)$has_pdf);
  206. } else {
  207. if ($this->session->getSessionValue('reqHasPdf') !== false) {
  208. $has_pdf = $this->session->getSessionValue('reqHasPdf');
  209. }
  210. }
  211. if ($has_pdf > -1) {
  212. if ($has_pdf == 0) {
  213. $this->db->having('total_reports', 0);
  214. } else {
  215. $this->db->having('total_reports', 0, '>');
  216. }
  217. } else {
  218. $this->session->deleteSession('reqHasPdf');
  219. }
  220. $searchId = 0;
  221. if (isset($this->view->strOutput['search']['id'])) {
  222. $this->session->deleteSession('reqSearStorId');
  223. $searchId = (int)$this->view->strOutput['search']['id'];
  224. $this->session->refreshSession('reqSearStorId', $searchId);
  225. } else {
  226. if ($this->session->getSessionValue('reqSearStorId') !== false) {
  227. $searchId = $this->session->getSessionValue('reqSearStorId');
  228. }
  229. }
  230. if ($searchId > 0) {
  231. $this->db->where('r.id', $searchId);
  232. } else {
  233. $this->session->deleteSession('reqSearStorId');
  234. }
  235. $searchRequester = 0;
  236. if (isset($this->view->strOutput['search']['requester'])) {
  237. $this->session->deleteSession('reqSearStorUid');
  238. $searchRequester = (int)$this->view->strOutput['search']['requester'];
  239. $this->session->refreshSession('reqSearStorUid', $searchRequester);
  240. } else {
  241. if ($this->session->getSessionValue('reqSearStorUid') !== false) {
  242. $searchRequester = $this->session->getSessionValue('reqSearStorUid');
  243. }
  244. }
  245. if ($searchRequester > 0) {
  246. $this->db->where('r.user_id', $searchRequester);
  247. } else {
  248. $this->session->deleteSession('reqSearStorUid');
  249. }
  250. //////////////
  251. //
  252. $searchPatient = '';
  253. if (isset($this->view->strOutput['search']['patient'])) {
  254. $this->session->deleteSession('reqSearPatient');
  255. $searchPatient = (string)$this->view->strOutput['search']['patient'];
  256. $this->session->refreshSession('reqSearPatient', $searchPatient);
  257. } else {
  258. if ($this->session->getSessionValue('reqSearPatient') !== false) {
  259. $searchPatient = $this->session->getSessionValue('reqSearPatient');
  260. }
  261. }
  262. if ($searchPatient != '') {
  263. $regexp = '';
  264. $arr_lists = explode(' ', $searchPatient);
  265. foreach($arr_lists as $key=>$value){
  266. if($key == 0){
  267. $regexp .= '"'.$value.'"';
  268. }else{
  269. $regexp .= '|"'.$value.'"';
  270. }
  271. }
  272. // $this->db->where('CONCAT(rr.surname," ",rr.name) REGEXP '.$regexp.'');
  273. if (is_array($arr_lists) && !empty($arr_lists)) {
  274. foreach($arr_lists as $list_value) {
  275. $this->db->where('CONCAT(rr.surname," ",rr.name)', '%'.$list_value.'%', 'LIKE');
  276. }
  277. } else {
  278. $this->db->where('CONCAT(rr.surname," ",rr.name)', '%'.$arr_lists.'%', 'LIKE');
  279. }
  280. } else {
  281. $this->session->deleteSession('reqSearPatient');
  282. }
  283. //////////////
  284. $searchStatus = '';
  285. if (isset($this->view->strOutput['search']['status'])) {
  286. $this->session->deleteSession('reqSearStorStat');
  287. $searchStatus = $this->view->strOutput['search']['status'];
  288. $this->session->refreshSession('reqSearStorStat', $searchStatus);
  289. } else {
  290. if ($this->session->getSessionValue('reqSearStorStat') !== false) {
  291. $searchStatus = $this->session->getSessionValue('reqSearStorStat');
  292. }
  293. }
  294. if ($searchStatus != '') {
  295. $this->db->where('r.request_status', $searchStatus);
  296. } else {
  297. $this->session->deleteSession('reqSearStorStat');
  298. }
  299. $seachCc = 0;
  300. if (isset($this->view->strOutput['search']['cc'])) {
  301. $this->session->deleteSession('reqSearStorCc');
  302. $seachCc = (int)$this->view->strOutput['search']['cc'];
  303. $this->session->refreshSession('reqSearStorCc', $seachCc);
  304. } else {
  305. if ($this->session->getSessionValue('reqSearStorCc') !== false) {
  306. $seachCc = $this->session->getSessionValue('reqSearStorCc');
  307. }
  308. }
  309. if ($seachCc > 0) {
  310. $this->db->where('r.center_id', $seachCc);
  311. } else {
  312. $this->session->deleteSession('reqSearStorCc');
  313. }
  314. $seachMs = 0;
  315. if (isset($this->view->strOutput['search']['ms'])) {
  316. $this->session->deleteSession('reqSearStorMs');
  317. $seachMs = (int)$this->view->strOutput['search']['ms'];
  318. $this->session->refreshSession('reqSearStorMs', $seachMs);
  319. } else {
  320. if ($this->session->getSessionValue('reqSearStorMs') !== false) {
  321. $seachMs = $this->session->getSessionValue('reqSearStorMs');
  322. }
  323. }
  324. if ($seachMs > 0) {
  325. $this->db->join('requests_medical_specialties_to rmst', 'rmst.request_id=r.id', 'INNER')->where('rmst.specialty_id', $seachMs);
  326. } else {
  327. $this->session->deleteSession('reqSearStorMs');
  328. }
  329. //}
  330. $this->db->join('clinical_centers cc', 'cc.id=r.center_id', 'INNER')
  331. ->join('users u', 'u.id=r.user_id', 'INNER')
  332. ->join('requests_registry rr', 'rr.request_id=r.id', 'INNER')
  333. ->orderBy($this->view->orderField, $this->view->orderDir);
  334. if ($this->view->orderField == 'request_status_number') {
  335. $this->db->orderBy('created_at', 'desc');
  336. }
  337. $requests = $this->db->paginate('requests r', $this->view->currentPage, ['r.*', 'u.name applicant_name', 'u.surname applicant_surname', 'rr.id patient_id', 'rr.name patient_name', 'rr.surname patient_surname', '(SELECT TIMESTAMPDIFF(YEAR, rr.birthdate, CURDATE())) patient_age_years', '(SELECT TIMESTAMPDIFF(MONTH, rr.birthdate, CURDATE())) patient_age_months', '(SELECT TIMESTAMPDIFF(DAY, rr.birthdate, CURDATE())) patient_age_days', 'rr.gender patient_gender', 'cc.description center_name', "(SELECT COUNT(*) FROM requests_attachments ra WHERE ra.request_id=r.id) AS total_attach", "(SELECT COUNT(*) FROM sportellocura_log sptc WHERE sptc.request_id=r.id) AS total_reports",
  338. //Remove (?)
  339. "(SELECT GROUP_CONCAT(ums.description SEPARATOR ', ') AS specialty_list FROM requests_medical_specialties_to rmst JOIN users_medical_specialties ums ON ums.id=rmst.specialty_id WHERE rmst.id=r.id) AS med_specialties",
  340. "(SELECT COUNT(*) FROM sportellocura sca WHERE sca.request_id=r.id) sportello_total",
  341. "(SELECT COUNT(*) FROM requests_comments rc WHERE rc.request_id=r.id AND rc.user_id=".$this->view->robot_id.") total_auto_tlc"]);
  342. $this->view->queryDebug = $this->db->getLastQuery();
  343. // SET INFO MAX REQUESTS
  344. $this->view->getTotRequests = $this->db->totalRequests;
  345. $this->view->getMaxRequests = $this->db->MaxAddRequests;
  346. $this->setPagination($this->db, $this->db->totalCount, $this->view->currentPage, $this->view->baseUri.'/'.$this->view->orderField.'/'.$this->view->orderDir);
  347. if (is_array($requests)) {
  348. foreach($requests as $index => $request) {
  349. //Check whether obfuscate the Patient name or don't
  350. if ($this->view->scope != 'my') {
  351. //Check whether the request has been market ad anonymous
  352. if ((int)$requests[$index]['request_anonymous'] == 0) {
  353. //If the request isn't anonymous, check the Clinical Center
  354. if (isset($anonymCenters[$request['center_id']])) { //The Center is anonymous by default
  355. $requests[$index]['request_anonymous'] = 1; //Make this request anonymous
  356. }
  357. }
  358. }
  359. //Overwrite the anonymous value if the current user is the request author
  360. if ($request['user_id'] == $this->user->getUserId()) {
  361. $requests[$index]['request_anonymous'] = 0;
  362. }
  363. //If there are no Clinical Center for the current user, foce anonymous anyway
  364. if (empty($userClinicalCenters)) {
  365. $requests[$index]['request_anonymous'] = 0;
  366. }
  367. //Get the Referrals for each Requests
  368. $this->view->referrals[$request['id']] = $this->db
  369. ->where('rc.request_id', $request['id'])
  370. ->where('(SELECT COUNT(*) FROM users_roles_to urt WHERE urt.user_id=rc.user_id AND role_id='.REFERRER_ROLE_ID.')', 0, '>')
  371. ->join('users u', 'u.id=rc.user_id', 'INNER')
  372. ->orderBy('u.surname', 'asc')
  373. ->groupBy('rc.user_id')
  374. ->get('requests_comments rc', null, [
  375. 'user_id',
  376. 'u.name user_name',
  377. 'u.surname user_surname',
  378. "(SELECT GROUP_CONCAT(umst.specialty_id SEPARATOR '|') FROM users_medical_specialties_to umst WHERE umst.user_id=rc.user_id) specialty_ids"
  379. ]);
  380. //Get the Medical Specialties for each Requests
  381. $this->view->specialties[$request['id']] = $this->db
  382. ->where('rmst.request_id', $request['id'])
  383. ->join('users_medical_specialties ums', 'ums.id=rmst.specialty_id', 'INNER')
  384. ->orderBy('ums.description', 'asc')
  385. ->get('requests_medical_specialties_to rmst', null, ['rmst.specialty_id specialty_id', 'ums.description specialty_name', 'NULL AS referrals']);
  386. //Combine Referrals and Specialties
  387. foreach($this->view->specialties as $request_id => $specialties) {
  388. foreach($specialties as $specialty_index => $specialty) {
  389. foreach($this->view->referrals[$request_id] as $referral) {
  390. //Check if referral has this specialty id
  391. if (in_array($specialty['specialty_id'], explode('|', $referral['specialty_ids']))) {
  392. $this->view->specialties[$request_id][$specialty_index]['referrals'][$referral['user_id']] = $this->helper->setDottedFullname(ucwords($referral['user_name']), ucwords($referral['user_surname']), false);
  393. }
  394. }
  395. }
  396. }
  397. //Add new item in the Request list
  398. $requests[$index]['specialties'] = isset($this->view->specialties[$request['id']]) ? $this->view->specialties[$request['id']] : [];
  399. }
  400. }
  401. $this->view->ucc = $userClinicalCenters;
  402. $this->view->actionTitle = rawurlencode($this->actionTitle); //Pass the action title to "New Request" button
  403. $this->view->parentBaseUri = rawurlencode($this->view->baseUri); //Pass the base uri to "New Request" button
  404. $this->view->requests = $requests;
  405. $this->breadcrumbs = [['hash'=>null, 'label'=>$this->actionTitle]];
  406. return $this->setJsonView('index');
  407. }
  408. //Request editing page (View)
  409. public function requestEdit() {
  410. /*if(!$this->checkPermissions([ADMIN_ROLE_ID, MODERATOR_ROLE_ID, APPLICANT_ROLE_ID])) {
  411. return $this->redirect('login', 'permissionDenied');
  412. }*/
  413. $handleRequest = new HandleRequest();
  414. $requestID = $this->getPost('requestID', 1);
  415. $this->view->parentActionTitle = $this->getPost('parentTitle', _('Requests'));
  416. $this->view->parentScope = $this->getPost('parentScope', 'my');
  417. $this->view->viewType = $this->getPost('viewType', 'view');
  418. $this->view->parentBaseUri = $this->getPost('parentBaseUri', '');
  419. $this->view->currentPage = $this->getPost('pageNumb', 1);
  420. $this->view->orderField = $this->getPost('orderField', 'created_at');
  421. $this->view->orderDir = $this->getPost('orderDir', 'desc');
  422. //Default values
  423. $this->view->userCanView = true;
  424. $this->view->requestData = [];
  425. $this->view->companies = [];
  426. $this->view->symptoms = [];
  427. $this->view->ICD10 = [];
  428. $this->view->medicalSpecialties = [];
  429. $this->view->requestMedicalSpecialties = [];
  430. $this->view->forwardMedicalSpecialties = [];
  431. $this->view->requestMedicalSpecialtiesIdList = [];
  432. $this->view->attachments = [];
  433. $this->view->comments = [];
  434. $this->view->ccReferral = []; //Clinical Centers referrals (recipients)
  435. $this->view->languages = $this->locale->getSupportedLanguages();
  436. $this->view->icd10 = [];
  437. $this->view->dermaPositions = [];
  438. $this->view->dermaPositionLabels = ['single'=>_('Single'), 'multiple-localized'=>_('Multiple localized'), 'multiple-spread'=>_('Multiple spread'), 'clusted'=>_('Cluster'), 'metameric'=>_('Metameric'), 'linear'=>_('Linear'), 'acral'=>_('Acral'), 'symmetrical'=>_('Symmetrical')];
  439. $this->view->otoImages = [];
  440. $this->view->otoPositionLabels = ['oto_myringitis'=>_('Bullous myringitis'),
  441. 'oto_polip'=>_('Polyp of the EAC'),
  442. 'oto_atelectasis'=>_('Tympanic membrane atelectasis'),
  443. 'oto_perforation'=>_('Tympanic membrane perforation / non-cholesteatomatous otitis media'),
  444. 'oto_chole'=>_('Cholesteatomatous otitis media'),
  445. 'oto_tympanoscler'=>_('Tympanosclerosis'),
  446. 'oto_tyjugular'=>_('Tympano-jugular paraganglioma'),
  447. 'oto_cholesterol'=>_('Cholesterol granuloma')];
  448. $this->view->statuses = [];
  449. $this->requestOrigin = '';
  450. $this->view->dreamCode = '';
  451. $this->view->dreamData = [];
  452. $this->view->dreamCompleteData = '';
  453. $this->view->requestDreamPDF = []; //Information for Dream PDF
  454. $this->view->provinceList = [];
  455. $this->view->cgProvince = '';
  456. $this->view->cgCity = '';
  457. $this->view->dreamItalyEndPoint = $this->config['settings']['api']['endpoint'];
  458. $this->view->dreamItalyApiKey = $this->config['settings']['api']['key'];
  459. $this->view->sportelloCuraEndPoint = $this->config['settings']['sportellocura']['api']['key'];
  460. $this->view->sportelloCuraApiKey = $this->config['settings']['sportellocura']['api']['endpoint'];
  461. $this->view->survey = []; //Sportello Cura data
  462. $provinces = $this->db->orderBy('name', 'ASC')->get('italian_provinces');
  463. if (is_array($provinces) && !empty($provinces)) {
  464. foreach($provinces as $item) {
  465. $this->view->provinceList[$item['id']] = $item['name'];
  466. }
  467. }
  468. //PDF sending log
  469. $this->view->pdfLog = $this->db
  470. ->where('sl.request_id', $requestID)
  471. ->join('requests_messages_queue rmq', 'rmq.mail_id=sl.mail_code', 'LEFT')
  472. ->orderBy('sl.created_at', 'ASC')
  473. ->get('sportellocura_log sl', NULL, ['sl.created_at queued_date', 'rmq.request_id', 'rmq.mail_id', 'rmq.delay_at']);
  474. //Default values
  475. $userIsAuthor = false; //The logged user id the author of this Request
  476. $userIsModerator = false; //The logged user is a moderator of this Clinical Center
  477. $this->view->userIsAuthor = $userIsAuthor;
  478. $this->view->userIsModerator = $userIsModerator;
  479. $userIsReferrer = false; //The logged user is a referral of this Request
  480. $this->view->userIsReferrer = $userIsReferrer;
  481. $this->view->icd10Categories = $handleRequest->getICD10Categories($this->user->getUserLang());
  482. $this->view->wizards = [];
  483. $advancedFields = $this->db->where('id', $this->user->getUserId())->getOne('users', 'advanced_request');
  484. $this->view->advancedFields = isset($advancedFields['advanced_request']) && (int)$advancedFields['advanced_request'] == 1 ? true : false;
  485. //Viewer
  486. $this->view->isSimpleViewer = false;
  487. //$viewer = $this->db->where('id', $this->user->getUserId())->getOne('users', 'simple_viewer');
  488. $viewer = 0;
  489. if (isset($viewer['simple_viewer']) && (int)$viewer['simple_viewer'] == 1) {
  490. $this->view->isSimpleViewer = true;
  491. }
  492. //Select the user's language by default
  493. foreach($this->view->languages as $index => $language) {
  494. if ($language['lang_code'] == $this->user->getUserLang()) {
  495. $this->view->languages[$index]['selected'] = true;
  496. } else {
  497. $this->view->languages[$index]['selected'] = false;
  498. }
  499. }
  500. if ($this->user->is(APPLICANT_ROLE_ID)) {
  501. $this->view->userClinicalCenters = $this->getUserClinicalCenters($this->user->getUserId(), APPLICANT_ROLE_ID); //In mainController()
  502. } else if ($this->user->is(REFERRER_ROLE_ID)) {
  503. $this->view->userClinicalCenters = $this->getUserClinicalCenters($this->user->getUserId(), REFERRER_ROLE_ID);
  504. } else if ($this->user->is(MODERATOR_ROLE_ID)) {
  505. $this->view->userClinicalCenters = $this->getUserClinicalCenters($this->user->getUserId(), MODERATOR_ROLE_ID); //In mainController()
  506. }
  507. $this->view->requestId = $requestID;
  508. //$this->view->medicalSpecialties = $this->db->orderBy('description', 'asc')->get('users_medical_specialties');
  509. $this->view->ccReferral = $this->db
  510. ->where('ucct.role_id', REFERRER_ROLE_ID)
  511. ->join('clinical_centers cc', 'cc.id=ucct.center_id', 'INNER')
  512. ->groupBy('cc.id')
  513. ->orderBy('cc.description', 'asc')
  514. ->get('users_clinical_centers_to ucct', null, ['cc.id id', 'cc.description description']);
  515. $this->view->referralList = $this->db
  516. ->where('role_id', REFERRER_ROLE_ID)
  517. ->where('u.status', 1)
  518. ->join('users u', 'u.id=urt.user_id', 'INNER')
  519. ->orderBy('u.surname', 'asc')
  520. ->get('users_roles_to urt', null, [
  521. 'u.id user_id',
  522. 'u.name user_name',
  523. 'u.surname user_surname',
  524. "(SELECT GROUP_CONCAT(ums.description SEPARATOR ', ') FROM users_medical_specialties_to umst JOIN users_medical_specialties ums ON ums.id=umst.specialty_id WHERE umst.user_id=u.id ORDER BY ums.description) medspec_list"
  525. ]);
  526. if ($this->view->viewType == 'view') {
  527. //Get all Medical Specialties (in the list for the comment form)
  528. $this->view->medicalSpecialties = $handleRequest->getSpecialtyByClinicalCenterId(0, $this->userGroupId);
  529. } else {
  530. //New Request: if there is just one Clinical Center, list its the Medical Specialties (else they are loaded by Ajax)
  531. if (count($this->view->userClinicalCenters) == 1) {
  532. $currentCenterId = array_values($this->view->userClinicalCenters)[0]['id'];
  533. $this->view->medicalSpecialties = $handleRequest->getSpecialtyByClinicalCenterId($currentCenterId, $this->userGroupId);
  534. }
  535. }
  536. if ($requestID == 0) {
  537. $this->actionTitle = _('Request : New');
  538. $this->view->requestUniqueCode = strtoupper(uniqid());
  539. $this->view->requestData = []; //Default: empty array
  540. $this->view->exams = $handleRequest->getExams();
  541. $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_NEW', ['userId'=>$this->user->getUserId()]);
  542. } else {
  543. $this->actionTitle = _('Request : Edit');
  544. if ($this->view->viewType == 'view') {
  545. $this->actionTitle = vsprintf(_('Request #%s'), [$requestID]);
  546. $this->actionTitlePDF = "#".$requestID;
  547. $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_VIEW', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestID]);
  548. }
  549. //TO DO: check whether the current user is authorized to access this request (i.e. changing the ID in the addess bar)
  550. //$this->view->testData = $handleRequest->forwardRequest($requestID);
  551. $requestData = $this->db
  552. ->where('r.id', $requestID)
  553. ->join('users u', 'u.id=r.user_id', 'INNER')
  554. ->join('requests_registry rr', 'rr.request_id=r.id', 'INNER')
  555. ->join('clinical_centers cc', 'cc.id=r.center_id', 'INNER')
  556. ->join('continents cnt', 'cnt.code=cc.continent_code', 'INNER')
  557. ->join('countries ctr', 'ctr.country_iso2_code=cc.country_code', 'INNER')
  558. ->getOne('requests r', "r.*, cc.description center_description, cc.address center_address, cc.lat, cc.lng, cnt.name center_continent, ctr.country_name center_country, cc.notes center_notes, rr.clinical_remarks, rr.medical_history, rr.name patient_name, rr.surname patient_surname, rr.birthdate, rr.gender, (SELECT TIMESTAMPDIFF(YEAR, rr.birthdate, CURDATE())) age_years, (SELECT TIMESTAMPDIFF(MONTH, rr.birthdate, CURDATE())) age_months, (SELECT TIMESTAMPDIFF(DAY, rr.birthdate, CURDATE())) age_days, rr.min_arterial_pressure, rr.max_arterial_pressure, rr.heart_rate, rr.saturation, u.name sender_name, u.surname sender_surname, u.updated_at user_updated_at");
  559. //Sporello Cura
  560. $sportellocura = $this->db->where('request_id', $requestID)->getOne('sportellocura');
  561. if (isset($sportellocura['survey_id'])) {
  562. $survey_record = json_decode($sportellocura['survey_data'], true);
  563. if (isset($survey_record['json_answers'])) {
  564. $survey_record['data'] = json_decode($survey_record['json_answers'], true);
  565. }
  566. $this->view->survey = $survey_record;
  567. }
  568. $companies = $this->db->getOne('companies');
  569. if (!is_array($requestData)) {
  570. return $this->setJsonView('requestError');
  571. }
  572. //Check whether the moderator can access this request or can't
  573. if ($this->user->is(MODERATOR_ROLE_ID)) {
  574. if (!isset($this->view->userClinicalCenters[$requestData['center_id']])) {
  575. return $this->setJsonView('requestError');
  576. }
  577. }
  578. //Get Dream code
  579. $dreamResult = $this->db->where('request_id', $requestID)->getOne('requests_dream_data', 'dream_code, dream_hash');
  580. if (isset($dreamResult['dream_code']) && trim($dreamResult['dream_code']) != '') {
  581. $this->view->dreamCode = $dreamResult['dream_code'];
  582. $this->view->dreamData = htmlspecialchars($dreamResult['dream_hash']);
  583. }
  584. $userIsAuthor = $requestData['user_id'] == $this->user->getUserId() ? true : false;
  585. $this->view->userIsAuthor = $userIsAuthor;
  586. $this->view->hasMoreDetails = trim($requestData['cgnamesurname']) != '' || trim($requestData['cgrole']) != '' || trim($requestData['cgemail']) != '' || trim($requestData['cgphone']) != '';
  587. //Get Caregiver's Province and City
  588. if ((int)$requestData['cgprovince'] > 0) {
  589. $cg_province = $this->db->where('id', $requestData['cgprovince'])->getOne('italian_provinces');
  590. $this->view->cgProvince = isset($cg_province['name']) ? $cg_province['name'] : '';
  591. }
  592. if ((int)$requestData['cgcity'] > 0) {
  593. $cg_city = $this->db->where('id', $requestData['cgcity'])->getOne('italian_cities');
  594. $this->view->cgCity = isset($cg_city['name']) ? $cg_city['name'] : '';
  595. }
  596. $userIsModerator = $handleRequest->isUserModerator($requestData['center_id'], $this->getUserClinicalCenters($this->user->getUserId(), MODERATOR_ROLE_ID), $this->user->getUserId());
  597. $this->view->userIsModerator = $userIsModerator;
  598. $userIsReferrer = $handleRequest->isUserReferrer($requestID, $this->user->getUserId());
  599. $this->view->userIsReferrer = $userIsReferrer;
  600. //Get the Medical Specialties for the saved Clinical Center
  601. $currentCenterId = $requestData['center_id'];
  602. $this->view->medicalSpecialties = $handleRequest->getSpecialtyByClinicalCenterId($currentCenterId, $this->userGroupId);
  603. $ccInfo = $this->db->where('id', $currentCenterId)->getOne('clinical_centers');
  604. $isCcAnonymous = isset($ccInfo['anonymize']) && (int)$ccInfo['anonymize'] == 1 ? true : false;
  605. if ($isCcAnonymous) {
  606. $requestData['request_anonymous'] = 1;
  607. }
  608. //Overwrite the previouse value
  609. if ($userIsAuthor) {
  610. $isCcAnonymous = false;
  611. }
  612. $this->view->requestData = $requestData;
  613. $this->view->companies = $companies;
  614. //TOOD: check whether current user can access this request
  615. //O. Is the right group?
  616. //1. Is the Author?
  617. //2. Is a Moderator in this Clinical Center?
  618. //3. Is a Referral of this Request?
  619. //4. Is an Admininstrator?
  620. $this->view->requestUniqueCode = $requestData['unique_code'];
  621. //$this->actionTitle .= ' ('.ucfirst($requestData['request_origin']).')';
  622. $this->requestOrigin = $requestData['request_origin'];
  623. //Symptons (old ICD10)
  624. $this->view->symptoms = $this->db
  625. ->where('rst.request_id', $requestID)
  626. ->where('rsl.language_code', $this->user->getUserLang())
  627. ->join('requests_symptoms_labels rsl', 'rsl.symptom_id=rst.symptom_id', 'INNER')
  628. ->orderBy('rsl.symptom_label', 'asc')
  629. ->get('requests_symptoms_to rst', null, ['rsl.symptom_label']);
  630. //ICD10 (new)
  631. $this->view->ICD10 = $this->db
  632. ->where('rst.request_id', $requestID)
  633. ->where('idl.lang_code', $this->user->getUserLang())
  634. ->join('icd10_desease_labels idl', 'idl.desease_id=rst.symptom_id', 'INNER')
  635. ->orderBy('idl.description', 'asc')
  636. ->get('requests_symptoms_to rst', null, ['idl.description symptom_label']);
  637. //Overwrite the symptoms with the new ICD10
  638. if (!empty($this->view->ICD10)) {
  639. $this->view->symptoms = $this->view->ICD10;
  640. }
  641. //Clinical Centers
  642. foreach($this->view->userClinicalCenters as $centerId => $centerItem) {
  643. if ($centerItem['id'] == $requestData['center_id']) {
  644. $this->view->userClinicalCenters[$centerId]['selected'] = true;
  645. } else {
  646. $this->view->userClinicalCenters[$centerId]['selected'] = false;
  647. }
  648. }
  649. if (is_array($this->view->referralList)) {
  650. $requestRecipients = $this->db
  651. ->where('request_id', $requestID)
  652. ->get('requests_recipients');
  653. $this->view->recipients = $requestRecipients;
  654. if (is_array($requestRecipients)) {
  655. foreach($this->view->referralList as $index => $referral) {
  656. $this->view->referralList[$index]['selected'] = false;
  657. foreach($requestRecipients as $recipient) {
  658. if ($referral['user_id'] == $recipient['user_id']) {
  659. $this->view->referralList[$index]['selected'] = true;
  660. }
  661. }
  662. }
  663. }
  664. }
  665. $requestMedSpec = $this->db
  666. ->where('request_id', $requestID)
  667. ->get('requests_medical_specialties_to');
  668. //Medical specialties of the request
  669. $idList = [];
  670. $requestMedicalSpecialties = $this->db
  671. ->where('rmst.request_id', $requestID)
  672. ->join('users_medical_specialties ums', 'ums.id=rmst.specialty_id', 'INNER')
  673. ->get('requests_medical_specialties_to rmst', null, ['ums.id', 'ums.description']);
  674. if (is_array($requestMedicalSpecialties)) {
  675. foreach($requestMedicalSpecialties as $item) {
  676. $this->view->requestMedicalSpecialties[$item['id']]['id'] = $item['id'];
  677. $this->view->requestMedicalSpecialties[$item['id']]['description'] = _($item['description']);
  678. $idList[] = $item['id'];
  679. }
  680. $this->view->requestMedicalSpecialtiesIdList = $idList;
  681. }
  682. //All possible Medical specialties
  683. foreach($this->view->medicalSpecialties as $index => $medSpecList) {
  684. $this->view->medicalSpecialties[$index]['selected'] = false;
  685. foreach($requestMedSpec as $reqMedSpecItem) {
  686. if ($reqMedSpecItem['specialty_id'] == $medSpecList['id']) {
  687. $this->view->medicalSpecialties[$index]['selected'] = true;
  688. }
  689. }
  690. //Request forward: list with mmedical specialties without the request medical specialties
  691. if (!isset($this->view->requestMedicalSpecialties[$medSpecList['id']])) {
  692. $this->view->forwardMedicalSpecialties[$medSpecList['id']]['id'] = $medSpecList['id'];
  693. $this->view->forwardMedicalSpecialties[$medSpecList['id']]['description'] = $medSpecList['description'];
  694. }
  695. }
  696. $requestLangs = $this->db
  697. ->where('request_id', $requestID)
  698. ->get('requests_languages_to');
  699. //If there are saved languages change the default value
  700. if (is_array($requestLangs) && !empty($requestLangs)) {
  701. foreach($this->view->languages as $index => $language) {
  702. $this->view->languages[$index]['selected'] = false;
  703. foreach($requestLangs as $reqLangItem) {
  704. if ($reqLangItem['language_code'] == $language['lang_code']) {
  705. $this->view->languages[$index]['selected'] = true;
  706. }
  707. }
  708. }
  709. }
  710. $requestCenters = $this->db
  711. ->where('request_id', $requestID)
  712. ->get('request_clinical_centers_to');
  713. foreach($this->view->ccReferral as $centerId => $referralCenter) {
  714. $this->view->ccReferral[$centerId]['selected'] = false;
  715. foreach($requestCenters as $centerItem) {
  716. if ($centerItem['center_id'] == $referralCenter['id']) {
  717. $this->view->ccReferral[$centerId]['selected'] = true;
  718. }
  719. }
  720. }
  721. $this->view->statuses = $this->db
  722. ->where('rs.code', '! referted', '<>')
  723. ->where('rs.code', 'draft', '<>')
  724. ->where('rs.code', 'pending', '<>')
  725. ->where('rs.code', 'opened', '<>')
  726. ->orderBy('rs.default_label', 'asc')
  727. ->get('requests_statuses rs');
  728. $this->view->attachments = $handleRequest->getAttachmentsByRequestId($requestID);
  729. //Group attachments by date
  730. $this->view->groupedAttachments = [];
  731. if (is_array($this->view->attachments) && !empty($this->view->attachments)) {
  732. foreach($this->view->attachments as $attachment) {
  733. //$ext = $this->helper->getExtension($attachment['file_name']);
  734. $attachment['previewType'] = $this->helper->getPreviewType($attachment['file_name']);
  735. $this->view->groupedAttachments[date('Y-m-d 00:00:00', strtotime($attachment['created_at']))][] = $attachment;
  736. }
  737. if (!empty($this->view->groupedAttachments)) {
  738. foreach($this->view->groupedAttachments as $ext => $attachList) {
  739. sort($attachList);
  740. $this->view->groupedAttachments[$ext] = $attachList;
  741. }
  742. }
  743. }
  744. //ICD-10
  745. $this->view->icd10 = $handleRequest->getECD10ListByRequestId($requestID, $this->user->getUserLang());
  746. //Wizards
  747. $this->view->wizardTitles = ['cardio'=>_('Wizard Cardio'), 'derma'=>_('Wizard Derma'), 'generic'=>_('Wizard Physical Examination'), 'oto'=>_('Wizard Ear')];
  748. $this->view->wizards = $handleRequest->getWizardsByRequestId($requestID);
  749. //Wizard Derma positions
  750. $this->view->dermaPositions = $handleRequest->getWizardsDermaPositions($requestID);
  751. //Wizard Ear images
  752. $this->view->otoImages = $handleRequest->getWizardsEarDeseases($requestID);;
  753. //Get all exams for the dialogs
  754. $this->view->exams = $handleRequest->getExams($this->view->wizards);
  755. }
  756. $pathParentUri = $this->view->parentBaseUri.'/'.$this->view->orderField.'/'.$this->view->orderDir.'/'.$this->view->currentPage;
  757. if ($this->view->parentBaseUri != 'hashtag') {
  758. $this->breadcrumbs = [['hash'=>$pathParentUri, 'label'=>$this->view->parentActionTitle], ['hash'=>null, 'label'=>$this->actionTitle]];
  759. } else {
  760. $this->breadcrumbs = [['hash'=>null, 'label'=>$this->actionTitle]];
  761. }
  762. if ($this->view->viewType == 'view') {
  763. if($this->checkPermissions([APPLICANT_ROLE_ID])) {
  764. //If not the author: $permissionDenied = true;
  765. }
  766. if($this->checkPermissions([MODERATOR_ROLE_ID])) {
  767. //If not moderator in this cc: $permissionDenied = true;
  768. }
  769. $this->view->comments = $handleRequest->getCommentList($requestID, $this->view->requestData['center_id'], true);
  770. //Add the information for the Dream PDF
  771. $pdfPatientString = strip_tags($this->helper->requestSubject(['anonymous'=>$this->view->requestData['request_anonymous'], 'patientSurname'=>$this->view->requestData['patient_surname'], 'patientName'=>$this->view->requestData['patient_name'], 'ageYears'=>$this->view->requestData['age_years'], 'ageMonths'=>$this->view->requestData['age_months'], 'ageDays'=>$this->view->requestData['age_days'], 'patientGender'=>$this->view->requestData['gender']]));
  772. $pdfComments = $this->view->comments;
  773. foreach($pdfComments as $index => $item) {
  774. $pdfComments[$index]['created_at_string'] = $this->helper->getDateString($pdfComments[$index]['created_at']);
  775. }
  776. $dreamResults = $this->db->where('request_id', $requestID)->getOne('requests_dream_data', 'dream_evt_id, dream_hash');
  777. $registryData = null;
  778. $registryEvtId = null;
  779. if (isset($dreamResults['dream_hash'])) {
  780. $registryData = json_decode($dreamResults['dream_hash'], true);
  781. $registryEvtId = $dreamResults['dream_evt_id'];
  782. }
  783. $hasDreamIntegration = false;
  784. if (isset($registryData['Anagrafica']) && !empty($registryData['Anagrafica'])) {
  785. $this->view->requestDreamPDF = [
  786. 'registry'=>$registryData['Anagrafica'],
  787. 'evtId'=>$registryEvtId,
  788. 'request'=>['id'=>$requestID, 'requester'=>$this->helper->setDottedFullname($this->view->requestData['sender_name'], $this->view->requestData['sender_surname'], false), 'dateCreatedString'=>date('Y-m-d-H-i-s', strtotime($this->view->requestData['created_at'])), 'created'=>$this->helper->getDateString($this->view->requestData['created_at']), 'lastUpdate'=>$this->helper->getDateString($this->view->requestData['updated_at']), 'pdfLastUpdate'=>$this->helper->getDateString(date('Y-m-d H:i:s')), 'patient'=>$pdfPatientString, 'center'=>$this->view->requestData['center_description'], 'mainQuestion'=>$this->view->requestData['request_question']],
  789. 'icd10'=>$this->view->icd10,
  790. 'wizards'=>$this->view->wizards,
  791. 'dermaPositions'=>$this->view->dermaPositions,
  792. 'maxBloodPressure'=>$this->view->requestData['max_arterial_pressure'],
  793. 'minBloodPressure'=>$this->view->requestData['min_arterial_pressure'],
  794. 'heartRate'=>$this->view->requestData['heart_rate'],
  795. 'saturation'=>$this->view->requestData['saturation'],
  796. 'clinicalRemarks'=>$this->view->requestData['clinical_remarks'],
  797. 'medicalHistory'=>$this->view->requestData['medical_history'],
  798. //'exams'=>$this->view->exams,
  799. 'comments'=>$pdfComments
  800. ];
  801. $hasDreamIntegration = true;
  802. }
  803. return $this->setJsonView('requestView', false, '', ['requestDreamPDF'=>$this->view->requestDreamPDF, 'userIsAuthor'=>$userIsAuthor, 'hasDreamIntegration'=>$hasDreamIntegration]);
  804. } else {
  805. return $this->setJsonView('requestEdit');
  806. }
  807. }
  808. //Save/Edit requests
  809. public function requestSave() {
  810. if (!$this->user->isLogged()) {
  811. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  812. }
  813. if(!$this->checkPermissions([ADMIN_ROLE_ID, APPLICANT_ROLE_ID])) {
  814. return $this->setRawJsonResponse('err', _('Permission denied.'));
  815. }
  816. $data = isset($_POST['data']) ? $_POST['data'] : null;
  817. $this->view->data = $data;
  818. $operation = $data['operation']['value'] == 'draft' ? 'draft' : 'pending';
  819. $hasFiles = (bool)$data['has_files']['value'];
  820. $fileCounter = (int)$data['files_counter']['value'];
  821. $handleRequest = new HandleRequest();
  822. $requestId = $data['request_id']['value'];
  823. $requestUniqueCode = $data['request_unique_code']['value'];
  824. $clinicalCenter = $data['request_cc']['value'];
  825. $dreamCode = isset($data['dream_code']['value']) ? $data['dream_code']['value'] : '';
  826. $patientName = trim($data['request_name']['value']);
  827. $patientSurname = trim($data['request_surname']['value']);
  828. $patientGender = $data['request_gender']['value'];
  829. $ageType = isset($data['request_birth_type']['value']) ? $data['request_birth_type']['value'] : null;
  830. $ageYear = $data['request_birth_year']['value'];
  831. $ageMonth = $data['request_birth_month']['value'];
  832. $ageMonthDay = $data['request_birth_month_day']['value'];
  833. $ageAgeInNumber = $data['request_age']['value'];
  834. $ageUnitOfTime = $data['request_unit_of_time']['value'];
  835. $triage = isset($data['triage']['value']) ? $data['triage']['value'] : null;
  836. $bpMin = (int)$data['request_bp_min']['value'];
  837. $bpMax = (int)$data['request_bp_max']['value'];
  838. $heartRate = (int)$data['request_heart_rate']['value'];
  839. $oxygenSaturation = (int)$data['request_oxy_sat']['value'];
  840. $medicalRemarks = strip_tags(trim($data['request_medremarks']['value']));
  841. $medicalHistory = strip_tags(trim($data['request_medicalhistory']['value']));
  842. $mainQuestion = strip_tags(trim($data['request_mainquestion']['value']));
  843. $visibility = $data['referral_visibility']['value'];
  844. $privacy = $data['privacy']['value'];
  845. $anonymous = $data['request_anonymisation']['value'];
  846. $dreamCode = trim($data['dream_code']['value']);
  847. $dreamData = $data['dream_data']['value'];
  848. $dreamEvtId = $data['dream_evt_id']['value'];
  849. $icd10List = isset($data['icd10_desease']['value']) ? $data['icd10_desease']['value'] : null;
  850. //Exams
  851. $supportedWizards = ['generic', 'derma', 'cardio', 'oto'];
  852. foreach ($supportedWizards as $wizard) {
  853. $this->view->wizard[$wizard] = isset($data['exam_'.$wizard]['value']) ? $data['exam_'.$wizard]['value'] : [];
  854. }
  855. //Derma positions
  856. $dermaPositions = isset($data['derma_position']['value']) ? $data['derma_position']['value'] : [];
  857. //Ear images
  858. $earImages = isset($data['ear_desease']['value']) ? $data['ear_desease']['value'] : [];
  859. //return $this->setRawJsonResponse('err', _("Test: ".json_encode($dermaPositions)));
  860. //Medical specialty (the only required filter)
  861. $medicalSpecialties = $data['referral_ms']['value'];
  862. //If no language is selected, assign the user's default language
  863. $referralLangs = is_array($data['referral_langs']['value']) && !empty($data['referral_langs']['value']) ? $data['referral_langs']['value'] : [$this->user->getUserLang()];
  864. //Referrals' Clinical Center (could be not set)
  865. $referralCc = isset($data['referral_cc']['value']) ? $data['referral_cc']['value'] : null;
  866. //Specific referral list (could be not set)
  867. $referralList = isset($data['request_referral_list']['value']) ? $data['request_referral_list']['value'] : null;
  868. //These numbers are used to sort the statuses and the triage colors
  869. //$status_numbers = ['pending'=>-1, 'draft'=>0, 'opened'=>1, '! referted'=>4, 'reopened'=>3, 'referted'=>2];
  870. $status_numbers = $handleRequest->statusNumbers;
  871. //UPDATE requests SET request_status_number = 2 WHERE request_status LIKE '! referted';
  872. //UPDATE requests SET request_status_number = 4 WHERE request_status LIKE 'referted';
  873. $triage_numbers = ['white'=>0, 'green'=>1, 'yellow'=>2, 'red'=>3];
  874. $referralVisibility = $data['referral_visibility']['value'];
  875. $dateOfBirth = '0000-00-00 00:00:00';
  876. //Dynamic checkboxes in Preview modal window
  877. $recipientsIds = isset($data['recipients_ids']['value']) ? $data['recipients_ids']['value'] : [];
  878. //Request Clinical Center
  879. if ($clinicalCenter == '') {
  880. return $this->setRawJsonResponse('err', _('Please provide the Clinical Center.'));
  881. }
  882. if ($patientName == '') {
  883. return $this->setRawJsonResponse('err', _("Please provide the Patient's Name."));
  884. }
  885. if ($patientSurname == '') {
  886. return $this->setRawJsonResponse('err', _("Please provide the Patient's Surname."));
  887. }
  888. if ($patientGender == '') {
  889. return $this->setRawJsonResponse('err', _("Please provide the Patient's Sex."));
  890. }
  891. if (is_null($ageType)) {
  892. return $this->setRawJsonResponse('err', _("Please provide the Patient's date of birth or the age in years or months."));
  893. }
  894. if ($ageType == 'date') {
  895. $dateOfBirth = "$ageYear-$ageMonth-$ageMonthDay 00:00:00";
  896. if (!$this->utility->isValidDate($dateOfBirth, 'Y-n-j H:i:s')) {
  897. return $this->setRawJsonResponse('err', _("The date of birth provided is not valid."));
  898. }
  899. }
  900. if ($ageType == 'number') {
  901. if ((int)$ageAgeInNumber > 0) {
  902. if ($ageUnitOfTime == 'y' && $ageAgeInNumber < 2) {
  903. return $this->setRawJsonResponse('err', _("Please provide the Patient's age in months."));
  904. }
  905. if ($ageUnitOfTime == 'y') {
  906. $diffYears = (int)date('Y')-$ageAgeInNumber;
  907. $dateOfBirth = "$diffYears-01-01 00:00:00";
  908. }
  909. if ($ageUnitOfTime == 'm') {
  910. $dateOfBirth = date('Y-m-01 00:00:00', strtotime("-$ageAgeInNumber months"));
  911. }
  912. } else {
  913. return $this->setRawJsonResponse('err', _("Patient's age must be a number."));
  914. }
  915. }
  916. //Check date of birth is in the future
  917. $checkBirthDate = new DateTime($dateOfBirth);
  918. $checkDateNow = new DateTime();
  919. if ($checkBirthDate > $checkDateNow) {
  920. return $this->setRawJsonResponse('err', _("The date of birth cannot be in the future."));
  921. }
  922. if ($bpMin > 0 && $bpMax > 0) {
  923. if ($bpMin > $bpMax) {
  924. return $this->setRawJsonResponse('err', _("Minimum Blood Pressure cannot be higher than the Maximum one."));
  925. }
  926. }
  927. if ($bpMax > 250) {
  928. return $this->setRawJsonResponse('err', _("Maximum Blood Pressure is too high."));
  929. }
  930. if ($bpMin > 250) {
  931. return $this->setRawJsonResponse('err', _("Minimum Blood Pressure is too high."));
  932. }
  933. if ($heartRate > 250) {
  934. return $this->setRawJsonResponse('err', _("Heart Rate cannot be higher then 250 bpm."));
  935. }
  936. if ($oxygenSaturation > 100) {
  937. return $this->setRawJsonResponse('err', _("Oxygen Saturation cannot be higher than 100%."));
  938. }
  939. if ($medicalRemarks == '') {
  940. return $this->setRawJsonResponse('err', _("Please provide the Medical Remarks."));
  941. }
  942. if ($mainQuestion == '') {
  943. return $this->setRawJsonResponse('err', _("Please provide the Main Question."));
  944. }
  945. if (!is_array($referralList)) {
  946. if (!is_array($medicalSpecialties)) {
  947. return $this->setRawJsonResponse('err', _('Please provide at least one Medical Specialty for this request.'));
  948. }
  949. }
  950. //Check whether is provided a referral list or isn't
  951. $specificReferralData = [];
  952. if (is_array($referralList)) {
  953. //Get Medical Specialties and Referral Languages
  954. $referralIds = implode(',', $referralList);
  955. $medicalSpecialties = [];
  956. $referralLangs = [];
  957. $specificReferralData = $this->db
  958. ->where("u.id IN($referralIds)")
  959. ->where('u.group_id', $this->userGroupId)
  960. ->join('users_medical_specialties_to umst', 'umst.user_id=u.id', 'INNER')
  961. ->groupBy('umst.specialty_id')
  962. ->get('users u', null, ['umst.specialty_id referral_md', 'u.language_default referral_lang']);
  963. if (is_array($specificReferralData) && !empty($specificReferralData)) {
  964. foreach($specificReferralData as $item) {
  965. $medicalSpecialties[$item['referral_md']] = $item['referral_md'];
  966. $referralLangs[$item['referral_lang']] = $item['referral_lang'];
  967. }
  968. }
  969. }
  970. if ((int)$privacy == 0) {
  971. return $this->setRawJsonResponse('err', _('Please provide the Privacy Policy consent.'));
  972. }
  973. $cgnamesurname = $data['cgnamesurname']['value'];
  974. $cgrole = $data['cgrole']['value'];
  975. $cgphone = $data['cgphone']['value'];
  976. $cgemail = $data['cgemail']['value'];
  977. $cgmmgnamesurname = $data['cgmmgnamesurname']['value'];
  978. $cgmmgphone = $data['cgmmgphone']['value'];
  979. $cgmmgemail = $data['cgmmgemail']['value'];
  980. $cgprovince = $data['cgprovince']['value'];
  981. $cgcity = isset($data['cgcity']['value']) ? $data['cgcity']['value'] : 0;
  982. $dbData = [
  983. 'group_id' => $this->userGroupId, //mainController
  984. 'center_id' => $clinicalCenter,
  985. 'user_id' => $this->user->getUserId(),
  986. 'unique_code' => $requestUniqueCode,
  987. 'request_question' => $mainQuestion,
  988. 'request_status' => $operation,
  989. 'request_visibility' => (int)$visibility == 1 ? 'all' : 'private',
  990. 'request_origin' => 'web',
  991. 'request_status_number' => isset($status_numbers[$operation]) ? $status_numbers[$operation] : 0, //Default Draft
  992. 'request_guid' => $this->security->getGUID(),
  993. 'triage_color' => $triage,
  994. 'triage_number' => isset($triage_numbers[$triage]) ? $triage_numbers[$triage] : 0,
  995. 'cgnamesurname' => $cgnamesurname,
  996. 'cgrole' => $cgrole,
  997. 'cgphone' => $cgphone,
  998. 'cgemail' => $cgemail,
  999. 'cgmmgnamesurname' => $cgmmgnamesurname,
  1000. 'cgmmgphone' => $cgmmgphone,
  1001. 'cgmmgemail' => $cgmmgemail,
  1002. 'cgprovince' => $cgprovince,
  1003. 'cgcity' => $cgcity,
  1004. 'patient_privacy' => $privacy,
  1005. 'send_status' => 'central',
  1006. 'request_anonymous' => $anonymous,
  1007. 'updated_at' => date('Y-m-d H:i:s'),
  1008. 'created_at' => date('Y-m-d H:i:s')
  1009. ];
  1010. //First check for recipients
  1011. if (empty($recipientsIds)) {
  1012. /*$recipients = $handleRequest->getRecipients([
  1013. 'recipientList' => [],
  1014. 'ms' => $medicalSpecialties,
  1015. 'cc' => $referralCc,
  1016. 'langs' => $referralLangs,
  1017. 'groupId' => $this->userGroupId
  1018. ]);*/
  1019. $recipients = $handleRequest->getRecipients([
  1020. 'recipientList' => [],
  1021. 'ms' => $medicalSpecialties,
  1022. 'cc' => [$clinicalCenter],
  1023. 'langs' => $referralLangs,
  1024. 'groupId' => $this->userGroupId
  1025. ]);
  1026. if (is_array($recipients) && !empty($recipients)) {
  1027. foreach($recipients as $recipient) {
  1028. $recipientsIds[] = $recipient['user_id'];
  1029. }
  1030. }
  1031. }
  1032. if ($requestId == 0) { //Add
  1033. //Add the request record if there are recipients
  1034. if (is_array($recipientsIds) && !empty($recipientsIds)) {
  1035. //$dbData['created_at'] = date('Y-m-d H:i:s');
  1036. $lastInsert = $this->db->insert('requests', $dbData);
  1037. $requestId = $lastInsert;
  1038. } else {
  1039. return $this->setRawJsonResponse('err', _('Unable to save the Request: the Recipient List is empty.'), ['log'=>[]]);
  1040. }
  1041. } else { //Update
  1042. $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_SAVED_DRAFT', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestId]);
  1043. $this->db->where('id', $requestId)->update('requests', $dbData);
  1044. }
  1045. if ($requestId > 0) {
  1046. //Sportello cura
  1047. $sportellocura_code = (int)$data['sportellocura_code']['value'];
  1048. $sportellocura_json_data = trim($data['sportellocura']['value']);
  1049. if ($sportellocura_code > 0 && $sportellocura_json_data != '') {
  1050. //Check wheather already added
  1051. //$check = $this->db->where('survey_id', $sportellocura_code)->getOne('sportellocura', 'survey_id');
  1052. //if (!isset($check['survey_id'])) {
  1053. $this->db->replace('sportellocura', [
  1054. 'survey_id'=>$sportellocura_code,
  1055. 'request_id'=>$requestId,
  1056. 'survey_data'=>$sportellocura_json_data,
  1057. 'created_at'=>date('Y-m-d H:i:s')
  1058. ]);
  1059. $endpoint = $this->config['settings']['sportellocura']['api']['endpoint'];
  1060. $apikey = $this->config['settings']['sportellocura']['api']['key'];
  1061. $vars = ['survey_id'=>$sportellocura_code, 'cmd'=>'set-added'];
  1062. $ch = curl_init();
  1063. curl_setopt($ch, CURLOPT_URL, $endpoint);
  1064. curl_setopt($ch, CURLOPT_POST, 1);
  1065. curl_setopt($ch, CURLOPT_POSTFIELDS, $vars); //Post Fields
  1066. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  1067. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
  1068. curl_setopt($ch, CURLOPT_TIMEOUT, 10); //timeout in seconds
  1069. $headers = [
  1070. 'Api-Key: '.$apikey,
  1071. ];
  1072. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  1073. $curldata = curl_exec($ch);
  1074. curl_close($ch);
  1075. //}
  1076. }
  1077. //DREAM Italy and Sportello Cura files
  1078. if (isset($data['cg']) && is_array($data['cg'])) {
  1079. foreach($data['cg'] as $cg_index => $cg_data) {
  1080. $cg_filename = $cg_data['filename'];
  1081. $cg_filesystem_name = md5(uniqid());
  1082. $cg_filedata_base64 = $cg_data['filedata'];
  1083. $cg_file_data = base64_decode($cg_filedata_base64);
  1084. $cg_file_path = ATTACH_DIR.$cg_filesystem_name;
  1085. file_put_contents($cg_file_path, $cg_file_data);
  1086. if (file_exists($cg_file_path)) {
  1087. $cg_file_size = filesize($cg_file_path);
  1088. $cg_filetype = mime_content_type($cg_file_path);
  1089. $cg_file_ext = $this->utility->mime2ext($cg_filetype);
  1090. if ($cg_file_ext !== false) {
  1091. $cg_filesystem_name = $cg_filesystem_name.'.'.$cg_file_ext;
  1092. rename($cg_file_path, ATTACH_DIR.$cg_filesystem_name);
  1093. $cg_filename = str_ireplace('.'.$cg_file_ext, '', $cg_filename);
  1094. $cg_filename = $cg_filename.'.'.$cg_file_ext;
  1095. $cg_file_title = $this->utility->slugify($cg_filename);
  1096. $this->db->insert('requests_attachments', [
  1097. 'request_id'=>$requestId,
  1098. 'user_id'=>$this->user->getUserId(),
  1099. 'file_name'=>$cg_filesystem_name,
  1100. 'file_title'=>$cg_file_title,
  1101. 'file_ext'=>$cg_file_ext,
  1102. 'file_size'=>$cg_file_size,
  1103. 'file_mime'=>$cg_filetype,
  1104. 'type'=>'others',
  1105. 'created_at'=>date('Y-m-d H:i:s')
  1106. ]);
  1107. }
  1108. }
  1109. }
  1110. } else {
  1111. file_put_contents(ATTACH_DIR.'nodata.log', '');
  1112. }
  1113. //Update the Patient's Registry
  1114. $registryData = [
  1115. 'request_id' => $requestId,
  1116. 'center_id' => $clinicalCenter,
  1117. 'name' => $patientName,
  1118. 'surname' => $patientSurname,
  1119. 'birthdate' => $dateOfBirth,
  1120. 'gender' => $patientGender,
  1121. 'min_arterial_pressure' => $bpMin,
  1122. 'max_arterial_pressure' => $bpMax,
  1123. 'heart_rate' => $heartRate,
  1124. 'saturation' => $oxygenSaturation,
  1125. 'clinical_remarks' => $medicalRemarks,
  1126. 'medical_history' => $medicalHistory,
  1127. 'updated_at' => date('Y-m-d H:i:s'),
  1128. 'created_at' => date('Y-m-d H:i:s')
  1129. ];
  1130. $this->db->replace('requests_registry', $registryData);
  1131. //Check Specific Referrals
  1132. $this->db->where('request_id', $requestId)->delete('requests_recipients');
  1133. if (is_array($referralList)) {
  1134. foreach($referralList as $referralId) {
  1135. $this->db->insert('requests_recipients', [
  1136. 'request_id' => $requestId,
  1137. 'user_id' => $referralId
  1138. ]);
  1139. }
  1140. }
  1141. //Add/Update the Medical Specialties
  1142. $this->db->where('request_id', $requestId)->delete('requests_medical_specialties_to');
  1143. foreach($medicalSpecialties as $specialtyId) {
  1144. $this->db->insert('requests_medical_specialties_to', [
  1145. 'request_id' => $requestId,
  1146. 'specialty_id' => $specialtyId
  1147. ]);
  1148. }
  1149. //Add/Update Clinical Centers
  1150. $this->db->where('request_id', $requestId)->delete('request_clinical_centers_to');
  1151. if (is_array($referralCc) && !empty($referralCc)) {
  1152. foreach($referralCc as $ccId) {
  1153. $this->db->insert('request_clinical_centers_to', [
  1154. 'request_id' => $requestId,
  1155. 'center_id' => $ccId
  1156. ]);
  1157. }
  1158. }
  1159. //Add/Update recipients' languages
  1160. $this->db->where('request_id', $requestId)->delete('requests_languages_to');
  1161. foreach($referralLangs as $language) {
  1162. $this->db->insert('requests_languages_to', [
  1163. 'request_id' => $requestId,
  1164. 'language_code' => $language
  1165. ]);
  1166. }
  1167. //ICD-10
  1168. $this->db->where('request_id', $requestId)->delete('requests_symptoms_to');
  1169. if (is_array($icd10List) && !empty($icd10List)) {
  1170. foreach($icd10List as $symptomId) {
  1171. $this->db->insert('requests_symptoms_to', [
  1172. 'request_id' => $requestId,
  1173. 'symptom_id' => $symptomId
  1174. ]);
  1175. }
  1176. }
  1177. //Wizards
  1178. $this->db->where('request_id', $requestId)->delete('requests_wizards_to');
  1179. if (is_array($this->view->wizard)) {
  1180. foreach($this->view->wizard as $wizardType => $wizardIds) {
  1181. if (is_array($wizardIds) && !empty($wizardIds)) {
  1182. foreach($wizardIds as $examId) {
  1183. $this->db->insert('requests_wizards_to', [
  1184. 'request_id' => $requestId,
  1185. 'exam_id' => $examId,
  1186. 'exam_type' => $wizardType
  1187. ]);
  1188. }
  1189. }
  1190. }
  1191. }
  1192. //Wizard Derma positions
  1193. $this->db->where('request_id', $requestId)->delete('requests_wizard_derma_position_to');
  1194. if (is_array($dermaPositions) && !empty($dermaPositions)) {
  1195. foreach($dermaPositions as $positionType) {
  1196. $this->db->insert('requests_wizard_derma_position_to', [
  1197. 'request_id' => $requestId,
  1198. 'position_type' => $positionType
  1199. ]);
  1200. }
  1201. }
  1202. //Wizard Ear images
  1203. $this->db->where('request_id', $requestId)->delete('requests_wizard_ear_deseases_to');
  1204. if (is_array($earImages) && !empty($earImages)) {
  1205. foreach($earImages as $earImagesType) {
  1206. $this->db->insert('requests_wizard_ear_deseases_to', [
  1207. 'request_id' => $requestId,
  1208. 'desease_type' => $earImagesType
  1209. ]);
  1210. }
  1211. }
  1212. //Dream
  1213. if ($dreamCode != '') {
  1214. $this->db->replace('requests_dream_data', [
  1215. 'request_id' => $requestId,
  1216. 'dream_code' => trim(strtoupper($dreamCode)),
  1217. 'dream_evt_id' => $dreamEvtId,
  1218. 'dream_hash' => $dreamData,
  1219. 'created_at' => date('Y-m-d H:i:s')
  1220. ]);
  1221. }
  1222. }
  1223. $this->view->dbData = $dbData; //Debug
  1224. //return $this->setJsonView('requestSave');
  1225. //$debug = $handleRequest->checkPartialUploads();
  1226. if ($operation == 'draft') {
  1227. return $this->setRawJsonResponse('ok', _('Request information successfully saved as draft.'), ['log'=>$dermaPositions], ['button'=>'refresh-hash', 'recordId'=>$requestId, 'idPosition'=>3]);
  1228. } else {
  1229. //Update the recipient list for this request and change the status to pending|opened
  1230. if (is_array($recipientsIds) && !empty($recipientsIds)) {
  1231. $this->db->where('request_id', $requestId)->delete('requests_recipients');
  1232. foreach($recipientsIds as $recipientId) {
  1233. $this->db->insert('requests_recipients', [
  1234. 'request_id' => $requestId,
  1235. 'user_id' => $recipientId
  1236. ]);
  1237. }
  1238. $requestStatus = $hasFiles ? $handleRequest::REQUEST_STATUS_PENDING : $handleRequest::REQUEST_STATUS_OPENED;
  1239. $handleRequest->setRequestStatus($requestId, $requestStatus, $this->user->getUserId());
  1240. $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_SENT', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestId]);
  1241. //return $this->setRawJsonResponse('ok', _('Test'), ['log'=>$requestStatus]);
  1242. return $this->setRawJsonResponse('ok', _('Request information successfully opened.'), ['log'=>[]], ['button'=>'goto', 'destination'=>'requests/'.time().'/my/created_at/desc/1']);
  1243. }
  1244. }
  1245. }
  1246. public function getDreamInformation() {
  1247. if (!$this->user->isLogged()) {
  1248. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1249. }
  1250. $requestId = $this->getPost('requestId', 0);
  1251. $dreamResult = $this->db->where('request_id', $requestId)->getOne('requests_dream_data', 'dream_code, dream_hash');
  1252. $html = _('No DREAM information available.');
  1253. if (isset($dreamResult['dream_code'])) {
  1254. $dreamData = json_decode($dreamResult['dream_hash'], true);
  1255. $registry = [];
  1256. $exams = [];
  1257. $examStats = [];
  1258. $daily = [];
  1259. $symptoms = [];
  1260. $diagnosis = [];
  1261. $HivStages = [];
  1262. $HivTestHistory = [];
  1263. $TarvHistory = [];
  1264. $ListaFarmaci = [];
  1265. /*$examsAcr = ['Leuco','Eritro','Hemo','Hema','VGM','HGM','CHGM','Plaq','LYM','MXD','NEUT','LYM2','MXD2','NEUT2','CD4','CD4%','CViral','Creat','Glic','Blt','Urea','N2','Bild','GTP','GOT','Albu','Ferro','BK','Plasmodium','Ferritina','AlfaAmilasi','ColTot','ColHDL','Trig','Ca','Na','K','Cl','rdwcv','rdwsd','pdw','mpv','plrc','PT','ALP','Uric','PCR','PCRq','MON','EOS','BAS','MON2','EOS2','BAS2','ProtUR','PCT'];*/
  1266. $examsAcr = ['Leuco', 'Eritro', 'Hemo', 'Hema', 'VGM', 'HGM', 'CHGM', 'Plaq', 'LYM', 'MXD', 'NEUT', 'LYM2', 'MXD2', 'NEUT2', 'CD4', 'CD4%', 'CViral', 'Creat', 'Glic', 'Blt', 'Urea', 'N2', 'Bild', 'GTP', 'GOT', 'Albu', 'Ferro', 'BK', 'Plasmodium', 'Ferritina', 'AlfaAmilasi', 'ColTot', 'ColHDL', 'Trig', 'Ca', 'Na', 'K', 'Cl', 'rdwcv', 'rdwsd', 'pdw', 'mpv', 'plrc', 'PT', 'ALP', 'Uric', 'PCR', 'PCRq', 'MON', 'EOS', 'BAS', 'MON2', 'EOS2', 'BAS2', 'ProtUR', 'PCT'];
  1267. if (isset($dreamData['Anagrafica'])) {
  1268. $registry = $dreamData['Anagrafica'];
  1269. $registry['age'] = $this->utility->getAge($registry['dataNascita']);
  1270. }
  1271. if (isset($dreamData['Esami'])) {
  1272. //$exams = $this->utility->orderArray($dreamData['Esami'], 'Data', 'desc');
  1273. $exams = $dreamData['Esami'];
  1274. $filter = ['1'=>'<40', '-3000'=>'<20', '-50'=>'<50', '-150'=>'<150', '-550'=>'<550', '-839'=>'<839', '-1000'=>'<1000', '500001'=>'>ULQ', '10000001'=>'>ULQ', '-2'=>'<LDL', '0'=>'ND', '-2000'=>'A', '-2001'=>'B', '-2002'=>'C', '-2003'=>'D'];
  1275. if (is_array($exams)) {
  1276. foreach($exams as $index => $exam) {
  1277. foreach ($exam as $key => $value) {
  1278. if ($key == 'CViral') {
  1279. $code = (int)$value;
  1280. //Default
  1281. //$exams[$index][$key] = 'ND';
  1282. if (isset($filter[$code])) {
  1283. $exams[$index][$key] = $filter[$code];
  1284. }
  1285. }
  1286. }
  1287. }
  1288. }
  1289. }
  1290. /*if (isset($dreamData['Diaria'])) {
  1291. //$daily = $this->utility->orderArray($dreamData['Diaria'], 'Data', 'desc');
  1292. $daily = $dreamData['Diaria'];
  1293. $years = [];
  1294. $yearList = [];
  1295. $examList = [];
  1296. $chartYears = [];
  1297. $dataValues = [];
  1298. if (is_array($daily)) {
  1299. foreach($daily as $exam) {
  1300. if (strlen($exam['Data']) > 4) {
  1301. $y = substr($exam['Data'], 0, 4);
  1302. $years[$y] = $y;
  1303. }
  1304. }
  1305. if (count($years) > 1) rsort($years);
  1306. if (count($years) > 3) {
  1307. $yearList = array_slice($years, 0, 3);
  1308. } else {
  1309. $yearList = $years;
  1310. }
  1311. foreach($daily as $exam) {
  1312. $y = substr($exam['Data'], 0, 4);
  1313. $m = substr($exam['Data'], 5, 2);
  1314. if (in_array($y, $yearList)) {
  1315. $examList[$y][$m]['TAmin'][] = (float)$exam['TA_min'];
  1316. $examList[$y][$m]['TAmax'][] = (float)$exam['TA_max'];
  1317. $examList[$y][$m]['FC'][] = (float)$exam['FC'];
  1318. }
  1319. }
  1320. ksort($examList);
  1321. $chartYears = array_keys($examList);
  1322. $monthList = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
  1323. foreach($examList as $year => $month) {
  1324. foreach($monthList as $monthNumb) {
  1325. if (isset($examList[$year][$monthNumb])) {
  1326. $tamin = $examList[$year][$monthNumb]['TAmin'];
  1327. $v = array_sum($tamin)/count($tamin);
  1328. $examList[$year][$monthNumb]['TAmin'] = $v > 0 ? $v : null;
  1329. $tamax = $examList[$year][$monthNumb]['TAmax'];
  1330. $v = array_sum($tamax)/count($tamax);
  1331. $examList[$year][$monthNumb]['TAmax'] = $v > 0 ? $v : null;
  1332. $fc = $examList[$year][$monthNumb]['FC'];
  1333. $v = array_sum($fc)/count($fc);
  1334. $examList[$year][$monthNumb]['FC'] = $v > 0 ? $v : null;
  1335. } else {
  1336. $examList[$year][$monthNumb] = ['TAmin'=>null, 'TAmax'=>null, 'FC'=>null];
  1337. }
  1338. }
  1339. }
  1340. foreach($examList as $year => $month) {
  1341. $yearMonthList = $examList[$year];
  1342. ksort($yearMonthList);
  1343. $examList[$year] = $yearMonthList;
  1344. }
  1345. foreach($examList as $year => $month) {
  1346. foreach($month as $monthNumb => $montValue) {
  1347. $dataValues[$year]['TAmin'][] = $montValue['TAmin'];
  1348. $dataValues[$year]['TAmax'][] = $montValue['TAmax'];
  1349. $dataValues[$year]['FC'][] = $montValue['FC'];
  1350. }
  1351. }
  1352. $examStats = $examList;
  1353. }
  1354. }*/
  1355. if (isset($dreamData['Diaria'])) {
  1356. //$daily = $this->utility->orderArray($dreamData['Diaria'], 'date_event', 'desc');
  1357. $daily = $dreamData['Diaria'];
  1358. $years = [];
  1359. $yearList = [];
  1360. $examList = [];
  1361. $chartYears = [];
  1362. $dataValues = [];
  1363. if (is_array($daily)) {
  1364. foreach($daily as $exam) {
  1365. if (strlen($exam['date_event']) > 4) {
  1366. $y = substr($exam['date_event'], 0, 4);
  1367. $years[$y] = $y;
  1368. }
  1369. }
  1370. if (count($years) > 1) rsort($years);
  1371. if (count($years) > 3) {
  1372. $yearList = array_slice($years, 0, 3);
  1373. } else {
  1374. $yearList = $years;
  1375. }
  1376. foreach($daily as $exam) {
  1377. $y = substr($exam['date_event'], 0, 4);
  1378. $m = substr($exam['date_event'], 5, 2);
  1379. if (in_array($y, $yearList)) {
  1380. $examList[$y][$m]['TAmin'][] = (float)$exam['vn26']; //TA_min
  1381. $examList[$y][$m]['TAmax'][] = (float)$exam['vn25']; //TA_max
  1382. $examList[$y][$m]['FC'][] = (float)$exam['vn10']; //FC
  1383. }
  1384. }
  1385. ksort($examList);
  1386. $chartYears = array_keys($examList);
  1387. $monthList = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
  1388. foreach($examList as $year => $month) {
  1389. foreach($monthList as $monthNumb) {
  1390. if (isset($examList[$year][$monthNumb])) {
  1391. $tamin = $examList[$year][$monthNumb]['TAmin'];
  1392. $v = array_sum($tamin)/count($tamin);
  1393. $examList[$year][$monthNumb]['TAmin'] = $v > 0 ? $v : null;
  1394. $tamax = $examList[$year][$monthNumb]['TAmax'];
  1395. $v = array_sum($tamax)/count($tamax);
  1396. $examList[$year][$monthNumb]['TAmax'] = $v > 0 ? $v : null;
  1397. $fc = $examList[$year][$monthNumb]['FC'];
  1398. $v = array_sum($fc)/count($fc);
  1399. $examList[$year][$monthNumb]['FC'] = $v > 0 ? $v : null;
  1400. } else {
  1401. $examList[$year][$monthNumb] = ['TAmin'=>null, 'TAmax'=>null, 'FC'=>null];
  1402. }
  1403. }
  1404. }
  1405. foreach($examList as $year => $month) {
  1406. $yearMonthList = $examList[$year];
  1407. ksort($yearMonthList);
  1408. $examList[$year] = $yearMonthList;
  1409. }
  1410. foreach($examList as $year => $month) {
  1411. foreach($month as $monthNumb => $montValue) {
  1412. $dataValues[$year]['TAmin'][] = $montValue['TAmin'];
  1413. $dataValues[$year]['TAmax'][] = $montValue['TAmax'];
  1414. $dataValues[$year]['FC'][] = $montValue['FC'];
  1415. }
  1416. }
  1417. $examStats = $examList;
  1418. }
  1419. }
  1420. if (isset($dreamData['Sintomi'])) {
  1421. $symptoms = $dreamData['Sintomi'];
  1422. }
  1423. if (isset($dreamData['Diagnosi'])) {
  1424. $diagnosis = $dreamData['Diagnosi'];
  1425. }
  1426. if (isset($dreamData['HivStages'])) {
  1427. $HivStages = $dreamData['HivStages'][0] ?? [];
  1428. }
  1429. if (isset($dreamData['HivTestHistory'])) {
  1430. $HivTestHistory = $dreamData['HivTestHistory'][0] ?? [];
  1431. }
  1432. if (isset($dreamData['TarvHistory'])) {
  1433. $TarvHistory = $this->utility->orderArray($dreamData['TarvHistory'], 'DataInizio', 'desc') ?? [];
  1434. //$TarvHistory = $dreamData['TarvHistory'][0] ?? [];
  1435. }
  1436. if (isset($dreamData['ListaFarmaci'])) {
  1437. $ListaFarmaci = $dreamData['ListaFarmaci'];
  1438. }
  1439. $dailyData = [];
  1440. if (is_array($daily) && !empty($daily)) {
  1441. foreach($daily as $item) {
  1442. $dailyData[$item['id_event']]['Diaria'] = $item;
  1443. foreach($symptoms as $symptom) {
  1444. if ($symptom['id_event'] == $item['id_event']) {
  1445. $dailyData[$item['id_event']]['Sintomi'][] = $symptom;
  1446. }
  1447. }
  1448. foreach($diagnosis as $diagnosi) {
  1449. if ($diagnosi['id_event'] == $item['id_event']) {
  1450. $dailyData[$item['id_event']]['Diagnosi'][] = $diagnosi;
  1451. }
  1452. }
  1453. }
  1454. }
  1455. $html = $this->partial('Request/dream-dialog-content', ['dreamData'=>$dreamData, 'registry'=>$registry, 'exams'=>$exams, 'examStats'=>$examStats, 'examsAcr'=>$examsAcr, 'dailyData'=>$dailyData, 'dataValues'=>$dataValues, 'daily'=>$daily, 'symptoms'=>$symptoms, 'diagnosis'=>$diagnosis, 'HivStages'=>$HivStages, 'HivTestHistory'=>$HivTestHistory, 'TarvHistory'=>$TarvHistory, 'ListaFarmaci'=>$ListaFarmaci]);
  1456. }
  1457. return $this->setRawJsonResponse('ok', '', ['html'=>$html, 'chartYears'=>$chartYears, 'dataValues'=>$dataValues]);
  1458. }
  1459. //Ajax function to update the Medical Specialties per Clinical Center
  1460. public function getSpecialtiesPerCenter() {
  1461. if (!$this->user->isLogged()) {
  1462. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1463. }
  1464. $medicalSpecialties = [];
  1465. $centerId = $this->getPost('centerId', 0);
  1466. $handleRequest = new HandleRequest();
  1467. $results = $handleRequest->getSpecialtyByClinicalCenterId($centerId, $this->userGroupId);
  1468. if (is_array($results)) {
  1469. $c=0;
  1470. foreach($results as $item) {
  1471. $medicalSpecialties[$c]['value'] = $item['id'];
  1472. $medicalSpecialties[$c]['text'] = _($item['description']);
  1473. $c++;
  1474. }
  1475. }
  1476. return $this->setRawJsonResponse('ok', '', ['specialties'=>$medicalSpecialties]);
  1477. }
  1478. //Ajax function to send message (comment) from Request page
  1479. public function requestSendMessage() {
  1480. if (!$this->user->isLogged()) {
  1481. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1482. }
  1483. $handleRequest = new HandleRequest();
  1484. $requestID = $this->getPost('requestID', 0);
  1485. $centerID = $this->getPost('centerID', 0);
  1486. $newStatus = $this->getPost('newStatus', '');
  1487. $message = trim($this->getPost('message', null));
  1488. $specialties = rawurldecode($this->getPost('specialtyList', ''));
  1489. $specialtyList = strpos($specialties, ',') !== false || (int)$specialties > 0 ? explode(',', $specialties) : null;
  1490. $hasAttachments = $this->getPost('hasAttachments', false);
  1491. $return = [];
  1492. //$buffer = $handleRequest->forwardRequest($requestID, $specialtyList, $this->userGroupId, $this->user->getUserId(), 15);
  1493. //return $this->setRawJsonResponse('err', $buffer, ['log'=>$buffer]);
  1494. if ($message == '') {
  1495. return $this->setRawJsonResponse('err', _('The Comment text field cannot be empty.'), ['log'=>[]]);
  1496. }
  1497. $id = $this->db->insert('requests_comments', [
  1498. 'request_id' => $requestID,
  1499. 'user_id' => $this->user->getUserId(),
  1500. 'comment' => $message,
  1501. 'comment_guid' => $this->security->getGUID(),
  1502. 'updated_at' => date('Y-m-d H:i:s'),
  1503. 'created_at' => date('Y-m-d H:i:s')
  1504. ]);
  1505. if ($id) {
  1506. $comments = $handleRequest->getCommentList($requestID, $centerID, true);
  1507. $request = $this->db->where('id', $requestID)->getOne('requests');
  1508. $html = $this->partial('Request/comment-list', ['comments'=>$comments]);
  1509. $return['commentID'] = $id;
  1510. $return['html'] = $html;
  1511. $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_MSG', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestID]);
  1512. //If the user is a referral, increment the comment counter (request_reports_counter table)
  1513. if ($handleRequest->isReferralInRequest($requestID, $this->user->getUserId())) {
  1514. //$handleRequest->setLog('position', 'dentro is referral in request');
  1515. //Check whether moderator or referral has added new medical specialty and notify new referrals
  1516. if ($handleRequest->forwardRequest($requestID, $specialtyList, $this->userGroupId, $request['user_id'], $request['center_id'])) {
  1517. $handleRequest->setRequestStatus($requestID, $handleRequest::REQUEST_STATUS_PART_REPORTED, $this->user->getUserId());
  1518. //$handleRequest->setLog('position', 'dentro forward');
  1519. } else {
  1520. //If previusly reported, just change the status to reported (closed)
  1521. /*if ($handleRequest->isRequestPreviouslyReopened($requestID)) {
  1522. $handleRequest->setLog('position', 'dentro is previuosly reopened');
  1523. $handleRequest->setRequestStatus($requestID, $handleRequest::REQUEST_STATUS_REPORTED, $this->user->getUserId());
  1524. //Notify the applicant (queue the message)
  1525. $msgStructure = $handleRequest->queueMessage($requestID, $request['user_id'], $request['user_id'], 'PARTIALLY_REPORTED');
  1526. } else {*/
  1527. //$handleRequest->setLog('position', 'dentro il commento normale, incrementa il contatore');
  1528. //If a referral comments again, doesn't add a new record in the table (see the table indexes)
  1529. $handleRequest->incrementReferralCounter($requestID, $this->user->getUserId());
  1530. //Change the request status
  1531. if ($handleRequest->isRequestFullyReported($requestID) === true) {
  1532. $handleRequest->setRequestStatus($requestID, $handleRequest::REQUEST_STATUS_REPORTED, $this->user->getUserId());
  1533. $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_CLOSED_AUTO', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestID]);
  1534. } else {
  1535. $handleRequest->setRequestStatus($requestID, $handleRequest::REQUEST_STATUS_PART_REPORTED, $this->user->getUserId());
  1536. }
  1537. //Notify the applicant (queue the message)
  1538. $msgStructure = $handleRequest->queueMessage($requestID, $request['user_id'], $request['user_id'], 'PARTIALLY_REPORTED');
  1539. //}
  1540. }
  1541. }
  1542. //TODO: check whether the comment has attachments (visible / not visible)
  1543. //Applicant's comment: change the status to REOPENED
  1544. if ($handleRequest->isApplicantInRequest($requestID, $this->user->getUserId())) {
  1545. $handleRequest->setRequestStatus($requestID, $handleRequest::REQUEST_STATUS_REOPENED, $this->user->getUserId());
  1546. $handleRequest->notifyAllReferrals($requestID, 'REQUEST_UPDATE');
  1547. }
  1548. //Force the new request status (Moderator)
  1549. if ($newStatus != '') {
  1550. $handleRequest->setRequestStatus($requestID, $newStatus, $this->user->getUserId());
  1551. $isFwd = $handleRequest->forwardRequest($requestID, $specialtyList, $this->userGroupId, $request['user_id'], $request['center_id']);
  1552. if ($newStatus == 'reopened') {
  1553. //Notifiy all referrals
  1554. $handleRequest->notifyAllReferrals($requestID, 'REQUEST_UPDATE');
  1555. //Notify the applicant
  1556. $handleRequest->queueMessage($requestID, $request['user_id'], $request['user_id'], 'REQUEST_UPDATE_APPLICANT');
  1557. }
  1558. if ($newStatus == 'referted') {
  1559. //Notify the applicant
  1560. $handleRequest->queueMessage($requestID, $request['user_id'], $request['user_id'], 'CLOSED_BY_MODERATOR');
  1561. }
  1562. $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_STATUS_CNG_MODERATOR', ['userId'=>$this->user->getUserId(), 'newStatus'=>$newStatus]);
  1563. }
  1564. //Update last update request field
  1565. $handleRequest->updateDate($requestID);
  1566. $return['action'] = 'refresh';
  1567. return $this->setRawJsonResponse('ok', '', $return);
  1568. } else {
  1569. return $this->setRawJsonResponse('err', _('Unable to send the message right now. Please try again in a few minutes.'), ['log'=>[]]);
  1570. }
  1571. }
  1572. //Ajax function to load all request comments
  1573. public function requestLoadAllComments() {
  1574. if (!$this->user->isLogged()) {
  1575. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1576. }
  1577. $requestID = $this->getPost('requestID', 0);
  1578. $centerID = $this->getPost('centerID', 0);
  1579. $comments = $handleRequest->getCommentList($requestID, $centerID, true);
  1580. $html = $this->partial('Request/comment-list', ['comments'=>$comments]);
  1581. return $this->setRawJsonResponse('ok', '', ['html'=>$html]);
  1582. }
  1583. //Ajax function to get the deaseses under a provided ICD10 category
  1584. public function requestGetDeseases() {
  1585. if (!$this->user->isLogged()) {
  1586. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1587. }
  1588. if(!$this->checkPermissions([ADMIN_ROLE_ID, APPLICANT_ROLE_ID])) {
  1589. return $this->setRawJsonResponse('err', _('Permission denied.'));
  1590. }
  1591. $icd10Id = $this->getPost('icd10Id', null); //Parent category ID
  1592. //If Draft mode some deseases could be selected
  1593. $selectedDeseases = $this->getPost('selectedDeseases', []);
  1594. $handleRequest = new HandleRequest();
  1595. $deseases = $handleRequest->getDeseasesByICD10Category($icd10Id, $this->user->getUserLang(), $selectedDeseases);
  1596. $html = $this->partial('Request/icd10-deseases-list', ['deseases'=>$deseases, 'checked'=>false]);
  1597. return $this->setRawJsonResponse('ok', '', ['html'=>$html]);
  1598. }
  1599. public function requestSearchDesease() {
  1600. if (!$this->user->isLogged()) {
  1601. return $this->setRawJsonResponse('ok', '', ['html'=>'']);
  1602. }
  1603. if(!$this->checkPermissions([ADMIN_ROLE_ID, APPLICANT_ROLE_ID])) {
  1604. return $this->setRawJsonResponse('ok', '', ['html'=>'']);
  1605. }
  1606. $handleRequest = new HandleRequest();
  1607. $keyword = addslashes($this->getPost('keyword', null));
  1608. $langCode = $this->getPost('lang', 'en');
  1609. $selectedDeseases = $this->getPost('selectedDeseases', []);
  1610. $deseases = $handleRequest->getDeseaseByKeyword($keyword, $langCode, $selectedDeseases);
  1611. $html = $this->partial('Request/icd10-search-deseases-list', ['deseases'=>$deseases, 'langCode'=>$langCode]);
  1612. return $this->setRawJsonResponse('ok', '', ['html'=>$html]);
  1613. }
  1614. //Ajax function to get all attachs by post code (used to render the attachs list after an Ajax call)
  1615. public function requestAttachs() {
  1616. if (!$this->user->isLogged()) {
  1617. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1618. }
  1619. if(!$this->checkPermissions([ADMIN_ROLE_ID, MODERATOR_ROLE_ID, APPLICANT_ROLE_ID])) {
  1620. return $this->setRawJsonResponse('err', _('Permission denied.'));
  1621. }
  1622. $postCode = $this->getPost('postCode', null);
  1623. $attachs = [];
  1624. $request = null;
  1625. if(!is_null($postCode)) {
  1626. $request = $this->db
  1627. ->where('r.unique_code', $postCode)
  1628. ->join('requests_attachments ra', 'ra.request_id=r.id', 'INNER')
  1629. ->get('requests r', null, ['ra.id attach_id', 'ra.file_name attach_name', 'ra.file_title attach_title', 'ra.file_ext attach_ext']);
  1630. if (is_array($request)) {
  1631. foreach($request as $index => $item) {
  1632. $ext = trim($item['attach_ext']) != '' ? $item['attach_ext'] : pathinfo($item['attach_name'], PATHINFO_EXTENSION);
  1633. $attachs[$index]['forceDownload'] = !in_array($ext, $this->config['settings']['preview-ext']) ? 1 : 0;
  1634. $attachs[$index]['ext'] = $ext;
  1635. $attachs[$index]['id'] = $item['attach_id'];
  1636. $attachs[$index]['name'] = $item['attach_name'];
  1637. $attachs[$index]['title'] = $this->helper->truncate($item['attach_title'], MAX_ATTACH_TITLE_LENGTH, '...'.$item['attach_ext']); }
  1638. }
  1639. }
  1640. return $this->setRawJsonResponse('ok', '', ['attachData'=>$attachs]);
  1641. }
  1642. //Ajax function to delete the passed attachment id
  1643. public function requestDeleteAttach() {
  1644. if (!$this->user->isLogged()) {
  1645. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1646. }
  1647. if(!$this->checkPermissions([ADMIN_ROLE_ID, APPLICANT_ROLE_ID])) {
  1648. return $this->setRawJsonResponse('err', _('Permission denied.'));
  1649. }
  1650. $attachId = $this->getPost('attachId', null);
  1651. $attachName = $this->getPost('attachName', null);
  1652. $delete = false;
  1653. if (!is_null($attachId) && !is_null($attachName)) {
  1654. $delete = $this->db->where('id', $attachId)->delete('requests_attachments');
  1655. @unlink(ATTACH_DIR.$attachName);
  1656. }
  1657. if ($delete) {
  1658. return $this->setRawJsonResponse('ok', '', ['attachId'=>$attachId]);
  1659. } else {
  1660. return $this->setRawJsonResponse('ok', '', ['attachId'=>0]);
  1661. }
  1662. }
  1663. //Ajax function to delete the request by id
  1664. public function requestDelete() {
  1665. if (!$this->user->isLogged()) {
  1666. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1667. }
  1668. if(!$this->checkPermissions([APPLICANT_ROLE_ID, MODERATOR_ROLE_ID])) {
  1669. return $this->setRawJsonResponse('err', _('Permission denied.'));
  1670. }
  1671. $scope = $this->user->is(APPLICANT_ROLE_ID) ? 'my' : 'moderations';
  1672. $requestId = $this->getPost('requestId', 0);
  1673. $handleRequest = new HandleRequest();
  1674. $return = $handleRequest->deleteRequest($requestId);
  1675. if ($return) {
  1676. $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_DELETED', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestId]);
  1677. return $this->setRawJsonResponse('ok', '', ['redirect'=>'requests/'.time().'/'.$scope.'/created_at/desc/1']);
  1678. } else {
  1679. return $this->setRawJsonResponse('err', _('Unable to delete the request right now, please try again in a few minutes.'));
  1680. }
  1681. }
  1682. public function getRequestResponders() {
  1683. if (!$this->user->isLogged()) {
  1684. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1685. }
  1686. if(!$this->checkPermissions([MODERATOR_ROLE_ID])) {
  1687. return $this->setRawJsonResponse('err', _('Permission denied.'));
  1688. }
  1689. $handleRequest = new HandleRequest();
  1690. $requestId = $this->getPost('requestId', 0);
  1691. $recipients = $handleRequest->getRecipientsByRequestId($requestId);
  1692. $html = $this->partial('Request/show-responders-list', ['recipients'=>$recipients]);
  1693. return $this->setRawJsonResponse('ok', '', ['html'=>$html]);
  1694. }
  1695. //Activity log page
  1696. public function logs() {
  1697. if (!$this->user->isLogged()) {
  1698. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1699. }
  1700. if(!$this->checkPermissions([ADMIN_ROLE_ID])) {
  1701. return $this->setRawJsonResponse('err', _('Permission denied.'));
  1702. }
  1703. $this->view->users = $this->db
  1704. ->where('status', 1)
  1705. ->where('group_id', $this->userGroupId)
  1706. ->orderBy('surname', 'asc')
  1707. ->get('users', null, ['id', 'username', 'name', 'surname']);
  1708. $this->view->requests = $this->db
  1709. ->where('u.status', 1)
  1710. ->where('u.group_id', $this->userGroupId)
  1711. ->join('users u', 'u.id=r.user_id', 'INNER')
  1712. ->orderBy('r.created_at', 'desc')
  1713. ->get('requests r', 100, ['r.id', 'r.created_at']);
  1714. $this->actionTitle = _('Activity logs');
  1715. return $this->setJsonView('logs');
  1716. }
  1717. //Sending Referral list preview (in a modal)
  1718. public function requestPreview() {
  1719. if (!$this->user->isLogged()) {
  1720. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1721. }
  1722. if(!$this->checkPermissions([ADMIN_ROLE_ID, APPLICANT_ROLE_ID])) {
  1723. return $this->setRawJsonResponse('err', _('Permission denied.'));
  1724. }
  1725. $data = isset($_POST['data']) ? $_POST['data'] : null;
  1726. $this->view->data = $data;
  1727. $this->view->error = '';
  1728. $userCount = 0;
  1729. $request = new HandleRequest();
  1730. $recipientList = $data['request_referral_list']['value'];
  1731. if (!is_array($recipientList)) {
  1732. if (!is_array($data['referral_ms']['value'])) {
  1733. $this->view->error = _('Please provide at least one Responder Medical for this request.');
  1734. return $this->setJsonView('requestPreview', true, '', ['userCount'=>$userCount]);
  1735. }
  1736. /*if (!is_array($data['referral_cc']['value'])) {
  1737. $this->view->error = _('Please provide at least one Responder Clinical Center.');
  1738. return $this->setJsonView('requestPreview', true, '', ['userCount'=>$userCount]);
  1739. }
  1740. */
  1741. if (!is_array($data['referral_langs']['value'])) {
  1742. $this->view->error = _('Please provide at least one Default Language for this request.');
  1743. return $this->setJsonView('requestPreview', true, '', ['userCount'=>$userCount]);
  1744. }
  1745. }
  1746. $referralMs = $data['referral_ms']['value'];
  1747. $referralCc = isset($data['referral_cc']['value']) && !empty($data['referral_cc']['value']) ? $data['referral_cc']['value'] : null;
  1748. $referralLangs = $data['referral_langs']['value'];
  1749. $referralVisibility = $data['referral_ms']['referral_visibility'];
  1750. //Recipients preview
  1751. $this->view->referrals = $request->getRecipients([
  1752. 'recipientList' => $recipientList,
  1753. 'ms' => $referralMs,
  1754. 'cc' => $referralCc,
  1755. 'langs' => $referralLangs
  1756. ]);
  1757. $userCount = count($this->view->referrals);
  1758. return $this->setJsonView('requestPreview', true, '', ['userCount'=>$userCount]);
  1759. }
  1760. public function generatePDF() {
  1761. if (!$this->user->isLogged()) {
  1762. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1763. }
  1764. $context = $this->getPost('context');
  1765. $operation = $this->getPost('operation');
  1766. $htmlContent = '';
  1767. $outputFilePath = '';
  1768. $fileTitle = 'print_preview';
  1769. $pdf = new PdfPrinter();
  1770. $layout = new Layout();
  1771. $destinationDir = DATA_TMP_DIR;
  1772. $printFileURI = $this->config['settings']['http-protocol'].$this->config['settings']['site-domain'].'/print/';
  1773. switch($context) {
  1774. case 'requestview':
  1775. $_POST['requestID'] = $this->getPost('requestId');
  1776. $_POST['viewType'] = 'view';
  1777. $this->requestEdit();
  1778. // footer dinamico
  1779. $headerURI = $printFileURI.'header-default.php?center_description='.rawurlencode($this->view->requestData['center_description'])
  1780. .'&center_continent='.rawurlencode($this->view->requestData['center_continent']).'&center_country='.rawurlencode($this->view->requestData['center_country']).'&center_address='.rawurlencode($this->view->requestData['center_address'])
  1781. .'&companies_title='.rawurlencode($this->view->companies['title'])
  1782. .'&head_title='._('Multidisciplinary teleconsultation service')
  1783. .'&app_report_header='.$this->config['settings']['app-report-header'].'';
  1784. $footerURI = $printFileURI.'footer-default.php?teleconsulto='.rawurlencode($this->actionTitle).'&paziente='.$this->view->requestData['patient_surname'].' '.$this->view->requestData['patient_name']
  1785. .'&request_date='.$this->view->requestData['created_at'].'&patient='._('Patient_pdf').'&request_date_txt='._('Request date').'&print_date_txt='._('Print date')
  1786. .'&request_date='.$this->view->requestData['created_at'].'';
  1787. $htmlContent = $this->partial('Print/request-view', ['publicUri'=>$layout->getPublicUri()]);
  1788. $outputFilePath = $destinationDir.'request_'.$this->user->getUserId().'.pdf';
  1789. $fileTitle = 'request_'.$this->view->requestData['id'];
  1790. break;
  1791. }
  1792. //Pass the HTML to $pdf object
  1793. $pdfContent = $pdf->convertHtmlToPdf($htmlContent, $headerURI, $footerURI);
  1794. //file_put_contents($destinationDir.'html.html', $htmlContent);
  1795. file_put_contents($outputFilePath, $pdfContent);
  1796. if ($operation == 'print') {
  1797. return $this->setRawJsonResponse('ok', '', ['outputFilePath'=>$outputFilePath, 'fileTitle'=>$fileTitle,'debug'=>$this->view->companies]);
  1798. } else {
  1799. $hr = new HandleRequest();
  1800. $request_id = $this->getPost('requestId');
  1801. $attach_ids = $this->getPost('attach_ids');
  1802. $delay = $this->getPost('delay', null);
  1803. $delay_date = $this->utility->setDateToIsoFormat($delay);
  1804. $attachs = [];
  1805. //return $this->setRawJsonResponse('err', '-'.strlen($delay).'-');
  1806. if (strlen($delay) > 0 && is_null($delay_date)) {
  1807. return $this->setRawJsonResponse('err', "Impossibile concludere l'operazione, la data di spedizione deve essere indicata nel formato gg/mm/aaaa.");
  1808. }
  1809. if (!is_null($delay_date) && $this->utility->isDateInThePast($delay_date)) {
  1810. return $this->setRawJsonResponse('err', "La data di spedizione non può essere corrente o nel passato.");
  1811. }
  1812. $survey = $this->db->where('request_id', $request_id)->getOne('sportellocura');
  1813. if (isset($survey['survey_id']) || trim($this->view->requestData['cgemail']) != '') {
  1814. $survey_data = json_decode($survey['survey_data'], true);
  1815. $attachs_data = [];
  1816. if (isset($survey['survey_id'])) {
  1817. $recipient_email = $survey_data['email'];
  1818. $recipient_name = $survey_data['name'];
  1819. $recipient_surname = $survey_data['surname'];
  1820. $mailcode = 'SURVEY_'.uniqid();
  1821. $survey_id = $survey['survey_id'];
  1822. } else {
  1823. $recipient_email = trim($this->view->requestData['cgemail']);
  1824. $recipient_name = '';
  1825. $recipient_surname = trim($this->view->requestData['cgnamesurname']) != '' ? trim($this->view->requestData['cgnamesurname']) : 'Paziente';
  1826. $mailcode = 'REPORT_'.uniqid();
  1827. $survey_id = 0;
  1828. }
  1829. //$recipient_email = 'agodegi@gmail.com';
  1830. if ($this->utility->validateEmail($recipient_email)) {
  1831. if (is_array($attach_ids) && !empty($attach_ids)) {
  1832. $attach_id_list = implode(',', $attach_ids);
  1833. $attachs = $this->db->where("id IN($attach_id_list)")->get('requests_attachments');
  1834. if (is_array($attachs) && !empty($attachs)) {
  1835. foreach($attachs as $index => $attach) {
  1836. $attachs_data[$index]['path'] = ATTACH_DIR.$attach['file_name'];
  1837. $attachs_data[$index]['name'] = $attach['file_title'].'.'.$attach['file_ext'];
  1838. }
  1839. }
  1840. }
  1841. $pdf_path = ATTACH_DIR.$request_id.'.pdf';
  1842. rename($outputFilePath, $pdf_path);
  1843. //////
  1844. $attachs_data[] = ['path'=>$pdf_path, 'name'=>'Risposta-Specialista.pdf'];
  1845. $subject = 'Risposta del TeleAmbulatorio';
  1846. $body = "Gentile $recipient_name $recipient_surname,<br>dopo aver ricevuto le varie notizie cliniche, le inoltriamo, in allegato, la risposta dello specialista alla sua visita ambulatoriale eseguita in modalità di telemedicina.<br><br>N.B.: questo messaggio è inviato automaticamente, eventuali risposte non saranno monitorate.<br><br>
  1847. Cordiali Saluti,<br>Servizio di TeleAmbulatorio";
  1848. //$nf = new Notification();
  1849. //$mailcode = 'SURVEY_'.uniqid();
  1850. //$nf->sendEmail($recipient_email, $subject, $body, $mailcode, [], $attachs_data);*/
  1851. //////
  1852. $hr->insertMsgInQueue([
  1853. 'senderId' => $this->user->getUserId(),
  1854. 'recipientId' => $this->user->getUserId(), //L'utente corrente deve avere l'invio delle email attivato
  1855. 'requestId' => $request_id,
  1856. 'mailId' => $mailcode,
  1857. 'subject' => $subject,
  1858. 'content' => $body,
  1859. 'type' => 'email',
  1860. 'recipient' => $recipient_email,
  1861. 'senderStatus' => 1,
  1862. 'attachments' => json_encode($attachs_data),
  1863. 'delay' => $delay_date
  1864. ]);
  1865. //Log
  1866. $this->db->insert('sportellocura_log', [
  1867. 'request_id'=>$request_id,
  1868. 'survey_id'=>$survey_id,
  1869. 'mail_code'=>$mailcode,
  1870. 'created_at'=>date('Y-m-d H:i:s')
  1871. ]);
  1872. $this->notifySendPdf($survey['survey_id']);
  1873. return $this->setRawJsonResponse('ok', 'PDF inviato correttamente', ['log'=>null], ['button'=>'refresh-hash']);
  1874. } else {
  1875. return $this->setRawJsonResponse('err', _('Not valid recipient e-mail address'));
  1876. }
  1877. }
  1878. //Send PDF
  1879. return $this->setRawJsonResponse('err', _('Not valid request'));
  1880. }
  1881. }
  1882. public function deleteSurveyMailQueue() {
  1883. $mail_id = $this->getPost('mail_id', null);
  1884. $request_id = $this->getPost('request_id', 0);
  1885. $this->db
  1886. ->where('request_id', $request_id)
  1887. ->where('mail_id', $mail_id)
  1888. ->delete('requests_messages_queue');
  1889. return $this->setRawJsonResponse('ok', 'Il tentativo di cancellazione della ricezione programmata è stato eseguito con successo.');
  1890. }
  1891. public function getCitiesByProvince() {
  1892. $province_id = $this->getPost('province_id', 0);
  1893. $selected_city_id = $this->getPost('selected_city_id', 0);
  1894. $options = ['<option value="0">...</option>'];
  1895. $html = '';
  1896. $cities = $this->db->where('province_id', $province_id)->orderBy('name', 'ASC')->get('italian_cities');
  1897. if (is_array($cities) && !empty($cities)) {
  1898. foreach($cities as $city) {
  1899. $selected = $city['id'] == $selected_city_id ? 'selected' : '';
  1900. $options[] = '<option value="'.$city['id'].'" '.$selected.'>'.$city['name'].'</option>';
  1901. }
  1902. $html = implode("\n", $options);
  1903. }
  1904. return $this->setRawJsonResponse('ok', '', ['html'=>$html]);
  1905. }
  1906. private function notifySendPdf($survey_id=0) {
  1907. $endpoint = $this->config['settings']['sportellocura']['api']['endpoint'];
  1908. $apikey = $this->config['settings']['sportellocura']['api']['key'];
  1909. $vars = ['survey_id'=>$survey_id, 'cmd'=>'notify-pdf'];
  1910. if ($survey_id < 1) return;
  1911. $ch = curl_init();
  1912. curl_setopt($ch, CURLOPT_URL, $endpoint);
  1913. curl_setopt($ch, CURLOPT_POST, 1);
  1914. curl_setopt($ch, CURLOPT_USERPWD, "dev:demo");
  1915. curl_setopt($ch, CURLOPT_POSTFIELDS, $vars); //Post Fields
  1916. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  1917. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
  1918. curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  1919. $headers = [
  1920. 'Api-Key: '.$apikey,
  1921. ];
  1922. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  1923. $data = curl_exec($ch);
  1924. //$output = json_decode($data, true);
  1925. curl_close($ch);
  1926. return $data;
  1927. }
  1928. public function getSportelloCura() {
  1929. $endpoint = $this->config['settings']['sportellocura']['api']['endpoint'];
  1930. $apikey = $this->config['settings']['sportellocura']['api']['key'];
  1931. $survey_id = $this->getPost('survey_id', 0);
  1932. $vars = ['survey_id'=>$survey_id, 'cmd'=>'get-survey'];
  1933. $ch = curl_init();
  1934. curl_setopt($ch, CURLOPT_URL, $endpoint);
  1935. curl_setopt($ch, CURLOPT_POST, 1);
  1936. curl_setopt($ch, CURLOPT_USERPWD, "dev:demo");
  1937. curl_setopt($ch, CURLOPT_POSTFIELDS, $vars); //Post Fields
  1938. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  1939. $headers = [
  1940. 'Api-Key: '.$apikey,
  1941. ];
  1942. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  1943. $data = curl_exec($ch);
  1944. $output = json_decode($data, true);
  1945. curl_close($ch);
  1946. $type_id = isset($output['survey']['type_id']) ? (int)$output['survey']['type_id'] : 0;
  1947. $output['survey']['ms'] = 0;
  1948. if ($type_id > 0) {
  1949. $ms = $this->db->where('sportello_type_id', $type_id)->getOne('users_medical_specialties');
  1950. if (isset($ms['id']) && (int)$ms['id']>0) {
  1951. $output['survey']['ms'] = $ms['id'];
  1952. }
  1953. }
  1954. return $this->setRawJsonResponse('ok', '', ['output'=>$output]);
  1955. }
  1956. public function getDreamItaly() {
  1957. $endpoint = $this->config['settings']['api']['endpoint'];
  1958. $apikey = $this->config['settings']['api']['key'];
  1959. $code = $this->getPost('code', 0);
  1960. $vars = ['request_id'=>$code];
  1961. $ch = curl_init();
  1962. curl_setopt($ch, CURLOPT_URL, $endpoint);
  1963. curl_setopt($ch, CURLOPT_POST, 1);
  1964. curl_setopt($ch, CURLOPT_POSTFIELDS, $vars); //Post Fields
  1965. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  1966. $headers = [
  1967. 'Api-Key: '.$apikey,
  1968. ];
  1969. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  1970. $data = curl_exec($ch);
  1971. $output = json_decode($data, true);
  1972. $output['r_citta_lcl_id'] = 0;
  1973. $output['r_provincia_lcl_id'] = 0;
  1974. curl_close ($ch);
  1975. return $this->setRawJsonResponse('ok', '', ['output'=>$output]);
  1976. }
  1977. public function setViewerType() {
  1978. $checked_value = $this->getPost('checked_value', -1);
  1979. $user_id = $this->user->getUserId();
  1980. if ((int)$checked_value > -1) {
  1981. //$updt = $this->db->where('id', $user_id)->update('users', ['simple_viewer'=>$checked_value]);
  1982. $updt = 0;
  1983. }
  1984. return $this->setRawJsonResponse('ok', '', ['output'=>$updt]);
  1985. }
  1986. public function allowAccess() {
  1987. if (!$this->user->isLogged()) {
  1988. return $this->redirect('login', 'index');
  1989. }
  1990. return false;
  1991. }
  1992. }