Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

requestController.php 110KB

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