Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

requestController copy.php 88KB

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