Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531
  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. $this->view->userLang = $this->user->getUserLang();
  423. //Default values
  424. $this->view->userCanView = true;
  425. $this->view->requestData = [];
  426. $this->view->companies = [];
  427. $this->view->symptoms = [];
  428. $this->view->ICD10 = [];
  429. $this->view->medicalSpecialties = [];
  430. $this->view->requestMedicalSpecialties = [];
  431. $this->view->forwardMedicalSpecialties = [];
  432. $this->view->requestMedicalSpecialtiesIdList = [];
  433. $this->view->attachments = [];
  434. $this->view->comments = [];
  435. $this->view->ccReferral = []; //Clinical Centers referrals (recipients)
  436. $this->view->languages = $this->locale->getSupportedLanguages();
  437. $this->view->icd10 = [];
  438. $this->view->dermaPositions = [];
  439. $this->view->dermaPositionLabels = ['single'=>_('Single'), 'multiple-localized'=>_('Multiple localized'), 'multiple-spread'=>_('Multiple spread'), 'clusted'=>_('Cluster'), 'metameric'=>_('Metameric'), 'linear'=>_('Linear'), 'acral'=>_('Acral'), 'symmetrical'=>_('Symmetrical')];
  440. $this->view->otoImages = [];
  441. $this->view->otoPositionLabels = ['oto_myringitis'=>_('Bullous myringitis'),
  442. 'oto_polip'=>_('Polyp of the EAC'),
  443. 'oto_atelectasis'=>_('Tympanic membrane atelectasis'),
  444. 'oto_perforation'=>_('Tympanic membrane perforation / non-cholesteatomatous otitis media'),
  445. 'oto_chole'=>_('Cholesteatomatous otitis media'),
  446. 'oto_tympanoscler'=>_('Tympanosclerosis'),
  447. 'oto_tyjugular'=>_('Tympano-jugular paraganglioma'),
  448. 'oto_cholesterol'=>_('Cholesterol granuloma')];
  449. $this->view->statuses = [];
  450. $this->requestOrigin = '';
  451. $this->view->dreamCode = '';
  452. $this->view->dreamData = [];
  453. $this->view->dreamCompleteData = '';
  454. $this->view->requestDreamPDF = []; //Information for Dream PDF
  455. $this->view->provinceList = [];
  456. $this->view->cgProvince = '';
  457. $this->view->cgCity = '';
  458. $this->view->dreamItalyEndPoint = $this->config['settings']['api']['endpoint'];
  459. $this->view->dreamItalyApiKey = $this->config['settings']['api']['key'];
  460. $this->view->sportelloCuraEndPoint = $this->config['settings']['sportellocura']['api']['key'];
  461. $this->view->sportelloCuraApiKey = $this->config['settings']['sportellocura']['api']['endpoint'];
  462. $this->view->survey = []; //Sportello Cura data
  463. $provinces = $this->db->orderBy('name', 'ASC')->get('italian_provinces');
  464. if (is_array($provinces) && !empty($provinces)) {
  465. foreach($provinces as $item) {
  466. $this->view->provinceList[$item['id']] = $item['name'];
  467. }
  468. }
  469. //PDF sending log
  470. $this->view->pdfLog = $this->db
  471. ->where('sl.request_id', $requestID)
  472. ->join('requests_messages_queue rmq', 'rmq.mail_id=sl.mail_code', 'LEFT')
  473. ->orderBy('sl.created_at', 'ASC')
  474. ->get('sportellocura_log sl', NULL, ['sl.created_at queued_date', 'rmq.request_id', 'rmq.mail_id', 'rmq.delay_at']);
  475. //Default values
  476. $userIsAuthor = false; //The logged user id the author of this Request
  477. $userIsModerator = false; //The logged user is a moderator of this Clinical Center
  478. $this->view->userIsAuthor = $userIsAuthor;
  479. $this->view->userIsModerator = $userIsModerator;
  480. $userIsReferrer = false; //The logged user is a referral of this Request
  481. $this->view->userIsReferrer = $userIsReferrer;
  482. $this->view->icd10Categories = $handleRequest->getICD10Categories($this->user->getUserLang());
  483. $this->view->wizards = [];
  484. $advancedFields = $this->db->where('id', $this->user->getUserId())->getOne('users', 'advanced_request');
  485. $this->view->advancedFields = isset($advancedFields['advanced_request']) && (int)$advancedFields['advanced_request'] == 1 ? true : false;
  486. //Viewer
  487. $this->view->isSimpleViewer = false;
  488. //$viewer = $this->db->where('id', $this->user->getUserId())->getOne('users', 'simple_viewer');
  489. $viewer = 0;
  490. if (isset($viewer['simple_viewer']) && (int)$viewer['simple_viewer'] == 1) {
  491. $this->view->isSimpleViewer = true;
  492. }
  493. //Select the user's language by default
  494. foreach($this->view->languages as $index => $language) {
  495. if ($language['lang_code'] == $this->user->getUserLang()) {
  496. $this->view->languages[$index]['selected'] = true;
  497. } else {
  498. $this->view->languages[$index]['selected'] = false;
  499. }
  500. }
  501. if ($this->user->is(APPLICANT_ROLE_ID)) {
  502. $this->view->userClinicalCenters = $this->getUserClinicalCenters($this->user->getUserId(), APPLICANT_ROLE_ID); //In mainController()
  503. } else if ($this->user->is(REFERRER_ROLE_ID)) {
  504. $this->view->userClinicalCenters = $this->getUserClinicalCenters($this->user->getUserId(), REFERRER_ROLE_ID);
  505. } else if ($this->user->is(MODERATOR_ROLE_ID)) {
  506. $this->view->userClinicalCenters = $this->getUserClinicalCenters($this->user->getUserId(), MODERATOR_ROLE_ID); //In mainController()
  507. }
  508. $this->view->requestId = $requestID;
  509. //$this->view->medicalSpecialties = $this->db->orderBy('description', 'asc')->get('users_medical_specialties');
  510. $this->view->ccReferral = $this->db
  511. ->where('ucct.role_id', REFERRER_ROLE_ID)
  512. ->join('clinical_centers cc', 'cc.id=ucct.center_id', 'INNER')
  513. ->groupBy('cc.id')
  514. ->orderBy('cc.description', 'asc')
  515. ->get('users_clinical_centers_to ucct', null, ['cc.id id', 'cc.description description']);
  516. $this->view->referralList = $this->db
  517. ->where('role_id', REFERRER_ROLE_ID)
  518. ->where('u.status', 1)
  519. ->join('users u', 'u.id=urt.user_id', 'INNER')
  520. ->orderBy('u.surname', 'asc')
  521. ->get('users_roles_to urt', null, [
  522. 'u.id user_id',
  523. 'u.name user_name',
  524. 'u.surname user_surname',
  525. "(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"
  526. ]);
  527. if ($this->view->viewType == 'view') {
  528. //Get all Medical Specialties (in the list for the comment form)
  529. $this->view->medicalSpecialties = $handleRequest->getSpecialtyByClinicalCenterId(0, $this->userGroupId);
  530. } else {
  531. //New Request: if there is just one Clinical Center, list its the Medical Specialties (else they are loaded by Ajax)
  532. if (count($this->view->userClinicalCenters) == 1) {
  533. $currentCenterId = array_values($this->view->userClinicalCenters)[0]['id'];
  534. $this->view->medicalSpecialties = $handleRequest->getSpecialtyByClinicalCenterId($currentCenterId, $this->userGroupId);
  535. }
  536. }
  537. if ($requestID == 0) {
  538. $this->actionTitle = _('Request : New');
  539. $this->view->requestUniqueCode = strtoupper(uniqid());
  540. $this->view->requestData = []; //Default: empty array
  541. $this->view->exams = $handleRequest->getExams();
  542. $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_NEW', ['userId'=>$this->user->getUserId()]);
  543. } else {
  544. $this->actionTitle = _('Request : Edit');
  545. if ($this->view->viewType == 'view') {
  546. $this->actionTitle = vsprintf(_('Request #%s'), [$requestID]);
  547. $this->actionTitlePDF = "#".$requestID;
  548. $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_VIEW', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestID]);
  549. }
  550. //TO DO: check whether the current user is authorized to access this request (i.e. changing the ID in the addess bar)
  551. //$this->view->testData = $handleRequest->forwardRequest($requestID);
  552. $requestData = $this->db
  553. ->where('r.id', $requestID)
  554. ->join('users u', 'u.id=r.user_id', 'INNER')
  555. ->join('requests_registry rr', 'rr.request_id=r.id', 'INNER')
  556. ->join('clinical_centers cc', 'cc.id=r.center_id', 'INNER')
  557. ->join('continents cnt', 'cnt.code=cc.continent_code', 'INNER')
  558. ->join('countries ctr', 'ctr.country_iso2_code=cc.country_code', 'INNER')
  559. ->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");
  560. //Sporello Cura
  561. $sportellocura = $this->db->where('request_id', $requestID)->getOne('sportellocura');
  562. if (isset($sportellocura['survey_id'])) {
  563. $survey_record = json_decode($sportellocura['survey_data'], true);
  564. if (isset($survey_record['json_answers'])) {
  565. $survey_record['data'] = json_decode($survey_record['json_answers'], true);
  566. }
  567. $this->view->survey = $survey_record;
  568. }
  569. $companies = $this->db->getOne('companies');
  570. if (!is_array($requestData)) {
  571. return $this->setJsonView('requestError');
  572. }
  573. //Check whether the moderator can access this request or can't
  574. if ($this->user->is(MODERATOR_ROLE_ID)) {
  575. if (!isset($this->view->userClinicalCenters[$requestData['center_id']])) {
  576. return $this->setJsonView('requestError');
  577. }
  578. }
  579. //Get Dream code
  580. $dreamResult = $this->db->where('request_id', $requestID)->getOne('requests_dream_data', 'dream_code, dream_hash');
  581. if (isset($dreamResult['dream_code']) && trim($dreamResult['dream_code']) != '') {
  582. $this->view->dreamCode = $dreamResult['dream_code'];
  583. $this->view->dreamData = htmlspecialchars($dreamResult['dream_hash']);
  584. }
  585. $userIsAuthor = $requestData['user_id'] == $this->user->getUserId() ? true : false;
  586. $this->view->userIsAuthor = $userIsAuthor;
  587. $this->view->hasMoreDetails = trim($requestData['cgnamesurname']) != '' || trim($requestData['cgrole']) != '' || trim($requestData['cgemail']) != '' || trim($requestData['cgphone']) != '';
  588. //Get Caregiver's Province and City
  589. if ((int)$requestData['cgprovince'] > 0) {
  590. $cg_province = $this->db->where('id', $requestData['cgprovince'])->getOne('italian_provinces');
  591. $this->view->cgProvince = isset($cg_province['name']) ? $cg_province['name'] : '';
  592. }
  593. if ((int)$requestData['cgcity'] > 0) {
  594. $cg_city = $this->db->where('id', $requestData['cgcity'])->getOne('italian_cities');
  595. $this->view->cgCity = isset($cg_city['name']) ? $cg_city['name'] : '';
  596. }
  597. $userIsModerator = $handleRequest->isUserModerator($requestData['center_id'], $this->getUserClinicalCenters($this->user->getUserId(), MODERATOR_ROLE_ID), $this->user->getUserId());
  598. $this->view->userIsModerator = $userIsModerator;
  599. $userIsReferrer = $handleRequest->isUserReferrer($requestID, $this->user->getUserId());
  600. $this->view->userIsReferrer = $userIsReferrer;
  601. //Get the Medical Specialties for the saved Clinical Center
  602. $currentCenterId = $requestData['center_id'];
  603. $this->view->medicalSpecialties = $handleRequest->getSpecialtyByClinicalCenterId($currentCenterId, $this->userGroupId);
  604. $ccInfo = $this->db->where('id', $currentCenterId)->getOne('clinical_centers');
  605. $isCcAnonymous = isset($ccInfo['anonymize']) && (int)$ccInfo['anonymize'] == 1 ? true : false;
  606. if ($isCcAnonymous) {
  607. $requestData['request_anonymous'] = 1;
  608. }
  609. //Overwrite the previouse value
  610. if ($userIsAuthor) {
  611. $isCcAnonymous = false;
  612. }
  613. $this->view->requestData = $requestData;
  614. $this->view->companies = $companies;
  615. //TOOD: check whether current user can access this request
  616. //O. Is the right group?
  617. //1. Is the Author?
  618. //2. Is a Moderator in this Clinical Center?
  619. //3. Is a Referral of this Request?
  620. //4. Is an Admininstrator?
  621. $this->view->requestUniqueCode = $requestData['unique_code'];
  622. //$this->actionTitle .= ' ('.ucfirst($requestData['request_origin']).')';
  623. $this->requestOrigin = $requestData['request_origin'];
  624. //Symptons (old ICD10)
  625. $this->view->symptoms = $this->db
  626. ->where('rst.request_id', $requestID)
  627. ->where('rsl.language_code', $this->user->getUserLang())
  628. ->join('requests_symptoms_labels rsl', 'rsl.symptom_id=rst.symptom_id', 'INNER')
  629. ->orderBy('rsl.symptom_label', 'asc')
  630. ->get('requests_symptoms_to rst', null, ['rsl.symptom_label']);
  631. //ICD10 (new)
  632. $this->view->ICD10 = $this->db
  633. ->where('rst.request_id', $requestID)
  634. ->where('idl.lang_code', $this->user->getUserLang())
  635. ->join('icd10_desease_labels idl', 'idl.desease_id=rst.symptom_id', 'INNER')
  636. ->orderBy('idl.description', 'asc')
  637. ->get('requests_symptoms_to rst', null, ['idl.description symptom_label']);
  638. //Overwrite the symptoms with the new ICD10
  639. if (!empty($this->view->ICD10)) {
  640. $this->view->symptoms = $this->view->ICD10;
  641. }
  642. //Clinical Centers
  643. foreach($this->view->userClinicalCenters as $centerId => $centerItem) {
  644. if ($centerItem['id'] == $requestData['center_id']) {
  645. $this->view->userClinicalCenters[$centerId]['selected'] = true;
  646. } else {
  647. $this->view->userClinicalCenters[$centerId]['selected'] = false;
  648. }
  649. }
  650. if (is_array($this->view->referralList)) {
  651. $requestRecipients = $this->db
  652. ->where('request_id', $requestID)
  653. ->get('requests_recipients');
  654. $this->view->recipients = $requestRecipients;
  655. if (is_array($requestRecipients)) {
  656. foreach($this->view->referralList as $index => $referral) {
  657. $this->view->referralList[$index]['selected'] = false;
  658. foreach($requestRecipients as $recipient) {
  659. if ($referral['user_id'] == $recipient['user_id']) {
  660. $this->view->referralList[$index]['selected'] = true;
  661. }
  662. }
  663. }
  664. }
  665. }
  666. $requestMedSpec = $this->db
  667. ->where('request_id', $requestID)
  668. ->get('requests_medical_specialties_to');
  669. //Medical specialties of the request
  670. $idList = [];
  671. $requestMedicalSpecialties = $this->db
  672. ->where('rmst.request_id', $requestID)
  673. ->join('users_medical_specialties ums', 'ums.id=rmst.specialty_id', 'INNER')
  674. ->get('requests_medical_specialties_to rmst', null, ['ums.id', 'ums.description']);
  675. if (is_array($requestMedicalSpecialties)) {
  676. foreach($requestMedicalSpecialties as $item) {
  677. $this->view->requestMedicalSpecialties[$item['id']]['id'] = $item['id'];
  678. $this->view->requestMedicalSpecialties[$item['id']]['description'] = _($item['description']);
  679. $idList[] = $item['id'];
  680. }
  681. $this->view->requestMedicalSpecialtiesIdList = $idList;
  682. }
  683. //All possible Medical specialties
  684. foreach($this->view->medicalSpecialties as $index => $medSpecList) {
  685. $this->view->medicalSpecialties[$index]['selected'] = false;
  686. foreach($requestMedSpec as $reqMedSpecItem) {
  687. if ($reqMedSpecItem['specialty_id'] == $medSpecList['id']) {
  688. $this->view->medicalSpecialties[$index]['selected'] = true;
  689. }
  690. }
  691. //Request forward: list with mmedical specialties without the request medical specialties
  692. if (!isset($this->view->requestMedicalSpecialties[$medSpecList['id']])) {
  693. $this->view->forwardMedicalSpecialties[$medSpecList['id']]['id'] = $medSpecList['id'];
  694. $this->view->forwardMedicalSpecialties[$medSpecList['id']]['description'] = $medSpecList['description'];
  695. }
  696. }
  697. $requestLangs = $this->db
  698. ->where('request_id', $requestID)
  699. ->get('requests_languages_to');
  700. //If there are saved languages change the default value
  701. if (is_array($requestLangs) && !empty($requestLangs)) {
  702. foreach($this->view->languages as $index => $language) {
  703. $this->view->languages[$index]['selected'] = false;
  704. foreach($requestLangs as $reqLangItem) {
  705. if ($reqLangItem['language_code'] == $language['lang_code']) {
  706. $this->view->languages[$index]['selected'] = true;
  707. }
  708. }
  709. }
  710. }
  711. $requestCenters = $this->db
  712. ->where('request_id', $requestID)
  713. ->get('request_clinical_centers_to');
  714. foreach($this->view->ccReferral as $centerId => $referralCenter) {
  715. $this->view->ccReferral[$centerId]['selected'] = false;
  716. foreach($requestCenters as $centerItem) {
  717. if ($centerItem['center_id'] == $referralCenter['id']) {
  718. $this->view->ccReferral[$centerId]['selected'] = true;
  719. }
  720. }
  721. }
  722. $this->view->statuses = $this->db
  723. ->where('rs.code', '! referted', '<>')
  724. ->where('rs.code', 'draft', '<>')
  725. ->where('rs.code', 'pending', '<>')
  726. ->where('rs.code', 'opened', '<>')
  727. ->orderBy('rs.default_label', 'asc')
  728. ->get('requests_statuses rs');
  729. $this->view->attachments = $handleRequest->getAttachmentsByRequestId($requestID);
  730. //Group attachments by date
  731. $this->view->groupedAttachments = [];
  732. if (is_array($this->view->attachments) && !empty($this->view->attachments)) {
  733. foreach($this->view->attachments as $attachment) {
  734. //$ext = $this->helper->getExtension($attachment['file_name']);
  735. $attachment['previewType'] = $this->helper->getPreviewType($attachment['file_name']);
  736. $this->view->groupedAttachments[date('Y-m-d 00:00:00', strtotime($attachment['created_at']))][] = $attachment;
  737. }
  738. if (!empty($this->view->groupedAttachments)) {
  739. foreach($this->view->groupedAttachments as $ext => $attachList) {
  740. sort($attachList);
  741. $this->view->groupedAttachments[$ext] = $attachList;
  742. }
  743. }
  744. }
  745. //ICD-10
  746. $this->view->icd10 = $handleRequest->getECD10ListByRequestId($requestID, $this->user->getUserLang());
  747. //Wizards
  748. $this->view->wizardTitles = ['cardio'=>_('Wizard Cardio'), 'derma'=>_('Wizard Derma'), 'generic'=>_('Wizard Physical Examination'), 'oto'=>_('Wizard Ear')];
  749. $this->view->wizards = $handleRequest->getWizardsByRequestId($requestID);
  750. //Wizard Derma positions
  751. $this->view->dermaPositions = $handleRequest->getWizardsDermaPositions($requestID);
  752. //Wizard Ear images
  753. $this->view->otoImages = $handleRequest->getWizardsEarDeseases($requestID);;
  754. //Get all exams for the dialogs
  755. $this->view->exams = $handleRequest->getExams($this->view->wizards);
  756. }
  757. $pathParentUri = $this->view->parentBaseUri.'/'.$this->view->orderField.'/'.$this->view->orderDir.'/'.$this->view->currentPage;
  758. if ($this->view->parentBaseUri != 'hashtag') {
  759. $this->breadcrumbs = [['hash'=>$pathParentUri, 'label'=>$this->view->parentActionTitle], ['hash'=>null, 'label'=>$this->actionTitle]];
  760. } else {
  761. $this->breadcrumbs = [['hash'=>null, 'label'=>$this->actionTitle]];
  762. }
  763. if ($this->view->viewType == 'view') {
  764. if($this->checkPermissions([APPLICANT_ROLE_ID])) {
  765. //If not the author: $permissionDenied = true;
  766. }
  767. if($this->checkPermissions([MODERATOR_ROLE_ID])) {
  768. //If not moderator in this cc: $permissionDenied = true;
  769. }
  770. $this->view->comments = $handleRequest->getCommentList($requestID, $this->view->requestData['center_id'], true);
  771. //Add the information for the Dream PDF
  772. $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']]));
  773. $pdfComments = $this->view->comments;
  774. foreach($pdfComments as $index => $item) {
  775. $pdfComments[$index]['created_at_string'] = $this->helper->getDateString($pdfComments[$index]['created_at']);
  776. }
  777. $dreamResults = $this->db->where('request_id', $requestID)->getOne('requests_dream_data', 'dream_evt_id, dream_hash');
  778. $registryData = null;
  779. $registryEvtId = null;
  780. if (isset($dreamResults['dream_hash'])) {
  781. $registryData = json_decode($dreamResults['dream_hash'], true);
  782. $registryEvtId = $dreamResults['dream_evt_id'];
  783. }
  784. $hasDreamIntegration = false;
  785. if (isset($registryData['Anagrafica']) && !empty($registryData['Anagrafica'])) {
  786. $this->view->requestDreamPDF = [
  787. 'registry'=>$registryData['Anagrafica'],
  788. 'evtId'=>$registryEvtId,
  789. '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']],
  790. 'icd10'=>$this->view->icd10,
  791. 'wizards'=>$this->view->wizards,
  792. 'dermaPositions'=>$this->view->dermaPositions,
  793. 'maxBloodPressure'=>$this->view->requestData['max_arterial_pressure'],
  794. 'minBloodPressure'=>$this->view->requestData['min_arterial_pressure'],
  795. 'heartRate'=>$this->view->requestData['heart_rate'],
  796. 'saturation'=>$this->view->requestData['saturation'],
  797. 'clinicalRemarks'=>$this->view->requestData['clinical_remarks'],
  798. 'medicalHistory'=>$this->view->requestData['medical_history'],
  799. //'exams'=>$this->view->exams,
  800. 'comments'=>$pdfComments
  801. ];
  802. $hasDreamIntegration = true;
  803. }
  804. return $this->setJsonView('requestView', false, '', ['requestDreamPDF'=>$this->view->requestDreamPDF, 'userIsAuthor'=>$userIsAuthor, 'hasDreamIntegration'=>$hasDreamIntegration]);
  805. } else {
  806. return $this->setJsonView('requestEdit');
  807. }
  808. }
  809. //Save/Edit requests
  810. public function requestSave() {
  811. if (!$this->user->isLogged()) {
  812. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  813. }
  814. if(!$this->checkPermissions([ADMIN_ROLE_ID, APPLICANT_ROLE_ID])) {
  815. return $this->setRawJsonResponse('err', _('Permission denied.'));
  816. }
  817. $data = isset($_POST['data']) ? $_POST['data'] : null;
  818. $this->view->data = $data;
  819. //$operation = $data['operation']['value'] == 'draft' ? 'draft' : 'pending';
  820. $operation = $data['operation']['value'];
  821. if (trim($operation) == '') $operation = 'pending';
  822. $hasFiles = (bool)$data['has_files']['value'];
  823. $fileCounter = (int)$data['files_counter']['value'];
  824. $handleRequest = new HandleRequest();
  825. $requestId = $data['request_id']['value'];
  826. $requestUniqueCode = $data['request_unique_code']['value'];
  827. $clinicalCenter = $data['request_cc']['value'];
  828. $dreamCode = isset($data['dream_code']['value']) ? $data['dream_code']['value'] : '';
  829. $patientName = trim($data['request_name']['value']);
  830. $patientSurname = trim($data['request_surname']['value']);
  831. $patientGender = $data['request_gender']['value'];
  832. $ageType = isset($data['request_birth_type']['value']) ? $data['request_birth_type']['value'] : null;
  833. $ageYear = $data['request_birth_year']['value'];
  834. $ageMonth = $data['request_birth_month']['value'];
  835. $ageMonthDay = $data['request_birth_month_day']['value'];
  836. $ageAgeInNumber = $data['request_age']['value'];
  837. $ageUnitOfTime = $data['request_unit_of_time']['value'];
  838. $triage = isset($data['triage']['value']) ? $data['triage']['value'] : null;
  839. $bpMin = (int)$data['request_bp_min']['value'];
  840. $bpMax = (int)$data['request_bp_max']['value'];
  841. $heartRate = (int)$data['request_heart_rate']['value'];
  842. $oxygenSaturation = (int)$data['request_oxy_sat']['value'];
  843. $medicalRemarks = strip_tags(trim($data['request_medremarks']['value']));
  844. $medicalHistory = strip_tags(trim($data['request_medicalhistory']['value']));
  845. $mainQuestion = strip_tags(trim($data['request_mainquestion']['value']));
  846. $visibility = $data['referral_visibility']['value'];
  847. $privacy = $data['privacy']['value'];
  848. $anonymous = $data['request_anonymisation']['value'];
  849. $dreamCode = trim($data['dream_code']['value']);
  850. $dreamData = $data['dream_data']['value'];
  851. $dreamEvtId = $data['dream_evt_id']['value'];
  852. $icd10List = isset($data['icd10_desease']['value']) ? $data['icd10_desease']['value'] : null;
  853. //Exams
  854. $supportedWizards = ['generic', 'derma', 'cardio', 'oto'];
  855. foreach ($supportedWizards as $wizard) {
  856. $this->view->wizard[$wizard] = isset($data['exam_'.$wizard]['value']) ? $data['exam_'.$wizard]['value'] : [];
  857. }
  858. //Derma positions
  859. $dermaPositions = isset($data['derma_position']['value']) ? $data['derma_position']['value'] : [];
  860. //Ear images
  861. $earImages = isset($data['ear_desease']['value']) ? $data['ear_desease']['value'] : [];
  862. //return $this->setRawJsonResponse('err', _("Test: ".json_encode($dermaPositions)));
  863. //Medical specialty (the only required filter)
  864. $medicalSpecialties = $data['referral_ms']['value'];
  865. //If no language is selected, assign the user's default language
  866. $referralLangs = is_array($data['referral_langs']['value']) && !empty($data['referral_langs']['value']) ? $data['referral_langs']['value'] : [$this->user->getUserLang()];
  867. //Referrals' Clinical Center (could be not set)
  868. $referralCc = isset($data['referral_cc']['value']) ? $data['referral_cc']['value'] : null;
  869. //Specific referral list (could be not set)
  870. $referralList = isset($data['request_referral_list']['value']) ? $data['request_referral_list']['value'] : null;
  871. //These numbers are used to sort the statuses and the triage colors
  872. //$status_numbers = ['pending'=>-1, 'draft'=>0, 'opened'=>1, '! referted'=>4, 'reopened'=>3, 'referted'=>2];
  873. $status_numbers = $handleRequest->statusNumbers;
  874. //UPDATE requests SET request_status_number = 2 WHERE request_status LIKE '! referted';
  875. //UPDATE requests SET request_status_number = 4 WHERE request_status LIKE 'referted';
  876. $triage_numbers = ['white'=>0, 'green'=>1, 'yellow'=>2, 'red'=>3];
  877. $referralVisibility = $data['referral_visibility']['value'];
  878. $dateOfBirth = '0000-00-00 00:00:00';
  879. //Dynamic checkboxes in Preview modal window
  880. $recipientsIds = isset($data['recipients_ids']['value']) ? $data['recipients_ids']['value'] : [];
  881. //Request Clinical Center
  882. if ($clinicalCenter == '') {
  883. return $this->setRawJsonResponse('err', _('Please provide the Clinical Center.'));
  884. }
  885. if ($patientName == '') {
  886. return $this->setRawJsonResponse('err', _("Please provide the Patient's Name."));
  887. }
  888. if ($patientSurname == '') {
  889. return $this->setRawJsonResponse('err', _("Please provide the Patient's Surname."));
  890. }
  891. if ($patientGender == '') {
  892. return $this->setRawJsonResponse('err', _("Please provide the Patient's Sex."));
  893. }
  894. if (is_null($ageType)) {
  895. return $this->setRawJsonResponse('err', _("Please provide the Patient's date of birth or the age in years or months."));
  896. }
  897. if ($ageType == 'date') {
  898. $dateOfBirth = "$ageYear-$ageMonth-$ageMonthDay 00:00:00";
  899. if (!$this->utility->isValidDate($dateOfBirth, 'Y-n-j H:i:s')) {
  900. return $this->setRawJsonResponse('err', _("The date of birth provided is not valid."));
  901. }
  902. }
  903. if ($ageType == 'number') {
  904. if ((int)$ageAgeInNumber > 0) {
  905. if ($ageUnitOfTime == 'y' && $ageAgeInNumber < 2) {
  906. return $this->setRawJsonResponse('err', _("Please provide the Patient's age in months."));
  907. }
  908. if ($ageUnitOfTime == 'y') {
  909. $diffYears = (int)date('Y')-$ageAgeInNumber;
  910. $dateOfBirth = "$diffYears-01-01 00:00:00";
  911. }
  912. if ($ageUnitOfTime == 'm') {
  913. $dateOfBirth = date('Y-m-01 00:00:00', strtotime("-$ageAgeInNumber months"));
  914. }
  915. } else {
  916. return $this->setRawJsonResponse('err', _("Patient's age must be a number."));
  917. }
  918. }
  919. //Check date of birth is in the future
  920. $checkBirthDate = new DateTime($dateOfBirth);
  921. $checkDateNow = new DateTime();
  922. if ($checkBirthDate > $checkDateNow) {
  923. return $this->setRawJsonResponse('err', _("The date of birth cannot be in the future."));
  924. }
  925. if ($bpMin > 0 && $bpMax > 0) {
  926. if ($bpMin > $bpMax) {
  927. return $this->setRawJsonResponse('err', _("Minimum Blood Pressure cannot be higher than the Maximum one."));
  928. }
  929. }
  930. if ($bpMax > 250) {
  931. return $this->setRawJsonResponse('err', _("Maximum Blood Pressure is too high."));
  932. }
  933. if ($bpMin > 250) {
  934. return $this->setRawJsonResponse('err', _("Minimum Blood Pressure is too high."));
  935. }
  936. if ($heartRate > 250) {
  937. return $this->setRawJsonResponse('err', _("Heart Rate cannot be higher then 250 bpm."));
  938. }
  939. if ($oxygenSaturation > 100) {
  940. return $this->setRawJsonResponse('err', _("Oxygen Saturation cannot be higher than 100%."));
  941. }
  942. if ($medicalRemarks == '') {
  943. return $this->setRawJsonResponse('err', _("Please provide the Medical Remarks."));
  944. }
  945. if ($mainQuestion == '') {
  946. return $this->setRawJsonResponse('err', _("Please provide the Main Question."));
  947. }
  948. if (!is_array($referralList)) {
  949. if (!is_array($medicalSpecialties)) {
  950. return $this->setRawJsonResponse('err', _('Please provide at least one Medical Specialty for this request.'));
  951. }
  952. }
  953. //Check whether is provided a referral list or isn't
  954. $specificReferralData = [];
  955. if (is_array($referralList)) {
  956. //Get Medical Specialties and Referral Languages
  957. $referralIds = implode(',', $referralList);
  958. $medicalSpecialties = [];
  959. $referralLangs = [];
  960. $specificReferralData = $this->db
  961. ->where("u.id IN($referralIds)")
  962. ->where('u.group_id', $this->userGroupId)
  963. ->join('users_medical_specialties_to umst', 'umst.user_id=u.id', 'INNER')
  964. ->groupBy('umst.specialty_id')
  965. ->get('users u', null, ['umst.specialty_id referral_md', 'u.language_default referral_lang']);
  966. if (is_array($specificReferralData) && !empty($specificReferralData)) {
  967. foreach($specificReferralData as $item) {
  968. $medicalSpecialties[$item['referral_md']] = $item['referral_md'];
  969. $referralLangs[$item['referral_lang']] = $item['referral_lang'];
  970. }
  971. }
  972. }
  973. if ((int)$privacy == 0) {
  974. return $this->setRawJsonResponse('err', _('Please provide the Privacy Policy consent.'));
  975. }
  976. $cgnamesurname = $data['cgnamesurname']['value'];
  977. $cgrole = $data['cgrole']['value'];
  978. $cgphone = $data['cgphone']['value'];
  979. $cgemail = $data['cgemail']['value'];
  980. $cgmmgnamesurname = $data['cgmmgnamesurname']['value'];
  981. $cgmmgphone = $data['cgmmgphone']['value'];
  982. $cgmmgemail = $data['cgmmgemail']['value'];
  983. $cgprovince = $data['cgprovince']['value'];
  984. $cgcity = isset($data['cgcity']['value']) ? $data['cgcity']['value'] : 0;
  985. $dbData = [
  986. 'group_id' => $this->userGroupId, //mainController
  987. 'center_id' => $clinicalCenter,
  988. 'user_id' => $this->user->getUserId(),
  989. 'unique_code' => $requestUniqueCode,
  990. 'request_question' => $mainQuestion,
  991. 'request_status' => $operation,
  992. 'request_visibility' => (int)$visibility == 1 ? 'all' : 'private',
  993. 'request_origin' => 'web',
  994. 'request_status_number' => isset($status_numbers[$operation]) ? $status_numbers[$operation] : 0, //Default Draft
  995. 'request_guid' => $this->security->getGUID(),
  996. 'triage_color' => $triage,
  997. 'triage_number' => isset($triage_numbers[$triage]) ? $triage_numbers[$triage] : 0,
  998. 'cgnamesurname' => $cgnamesurname,
  999. 'cgrole' => $cgrole,
  1000. 'cgphone' => $cgphone,
  1001. 'cgemail' => $cgemail,
  1002. 'cgmmgnamesurname' => $cgmmgnamesurname,
  1003. 'cgmmgphone' => $cgmmgphone,
  1004. 'cgmmgemail' => $cgmmgemail,
  1005. 'cgprovince' => $cgprovince,
  1006. 'cgcity' => $cgcity,
  1007. 'patient_privacy' => $privacy,
  1008. 'send_status' => 'central',
  1009. 'request_anonymous' => $anonymous,
  1010. 'updated_at' => date('Y-m-d H:i:s'),
  1011. 'created_at' => date('Y-m-d H:i:s')
  1012. ];
  1013. //First check for recipients
  1014. if (empty($recipientsIds)) {
  1015. /*$recipients = $handleRequest->getRecipients([
  1016. 'recipientList' => [],
  1017. 'ms' => $medicalSpecialties,
  1018. 'cc' => $referralCc,
  1019. 'langs' => $referralLangs,
  1020. 'groupId' => $this->userGroupId
  1021. ]);*/
  1022. $recipients = $handleRequest->getRecipients([
  1023. 'recipientList' => [],
  1024. 'ms' => $medicalSpecialties,
  1025. 'cc' => [$clinicalCenter],
  1026. 'langs' => $referralLangs,
  1027. 'groupId' => $this->userGroupId
  1028. ]);
  1029. if (is_array($recipients) && !empty($recipients)) {
  1030. foreach($recipients as $recipient) {
  1031. $recipientsIds[] = $recipient['user_id'];
  1032. }
  1033. }
  1034. }
  1035. if ($requestId == 0) { //Add
  1036. //Add the request record if there are recipients
  1037. if (is_array($recipientsIds) && !empty($recipientsIds)) {
  1038. //$dbData['created_at'] = date('Y-m-d H:i:s');
  1039. $lastInsert = $this->db->insert('requests', $dbData);
  1040. $requestId = $lastInsert;
  1041. } else {
  1042. return $this->setRawJsonResponse('err', _('Unable to save the Request: the Recipient List is empty.'), ['log'=>[]]);
  1043. }
  1044. } else { //Update
  1045. $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_SAVED_DRAFT', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestId]);
  1046. $this->db->where('id', $requestId)->update('requests', $dbData);
  1047. }
  1048. if ($requestId > 0) {
  1049. //Sportello cura
  1050. $sportellocura_code = (int)$data['sportellocura_code']['value'];
  1051. $sportellocura_json_data = trim($data['sportellocura']['value']);
  1052. if ($sportellocura_code > 0 && $sportellocura_json_data != '') {
  1053. //Check wheather already added
  1054. //$check = $this->db->where('survey_id', $sportellocura_code)->getOne('sportellocura', 'survey_id');
  1055. //if (!isset($check['survey_id'])) {
  1056. $this->db->replace('sportellocura', [
  1057. 'survey_id'=>$sportellocura_code,
  1058. 'request_id'=>$requestId,
  1059. 'survey_data'=>$sportellocura_json_data,
  1060. 'created_at'=>date('Y-m-d H:i:s')
  1061. ]);
  1062. $endpoint = $this->config['settings']['sportellocura']['api']['endpoint'];
  1063. $apikey = $this->config['settings']['sportellocura']['api']['key'];
  1064. $vars = ['survey_id'=>$sportellocura_code, 'cmd'=>'set-added'];
  1065. $ch = curl_init();
  1066. curl_setopt($ch, CURLOPT_URL, $endpoint);
  1067. curl_setopt($ch, CURLOPT_POST, 1);
  1068. curl_setopt($ch, CURLOPT_POSTFIELDS, $vars); //Post Fields
  1069. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  1070. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
  1071. curl_setopt($ch, CURLOPT_TIMEOUT, 10); //timeout in seconds
  1072. $headers = [
  1073. 'Api-Key: '.$apikey,
  1074. ];
  1075. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  1076. $curldata = curl_exec($ch);
  1077. curl_close($ch);
  1078. //}
  1079. }
  1080. //DREAM Italy and Sportello Cura files
  1081. if (isset($data['cg']) && is_array($data['cg'])) {
  1082. foreach($data['cg'] as $cg_index => $cg_data) {
  1083. $cg_filename = $cg_data['filename'];
  1084. $cg_filesystem_name = md5(uniqid());
  1085. $cg_filedata_base64 = $cg_data['filedata'];
  1086. $cg_file_data = base64_decode($cg_filedata_base64);
  1087. $cg_file_path = ATTACH_DIR.$cg_filesystem_name;
  1088. file_put_contents($cg_file_path, $cg_file_data);
  1089. if (file_exists($cg_file_path)) {
  1090. $cg_file_size = filesize($cg_file_path);
  1091. $cg_filetype = mime_content_type($cg_file_path);
  1092. $cg_file_ext = $this->utility->mime2ext($cg_filetype);
  1093. if ($cg_file_ext !== false) {
  1094. $cg_filesystem_name = $cg_filesystem_name.'.'.$cg_file_ext;
  1095. rename($cg_file_path, ATTACH_DIR.$cg_filesystem_name);
  1096. $cg_filename = str_ireplace('.'.$cg_file_ext, '', $cg_filename);
  1097. $cg_filename = $cg_filename.'.'.$cg_file_ext;
  1098. $cg_file_title = $this->utility->slugify($cg_filename);
  1099. $this->db->insert('requests_attachments', [
  1100. 'request_id'=>$requestId,
  1101. 'user_id'=>$this->user->getUserId(),
  1102. 'file_name'=>$cg_filesystem_name,
  1103. 'file_title'=>$cg_file_title,
  1104. 'file_ext'=>$cg_file_ext,
  1105. 'file_size'=>$cg_file_size,
  1106. 'file_mime'=>$cg_filetype,
  1107. 'type'=>'others',
  1108. 'created_at'=>date('Y-m-d H:i:s')
  1109. ]);
  1110. }
  1111. }
  1112. }
  1113. } else {
  1114. file_put_contents(ATTACH_DIR.'nodata.log', '');
  1115. }
  1116. //Update the Patient's Registry
  1117. $registryData = [
  1118. 'request_id' => $requestId,
  1119. 'center_id' => $clinicalCenter,
  1120. 'name' => $patientName,
  1121. 'surname' => $patientSurname,
  1122. 'birthdate' => $dateOfBirth,
  1123. 'gender' => $patientGender,
  1124. 'min_arterial_pressure' => $bpMin,
  1125. 'max_arterial_pressure' => $bpMax,
  1126. 'heart_rate' => $heartRate,
  1127. 'saturation' => $oxygenSaturation,
  1128. 'clinical_remarks' => $medicalRemarks,
  1129. 'medical_history' => $medicalHistory,
  1130. 'updated_at' => date('Y-m-d H:i:s'),
  1131. 'created_at' => date('Y-m-d H:i:s')
  1132. ];
  1133. $this->db->replace('requests_registry', $registryData);
  1134. //Check Specific Referrals
  1135. $this->db->where('request_id', $requestId)->delete('requests_recipients');
  1136. if (is_array($referralList)) {
  1137. foreach($referralList as $referralId) {
  1138. $this->db->insert('requests_recipients', [
  1139. 'request_id' => $requestId,
  1140. 'user_id' => $referralId
  1141. ]);
  1142. }
  1143. }
  1144. //Add/Update the Medical Specialties
  1145. $this->db->where('request_id', $requestId)->delete('requests_medical_specialties_to');
  1146. foreach($medicalSpecialties as $specialtyId) {
  1147. $this->db->insert('requests_medical_specialties_to', [
  1148. 'request_id' => $requestId,
  1149. 'specialty_id' => $specialtyId
  1150. ]);
  1151. }
  1152. //Add/Update Clinical Centers
  1153. $this->db->where('request_id', $requestId)->delete('request_clinical_centers_to');
  1154. if (is_array($referralCc) && !empty($referralCc)) {
  1155. foreach($referralCc as $ccId) {
  1156. $this->db->insert('request_clinical_centers_to', [
  1157. 'request_id' => $requestId,
  1158. 'center_id' => $ccId
  1159. ]);
  1160. }
  1161. }
  1162. //Add/Update recipients' languages
  1163. $this->db->where('request_id', $requestId)->delete('requests_languages_to');
  1164. foreach($referralLangs as $language) {
  1165. $this->db->insert('requests_languages_to', [
  1166. 'request_id' => $requestId,
  1167. 'language_code' => $language
  1168. ]);
  1169. }
  1170. //ICD-10
  1171. $this->db->where('request_id', $requestId)->delete('requests_symptoms_to');
  1172. if (is_array($icd10List) && !empty($icd10List)) {
  1173. foreach($icd10List as $symptomId) {
  1174. $this->db->insert('requests_symptoms_to', [
  1175. 'request_id' => $requestId,
  1176. 'symptom_id' => $symptomId
  1177. ]);
  1178. }
  1179. }
  1180. //Wizards
  1181. $this->db->where('request_id', $requestId)->delete('requests_wizards_to');
  1182. if (is_array($this->view->wizard)) {
  1183. foreach($this->view->wizard as $wizardType => $wizardIds) {
  1184. if (is_array($wizardIds) && !empty($wizardIds)) {
  1185. foreach($wizardIds as $examId) {
  1186. $this->db->insert('requests_wizards_to', [
  1187. 'request_id' => $requestId,
  1188. 'exam_id' => $examId,
  1189. 'exam_type' => $wizardType
  1190. ]);
  1191. }
  1192. }
  1193. }
  1194. }
  1195. //Wizard Derma positions
  1196. $this->db->where('request_id', $requestId)->delete('requests_wizard_derma_position_to');
  1197. if (is_array($dermaPositions) && !empty($dermaPositions)) {
  1198. foreach($dermaPositions as $positionType) {
  1199. $this->db->insert('requests_wizard_derma_position_to', [
  1200. 'request_id' => $requestId,
  1201. 'position_type' => $positionType
  1202. ]);
  1203. }
  1204. }
  1205. //Wizard Ear images
  1206. $this->db->where('request_id', $requestId)->delete('requests_wizard_ear_deseases_to');
  1207. if (is_array($earImages) && !empty($earImages)) {
  1208. foreach($earImages as $earImagesType) {
  1209. $this->db->insert('requests_wizard_ear_deseases_to', [
  1210. 'request_id' => $requestId,
  1211. 'desease_type' => $earImagesType
  1212. ]);
  1213. }
  1214. }
  1215. //Dream
  1216. if ($dreamCode != '') {
  1217. $this->db->replace('requests_dream_data', [
  1218. 'request_id' => $requestId,
  1219. 'dream_code' => trim(strtoupper($dreamCode)),
  1220. 'dream_evt_id' => $dreamEvtId,
  1221. 'dream_hash' => $dreamData,
  1222. 'created_at' => date('Y-m-d H:i:s')
  1223. ]);
  1224. }
  1225. }
  1226. $this->view->dbData = $dbData; //Debug
  1227. //return $this->setJsonView('requestSave');
  1228. //$debug = $handleRequest->checkPartialUploads();
  1229. if ($operation == 'draft') {
  1230. return $this->setRawJsonResponse('ok', _('Request information successfully saved as draft.'), ['log'=>$dermaPositions], ['button'=>'refresh-hash', 'recordId'=>$requestId, 'idPosition'=>3]);
  1231. } else {
  1232. //Update the recipient list for this request and change the status to pending|opened
  1233. if (is_array($recipientsIds) && !empty($recipientsIds)) {
  1234. $this->db->where('request_id', $requestId)->delete('requests_recipients');
  1235. foreach($recipientsIds as $recipientId) {
  1236. $this->db->insert('requests_recipients', [
  1237. 'request_id' => $requestId,
  1238. 'user_id' => $recipientId
  1239. ]);
  1240. }
  1241. if ($operation != 'referted') {
  1242. $requestStatus = $hasFiles ? $handleRequest::REQUEST_STATUS_PENDING : $handleRequest::REQUEST_STATUS_OPENED;
  1243. $handleRequest->setRequestStatus($requestId, $requestStatus, $this->user->getUserId());
  1244. }
  1245. $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_SENT', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestId]);
  1246. //return $this->setRawJsonResponse('ok', _('Test'), ['log'=>$requestStatus]);
  1247. return $this->setRawJsonResponse('ok', _('Request information successfully opened.'), ['log'=>[]], ['button'=>'goto', 'destination'=>'requests/'.time().'/my/created_at/desc/1']);
  1248. }
  1249. }
  1250. }
  1251. public function getDreamInformation() {
  1252. if (!$this->user->isLogged()) {
  1253. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1254. }
  1255. $requestId = $this->getPost('requestId', 0);
  1256. $dreamResult = $this->db->where('request_id', $requestId)->getOne('requests_dream_data', 'dream_code, dream_hash');
  1257. $html = _('No DREAM information available.');
  1258. if (isset($dreamResult['dream_code'])) {
  1259. $dreamData = json_decode($dreamResult['dream_hash'], true);
  1260. $registry = [];
  1261. $exams = [];
  1262. $examStats = [];
  1263. $daily = [];
  1264. $symptoms = [];
  1265. $diagnosis = [];
  1266. $HivStages = [];
  1267. $HivTestHistory = [];
  1268. $TarvHistory = [];
  1269. $ListaFarmaci = [];
  1270. /*$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'];*/
  1271. $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'];
  1272. if (isset($dreamData['Anagrafica'])) {
  1273. $registry = $dreamData['Anagrafica'];
  1274. $registry['age'] = $this->utility->getAge($registry['dataNascita']);
  1275. }
  1276. if (isset($dreamData['Esami'])) {
  1277. //$exams = $this->utility->orderArray($dreamData['Esami'], 'Data', 'desc');
  1278. $exams = $dreamData['Esami'];
  1279. $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'];
  1280. if (is_array($exams)) {
  1281. foreach($exams as $index => $exam) {
  1282. foreach ($exam as $key => $value) {
  1283. if ($key == 'CViral') {
  1284. $code = (int)$value;
  1285. //Default
  1286. //$exams[$index][$key] = 'ND';
  1287. if (isset($filter[$code])) {
  1288. $exams[$index][$key] = $filter[$code];
  1289. }
  1290. }
  1291. }
  1292. }
  1293. }
  1294. }
  1295. /*if (isset($dreamData['Diaria'])) {
  1296. //$daily = $this->utility->orderArray($dreamData['Diaria'], 'Data', 'desc');
  1297. $daily = $dreamData['Diaria'];
  1298. $years = [];
  1299. $yearList = [];
  1300. $examList = [];
  1301. $chartYears = [];
  1302. $dataValues = [];
  1303. if (is_array($daily)) {
  1304. foreach($daily as $exam) {
  1305. if (strlen($exam['Data']) > 4) {
  1306. $y = substr($exam['Data'], 0, 4);
  1307. $years[$y] = $y;
  1308. }
  1309. }
  1310. if (count($years) > 1) rsort($years);
  1311. if (count($years) > 3) {
  1312. $yearList = array_slice($years, 0, 3);
  1313. } else {
  1314. $yearList = $years;
  1315. }
  1316. foreach($daily as $exam) {
  1317. $y = substr($exam['Data'], 0, 4);
  1318. $m = substr($exam['Data'], 5, 2);
  1319. if (in_array($y, $yearList)) {
  1320. $examList[$y][$m]['TAmin'][] = (float)$exam['TA_min'];
  1321. $examList[$y][$m]['TAmax'][] = (float)$exam['TA_max'];
  1322. $examList[$y][$m]['FC'][] = (float)$exam['FC'];
  1323. }
  1324. }
  1325. ksort($examList);
  1326. $chartYears = array_keys($examList);
  1327. $monthList = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
  1328. foreach($examList as $year => $month) {
  1329. foreach($monthList as $monthNumb) {
  1330. if (isset($examList[$year][$monthNumb])) {
  1331. $tamin = $examList[$year][$monthNumb]['TAmin'];
  1332. $v = array_sum($tamin)/count($tamin);
  1333. $examList[$year][$monthNumb]['TAmin'] = $v > 0 ? $v : null;
  1334. $tamax = $examList[$year][$monthNumb]['TAmax'];
  1335. $v = array_sum($tamax)/count($tamax);
  1336. $examList[$year][$monthNumb]['TAmax'] = $v > 0 ? $v : null;
  1337. $fc = $examList[$year][$monthNumb]['FC'];
  1338. $v = array_sum($fc)/count($fc);
  1339. $examList[$year][$monthNumb]['FC'] = $v > 0 ? $v : null;
  1340. } else {
  1341. $examList[$year][$monthNumb] = ['TAmin'=>null, 'TAmax'=>null, 'FC'=>null];
  1342. }
  1343. }
  1344. }
  1345. foreach($examList as $year => $month) {
  1346. $yearMonthList = $examList[$year];
  1347. ksort($yearMonthList);
  1348. $examList[$year] = $yearMonthList;
  1349. }
  1350. foreach($examList as $year => $month) {
  1351. foreach($month as $monthNumb => $montValue) {
  1352. $dataValues[$year]['TAmin'][] = $montValue['TAmin'];
  1353. $dataValues[$year]['TAmax'][] = $montValue['TAmax'];
  1354. $dataValues[$year]['FC'][] = $montValue['FC'];
  1355. }
  1356. }
  1357. $examStats = $examList;
  1358. }
  1359. }*/
  1360. if (isset($dreamData['Diaria'])) {
  1361. //$daily = $this->utility->orderArray($dreamData['Diaria'], 'date_event', 'desc');
  1362. $daily = $dreamData['Diaria'];
  1363. $years = [];
  1364. $yearList = [];
  1365. $examList = [];
  1366. $chartYears = [];
  1367. $dataValues = [];
  1368. if (is_array($daily)) {
  1369. foreach($daily as $exam) {
  1370. if (strlen($exam['date_event']) > 4) {
  1371. $y = substr($exam['date_event'], 0, 4);
  1372. $years[$y] = $y;
  1373. }
  1374. }
  1375. if (count($years) > 1) rsort($years);
  1376. if (count($years) > 3) {
  1377. $yearList = array_slice($years, 0, 3);
  1378. } else {
  1379. $yearList = $years;
  1380. }
  1381. foreach($daily as $exam) {
  1382. $y = substr($exam['date_event'], 0, 4);
  1383. $m = substr($exam['date_event'], 5, 2);
  1384. if (in_array($y, $yearList)) {
  1385. $examList[$y][$m]['TAmin'][] = (float)$exam['vn26']; //TA_min
  1386. $examList[$y][$m]['TAmax'][] = (float)$exam['vn25']; //TA_max
  1387. $examList[$y][$m]['FC'][] = (float)$exam['vn10']; //FC
  1388. }
  1389. }
  1390. ksort($examList);
  1391. $chartYears = array_keys($examList);
  1392. $monthList = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
  1393. foreach($examList as $year => $month) {
  1394. foreach($monthList as $monthNumb) {
  1395. if (isset($examList[$year][$monthNumb])) {
  1396. $tamin = $examList[$year][$monthNumb]['TAmin'];
  1397. $v = array_sum($tamin)/count($tamin);
  1398. $examList[$year][$monthNumb]['TAmin'] = $v > 0 ? $v : null;
  1399. $tamax = $examList[$year][$monthNumb]['TAmax'];
  1400. $v = array_sum($tamax)/count($tamax);
  1401. $examList[$year][$monthNumb]['TAmax'] = $v > 0 ? $v : null;
  1402. $fc = $examList[$year][$monthNumb]['FC'];
  1403. $v = array_sum($fc)/count($fc);
  1404. $examList[$year][$monthNumb]['FC'] = $v > 0 ? $v : null;
  1405. } else {
  1406. $examList[$year][$monthNumb] = ['TAmin'=>null, 'TAmax'=>null, 'FC'=>null];
  1407. }
  1408. }
  1409. }
  1410. foreach($examList as $year => $month) {
  1411. $yearMonthList = $examList[$year];
  1412. ksort($yearMonthList);
  1413. $examList[$year] = $yearMonthList;
  1414. }
  1415. foreach($examList as $year => $month) {
  1416. foreach($month as $monthNumb => $montValue) {
  1417. $dataValues[$year]['TAmin'][] = $montValue['TAmin'];
  1418. $dataValues[$year]['TAmax'][] = $montValue['TAmax'];
  1419. $dataValues[$year]['FC'][] = $montValue['FC'];
  1420. }
  1421. }
  1422. $examStats = $examList;
  1423. }
  1424. }
  1425. if (isset($dreamData['Sintomi'])) {
  1426. $symptoms = $dreamData['Sintomi'];
  1427. }
  1428. if (isset($dreamData['Diagnosi'])) {
  1429. $diagnosis = $dreamData['Diagnosi'];
  1430. }
  1431. if (isset($dreamData['HivStages'])) {
  1432. $HivStages = $dreamData['HivStages'][0] ?? [];
  1433. }
  1434. if (isset($dreamData['HivTestHistory'])) {
  1435. $HivTestHistory = $dreamData['HivTestHistory'][0] ?? [];
  1436. }
  1437. if (isset($dreamData['TarvHistory'])) {
  1438. $TarvHistory = $this->utility->orderArray($dreamData['TarvHistory'], 'DataInizio', 'desc') ?? [];
  1439. //$TarvHistory = $dreamData['TarvHistory'][0] ?? [];
  1440. }
  1441. if (isset($dreamData['ListaFarmaci'])) {
  1442. $ListaFarmaci = $dreamData['ListaFarmaci'];
  1443. }
  1444. $dailyData = [];
  1445. if (is_array($daily) && !empty($daily)) {
  1446. foreach($daily as $item) {
  1447. $dailyData[$item['id_event']]['Diaria'] = $item;
  1448. foreach($symptoms as $symptom) {
  1449. if ($symptom['id_event'] == $item['id_event']) {
  1450. $dailyData[$item['id_event']]['Sintomi'][] = $symptom;
  1451. }
  1452. }
  1453. foreach($diagnosis as $diagnosi) {
  1454. if ($diagnosi['id_event'] == $item['id_event']) {
  1455. $dailyData[$item['id_event']]['Diagnosi'][] = $diagnosi;
  1456. }
  1457. }
  1458. }
  1459. }
  1460. $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]);
  1461. }
  1462. return $this->setRawJsonResponse('ok', '', ['html'=>$html, 'chartYears'=>$chartYears, 'dataValues'=>$dataValues]);
  1463. }
  1464. //Ajax function to update the Medical Specialties per Clinical Center
  1465. public function getSpecialtiesPerCenter() {
  1466. if (!$this->user->isLogged()) {
  1467. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1468. }
  1469. $medicalSpecialties = [];
  1470. $centerId = $this->getPost('centerId', 0);
  1471. $handleRequest = new HandleRequest();
  1472. $results = $handleRequest->getSpecialtyByClinicalCenterId($centerId, $this->userGroupId);
  1473. if (is_array($results)) {
  1474. $c=0;
  1475. foreach($results as $item) {
  1476. $medicalSpecialties[$c]['value'] = $item['id'];
  1477. $medicalSpecialties[$c]['text'] = _($item['description']);
  1478. $c++;
  1479. }
  1480. }
  1481. return $this->setRawJsonResponse('ok', '', ['specialties'=>$medicalSpecialties]);
  1482. }
  1483. //Ajax function to send message (comment) from Request page
  1484. public function requestSendMessage() {
  1485. if (!$this->user->isLogged()) {
  1486. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1487. }
  1488. $handleRequest = new HandleRequest();
  1489. $requestID = $this->getPost('requestID', 0);
  1490. $centerID = $this->getPost('centerID', 0);
  1491. $newStatus = $this->getPost('newStatus', '');
  1492. $message = trim($this->getPost('message', null));
  1493. $specialties = rawurldecode($this->getPost('specialtyList', ''));
  1494. $specialtyList = strpos($specialties, ',') !== false || (int)$specialties > 0 ? explode(',', $specialties) : null;
  1495. $hasAttachments = $this->getPost('hasAttachments', false);
  1496. $return = [];
  1497. //$buffer = $handleRequest->forwardRequest($requestID, $specialtyList, $this->userGroupId, $this->user->getUserId(), 15);
  1498. //return $this->setRawJsonResponse('err', $buffer, ['log'=>$buffer]);
  1499. if ($message == '') {
  1500. return $this->setRawJsonResponse('err', _('The Comment text field cannot be empty.'), ['log'=>[]]);
  1501. }
  1502. $id = $this->db->insert('requests_comments', [
  1503. 'request_id' => $requestID,
  1504. 'user_id' => $this->user->getUserId(),
  1505. 'comment' => $message,
  1506. 'comment_guid' => $this->security->getGUID(),
  1507. 'updated_at' => date('Y-m-d H:i:s'),
  1508. 'created_at' => date('Y-m-d H:i:s')
  1509. ]);
  1510. if ($id) {
  1511. $comments = $handleRequest->getCommentList($requestID, $centerID, true);
  1512. $request = $this->db->where('id', $requestID)->getOne('requests');
  1513. $html = $this->partial('Request/comment-list', ['comments'=>$comments]);
  1514. $return['commentID'] = $id;
  1515. $return['html'] = $html;
  1516. $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_MSG', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestID]);
  1517. //If the user is a referral, increment the comment counter (request_reports_counter table)
  1518. if ($handleRequest->isReferralInRequest($requestID, $this->user->getUserId())) {
  1519. //$handleRequest->setLog('position', 'dentro is referral in request');
  1520. //Check whether moderator or referral has added new medical specialty and notify new referrals
  1521. if ($handleRequest->forwardRequest($requestID, $specialtyList, $this->userGroupId, $request['user_id'], $request['center_id'])) {
  1522. $handleRequest->setRequestStatus($requestID, $handleRequest::REQUEST_STATUS_PART_REPORTED, $this->user->getUserId());
  1523. //$handleRequest->setLog('position', 'dentro forward');
  1524. } else {
  1525. //If previusly reported, just change the status to reported (closed)
  1526. /*if ($handleRequest->isRequestPreviouslyReopened($requestID)) {
  1527. $handleRequest->setLog('position', 'dentro is previuosly reopened');
  1528. $handleRequest->setRequestStatus($requestID, $handleRequest::REQUEST_STATUS_REPORTED, $this->user->getUserId());
  1529. //Notify the applicant (queue the message)
  1530. $msgStructure = $handleRequest->queueMessage($requestID, $request['user_id'], $request['user_id'], 'PARTIALLY_REPORTED');
  1531. } else {*/
  1532. //$handleRequest->setLog('position', 'dentro il commento normale, incrementa il contatore');
  1533. //If a referral comments again, doesn't add a new record in the table (see the table indexes)
  1534. $handleRequest->incrementReferralCounter($requestID, $this->user->getUserId());
  1535. //Change the request status
  1536. if ($handleRequest->isRequestFullyReported($requestID) === true) {
  1537. $handleRequest->setRequestStatus($requestID, $handleRequest::REQUEST_STATUS_REPORTED, $this->user->getUserId());
  1538. $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_CLOSED_AUTO', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestID]);
  1539. } else {
  1540. $handleRequest->setRequestStatus($requestID, $handleRequest::REQUEST_STATUS_PART_REPORTED, $this->user->getUserId());
  1541. }
  1542. //Notify the applicant (queue the message)
  1543. $msgStructure = $handleRequest->queueMessage($requestID, $request['user_id'], $request['user_id'], 'PARTIALLY_REPORTED');
  1544. //}
  1545. }
  1546. }
  1547. //TODO: check whether the comment has attachments (visible / not visible)
  1548. //Applicant's comment: change the status to REOPENED
  1549. if ($handleRequest->isApplicantInRequest($requestID, $this->user->getUserId())) {
  1550. $handleRequest->setRequestStatus($requestID, $handleRequest::REQUEST_STATUS_REOPENED, $this->user->getUserId());
  1551. $handleRequest->notifyAllReferrals($requestID, 'REQUEST_UPDATE');
  1552. }
  1553. //Force the new request status (Moderator)
  1554. if ($newStatus != '') {
  1555. $handleRequest->setRequestStatus($requestID, $newStatus, $this->user->getUserId());
  1556. $isFwd = $handleRequest->forwardRequest($requestID, $specialtyList, $this->userGroupId, $request['user_id'], $request['center_id']);
  1557. if ($newStatus == 'reopened') {
  1558. //Notifiy all referrals
  1559. $handleRequest->notifyAllReferrals($requestID, 'REQUEST_UPDATE');
  1560. //Notify the applicant
  1561. $handleRequest->queueMessage($requestID, $request['user_id'], $request['user_id'], 'REQUEST_UPDATE_APPLICANT');
  1562. }
  1563. if ($newStatus == 'referted') {
  1564. //Notify the applicant
  1565. $handleRequest->queueMessage($requestID, $request['user_id'], $request['user_id'], 'CLOSED_BY_MODERATOR');
  1566. }
  1567. $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_STATUS_CNG_MODERATOR', ['userId'=>$this->user->getUserId(), 'newStatus'=>$newStatus]);
  1568. }
  1569. //Update last update request field
  1570. $handleRequest->updateDate($requestID);
  1571. $return['action'] = 'refresh';
  1572. return $this->setRawJsonResponse('ok', '', $return);
  1573. } else {
  1574. return $this->setRawJsonResponse('err', _('Unable to send the message right now. Please try again in a few minutes.'), ['log'=>[]]);
  1575. }
  1576. }
  1577. //Ajax function to load all request comments
  1578. public function requestLoadAllComments() {
  1579. if (!$this->user->isLogged()) {
  1580. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1581. }
  1582. $requestID = $this->getPost('requestID', 0);
  1583. $centerID = $this->getPost('centerID', 0);
  1584. $comments = $handleRequest->getCommentList($requestID, $centerID, true);
  1585. $html = $this->partial('Request/comment-list', ['comments'=>$comments]);
  1586. return $this->setRawJsonResponse('ok', '', ['html'=>$html]);
  1587. }
  1588. //Ajax function to get the deaseses under a provided ICD10 category
  1589. public function requestGetDeseases() {
  1590. if (!$this->user->isLogged()) {
  1591. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1592. }
  1593. if(!$this->checkPermissions([ADMIN_ROLE_ID, APPLICANT_ROLE_ID])) {
  1594. return $this->setRawJsonResponse('err', _('Permission denied.'));
  1595. }
  1596. $icd10Id = $this->getPost('icd10Id', null); //Parent category ID
  1597. //If Draft mode some deseases could be selected
  1598. $selectedDeseases = $this->getPost('selectedDeseases', []);
  1599. $handleRequest = new HandleRequest();
  1600. $deseases = $handleRequest->getDeseasesByICD10Category($icd10Id, $this->user->getUserLang(), $selectedDeseases);
  1601. $html = $this->partial('Request/icd10-deseases-list', ['deseases'=>$deseases, 'checked'=>false]);
  1602. return $this->setRawJsonResponse('ok', '', ['html'=>$html]);
  1603. }
  1604. public function requestSearchDesease() {
  1605. if (!$this->user->isLogged()) {
  1606. return $this->setRawJsonResponse('ok', '', ['html'=>'']);
  1607. }
  1608. if(!$this->checkPermissions([ADMIN_ROLE_ID, APPLICANT_ROLE_ID])) {
  1609. return $this->setRawJsonResponse('ok', '', ['html'=>'']);
  1610. }
  1611. $handleRequest = new HandleRequest();
  1612. $keyword = addslashes($this->getPost('keyword', null));
  1613. $langCode = $this->getPost('lang', 'en');
  1614. $selectedDeseases = $this->getPost('selectedDeseases', []);
  1615. $deseases = $handleRequest->getDeseaseByKeyword($keyword, $langCode, $selectedDeseases);
  1616. $html = $this->partial('Request/icd10-search-deseases-list', ['deseases'=>$deseases, 'langCode'=>$langCode]);
  1617. return $this->setRawJsonResponse('ok', '', ['html'=>$html]);
  1618. }
  1619. //Ajax function to get all attachs by post code (used to render the attachs list after an Ajax call)
  1620. public function requestAttachs() {
  1621. if (!$this->user->isLogged()) {
  1622. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1623. }
  1624. if(!$this->checkPermissions([ADMIN_ROLE_ID, MODERATOR_ROLE_ID, APPLICANT_ROLE_ID])) {
  1625. return $this->setRawJsonResponse('err', _('Permission denied.'));
  1626. }
  1627. $postCode = $this->getPost('postCode', null);
  1628. $attachs = [];
  1629. $request = null;
  1630. if(!is_null($postCode)) {
  1631. $request = $this->db
  1632. ->where('r.unique_code', $postCode)
  1633. ->join('requests_attachments ra', 'ra.request_id=r.id', 'INNER')
  1634. ->get('requests r', null, ['ra.id attach_id', 'ra.file_name attach_name', 'ra.file_title attach_title', 'ra.file_ext attach_ext']);
  1635. if (is_array($request)) {
  1636. foreach($request as $index => $item) {
  1637. $ext = trim($item['attach_ext']) != '' ? $item['attach_ext'] : pathinfo($item['attach_name'], PATHINFO_EXTENSION);
  1638. $attachs[$index]['forceDownload'] = !in_array($ext, $this->config['settings']['preview-ext']) ? 1 : 0;
  1639. $attachs[$index]['ext'] = $ext;
  1640. $attachs[$index]['id'] = $item['attach_id'];
  1641. $attachs[$index]['name'] = $item['attach_name'];
  1642. $attachs[$index]['title'] = $this->helper->truncate($item['attach_title'], MAX_ATTACH_TITLE_LENGTH, '...'.$item['attach_ext']); }
  1643. }
  1644. }
  1645. return $this->setRawJsonResponse('ok', '', ['attachData'=>$attachs]);
  1646. }
  1647. //Ajax function to delete the passed attachment id
  1648. public function requestDeleteAttach() {
  1649. if (!$this->user->isLogged()) {
  1650. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1651. }
  1652. if(!$this->checkPermissions([ADMIN_ROLE_ID, APPLICANT_ROLE_ID])) {
  1653. return $this->setRawJsonResponse('err', _('Permission denied.'));
  1654. }
  1655. $attachId = $this->getPost('attachId', null);
  1656. $attachName = $this->getPost('attachName', null);
  1657. $delete = false;
  1658. if (!is_null($attachId) && !is_null($attachName)) {
  1659. $delete = $this->db->where('id', $attachId)->delete('requests_attachments');
  1660. @unlink(ATTACH_DIR.$attachName);
  1661. }
  1662. if ($delete) {
  1663. return $this->setRawJsonResponse('ok', '', ['attachId'=>$attachId]);
  1664. } else {
  1665. return $this->setRawJsonResponse('ok', '', ['attachId'=>0]);
  1666. }
  1667. }
  1668. //Ajax function to delete the request by id
  1669. public function requestDelete() {
  1670. if (!$this->user->isLogged()) {
  1671. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1672. }
  1673. if(!$this->checkPermissions([APPLICANT_ROLE_ID, MODERATOR_ROLE_ID])) {
  1674. return $this->setRawJsonResponse('err', _('Permission denied.'));
  1675. }
  1676. $scope = $this->user->is(APPLICANT_ROLE_ID) ? 'my' : 'moderations';
  1677. $requestId = $this->getPost('requestId', 0);
  1678. $handleRequest = new HandleRequest();
  1679. $return = $handleRequest->deleteRequest($requestId);
  1680. if ($return) {
  1681. $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_DELETED', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestId]);
  1682. return $this->setRawJsonResponse('ok', '', ['redirect'=>'requests/'.time().'/'.$scope.'/created_at/desc/1']);
  1683. } else {
  1684. return $this->setRawJsonResponse('err', _('Unable to delete the request right now, please try again in a few minutes.'));
  1685. }
  1686. }
  1687. public function getRequestResponders() {
  1688. if (!$this->user->isLogged()) {
  1689. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1690. }
  1691. if(!$this->checkPermissions([MODERATOR_ROLE_ID])) {
  1692. return $this->setRawJsonResponse('err', _('Permission denied.'));
  1693. }
  1694. $handleRequest = new HandleRequest();
  1695. $requestId = $this->getPost('requestId', 0);
  1696. $recipients = $handleRequest->getRecipientsByRequestId($requestId);
  1697. $html = $this->partial('Request/show-responders-list', ['recipients'=>$recipients]);
  1698. return $this->setRawJsonResponse('ok', '', ['html'=>$html]);
  1699. }
  1700. //Activity log page
  1701. public function logs() {
  1702. if (!$this->user->isLogged()) {
  1703. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1704. }
  1705. if(!$this->checkPermissions([ADMIN_ROLE_ID])) {
  1706. return $this->setRawJsonResponse('err', _('Permission denied.'));
  1707. }
  1708. $this->view->users = $this->db
  1709. ->where('status', 1)
  1710. ->where('group_id', $this->userGroupId)
  1711. ->orderBy('surname', 'asc')
  1712. ->get('users', null, ['id', 'username', 'name', 'surname']);
  1713. $this->view->requests = $this->db
  1714. ->where('u.status', 1)
  1715. ->where('u.group_id', $this->userGroupId)
  1716. ->join('users u', 'u.id=r.user_id', 'INNER')
  1717. ->orderBy('r.created_at', 'desc')
  1718. ->get('requests r', 100, ['r.id', 'r.created_at']);
  1719. $this->actionTitle = _('Activity logs');
  1720. return $this->setJsonView('logs');
  1721. }
  1722. //Sending Referral list preview (in a modal)
  1723. public function requestPreview() {
  1724. if (!$this->user->isLogged()) {
  1725. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1726. }
  1727. if(!$this->checkPermissions([ADMIN_ROLE_ID, APPLICANT_ROLE_ID])) {
  1728. return $this->setRawJsonResponse('err', _('Permission denied.'));
  1729. }
  1730. $data = isset($_POST['data']) ? $_POST['data'] : null;
  1731. $this->view->data = $data;
  1732. $this->view->error = '';
  1733. $userCount = 0;
  1734. $request = new HandleRequest();
  1735. $recipientList = $data['request_referral_list']['value'];
  1736. if (!is_array($recipientList)) {
  1737. if (!is_array($data['referral_ms']['value'])) {
  1738. $this->view->error = _('Please provide at least one Responder Medical for this request.');
  1739. return $this->setJsonView('requestPreview', true, '', ['userCount'=>$userCount]);
  1740. }
  1741. /*if (!is_array($data['referral_cc']['value'])) {
  1742. $this->view->error = _('Please provide at least one Responder Clinical Center.');
  1743. return $this->setJsonView('requestPreview', true, '', ['userCount'=>$userCount]);
  1744. }
  1745. */
  1746. if (!is_array($data['referral_langs']['value'])) {
  1747. $this->view->error = _('Please provide at least one Default Language for this request.');
  1748. return $this->setJsonView('requestPreview', true, '', ['userCount'=>$userCount]);
  1749. }
  1750. }
  1751. $referralMs = $data['referral_ms']['value'];
  1752. $referralCc = isset($data['referral_cc']['value']) && !empty($data['referral_cc']['value']) ? $data['referral_cc']['value'] : null;
  1753. $referralLangs = $data['referral_langs']['value'];
  1754. $referralVisibility = $data['referral_ms']['referral_visibility'];
  1755. //Recipients preview
  1756. $this->view->referrals = $request->getRecipients([
  1757. 'recipientList' => $recipientList,
  1758. 'ms' => $referralMs,
  1759. 'cc' => $referralCc,
  1760. 'langs' => $referralLangs
  1761. ]);
  1762. $userCount = count($this->view->referrals);
  1763. return $this->setJsonView('requestPreview', true, '', ['userCount'=>$userCount]);
  1764. }
  1765. public function generatePDF() {
  1766. if (!$this->user->isLogged()) {
  1767. return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
  1768. }
  1769. $context = $this->getPost('context');
  1770. $operation = $this->getPost('operation');
  1771. $htmlContent = '';
  1772. $outputFilePath = '';
  1773. $fileTitle = 'print_preview';
  1774. $pdf = new PdfPrinter();
  1775. $layout = new Layout();
  1776. $destinationDir = DATA_TMP_DIR;
  1777. $printFileURI = $this->config['settings']['http-protocol'].$this->config['settings']['site-domain'].'/print/';
  1778. switch($context) {
  1779. case 'requestview':
  1780. $_POST['requestID'] = $this->getPost('requestId');
  1781. $_POST['viewType'] = 'view';
  1782. $this->requestEdit();
  1783. // footer dinamico
  1784. $headerURI = $printFileURI.'header-default.php?center_description='.rawurlencode($this->view->requestData['center_description'])
  1785. .'&center_continent='.rawurlencode($this->view->requestData['center_continent']).'&center_country='.rawurlencode($this->view->requestData['center_country']).'&center_address='.rawurlencode($this->view->requestData['center_address'])
  1786. .'&companies_title='.rawurlencode($this->view->companies['title'])
  1787. .'&head_title='._('Multidisciplinary teleconsultation service')
  1788. .'&app_report_header='.$this->config['settings']['app-report-header'].'';
  1789. $footerURI = $printFileURI.'footer-default.php?teleconsulto='.rawurlencode($this->actionTitle).'&paziente='.$this->view->requestData['patient_surname'].' '.$this->view->requestData['patient_name']
  1790. .'&request_date='.$this->view->requestData['created_at'].'&patient='._('Patient_pdf').'&request_date_txt='._('Request date').'&print_date_txt='._('Print date')
  1791. .'&request_date='.$this->view->requestData['created_at'].'';
  1792. $htmlContent = $this->partial('Print/request-view', ['publicUri'=>$layout->getPublicUri()]);
  1793. $outputFilePath = $destinationDir.'request_'.$this->user->getUserId().'.pdf';
  1794. $fileTitle = 'request_'.$this->view->requestData['id'];
  1795. break;
  1796. }
  1797. //Pass the HTML to $pdf object
  1798. $pdfContent = $pdf->convertHtmlToPdf($htmlContent, $headerURI, $footerURI);
  1799. //file_put_contents($destinationDir.'html.html', $htmlContent);
  1800. file_put_contents($outputFilePath, $pdfContent);
  1801. if ($operation == 'print') {
  1802. return $this->setRawJsonResponse('ok', '', ['outputFilePath'=>$outputFilePath, 'fileTitle'=>$fileTitle,'debug'=>$this->view->companies]);
  1803. } else {
  1804. $hr = new HandleRequest();
  1805. $request_id = $this->getPost('requestId');
  1806. $attach_ids = $this->getPost('attach_ids');
  1807. $delay = $this->getPost('delay', null);
  1808. $delay_date = $this->utility->setDateToIsoFormat($delay);
  1809. $attachs = [];
  1810. //return $this->setRawJsonResponse('err', '-'.strlen($delay).'-');
  1811. if (strlen($delay) > 0 && is_null($delay_date)) {
  1812. return $this->setRawJsonResponse('err', "Impossibile concludere l'operazione, la data di spedizione deve essere indicata nel formato gg/mm/aaaa.");
  1813. }
  1814. if (!is_null($delay_date) && $this->utility->isDateInThePast($delay_date)) {
  1815. return $this->setRawJsonResponse('err', "La data di spedizione non può essere corrente o nel passato.");
  1816. }
  1817. $survey = $this->db->where('request_id', $request_id)->getOne('sportellocura');
  1818. if (isset($survey['survey_id']) || trim($this->view->requestData['cgemail']) != '') {
  1819. $survey_data = json_decode($survey['survey_data'], true);
  1820. $attachs_data = [];
  1821. if (isset($survey['survey_id'])) {
  1822. $recipient_email = $survey_data['email'];
  1823. $recipient_name = $survey_data['name'];
  1824. $recipient_surname = $survey_data['surname'];
  1825. $mailcode = 'SURVEY_'.uniqid();
  1826. $survey_id = $survey['survey_id'];
  1827. } else {
  1828. $recipient_email = trim($this->view->requestData['cgemail']);
  1829. $recipient_name = '';
  1830. $recipient_surname = trim($this->view->requestData['cgnamesurname']) != '' ? trim($this->view->requestData['cgnamesurname']) : 'Paziente';
  1831. $mailcode = 'REPORT_'.uniqid();
  1832. $survey_id = 0;
  1833. }
  1834. //$recipient_email = 'agodegi@gmail.com';
  1835. if ($this->utility->validateEmail($recipient_email)) {
  1836. if (is_array($attach_ids) && !empty($attach_ids)) {
  1837. $attach_id_list = implode(',', $attach_ids);
  1838. $attachs = $this->db->where("id IN($attach_id_list)")->get('requests_attachments');
  1839. if (is_array($attachs) && !empty($attachs)) {
  1840. foreach($attachs as $index => $attach) {
  1841. $attachs_data[$index]['path'] = ATTACH_DIR.$attach['file_name'];
  1842. $attachs_data[$index]['name'] = $attach['file_title'].'.'.$attach['file_ext'];
  1843. }
  1844. }
  1845. }
  1846. $pdf_path = ATTACH_DIR.$request_id.'.pdf';
  1847. rename($outputFilePath, $pdf_path);
  1848. //////
  1849. $attachs_data[] = ['path'=>$pdf_path, 'name'=>'Risposta-Specialista.pdf'];
  1850. $subject = 'Risposta del TeleAmbulatorio';
  1851. $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>
  1852. Cordiali Saluti,<br>Servizio di TeleAmbulatorio";
  1853. //$nf = new Notification();
  1854. //$mailcode = 'SURVEY_'.uniqid();
  1855. //$nf->sendEmail($recipient_email, $subject, $body, $mailcode, [], $attachs_data);*/
  1856. //////
  1857. $hr->insertMsgInQueue([
  1858. 'senderId' => $this->user->getUserId(),
  1859. 'recipientId' => $this->user->getUserId(), //L'utente corrente deve avere l'invio delle email attivato
  1860. 'requestId' => $request_id,
  1861. 'mailId' => $mailcode,
  1862. 'subject' => $subject,
  1863. 'content' => $body,
  1864. 'type' => 'email',
  1865. 'recipient' => $recipient_email,
  1866. 'senderStatus' => 1,
  1867. 'attachments' => json_encode($attachs_data),
  1868. 'delay' => $delay_date
  1869. ]);
  1870. //Log
  1871. $this->db->insert('sportellocura_log', [
  1872. 'request_id'=>$request_id,
  1873. 'survey_id'=>$survey_id,
  1874. 'mail_code'=>$mailcode,
  1875. 'created_at'=>date('Y-m-d H:i:s')
  1876. ]);
  1877. $this->notifySendPdf($survey['survey_id']);
  1878. return $this->setRawJsonResponse('ok', 'PDF inviato correttamente', ['log'=>null], ['button'=>'refresh-hash']);
  1879. } else {
  1880. return $this->setRawJsonResponse('err', _('Not valid recipient e-mail address'));
  1881. }
  1882. }
  1883. //Send PDF
  1884. return $this->setRawJsonResponse('err', _('Not valid request'));
  1885. }
  1886. }
  1887. public function deleteSurveyMailQueue() {
  1888. $mail_id = $this->getPost('mail_id', null);
  1889. $request_id = $this->getPost('request_id', 0);
  1890. $this->db
  1891. ->where('request_id', $request_id)
  1892. ->where('mail_id', $mail_id)
  1893. ->delete('requests_messages_queue');
  1894. return $this->setRawJsonResponse('ok', 'Il tentativo di cancellazione della ricezione programmata è stato eseguito con successo.');
  1895. }
  1896. public function getCitiesByProvince() {
  1897. $province_id = $this->getPost('province_id', 0);
  1898. $selected_city_id = $this->getPost('selected_city_id', 0);
  1899. $options = ['<option value="0">...</option>'];
  1900. $html = '';
  1901. $cities = $this->db->where('province_id', $province_id)->orderBy('name', 'ASC')->get('italian_cities');
  1902. if (is_array($cities) && !empty($cities)) {
  1903. foreach($cities as $city) {
  1904. $selected = $city['id'] == $selected_city_id ? 'selected' : '';
  1905. $options[] = '<option value="'.$city['id'].'" '.$selected.'>'.$city['name'].'</option>';
  1906. }
  1907. $html = implode("\n", $options);
  1908. }
  1909. return $this->setRawJsonResponse('ok', '', ['html'=>$html]);
  1910. }
  1911. private function notifySendPdf($survey_id=0) {
  1912. $endpoint = $this->config['settings']['sportellocura']['api']['endpoint'];
  1913. $apikey = $this->config['settings']['sportellocura']['api']['key'];
  1914. $vars = ['survey_id'=>$survey_id, 'cmd'=>'notify-pdf'];
  1915. if ($survey_id < 1) return;
  1916. $ch = curl_init();
  1917. curl_setopt($ch, CURLOPT_URL, $endpoint);
  1918. curl_setopt($ch, CURLOPT_POST, 1);
  1919. curl_setopt($ch, CURLOPT_USERPWD, "dev:demo");
  1920. curl_setopt($ch, CURLOPT_POSTFIELDS, $vars); //Post Fields
  1921. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  1922. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
  1923. curl_setopt($ch, CURLOPT_TIMEOUT, 30);
  1924. $headers = [
  1925. 'Api-Key: '.$apikey,
  1926. ];
  1927. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  1928. $data = curl_exec($ch);
  1929. //$output = json_decode($data, true);
  1930. curl_close($ch);
  1931. return $data;
  1932. }
  1933. public function getSportelloCura() {
  1934. $endpoint = $this->config['settings']['sportellocura']['api']['endpoint'];
  1935. $apikey = $this->config['settings']['sportellocura']['api']['key'];
  1936. $survey_id = $this->getPost('survey_id', 0);
  1937. $vars = ['survey_id'=>$survey_id, 'cmd'=>'get-survey'];
  1938. $ch = curl_init();
  1939. curl_setopt($ch, CURLOPT_URL, $endpoint);
  1940. curl_setopt($ch, CURLOPT_POST, 1);
  1941. curl_setopt($ch, CURLOPT_USERPWD, "dev:demo");
  1942. curl_setopt($ch, CURLOPT_POSTFIELDS, $vars); //Post Fields
  1943. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  1944. $headers = [
  1945. 'Api-Key: '.$apikey,
  1946. ];
  1947. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  1948. $data = curl_exec($ch);
  1949. $output = json_decode($data, true);
  1950. curl_close($ch);
  1951. $type_id = isset($output['survey']['type_id']) ? (int)$output['survey']['type_id'] : 0;
  1952. $output['survey']['ms'] = 0;
  1953. if ($type_id > 0) {
  1954. $ms = $this->db->where('sportello_type_id', $type_id)->getOne('users_medical_specialties');
  1955. if (isset($ms['id']) && (int)$ms['id']>0) {
  1956. $output['survey']['ms'] = $ms['id'];
  1957. }
  1958. }
  1959. return $this->setRawJsonResponse('ok', '', ['output'=>$output]);
  1960. }
  1961. public function getDreamItaly() {
  1962. $endpoint = $this->config['settings']['api']['endpoint'];
  1963. $apikey = $this->config['settings']['api']['key'];
  1964. $code = $this->getPost('code', 0);
  1965. $vars = ['request_id'=>$code];
  1966. $ch = curl_init();
  1967. curl_setopt($ch, CURLOPT_URL, $endpoint);
  1968. curl_setopt($ch, CURLOPT_POST, 1);
  1969. curl_setopt($ch, CURLOPT_POSTFIELDS, $vars); //Post Fields
  1970. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  1971. $headers = [
  1972. 'Api-Key: '.$apikey,
  1973. ];
  1974. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
  1975. $data = curl_exec($ch);
  1976. $output = json_decode($data, true);
  1977. $output['r_citta_lcl_id'] = 0;
  1978. $output['r_provincia_lcl_id'] = 0;
  1979. curl_close ($ch);
  1980. return $this->setRawJsonResponse('ok', '', ['output'=>$output]);
  1981. }
  1982. public function setViewerType() {
  1983. $checked_value = $this->getPost('checked_value', -1);
  1984. $user_id = $this->user->getUserId();
  1985. if ((int)$checked_value > -1) {
  1986. //$updt = $this->db->where('id', $user_id)->update('users', ['simple_viewer'=>$checked_value]);
  1987. $updt = 0;
  1988. }
  1989. return $this->setRawJsonResponse('ok', '', ['output'=>$updt]);
  1990. }
  1991. public function allowAccess() {
  1992. if (!$this->user->isLogged()) {
  1993. return $this->redirect('login', 'index');
  1994. }
  1995. return false;
  1996. }
  1997. }