| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523 |
- <?php
- class requestController extends mainController {
-
- function __construct() {
- parent::__construct();
-
- //To change for every Controllers
- $this->viewDir = 'Request';
-
- //$this->allow = [];
-
- define('MAX_ATTACH_TITLE_LENGTH', 30);
- }
-
- //List the requests
- public function index() {
-
- if(!$this->checkPermissions([ADMIN_ROLE_ID, MODERATOR_ROLE_ID, APPLICANT_ROLE_ID, REFERRER_ROLE_ID, GUEST_ROLE_ID])) {
- return $this->redirect('login', 'permissionDenied');
- }
-
- $this->controllerName = 'request';
- $this->actionName = 'index';
-
- $hr = new HandleRequest();
-
- $this->view->logList = $hr->getActivityLogList();
-
- //Scopes: "my" | "center" | "moderations" | "reports (referral)"
- $this->view->scope = $this->getPost('scope', 'my');
- $this->view->userHasClinicalCenters = true;
- $this->view->baseUri = 'requests/'.time().'/'.$this->view->scope;
-
- $this->view->currentPage = $this->getPost('pageNumb', 1);
- //$this->view->orderField = $this->getPost('orderField', 'created_at');
- $this->view->orderField = $this->getPost('orderField', 'request_status_number');
- $this->view->orderDir = $this->getPost('orderDir', 'asc');
- //$this->view->orderDir = $this->getPost('orderDir', 'desc');
- $this->view->statusSelectList = $hr->requestStatusLabels;
-
- //Robot (teleconsulti automatici)
- $robot_path = null;
- $this->view->robot_id = -1;
- if (file_exists(PUBLIC_HTML.'sportellocura-aosga-api/robot-id.txt')) {
- $robot_path = PUBLIC_HTML.'sportellocura-aosga-api/robot-id.txt';
- } else {
- if (file_exists(PUBLIC_HTML.'sportellocura-api/robot-id.txt')) {
- $robot_path = PUBLIC_HTML.'sportellocura-api/robot-id.txt';
- }
- }
-
- if (!is_null($robot_path)) {
- $this->view->robot_id = (int)file_get_contents($robot_path);
- }
-
- $userClinicalCenters = [];
- $userCcRole = 0;
- switch ($this->view->scope) {
- case 'my':
- $userCcRole = APPLICANT_ROLE_ID;
- break;
-
- case 'center':
- $userCcRole = APPLICANT_ROLE_ID;
- break;
-
- case 'moderations':
- $userCcRole = MODERATOR_ROLE_ID;
- break;
-
- case 'reports':
- $userCcRole = REFERRER_ROLE_ID;
- break;
-
- case 'center-guest':
- $userCcRole = GUEST_ROLE_ID;
- break;
- }
-
- $hr->setActivityLog($this->user->getUserId(), 'REQ_LISTED', ['userId'=>$this->user->getUserId(), 'scope'=>$this->view->scope]);
-
- if ($userCcRole > 0) {
- $userClinicalCenters = $this->getUserClinicalCenters($this->user->getUserId(), $userCcRole); //In mainController()
- }
-
- $this->view->ccSelectList = $userClinicalCenters;
-
- //Populate the Medical specialties list and the requester list for the column filter
- $ccIdList = [];
- $ccIdListString = '';
- $this->view->msSelectList = [];
- $this->view->requesterSelectList = [];
- foreach($userClinicalCenters as $ccId => $ccInfo) {
- $ccIdList[] = $ccId;
- }
-
- if (!empty($ccIdList)) {
- $ccIdListString = implode(',', $ccIdList);
- $this->view->debug = $ccIdListString;
-
- $msResults = $this->db
- ->where('ccmst.center_id IN('.$ccIdListString.')')
- ->where('ums.status', 1)
- ->join('users_medical_specialties ums', 'ums.id=ccmst.specialty_id', 'INNER')
- ->groupBy('ccmst.specialty_id')
- ->get('clinical_center_medical_specialties_to ccmst', null, ['ccmst.specialty_id', 'ums.description']);
-
- if (is_array($msResults) && !empty($msResults)) {
- foreach($msResults as $item) {
- $msSelectList[$item['specialty_id']] = _($item['description']);
- }
-
- //Sorting based on translated descriptions
- asort($msSelectList);
-
- //Medical specialties list
- $this->view->msSelectList = $msSelectList;
- }
-
- //Requester list
- $requestersResult = $this->db
- ->where('ucct.center_id IN('.$ccIdListString.')')
- ->where('ucct.role_id', APPLICANT_ROLE_ID)
- ->where('u.status', 1)
- ->where('u.trashed', 0)
- ->join('users u', 'u.id=ucct.user_id', 'INNER')
- ->groupBy('ucct.user_id')
- ->orderBy('u.surname', 'ASC')
- ->get('users_clinical_centers_to ucct', null, ['u.id', 'u.name', 'u.surname']);
-
- if (is_array($requestersResult) && !empty($requestersResult)) {
- foreach($requestersResult as $item) {
- $name = ucwords(strtolower($item['name']));
- $surname = ucwords(strtolower($item['surname']));
-
- $this->view->requesterSelectList[$item['id']] = $this->helper->setDottedFullname($name, $surname, false);
- }
- }
-
- //$this->view->debug = $this->view->requesterSelectList;
- }
-
- $this->view->ccStringList = '';
- $userCcList = [];
- $ccStringList = [];
-
- $this->view->referrals = [];
- $this->view->specialties = [];
- $searchData = $this->getPost('searchData', []);
- parse_str($searchData, $this->view->strOutput);
-
- //Default value
- $obscure = false;
-
- //Select the Clinical Center ID to anonymize
- $anonymCenters = [];
- foreach($userClinicalCenters as $uCC) {
- if (isset($uCC['anonymize']) && (int)$uCC['anonymize'] > 0) {
- $anonymCenters[$uCC['id']] = true;
- }
- }
- $this->view->anonymCenters = $anonymCenters;
-
- //Show user's requests
- if ($this->view->scope == 'my') {
-
- $this->actionTitle = _('My Requests');
-
- if ($this->user->is(APPLICANT_ROLE_ID)) {
- $this->db->where('user_id', $this->user->getUserId());
- }
-
- } else if ($this->view->scope == 'center' || $this->view->scope == 'moderations') {
-
- if ($this->view->scope == 'moderations' && $this->user->is(MODERATOR_ROLE_ID)) {
- $userClinicalCenters = $this->getUserClinicalCenters($this->user->getUserId(), MODERATOR_ROLE_ID);
- }
-
- $this->actionTitle = _('Center(s) Requests');
- if (is_array($userClinicalCenters) && !empty($userClinicalCenters)) {
- foreach($userClinicalCenters as $ccItem) {
- $userCcList[] = $ccItem['id'];
- $ccStringList[] = $ccItem['description'];
- }
- }
-
- $this->db->where('r.request_visibility', 'all');
- $this->db->where('r.group_id', $this->userGroupId);
-
- if ($this->user->is([MODERATOR_ROLE_ID])) {
- $this->db->where("r.request_status IN('draft', 'pending', 'opened', 'referted', 'reopened', '! referted')");
- } else {
- $this->db->where("r.request_status IN('pending', 'opened', 'referted', 'reopened', '! referted')");
- }
-
- if (!empty($userCcList)) {
- $userCcListString = implode(',', $userCcList);
- $this->db->where("cc.id IN($userCcListString)");
-
- $this->view->ccStringList = implode(', ', $ccStringList);
- } else {
- $this->db->where('cc.id', -1); //Force no results
- $this->view->userHasClinicalCenters = false;
- }
-
- } else if ($this->view->scope == 'reports') {
- $this->actionTitle = _('My Requests');
-
- if (is_array($userClinicalCenters) && !empty($userClinicalCenters)) {
- foreach($userClinicalCenters as $ccItem) {
- $ccStringList[] = $ccItem['description'];
- }
- }
-
- $this->view->ccStringList = implode(', ', $ccStringList);
-
- $this->db->where('r.request_visibility', 'all');
- $this->db->where('r.group_id', $this->userGroupId);
- $this->db->where("r.request_status IN('opened', 'referted', 'reopened', '! referted')");
- $this->db->where('rere.user_id', $this->user->getUserId());
- $this->db->join('requests_recipients rere', 'rere.request_id=r.id', 'INNER');
-
- } else if ($this->view->scope == 'center-guest') {
- $this->actionTitle = _('Requests');
-
- if (is_array($userClinicalCenters) && !empty($userClinicalCenters)) {
- foreach($userClinicalCenters as $ccItem) {
- $userCcList[] = $ccItem['id'];
- $ccStringList[] = $ccItem['description'];
- }
- }
-
- $this->db->where('r.request_visibility', 'all');
- $this->db->where('r.group_id', $this->userGroupId);
- $this->db->where("r.request_status IN('opened', 'referted', 'reopened', '! referted')");
-
- if (!empty($userCcList)) {
- $userCcListString = implode(',', $userCcList);
- $this->db->where("cc.id IN($userCcListString)");
-
- $this->view->ccStringList = implode(', ', $ccStringList);
- } else {
- $this->db->where('cc.id', -1); //Force no results
- $this->view->userHasClinicalCenters = false;
- }
- }
-
- //if (!empty($this->view->strOutput)) {
-
- /*$searchRequester = isset($this->view->strOutput['search']['requester']) ? (int)$this->view->strOutput['search']['requester'] : 0;
- $searchStatus = isset($this->view->strOutput['search']['status']) ? $this->view->strOutput['search']['status'] : '';
- $seachMs = isset($this->view->strOutput['search']['ms']) ? (int)$this->view->strOutput['search']['ms'] : 0;
- $seachCc = isset($this->view->strOutput['search']['cc']) ? (int)$this->view->strOutput['search']['cc'] : 0;*/
-
- // SET INFO MAX REQUESTS
- $this->view->getTotRequests = $this->db->totalCount;
- $this->view->getMaxRequests = $this->db->MaxAddRequests;
-
- $has_pdf = -1;
- if (isset($this->view->strOutput['search']['has_pdf'])) {
- $this->session->deleteSession('reqHasPdf');
- $has_pdf = $this->view->strOutput['search']['has_pdf'];
- $this->session->refreshSession('reqHasPdf', (int)$has_pdf);
- } else {
- if ($this->session->getSessionValue('reqHasPdf') !== false) {
- $has_pdf = $this->session->getSessionValue('reqHasPdf');
- }
- }
- if ($has_pdf > -1) {
- if ($has_pdf == 0) {
- $this->db->having('total_reports', 0);
- } else {
- $this->db->having('total_reports', 0, '>');
- }
- } else {
- $this->session->deleteSession('reqHasPdf');
- }
-
- $searchId = 0;
- if (isset($this->view->strOutput['search']['id'])) {
- $this->session->deleteSession('reqSearStorId');
- $searchId = (int)$this->view->strOutput['search']['id'];
- $this->session->refreshSession('reqSearStorId', $searchId);
- } else {
- if ($this->session->getSessionValue('reqSearStorId') !== false) {
- $searchId = $this->session->getSessionValue('reqSearStorId');
- }
- }
- if ($searchId > 0) {
- $this->db->where('r.id', $searchId);
- } else {
- $this->session->deleteSession('reqSearStorId');
- }
-
- $searchRequester = 0;
- if (isset($this->view->strOutput['search']['requester'])) {
- $this->session->deleteSession('reqSearStorUid');
- $searchRequester = (int)$this->view->strOutput['search']['requester'];
- $this->session->refreshSession('reqSearStorUid', $searchRequester);
- } else {
- if ($this->session->getSessionValue('reqSearStorUid') !== false) {
- $searchRequester = $this->session->getSessionValue('reqSearStorUid');
- }
- }
- if ($searchRequester > 0) {
- $this->db->where('r.user_id', $searchRequester);
- } else {
- $this->session->deleteSession('reqSearStorUid');
- }
-
-
- //////////////
- //
- $searchPatient = '';
- if (isset($this->view->strOutput['search']['patient'])) {
- $this->session->deleteSession('reqSearPatient');
- $searchPatient = (string)$this->view->strOutput['search']['patient'];
- $this->session->refreshSession('reqSearPatient', $searchPatient);
- } else {
- if ($this->session->getSessionValue('reqSearPatient') !== false) {
- $searchPatient = $this->session->getSessionValue('reqSearPatient');
- }
- }
-
- if ($searchPatient != '') {
-
- $regexp = '';
- $arr_lists = explode(' ', $searchPatient);
-
- foreach($arr_lists as $key=>$value){
- if($key == 0){
- $regexp .= '"'.$value.'"';
- }else{
- $regexp .= '|"'.$value.'"';
- }
- }
-
- // $this->db->where('CONCAT(rr.surname," ",rr.name) REGEXP '.$regexp.'');
-
- if (is_array($arr_lists) && !empty($arr_lists)) {
- foreach($arr_lists as $list_value) {
- $this->db->where('CONCAT(rr.surname," ",rr.name)', '%'.$list_value.'%', 'LIKE');
- }
- } else {
- $this->db->where('CONCAT(rr.surname," ",rr.name)', '%'.$arr_lists.'%', 'LIKE');
- }
-
- } else {
- $this->session->deleteSession('reqSearPatient');
- }
-
- //////////////
-
-
- $searchStatus = '';
- if (isset($this->view->strOutput['search']['status'])) {
- $this->session->deleteSession('reqSearStorStat');
- $searchStatus = $this->view->strOutput['search']['status'];
- $this->session->refreshSession('reqSearStorStat', $searchStatus);
- } else {
- if ($this->session->getSessionValue('reqSearStorStat') !== false) {
- $searchStatus = $this->session->getSessionValue('reqSearStorStat');
- }
- }
- if ($searchStatus != '') {
- $this->db->where('r.request_status', $searchStatus);
- } else {
- $this->session->deleteSession('reqSearStorStat');
- }
-
-
- $seachCc = 0;
- if (isset($this->view->strOutput['search']['cc'])) {
- $this->session->deleteSession('reqSearStorCc');
- $seachCc = (int)$this->view->strOutput['search']['cc'];
- $this->session->refreshSession('reqSearStorCc', $seachCc);
- } else {
- if ($this->session->getSessionValue('reqSearStorCc') !== false) {
- $seachCc = $this->session->getSessionValue('reqSearStorCc');
- }
- }
- if ($seachCc > 0) {
- $this->db->where('r.center_id', $seachCc);
- } else {
- $this->session->deleteSession('reqSearStorCc');
- }
-
- $seachMs = 0;
- if (isset($this->view->strOutput['search']['ms'])) {
- $this->session->deleteSession('reqSearStorMs');
- $seachMs = (int)$this->view->strOutput['search']['ms'];
- $this->session->refreshSession('reqSearStorMs', $seachMs);
- } else {
- if ($this->session->getSessionValue('reqSearStorMs') !== false) {
- $seachMs = $this->session->getSessionValue('reqSearStorMs');
- }
- }
- if ($seachMs > 0) {
- $this->db->join('requests_medical_specialties_to rmst', 'rmst.request_id=r.id', 'INNER')->where('rmst.specialty_id', $seachMs);
- } else {
- $this->session->deleteSession('reqSearStorMs');
- }
-
- //}
-
- $this->db->join('clinical_centers cc', 'cc.id=r.center_id', 'INNER')
- ->join('users u', 'u.id=r.user_id', 'INNER')
- ->join('requests_registry rr', 'rr.request_id=r.id', 'INNER')
- ->orderBy($this->view->orderField, $this->view->orderDir);
-
- if ($this->view->orderField == 'request_status_number') {
- $this->db->orderBy('created_at', 'desc');
- }
-
- $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",
-
- //Remove (?)
- "(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",
-
- "(SELECT COUNT(*) FROM sportellocura sca WHERE sca.request_id=r.id) sportello_total",
- "(SELECT COUNT(*) FROM requests_comments rc WHERE rc.request_id=r.id AND rc.user_id=".$this->view->robot_id.") total_auto_tlc"]);
-
- $this->view->queryDebug = $this->db->getLastQuery();
-
- // SET INFO MAX REQUESTS
- $this->view->getTotRequests = $this->db->totalRequests;
- $this->view->getMaxRequests = $this->db->MaxAddRequests;
-
- $this->setPagination($this->db, $this->db->totalCount, $this->view->currentPage, $this->view->baseUri.'/'.$this->view->orderField.'/'.$this->view->orderDir);
-
- if (is_array($requests)) {
- foreach($requests as $index => $request) {
-
- //Check whether obfuscate the Patient name or don't
- if ($this->view->scope != 'my') {
-
- //Check whether the request has been market ad anonymous
- if ((int)$requests[$index]['request_anonymous'] == 0) {
-
- //If the request isn't anonymous, check the Clinical Center
- if (isset($anonymCenters[$request['center_id']])) { //The Center is anonymous by default
- $requests[$index]['request_anonymous'] = 1; //Make this request anonymous
- }
- }
-
- }
-
- //Overwrite the anonymous value if the current user is the request author
- if ($request['user_id'] == $this->user->getUserId()) {
- $requests[$index]['request_anonymous'] = 0;
- }
-
- //If there are no Clinical Center for the current user, foce anonymous anyway
- if (empty($userClinicalCenters)) {
- $requests[$index]['request_anonymous'] = 0;
- }
-
- //Get the Referrals for each Requests
- $this->view->referrals[$request['id']] = $this->db
- ->where('rc.request_id', $request['id'])
- ->where('(SELECT COUNT(*) FROM users_roles_to urt WHERE urt.user_id=rc.user_id AND role_id='.REFERRER_ROLE_ID.')', 0, '>')
- ->join('users u', 'u.id=rc.user_id', 'INNER')
- ->orderBy('u.surname', 'asc')
- ->groupBy('rc.user_id')
- ->get('requests_comments rc', null, [
- 'user_id',
- 'u.name user_name',
- 'u.surname user_surname',
- "(SELECT GROUP_CONCAT(umst.specialty_id SEPARATOR '|') FROM users_medical_specialties_to umst WHERE umst.user_id=rc.user_id) specialty_ids"
- ]);
-
- //Get the Medical Specialties for each Requests
- $this->view->specialties[$request['id']] = $this->db
- ->where('rmst.request_id', $request['id'])
- ->join('users_medical_specialties ums', 'ums.id=rmst.specialty_id', 'INNER')
- ->orderBy('ums.description', 'asc')
- ->get('requests_medical_specialties_to rmst', null, ['rmst.specialty_id specialty_id', 'ums.description specialty_name', 'NULL AS referrals']);
-
- //Combine Referrals and Specialties
- foreach($this->view->specialties as $request_id => $specialties) {
- foreach($specialties as $specialty_index => $specialty) {
- foreach($this->view->referrals[$request_id] as $referral) {
-
- //Check if referral has this specialty id
- if (in_array($specialty['specialty_id'], explode('|', $referral['specialty_ids']))) {
- $this->view->specialties[$request_id][$specialty_index]['referrals'][$referral['user_id']] = $this->helper->setDottedFullname(ucwords($referral['user_name']), ucwords($referral['user_surname']), false);
- }
- }
- }
- }
-
- //Add new item in the Request list
- $requests[$index]['specialties'] = isset($this->view->specialties[$request['id']]) ? $this->view->specialties[$request['id']] : [];
- }
- }
-
- $this->view->ucc = $userClinicalCenters;
- $this->view->actionTitle = rawurlencode($this->actionTitle); //Pass the action title to "New Request" button
- $this->view->parentBaseUri = rawurlencode($this->view->baseUri); //Pass the base uri to "New Request" button
- $this->view->requests = $requests;
- $this->breadcrumbs = [['hash'=>null, 'label'=>$this->actionTitle]];
-
- return $this->setJsonView('index');
- }
-
- //Request editing page (View)
- public function requestEdit() {
- /*if(!$this->checkPermissions([ADMIN_ROLE_ID, MODERATOR_ROLE_ID, APPLICANT_ROLE_ID])) {
- return $this->redirect('login', 'permissionDenied');
- }*/
-
- $handleRequest = new HandleRequest();
-
- $requestID = $this->getPost('requestID', 1);
- $this->view->parentActionTitle = $this->getPost('parentTitle', _('Requests'));
- $this->view->parentScope = $this->getPost('parentScope', 'my');
- $this->view->viewType = $this->getPost('viewType', 'view');
- $this->view->parentBaseUri = $this->getPost('parentBaseUri', '');
- $this->view->currentPage = $this->getPost('pageNumb', 1);
- $this->view->orderField = $this->getPost('orderField', 'created_at');
- $this->view->orderDir = $this->getPost('orderDir', 'desc');
-
- //Default values
- $this->view->userCanView = true;
- $this->view->requestData = [];
- $this->view->companies = [];
- $this->view->symptoms = [];
- $this->view->ICD10 = [];
- $this->view->medicalSpecialties = [];
- $this->view->requestMedicalSpecialties = [];
- $this->view->forwardMedicalSpecialties = [];
- $this->view->requestMedicalSpecialtiesIdList = [];
- $this->view->attachments = [];
- $this->view->comments = [];
- $this->view->ccReferral = []; //Clinical Centers referrals (recipients)
- $this->view->languages = $this->locale->getSupportedLanguages();
- $this->view->icd10 = [];
- $this->view->dermaPositions = [];
- $this->view->dermaPositionLabels = ['single'=>_('Single'), 'multiple-localized'=>_('Multiple localized'), 'multiple-spread'=>_('Multiple spread'), 'clusted'=>_('Cluster'), 'metameric'=>_('Metameric'), 'linear'=>_('Linear'), 'acral'=>_('Acral'), 'symmetrical'=>_('Symmetrical')];
- $this->view->otoImages = [];
- $this->view->otoPositionLabels = ['oto_myringitis'=>_('Bullous myringitis'),
- 'oto_polip'=>_('Polyp of the EAC'),
- 'oto_atelectasis'=>_('Tympanic membrane atelectasis'),
- 'oto_perforation'=>_('Tympanic membrane perforation / non-cholesteatomatous otitis media'),
- 'oto_chole'=>_('Cholesteatomatous otitis media'),
- 'oto_tympanoscler'=>_('Tympanosclerosis'),
- 'oto_tyjugular'=>_('Tympano-jugular paraganglioma'),
- 'oto_cholesterol'=>_('Cholesterol granuloma')];
- $this->view->statuses = [];
- $this->requestOrigin = '';
- $this->view->dreamCode = '';
- $this->view->dreamData = [];
- $this->view->dreamCompleteData = '';
- $this->view->requestDreamPDF = []; //Information for Dream PDF
- $this->view->provinceList = [];
- $this->view->cgProvince = '';
- $this->view->cgCity = '';
- $this->view->dreamItalyEndPoint = $this->config['settings']['api']['endpoint'];
- $this->view->dreamItalyApiKey = $this->config['settings']['api']['key'];
-
- $this->view->sportelloCuraEndPoint = $this->config['settings']['sportellocura']['api']['key'];
- $this->view->sportelloCuraApiKey = $this->config['settings']['sportellocura']['api']['endpoint'];
- $this->view->survey = []; //Sportello Cura data
-
- $provinces = $this->db->orderBy('name', 'ASC')->get('italian_provinces');
- if (is_array($provinces) && !empty($provinces)) {
- foreach($provinces as $item) {
- $this->view->provinceList[$item['id']] = $item['name'];
- }
- }
-
- //PDF sending log
- $this->view->pdfLog = $this->db
- ->where('sl.request_id', $requestID)
- ->join('requests_messages_queue rmq', 'rmq.mail_id=sl.mail_code', 'LEFT')
- ->orderBy('sl.created_at', 'ASC')
- ->get('sportellocura_log sl', NULL, ['sl.created_at queued_date', 'rmq.request_id', 'rmq.mail_id', 'rmq.delay_at']);
-
- //Default values
- $userIsAuthor = false; //The logged user id the author of this Request
- $userIsModerator = false; //The logged user is a moderator of this Clinical Center
- $this->view->userIsAuthor = $userIsAuthor;
- $this->view->userIsModerator = $userIsModerator;
- $userIsReferrer = false; //The logged user is a referral of this Request
- $this->view->userIsReferrer = $userIsReferrer;
-
- $this->view->icd10Categories = $handleRequest->getICD10Categories($this->user->getUserLang());
- $this->view->wizards = [];
-
- $advancedFields = $this->db->where('id', $this->user->getUserId())->getOne('users', 'advanced_request');
- $this->view->advancedFields = isset($advancedFields['advanced_request']) && (int)$advancedFields['advanced_request'] == 1 ? true : false;
-
- //Viewer
- $this->view->isSimpleViewer = false;
- //$viewer = $this->db->where('id', $this->user->getUserId())->getOne('users', 'simple_viewer');
- $viewer = 0;
- if (isset($viewer['simple_viewer']) && (int)$viewer['simple_viewer'] == 1) {
- $this->view->isSimpleViewer = true;
- }
-
- //Select the user's language by default
- foreach($this->view->languages as $index => $language) {
- if ($language['lang_code'] == $this->user->getUserLang()) {
- $this->view->languages[$index]['selected'] = true;
- } else {
- $this->view->languages[$index]['selected'] = false;
- }
- }
-
- if ($this->user->is(APPLICANT_ROLE_ID)) {
- $this->view->userClinicalCenters = $this->getUserClinicalCenters($this->user->getUserId(), APPLICANT_ROLE_ID); //In mainController()
- } else if ($this->user->is(REFERRER_ROLE_ID)) {
- $this->view->userClinicalCenters = $this->getUserClinicalCenters($this->user->getUserId(), REFERRER_ROLE_ID);
- } else if ($this->user->is(MODERATOR_ROLE_ID)) {
- $this->view->userClinicalCenters = $this->getUserClinicalCenters($this->user->getUserId(), MODERATOR_ROLE_ID); //In mainController()
- }
-
- $this->view->requestId = $requestID;
- //$this->view->medicalSpecialties = $this->db->orderBy('description', 'asc')->get('users_medical_specialties');
- $this->view->ccReferral = $this->db
- ->where('ucct.role_id', REFERRER_ROLE_ID)
- ->join('clinical_centers cc', 'cc.id=ucct.center_id', 'INNER')
- ->groupBy('cc.id')
- ->orderBy('cc.description', 'asc')
- ->get('users_clinical_centers_to ucct', null, ['cc.id id', 'cc.description description']);
-
- $this->view->referralList = $this->db
- ->where('role_id', REFERRER_ROLE_ID)
- ->where('u.status', 1)
- ->join('users u', 'u.id=urt.user_id', 'INNER')
- ->orderBy('u.surname', 'asc')
- ->get('users_roles_to urt', null, [
- 'u.id user_id',
- 'u.name user_name',
- 'u.surname user_surname',
- "(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"
- ]);
-
- if ($this->view->viewType == 'view') {
- //Get all Medical Specialties (in the list for the comment form)
- $this->view->medicalSpecialties = $handleRequest->getSpecialtyByClinicalCenterId(0, $this->userGroupId);
- } else {
- //New Request: if there is just one Clinical Center, list its the Medical Specialties (else they are loaded by Ajax)
- if (count($this->view->userClinicalCenters) == 1) {
- $currentCenterId = array_values($this->view->userClinicalCenters)[0]['id'];
- $this->view->medicalSpecialties = $handleRequest->getSpecialtyByClinicalCenterId($currentCenterId, $this->userGroupId);
- }
- }
-
- if ($requestID == 0) {
- $this->actionTitle = _('Request : New');
- $this->view->requestUniqueCode = strtoupper(uniqid());
- $this->view->requestData = []; //Default: empty array
-
- $this->view->exams = $handleRequest->getExams();
-
- $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_NEW', ['userId'=>$this->user->getUserId()]);
-
- } else {
- $this->actionTitle = _('Request : Edit');
-
-
- if ($this->view->viewType == 'view') {
- $this->actionTitle = vsprintf(_('Request #%s'), [$requestID]);
- $this->actionTitlePDF = "#".$requestID;
- $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_VIEW', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestID]);
-
-
- }
-
- //TO DO: check whether the current user is authorized to access this request (i.e. changing the ID in the addess bar)
-
- //$this->view->testData = $handleRequest->forwardRequest($requestID);
-
- $requestData = $this->db
- ->where('r.id', $requestID)
- ->join('users u', 'u.id=r.user_id', 'INNER')
- ->join('requests_registry rr', 'rr.request_id=r.id', 'INNER')
- ->join('clinical_centers cc', 'cc.id=r.center_id', 'INNER')
- ->join('continents cnt', 'cnt.code=cc.continent_code', 'INNER')
- ->join('countries ctr', 'ctr.country_iso2_code=cc.country_code', 'INNER')
- ->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");
-
- //Sporello Cura
- $sportellocura = $this->db->where('request_id', $requestID)->getOne('sportellocura');
- if (isset($sportellocura['survey_id'])) {
- $survey_record = json_decode($sportellocura['survey_data'], true);
- if (isset($survey_record['json_answers'])) {
- $survey_record['data'] = json_decode($survey_record['json_answers'], true);
- }
- $this->view->survey = $survey_record;
- }
-
- $companies = $this->db->getOne('companies');
-
- if (!is_array($requestData)) {
- return $this->setJsonView('requestError');
- }
-
- //Check whether the moderator can access this request or can't
- if ($this->user->is(MODERATOR_ROLE_ID)) {
- if (!isset($this->view->userClinicalCenters[$requestData['center_id']])) {
- return $this->setJsonView('requestError');
- }
- }
-
- //Get Dream code
- $dreamResult = $this->db->where('request_id', $requestID)->getOne('requests_dream_data', 'dream_code, dream_hash');
-
- if (isset($dreamResult['dream_code']) && trim($dreamResult['dream_code']) != '') {
- $this->view->dreamCode = $dreamResult['dream_code'];
- $this->view->dreamData = htmlspecialchars($dreamResult['dream_hash']);
- }
-
- $userIsAuthor = $requestData['user_id'] == $this->user->getUserId() ? true : false;
- $this->view->userIsAuthor = $userIsAuthor;
-
- $this->view->hasMoreDetails = trim($requestData['cgnamesurname']) != '' || trim($requestData['cgrole']) != '' || trim($requestData['cgemail']) != '' || trim($requestData['cgphone']) != '';
-
- //Get Caregiver's Province and City
-
- if ((int)$requestData['cgprovince'] > 0) {
- $cg_province = $this->db->where('id', $requestData['cgprovince'])->getOne('italian_provinces');
-
- $this->view->cgProvince = isset($cg_province['name']) ? $cg_province['name'] : '';
- }
-
- if ((int)$requestData['cgcity'] > 0) {
- $cg_city = $this->db->where('id', $requestData['cgcity'])->getOne('italian_cities');
-
- $this->view->cgCity = isset($cg_city['name']) ? $cg_city['name'] : '';
- }
-
- $userIsModerator = $handleRequest->isUserModerator($requestData['center_id'], $this->getUserClinicalCenters($this->user->getUserId(), MODERATOR_ROLE_ID), $this->user->getUserId());
- $this->view->userIsModerator = $userIsModerator;
-
- $userIsReferrer = $handleRequest->isUserReferrer($requestID, $this->user->getUserId());
- $this->view->userIsReferrer = $userIsReferrer;
-
- //Get the Medical Specialties for the saved Clinical Center
- $currentCenterId = $requestData['center_id'];
- $this->view->medicalSpecialties = $handleRequest->getSpecialtyByClinicalCenterId($currentCenterId, $this->userGroupId);
-
- $ccInfo = $this->db->where('id', $currentCenterId)->getOne('clinical_centers');
- $isCcAnonymous = isset($ccInfo['anonymize']) && (int)$ccInfo['anonymize'] == 1 ? true : false;
-
- if ($isCcAnonymous) {
- $requestData['request_anonymous'] = 1;
- }
-
- //Overwrite the previouse value
- if ($userIsAuthor) {
- $isCcAnonymous = false;
- }
-
- $this->view->requestData = $requestData;
- $this->view->companies = $companies;
-
- //TOOD: check whether current user can access this request
- //O. Is the right group?
- //1. Is the Author?
- //2. Is a Moderator in this Clinical Center?
- //3. Is a Referral of this Request?
- //4. Is an Admininstrator?
-
- $this->view->requestUniqueCode = $requestData['unique_code'];
- //$this->actionTitle .= ' ('.ucfirst($requestData['request_origin']).')';
- $this->requestOrigin = $requestData['request_origin'];
-
- //Symptons (old ICD10)
- $this->view->symptoms = $this->db
- ->where('rst.request_id', $requestID)
- ->where('rsl.language_code', $this->user->getUserLang())
- ->join('requests_symptoms_labels rsl', 'rsl.symptom_id=rst.symptom_id', 'INNER')
- ->orderBy('rsl.symptom_label', 'asc')
- ->get('requests_symptoms_to rst', null, ['rsl.symptom_label']);
-
- //ICD10 (new)
- $this->view->ICD10 = $this->db
- ->where('rst.request_id', $requestID)
- ->where('idl.lang_code', $this->user->getUserLang())
- ->join('icd10_desease_labels idl', 'idl.desease_id=rst.symptom_id', 'INNER')
- ->orderBy('idl.description', 'asc')
- ->get('requests_symptoms_to rst', null, ['idl.description symptom_label']);
-
- //Overwrite the symptoms with the new ICD10
- if (!empty($this->view->ICD10)) {
- $this->view->symptoms = $this->view->ICD10;
- }
-
- //Clinical Centers
- foreach($this->view->userClinicalCenters as $centerId => $centerItem) {
- if ($centerItem['id'] == $requestData['center_id']) {
- $this->view->userClinicalCenters[$centerId]['selected'] = true;
- } else {
- $this->view->userClinicalCenters[$centerId]['selected'] = false;
- }
- }
-
- if (is_array($this->view->referralList)) {
- $requestRecipients = $this->db
- ->where('request_id', $requestID)
- ->get('requests_recipients');
-
- $this->view->recipients = $requestRecipients;
-
- if (is_array($requestRecipients)) {
- foreach($this->view->referralList as $index => $referral) {
- $this->view->referralList[$index]['selected'] = false;
- foreach($requestRecipients as $recipient) {
- if ($referral['user_id'] == $recipient['user_id']) {
- $this->view->referralList[$index]['selected'] = true;
- }
- }
- }
- }
- }
-
- $requestMedSpec = $this->db
- ->where('request_id', $requestID)
- ->get('requests_medical_specialties_to');
-
- //Medical specialties of the request
- $idList = [];
- $requestMedicalSpecialties = $this->db
- ->where('rmst.request_id', $requestID)
- ->join('users_medical_specialties ums', 'ums.id=rmst.specialty_id', 'INNER')
- ->get('requests_medical_specialties_to rmst', null, ['ums.id', 'ums.description']);
- if (is_array($requestMedicalSpecialties)) {
- foreach($requestMedicalSpecialties as $item) {
- $this->view->requestMedicalSpecialties[$item['id']]['id'] = $item['id'];
- $this->view->requestMedicalSpecialties[$item['id']]['description'] = _($item['description']);
- $idList[] = $item['id'];
- }
-
- $this->view->requestMedicalSpecialtiesIdList = $idList;
- }
-
- //All possible Medical specialties
- foreach($this->view->medicalSpecialties as $index => $medSpecList) {
- $this->view->medicalSpecialties[$index]['selected'] = false;
- foreach($requestMedSpec as $reqMedSpecItem) {
- if ($reqMedSpecItem['specialty_id'] == $medSpecList['id']) {
- $this->view->medicalSpecialties[$index]['selected'] = true;
- }
- }
-
- //Request forward: list with mmedical specialties without the request medical specialties
- if (!isset($this->view->requestMedicalSpecialties[$medSpecList['id']])) {
- $this->view->forwardMedicalSpecialties[$medSpecList['id']]['id'] = $medSpecList['id'];
- $this->view->forwardMedicalSpecialties[$medSpecList['id']]['description'] = $medSpecList['description'];
- }
-
- }
-
-
- $requestLangs = $this->db
- ->where('request_id', $requestID)
- ->get('requests_languages_to');
-
- //If there are saved languages change the default value
- if (is_array($requestLangs) && !empty($requestLangs)) {
- foreach($this->view->languages as $index => $language) {
- $this->view->languages[$index]['selected'] = false;
- foreach($requestLangs as $reqLangItem) {
- if ($reqLangItem['language_code'] == $language['lang_code']) {
- $this->view->languages[$index]['selected'] = true;
- }
- }
- }
- }
-
- $requestCenters = $this->db
- ->where('request_id', $requestID)
- ->get('request_clinical_centers_to');
-
- foreach($this->view->ccReferral as $centerId => $referralCenter) {
- $this->view->ccReferral[$centerId]['selected'] = false;
- foreach($requestCenters as $centerItem) {
- if ($centerItem['center_id'] == $referralCenter['id']) {
- $this->view->ccReferral[$centerId]['selected'] = true;
- }
- }
- }
-
- $this->view->statuses = $this->db
- ->where('rs.code', '! referted', '<>')
- ->where('rs.code', 'draft', '<>')
- ->where('rs.code', 'pending', '<>')
- ->where('rs.code', 'opened', '<>')
- ->orderBy('rs.default_label', 'asc')
- ->get('requests_statuses rs');
-
- $this->view->attachments = $handleRequest->getAttachmentsByRequestId($requestID);
-
- //Group attachments by date
- $this->view->groupedAttachments = [];
- if (is_array($this->view->attachments) && !empty($this->view->attachments)) {
- foreach($this->view->attachments as $attachment) {
- //$ext = $this->helper->getExtension($attachment['file_name']);
- $attachment['previewType'] = $this->helper->getPreviewType($attachment['file_name']);
- $this->view->groupedAttachments[date('Y-m-d 00:00:00', strtotime($attachment['created_at']))][] = $attachment;
- }
-
- if (!empty($this->view->groupedAttachments)) {
- foreach($this->view->groupedAttachments as $ext => $attachList) {
- sort($attachList);
- $this->view->groupedAttachments[$ext] = $attachList;
- }
- }
- }
-
- //ICD-10
- $this->view->icd10 = $handleRequest->getECD10ListByRequestId($requestID, $this->user->getUserLang());
-
- //Wizards
- $this->view->wizardTitles = ['cardio'=>_('Wizard Cardio'), 'derma'=>_('Wizard Derma'), 'generic'=>_('Wizard Physical Examination'), 'oto'=>_('Wizard Ear')];
- $this->view->wizards = $handleRequest->getWizardsByRequestId($requestID);
-
- //Wizard Derma positions
- $this->view->dermaPositions = $handleRequest->getWizardsDermaPositions($requestID);
-
- //Wizard Ear images
- $this->view->otoImages = $handleRequest->getWizardsEarDeseases($requestID);;
-
- //Get all exams for the dialogs
- $this->view->exams = $handleRequest->getExams($this->view->wizards);
-
- }
-
- $pathParentUri = $this->view->parentBaseUri.'/'.$this->view->orderField.'/'.$this->view->orderDir.'/'.$this->view->currentPage;
-
- if ($this->view->parentBaseUri != 'hashtag') {
- $this->breadcrumbs = [['hash'=>$pathParentUri, 'label'=>$this->view->parentActionTitle], ['hash'=>null, 'label'=>$this->actionTitle]];
- } else {
- $this->breadcrumbs = [['hash'=>null, 'label'=>$this->actionTitle]];
- }
-
- if ($this->view->viewType == 'view') {
-
- if($this->checkPermissions([APPLICANT_ROLE_ID])) {
- //If not the author: $permissionDenied = true;
- }
-
- if($this->checkPermissions([MODERATOR_ROLE_ID])) {
- //If not moderator in this cc: $permissionDenied = true;
- }
-
- $this->view->comments = $handleRequest->getCommentList($requestID, $this->view->requestData['center_id'], true);
-
- //Add the information for the Dream PDF
- $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']]));
-
- $pdfComments = $this->view->comments;
-
- foreach($pdfComments as $index => $item) {
- $pdfComments[$index]['created_at_string'] = $this->helper->getDateString($pdfComments[$index]['created_at']);
- }
-
- $dreamResults = $this->db->where('request_id', $requestID)->getOne('requests_dream_data', 'dream_evt_id, dream_hash');
- $registryData = null;
- $registryEvtId = null;
- if (isset($dreamResults['dream_hash'])) {
- $registryData = json_decode($dreamResults['dream_hash'], true);
- $registryEvtId = $dreamResults['dream_evt_id'];
- }
-
- $hasDreamIntegration = false;
-
- if (isset($registryData['Anagrafica']) && !empty($registryData['Anagrafica'])) {
- $this->view->requestDreamPDF = [
- 'registry'=>$registryData['Anagrafica'],
- 'evtId'=>$registryEvtId,
- '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']],
- 'icd10'=>$this->view->icd10,
- 'wizards'=>$this->view->wizards,
- 'dermaPositions'=>$this->view->dermaPositions,
- 'maxBloodPressure'=>$this->view->requestData['max_arterial_pressure'],
- 'minBloodPressure'=>$this->view->requestData['min_arterial_pressure'],
- 'heartRate'=>$this->view->requestData['heart_rate'],
- 'saturation'=>$this->view->requestData['saturation'],
- 'clinicalRemarks'=>$this->view->requestData['clinical_remarks'],
- 'medicalHistory'=>$this->view->requestData['medical_history'],
- //'exams'=>$this->view->exams,
- 'comments'=>$pdfComments
- ];
-
- $hasDreamIntegration = true;
- }
-
- return $this->setJsonView('requestView', false, '', ['requestDreamPDF'=>$this->view->requestDreamPDF, 'userIsAuthor'=>$userIsAuthor, 'hasDreamIntegration'=>$hasDreamIntegration]);
-
- } else {
- return $this->setJsonView('requestEdit');
- }
- }
-
- //Save/Edit requests
- public function requestSave() {
- if (!$this->user->isLogged()) {
- return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
- }
-
- if(!$this->checkPermissions([ADMIN_ROLE_ID, APPLICANT_ROLE_ID])) {
- return $this->setRawJsonResponse('err', _('Permission denied.'));
- }
-
- $data = isset($_POST['data']) ? $_POST['data'] : null;
- $this->view->data = $data;
-
- $operation = $data['operation']['value'] == 'draft' ? 'draft' : 'pending';
- $hasFiles = (bool)$data['has_files']['value'];
- $fileCounter = (int)$data['files_counter']['value'];
- $handleRequest = new HandleRequest();
-
- $requestId = $data['request_id']['value'];
- $requestUniqueCode = $data['request_unique_code']['value'];
- $clinicalCenter = $data['request_cc']['value'];
- $dreamCode = isset($data['dream_code']['value']) ? $data['dream_code']['value'] : '';
- $patientName = trim($data['request_name']['value']);
- $patientSurname = trim($data['request_surname']['value']);
- $patientGender = $data['request_gender']['value'];
- $ageType = isset($data['request_birth_type']['value']) ? $data['request_birth_type']['value'] : null;
-
- $ageYear = $data['request_birth_year']['value'];
- $ageMonth = $data['request_birth_month']['value'];
- $ageMonthDay = $data['request_birth_month_day']['value'];
-
- $ageAgeInNumber = $data['request_age']['value'];
- $ageUnitOfTime = $data['request_unit_of_time']['value'];
- $triage = isset($data['triage']['value']) ? $data['triage']['value'] : null;
- $bpMin = (int)$data['request_bp_min']['value'];
- $bpMax = (int)$data['request_bp_max']['value'];
- $heartRate = (int)$data['request_heart_rate']['value'];
- $oxygenSaturation = (int)$data['request_oxy_sat']['value'];
- $medicalRemarks = strip_tags(trim($data['request_medremarks']['value']));
- $medicalHistory = strip_tags(trim($data['request_medicalhistory']['value']));
- $mainQuestion = strip_tags(trim($data['request_mainquestion']['value']));
- $visibility = $data['referral_visibility']['value'];
- $privacy = $data['privacy']['value'];
- $anonymous = $data['request_anonymisation']['value'];
- $dreamCode = trim($data['dream_code']['value']);
- $dreamData = $data['dream_data']['value'];
- $dreamEvtId = $data['dream_evt_id']['value'];
-
- $icd10List = isset($data['icd10_desease']['value']) ? $data['icd10_desease']['value'] : null;
-
- //Exams
- $supportedWizards = ['generic', 'derma', 'cardio', 'oto'];
- foreach ($supportedWizards as $wizard) {
- $this->view->wizard[$wizard] = isset($data['exam_'.$wizard]['value']) ? $data['exam_'.$wizard]['value'] : [];
- }
-
- //Derma positions
- $dermaPositions = isset($data['derma_position']['value']) ? $data['derma_position']['value'] : [];
-
- //Ear images
- $earImages = isset($data['ear_desease']['value']) ? $data['ear_desease']['value'] : [];
-
- //return $this->setRawJsonResponse('err', _("Test: ".json_encode($dermaPositions)));
-
- //Medical specialty (the only required filter)
- $medicalSpecialties = $data['referral_ms']['value'];
-
- //If no language is selected, assign the user's default language
- $referralLangs = is_array($data['referral_langs']['value']) && !empty($data['referral_langs']['value']) ? $data['referral_langs']['value'] : [$this->user->getUserLang()];
-
- //Referrals' Clinical Center (could be not set)
- $referralCc = isset($data['referral_cc']['value']) ? $data['referral_cc']['value'] : null;
- //Specific referral list (could be not set)
- $referralList = isset($data['request_referral_list']['value']) ? $data['request_referral_list']['value'] : null;
-
- //These numbers are used to sort the statuses and the triage colors
-
- //$status_numbers = ['pending'=>-1, 'draft'=>0, 'opened'=>1, '! referted'=>4, 'reopened'=>3, 'referted'=>2];
- $status_numbers = $handleRequest->statusNumbers;
-
- //UPDATE requests SET request_status_number = 2 WHERE request_status LIKE '! referted';
- //UPDATE requests SET request_status_number = 4 WHERE request_status LIKE 'referted';
-
- $triage_numbers = ['white'=>0, 'green'=>1, 'yellow'=>2, 'red'=>3];
-
- $referralVisibility = $data['referral_visibility']['value'];
- $dateOfBirth = '0000-00-00 00:00:00';
-
- //Dynamic checkboxes in Preview modal window
- $recipientsIds = isset($data['recipients_ids']['value']) ? $data['recipients_ids']['value'] : [];
-
- //Request Clinical Center
- if ($clinicalCenter == '') {
- return $this->setRawJsonResponse('err', _('Please provide the Clinical Center.'));
- }
-
- if ($patientName == '') {
- return $this->setRawJsonResponse('err', _("Please provide the Patient's Name."));
- }
-
- if ($patientSurname == '') {
- return $this->setRawJsonResponse('err', _("Please provide the Patient's Surname."));
- }
-
- if ($patientGender == '') {
- return $this->setRawJsonResponse('err', _("Please provide the Patient's Sex."));
- }
-
- if (is_null($ageType)) {
- return $this->setRawJsonResponse('err', _("Please provide the Patient's date of birth or the age in years or months."));
- }
-
- if ($ageType == 'date') {
- $dateOfBirth = "$ageYear-$ageMonth-$ageMonthDay 00:00:00";
-
- if (!$this->utility->isValidDate($dateOfBirth, 'Y-n-j H:i:s')) {
- return $this->setRawJsonResponse('err', _("The date of birth provided is not valid."));
- }
- }
-
- if ($ageType == 'number') {
- if ((int)$ageAgeInNumber > 0) {
-
- if ($ageUnitOfTime == 'y' && $ageAgeInNumber < 2) {
- return $this->setRawJsonResponse('err', _("Please provide the Patient's age in months."));
- }
-
- if ($ageUnitOfTime == 'y') {
- $diffYears = (int)date('Y')-$ageAgeInNumber;
- $dateOfBirth = "$diffYears-01-01 00:00:00";
- }
-
- if ($ageUnitOfTime == 'm') {
- $dateOfBirth = date('Y-m-01 00:00:00', strtotime("-$ageAgeInNumber months"));
- }
-
- } else {
- return $this->setRawJsonResponse('err', _("Patient's age must be a number."));
- }
- }
-
- //Check date of birth is in the future
- $checkBirthDate = new DateTime($dateOfBirth);
- $checkDateNow = new DateTime();
- if ($checkBirthDate > $checkDateNow) {
- return $this->setRawJsonResponse('err', _("The date of birth cannot be in the future."));
- }
-
- if ($bpMin > 0 && $bpMax > 0) {
- if ($bpMin > $bpMax) {
- return $this->setRawJsonResponse('err', _("Minimum Blood Pressure cannot be higher than the Maximum one."));
- }
- }
-
- if ($bpMax > 250) {
- return $this->setRawJsonResponse('err', _("Maximum Blood Pressure is too high."));
- }
-
- if ($bpMin > 250) {
- return $this->setRawJsonResponse('err', _("Minimum Blood Pressure is too high."));
- }
-
- if ($heartRate > 250) {
- return $this->setRawJsonResponse('err', _("Heart Rate cannot be higher then 250 bpm."));
- }
-
- if ($oxygenSaturation > 100) {
- return $this->setRawJsonResponse('err', _("Oxygen Saturation cannot be higher than 100%."));
- }
-
- if ($medicalRemarks == '') {
- return $this->setRawJsonResponse('err', _("Please provide the Medical Remarks."));
- }
-
- if ($mainQuestion == '') {
- return $this->setRawJsonResponse('err', _("Please provide the Main Question."));
- }
-
- if (!is_array($referralList)) {
- if (!is_array($medicalSpecialties)) {
- return $this->setRawJsonResponse('err', _('Please provide at least one Medical Specialty for this request.'));
- }
- }
-
- //Check whether is provided a referral list or isn't
- $specificReferralData = [];
- if (is_array($referralList)) {
- //Get Medical Specialties and Referral Languages
- $referralIds = implode(',', $referralList);
-
- $medicalSpecialties = [];
- $referralLangs = [];
-
- $specificReferralData = $this->db
- ->where("u.id IN($referralIds)")
- ->where('u.group_id', $this->userGroupId)
- ->join('users_medical_specialties_to umst', 'umst.user_id=u.id', 'INNER')
- ->groupBy('umst.specialty_id')
- ->get('users u', null, ['umst.specialty_id referral_md', 'u.language_default referral_lang']);
-
- if (is_array($specificReferralData) && !empty($specificReferralData)) {
- foreach($specificReferralData as $item) {
- $medicalSpecialties[$item['referral_md']] = $item['referral_md'];
- $referralLangs[$item['referral_lang']] = $item['referral_lang'];
- }
- }
-
- }
-
- if ((int)$privacy == 0) {
- return $this->setRawJsonResponse('err', _('Please provide the Privacy Policy consent.'));
- }
-
- $cgnamesurname = $data['cgnamesurname']['value'];
- $cgrole = $data['cgrole']['value'];
- $cgphone = $data['cgphone']['value'];
- $cgemail = $data['cgemail']['value'];
- $cgmmgnamesurname = $data['cgmmgnamesurname']['value'];
- $cgmmgphone = $data['cgmmgphone']['value'];
- $cgmmgemail = $data['cgmmgemail']['value'];
- $cgprovince = $data['cgprovince']['value'];
- $cgcity = isset($data['cgcity']['value']) ? $data['cgcity']['value'] : 0;
-
- $dbData = [
- 'group_id' => $this->userGroupId, //mainController
- 'center_id' => $clinicalCenter,
- 'user_id' => $this->user->getUserId(),
- 'unique_code' => $requestUniqueCode,
- 'request_question' => $mainQuestion,
- 'request_status' => $operation,
- 'request_visibility' => (int)$visibility == 1 ? 'all' : 'private',
- 'request_origin' => 'web',
- 'request_status_number' => isset($status_numbers[$operation]) ? $status_numbers[$operation] : 0, //Default Draft
- 'request_guid' => $this->security->getGUID(),
- 'triage_color' => $triage,
- 'triage_number' => isset($triage_numbers[$triage]) ? $triage_numbers[$triage] : 0,
- 'cgnamesurname' => $cgnamesurname,
- 'cgrole' => $cgrole,
- 'cgphone' => $cgphone,
- 'cgemail' => $cgemail,
- 'cgmmgnamesurname' => $cgmmgnamesurname,
- 'cgmmgphone' => $cgmmgphone,
- 'cgmmgemail' => $cgmmgemail,
- 'cgprovince' => $cgprovince,
- 'cgcity' => $cgcity,
- 'patient_privacy' => $privacy,
- 'send_status' => 'central',
- 'request_anonymous' => $anonymous,
- 'updated_at' => date('Y-m-d H:i:s'),
- 'created_at' => date('Y-m-d H:i:s')
- ];
-
- //First check for recipients
- if (empty($recipientsIds)) {
- /*$recipients = $handleRequest->getRecipients([
- 'recipientList' => [],
- 'ms' => $medicalSpecialties,
- 'cc' => $referralCc,
- 'langs' => $referralLangs,
- 'groupId' => $this->userGroupId
- ]);*/
-
- $recipients = $handleRequest->getRecipients([
- 'recipientList' => [],
- 'ms' => $medicalSpecialties,
- 'cc' => [$clinicalCenter],
- 'langs' => $referralLangs,
- 'groupId' => $this->userGroupId
- ]);
-
- if (is_array($recipients) && !empty($recipients)) {
- foreach($recipients as $recipient) {
- $recipientsIds[] = $recipient['user_id'];
- }
- }
-
- }
-
- if ($requestId == 0) { //Add
-
- //Add the request record if there are recipients
- if (is_array($recipientsIds) && !empty($recipientsIds)) {
- //$dbData['created_at'] = date('Y-m-d H:i:s');
- $lastInsert = $this->db->insert('requests', $dbData);
- $requestId = $lastInsert;
-
- } else {
- return $this->setRawJsonResponse('err', _('Unable to save the Request: the Recipient List is empty.'), ['log'=>[]]);
- }
-
-
- } else { //Update
- $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_SAVED_DRAFT', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestId]);
- $this->db->where('id', $requestId)->update('requests', $dbData);
- }
-
- if ($requestId > 0) {
-
- //Sportello cura
-
- $sportellocura_code = (int)$data['sportellocura_code']['value'];
- $sportellocura_json_data = trim($data['sportellocura']['value']);
-
- if ($sportellocura_code > 0 && $sportellocura_json_data != '') {
-
- //Check wheather already added
- //$check = $this->db->where('survey_id', $sportellocura_code)->getOne('sportellocura', 'survey_id');
-
- //if (!isset($check['survey_id'])) {
-
- $this->db->replace('sportellocura', [
- 'survey_id'=>$sportellocura_code,
- 'request_id'=>$requestId,
- 'survey_data'=>$sportellocura_json_data,
- 'created_at'=>date('Y-m-d H:i:s')
- ]);
-
- $endpoint = $this->config['settings']['sportellocura']['api']['endpoint'];
- $apikey = $this->config['settings']['sportellocura']['api']['key'];
- $vars = ['survey_id'=>$sportellocura_code, 'cmd'=>'set-added'];
-
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $endpoint);
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $vars); //Post Fields
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
- curl_setopt($ch, CURLOPT_TIMEOUT, 10); //timeout in seconds
-
- $headers = [
- 'Api-Key: '.$apikey,
- ];
-
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
-
- $curldata = curl_exec($ch);
- curl_close($ch);
- //}
- }
-
- //DREAM Italy and Sportello Cura files
- if (isset($data['cg']) && is_array($data['cg'])) {
- foreach($data['cg'] as $cg_index => $cg_data) {
-
- $cg_filename = $cg_data['filename'];
- $cg_filesystem_name = md5(uniqid());
-
- $cg_filedata_base64 = $cg_data['filedata'];
- $cg_file_data = base64_decode($cg_filedata_base64);
-
- $cg_file_path = ATTACH_DIR.$cg_filesystem_name;
- file_put_contents($cg_file_path, $cg_file_data);
-
- if (file_exists($cg_file_path)) {
-
- $cg_file_size = filesize($cg_file_path);
- $cg_filetype = mime_content_type($cg_file_path);
- $cg_file_ext = $this->utility->mime2ext($cg_filetype);
-
- if ($cg_file_ext !== false) {
-
- $cg_filesystem_name = $cg_filesystem_name.'.'.$cg_file_ext;
-
- rename($cg_file_path, ATTACH_DIR.$cg_filesystem_name);
-
- $cg_filename = str_ireplace('.'.$cg_file_ext, '', $cg_filename);
- $cg_filename = $cg_filename.'.'.$cg_file_ext;
-
- $cg_file_title = $this->utility->slugify($cg_filename);
-
- $this->db->insert('requests_attachments', [
- 'request_id'=>$requestId,
- 'user_id'=>$this->user->getUserId(),
- 'file_name'=>$cg_filesystem_name,
- 'file_title'=>$cg_file_title,
- 'file_ext'=>$cg_file_ext,
- 'file_size'=>$cg_file_size,
- 'file_mime'=>$cg_filetype,
- 'type'=>'others',
- 'created_at'=>date('Y-m-d H:i:s')
- ]);
- }
-
- }
-
- }
- } else {
- file_put_contents(ATTACH_DIR.'nodata.log', '');
- }
-
- //Update the Patient's Registry
- $registryData = [
- 'request_id' => $requestId,
- 'center_id' => $clinicalCenter,
- 'name' => $patientName,
- 'surname' => $patientSurname,
- 'birthdate' => $dateOfBirth,
- 'gender' => $patientGender,
- 'min_arterial_pressure' => $bpMin,
- 'max_arterial_pressure' => $bpMax,
- 'heart_rate' => $heartRate,
- 'saturation' => $oxygenSaturation,
- 'clinical_remarks' => $medicalRemarks,
- 'medical_history' => $medicalHistory,
- 'updated_at' => date('Y-m-d H:i:s'),
- 'created_at' => date('Y-m-d H:i:s')
- ];
-
- $this->db->replace('requests_registry', $registryData);
-
- //Check Specific Referrals
- $this->db->where('request_id', $requestId)->delete('requests_recipients');
- if (is_array($referralList)) {
- foreach($referralList as $referralId) {
- $this->db->insert('requests_recipients', [
- 'request_id' => $requestId,
- 'user_id' => $referralId
- ]);
- }
- }
-
- //Add/Update the Medical Specialties
- $this->db->where('request_id', $requestId)->delete('requests_medical_specialties_to');
- foreach($medicalSpecialties as $specialtyId) {
- $this->db->insert('requests_medical_specialties_to', [
- 'request_id' => $requestId,
- 'specialty_id' => $specialtyId
- ]);
- }
-
- //Add/Update Clinical Centers
- $this->db->where('request_id', $requestId)->delete('request_clinical_centers_to');
- if (is_array($referralCc) && !empty($referralCc)) {
- foreach($referralCc as $ccId) {
- $this->db->insert('request_clinical_centers_to', [
- 'request_id' => $requestId,
- 'center_id' => $ccId
- ]);
- }
- }
-
- //Add/Update recipients' languages
- $this->db->where('request_id', $requestId)->delete('requests_languages_to');
- foreach($referralLangs as $language) {
- $this->db->insert('requests_languages_to', [
- 'request_id' => $requestId,
- 'language_code' => $language
- ]);
- }
-
- //ICD-10
- $this->db->where('request_id', $requestId)->delete('requests_symptoms_to');
- if (is_array($icd10List) && !empty($icd10List)) {
- foreach($icd10List as $symptomId) {
- $this->db->insert('requests_symptoms_to', [
- 'request_id' => $requestId,
- 'symptom_id' => $symptomId
- ]);
- }
- }
-
- //Wizards
- $this->db->where('request_id', $requestId)->delete('requests_wizards_to');
- if (is_array($this->view->wizard)) {
- foreach($this->view->wizard as $wizardType => $wizardIds) {
- if (is_array($wizardIds) && !empty($wizardIds)) {
- foreach($wizardIds as $examId) {
- $this->db->insert('requests_wizards_to', [
- 'request_id' => $requestId,
- 'exam_id' => $examId,
- 'exam_type' => $wizardType
- ]);
- }
- }
- }
- }
-
- //Wizard Derma positions
- $this->db->where('request_id', $requestId)->delete('requests_wizard_derma_position_to');
- if (is_array($dermaPositions) && !empty($dermaPositions)) {
- foreach($dermaPositions as $positionType) {
- $this->db->insert('requests_wizard_derma_position_to', [
- 'request_id' => $requestId,
- 'position_type' => $positionType
- ]);
- }
- }
-
- //Wizard Ear images
- $this->db->where('request_id', $requestId)->delete('requests_wizard_ear_deseases_to');
- if (is_array($earImages) && !empty($earImages)) {
- foreach($earImages as $earImagesType) {
- $this->db->insert('requests_wizard_ear_deseases_to', [
- 'request_id' => $requestId,
- 'desease_type' => $earImagesType
- ]);
- }
- }
-
- //Dream
- if ($dreamCode != '') {
- $this->db->replace('requests_dream_data', [
- 'request_id' => $requestId,
- 'dream_code' => trim(strtoupper($dreamCode)),
- 'dream_evt_id' => $dreamEvtId,
- 'dream_hash' => $dreamData,
- 'created_at' => date('Y-m-d H:i:s')
- ]);
- }
- }
-
- $this->view->dbData = $dbData; //Debug
-
- //return $this->setJsonView('requestSave');
- //$debug = $handleRequest->checkPartialUploads();
-
- if ($operation == 'draft') {
- return $this->setRawJsonResponse('ok', _('Request information successfully saved as draft.'), ['log'=>$dermaPositions], ['button'=>'refresh-hash', 'recordId'=>$requestId, 'idPosition'=>3]);
- } else {
-
- //Update the recipient list for this request and change the status to pending|opened
- if (is_array($recipientsIds) && !empty($recipientsIds)) {
- $this->db->where('request_id', $requestId)->delete('requests_recipients');
- foreach($recipientsIds as $recipientId) {
- $this->db->insert('requests_recipients', [
- 'request_id' => $requestId,
- 'user_id' => $recipientId
- ]);
- }
-
- $requestStatus = $hasFiles ? $handleRequest::REQUEST_STATUS_PENDING : $handleRequest::REQUEST_STATUS_OPENED;
-
- $handleRequest->setRequestStatus($requestId, $requestStatus, $this->user->getUserId());
-
- $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_SENT', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestId]);
-
- //return $this->setRawJsonResponse('ok', _('Test'), ['log'=>$requestStatus]);
-
- return $this->setRawJsonResponse('ok', _('Request information successfully opened.'), ['log'=>[]], ['button'=>'goto', 'destination'=>'requests/'.time().'/my/created_at/desc/1']);
-
- }
- }
- }
-
- public function getDreamInformation() {
- if (!$this->user->isLogged()) {
- return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
- }
-
- $requestId = $this->getPost('requestId', 0);
- $dreamResult = $this->db->where('request_id', $requestId)->getOne('requests_dream_data', 'dream_code, dream_hash');
- $html = _('No DREAM information available.');
-
- if (isset($dreamResult['dream_code'])) {
- $dreamData = json_decode($dreamResult['dream_hash'], true);
- $registry = [];
- $exams = [];
- $examStats = [];
- $daily = [];
- $symptoms = [];
- $diagnosis = [];
- $HivStages = [];
- $HivTestHistory = [];
- $TarvHistory = [];
- $ListaFarmaci = [];
- /*$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'];*/
-
- $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'];
-
- if (isset($dreamData['Anagrafica'])) {
- $registry = $dreamData['Anagrafica'];
- $registry['age'] = $this->utility->getAge($registry['dataNascita']);
- }
-
- if (isset($dreamData['Esami'])) {
- //$exams = $this->utility->orderArray($dreamData['Esami'], 'Data', 'desc');
- $exams = $dreamData['Esami'];
- $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'];
-
- if (is_array($exams)) {
- foreach($exams as $index => $exam) {
- foreach ($exam as $key => $value) {
- if ($key == 'CViral') {
- $code = (int)$value;
-
- //Default
- //$exams[$index][$key] = 'ND';
-
- if (isset($filter[$code])) {
- $exams[$index][$key] = $filter[$code];
- }
- }
- }
- }
- }
- }
-
- /*if (isset($dreamData['Diaria'])) {
- //$daily = $this->utility->orderArray($dreamData['Diaria'], 'Data', 'desc');
- $daily = $dreamData['Diaria'];
-
- $years = [];
- $yearList = [];
- $examList = [];
- $chartYears = [];
- $dataValues = [];
-
- if (is_array($daily)) {
- foreach($daily as $exam) {
- if (strlen($exam['Data']) > 4) {
- $y = substr($exam['Data'], 0, 4);
- $years[$y] = $y;
- }
- }
-
- if (count($years) > 1) rsort($years);
-
- if (count($years) > 3) {
- $yearList = array_slice($years, 0, 3);
- } else {
- $yearList = $years;
- }
-
- foreach($daily as $exam) {
- $y = substr($exam['Data'], 0, 4);
- $m = substr($exam['Data'], 5, 2);
- if (in_array($y, $yearList)) {
- $examList[$y][$m]['TAmin'][] = (float)$exam['TA_min'];
- $examList[$y][$m]['TAmax'][] = (float)$exam['TA_max'];
- $examList[$y][$m]['FC'][] = (float)$exam['FC'];
- }
- }
-
- ksort($examList);
- $chartYears = array_keys($examList);
-
- $monthList = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
- foreach($examList as $year => $month) {
- foreach($monthList as $monthNumb) {
- if (isset($examList[$year][$monthNumb])) {
- $tamin = $examList[$year][$monthNumb]['TAmin'];
- $v = array_sum($tamin)/count($tamin);
- $examList[$year][$monthNumb]['TAmin'] = $v > 0 ? $v : null;
-
- $tamax = $examList[$year][$monthNumb]['TAmax'];
- $v = array_sum($tamax)/count($tamax);
- $examList[$year][$monthNumb]['TAmax'] = $v > 0 ? $v : null;
-
- $fc = $examList[$year][$monthNumb]['FC'];
- $v = array_sum($fc)/count($fc);
- $examList[$year][$monthNumb]['FC'] = $v > 0 ? $v : null;
- } else {
- $examList[$year][$monthNumb] = ['TAmin'=>null, 'TAmax'=>null, 'FC'=>null];
- }
- }
- }
-
- foreach($examList as $year => $month) {
- $yearMonthList = $examList[$year];
- ksort($yearMonthList);
- $examList[$year] = $yearMonthList;
- }
-
- foreach($examList as $year => $month) {
-
- foreach($month as $monthNumb => $montValue) {
- $dataValues[$year]['TAmin'][] = $montValue['TAmin'];
- $dataValues[$year]['TAmax'][] = $montValue['TAmax'];
- $dataValues[$year]['FC'][] = $montValue['FC'];
- }
- }
-
-
- $examStats = $examList;
-
- }
- }*/
-
- if (isset($dreamData['Diaria'])) {
- //$daily = $this->utility->orderArray($dreamData['Diaria'], 'date_event', 'desc');
- $daily = $dreamData['Diaria'];
-
- $years = [];
- $yearList = [];
- $examList = [];
- $chartYears = [];
- $dataValues = [];
-
- if (is_array($daily)) {
- foreach($daily as $exam) {
- if (strlen($exam['date_event']) > 4) {
- $y = substr($exam['date_event'], 0, 4);
- $years[$y] = $y;
- }
- }
-
- if (count($years) > 1) rsort($years);
-
- if (count($years) > 3) {
- $yearList = array_slice($years, 0, 3);
- } else {
- $yearList = $years;
- }
-
- foreach($daily as $exam) {
- $y = substr($exam['date_event'], 0, 4);
- $m = substr($exam['date_event'], 5, 2);
- if (in_array($y, $yearList)) {
- $examList[$y][$m]['TAmin'][] = (float)$exam['vn26']; //TA_min
- $examList[$y][$m]['TAmax'][] = (float)$exam['vn25']; //TA_max
- $examList[$y][$m]['FC'][] = (float)$exam['vn10']; //FC
- }
- }
-
- ksort($examList);
- $chartYears = array_keys($examList);
-
- $monthList = ['01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12'];
- foreach($examList as $year => $month) {
- foreach($monthList as $monthNumb) {
- if (isset($examList[$year][$monthNumb])) {
- $tamin = $examList[$year][$monthNumb]['TAmin'];
- $v = array_sum($tamin)/count($tamin);
- $examList[$year][$monthNumb]['TAmin'] = $v > 0 ? $v : null;
-
- $tamax = $examList[$year][$monthNumb]['TAmax'];
- $v = array_sum($tamax)/count($tamax);
- $examList[$year][$monthNumb]['TAmax'] = $v > 0 ? $v : null;
-
- $fc = $examList[$year][$monthNumb]['FC'];
- $v = array_sum($fc)/count($fc);
- $examList[$year][$monthNumb]['FC'] = $v > 0 ? $v : null;
- } else {
- $examList[$year][$monthNumb] = ['TAmin'=>null, 'TAmax'=>null, 'FC'=>null];
- }
- }
- }
-
- foreach($examList as $year => $month) {
- $yearMonthList = $examList[$year];
- ksort($yearMonthList);
- $examList[$year] = $yearMonthList;
- }
-
- foreach($examList as $year => $month) {
-
- foreach($month as $monthNumb => $montValue) {
- $dataValues[$year]['TAmin'][] = $montValue['TAmin'];
- $dataValues[$year]['TAmax'][] = $montValue['TAmax'];
- $dataValues[$year]['FC'][] = $montValue['FC'];
- }
- }
-
-
- $examStats = $examList;
-
- }
- }
-
- if (isset($dreamData['Sintomi'])) {
- $symptoms = $dreamData['Sintomi'];
- }
-
- if (isset($dreamData['Diagnosi'])) {
- $diagnosis = $dreamData['Diagnosi'];
- }
-
- if (isset($dreamData['HivStages'])) {
- $HivStages = $dreamData['HivStages'][0] ?? [];
- }
-
- if (isset($dreamData['HivTestHistory'])) {
- $HivTestHistory = $dreamData['HivTestHistory'][0] ?? [];
- }
-
- if (isset($dreamData['TarvHistory'])) {
- $TarvHistory = $this->utility->orderArray($dreamData['TarvHistory'], 'DataInizio', 'desc') ?? [];
- //$TarvHistory = $dreamData['TarvHistory'][0] ?? [];
- }
-
- if (isset($dreamData['ListaFarmaci'])) {
- $ListaFarmaci = $dreamData['ListaFarmaci'];
- }
-
- $dailyData = [];
- if (is_array($daily) && !empty($daily)) {
- foreach($daily as $item) {
- $dailyData[$item['id_event']]['Diaria'] = $item;
-
- foreach($symptoms as $symptom) {
- if ($symptom['id_event'] == $item['id_event']) {
- $dailyData[$item['id_event']]['Sintomi'][] = $symptom;
- }
- }
-
- foreach($diagnosis as $diagnosi) {
- if ($diagnosi['id_event'] == $item['id_event']) {
- $dailyData[$item['id_event']]['Diagnosi'][] = $diagnosi;
- }
- }
- }
- }
-
- $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]);
- }
-
- return $this->setRawJsonResponse('ok', '', ['html'=>$html, 'chartYears'=>$chartYears, 'dataValues'=>$dataValues]);
- }
-
- //Ajax function to update the Medical Specialties per Clinical Center
- public function getSpecialtiesPerCenter() {
- if (!$this->user->isLogged()) {
- return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
- }
-
- $medicalSpecialties = [];
-
- $centerId = $this->getPost('centerId', 0);
- $handleRequest = new HandleRequest();
- $results = $handleRequest->getSpecialtyByClinicalCenterId($centerId, $this->userGroupId);
-
- if (is_array($results)) {
- $c=0;
- foreach($results as $item) {
- $medicalSpecialties[$c]['value'] = $item['id'];
- $medicalSpecialties[$c]['text'] = _($item['description']);
- $c++;
- }
- }
-
- return $this->setRawJsonResponse('ok', '', ['specialties'=>$medicalSpecialties]);
- }
-
- //Ajax function to send message (comment) from Request page
- public function requestSendMessage() {
- if (!$this->user->isLogged()) {
- return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
- }
-
- $handleRequest = new HandleRequest();
- $requestID = $this->getPost('requestID', 0);
- $centerID = $this->getPost('centerID', 0);
- $newStatus = $this->getPost('newStatus', '');
- $message = trim($this->getPost('message', null));
- $specialties = rawurldecode($this->getPost('specialtyList', ''));
- $specialtyList = strpos($specialties, ',') !== false || (int)$specialties > 0 ? explode(',', $specialties) : null;
- $hasAttachments = $this->getPost('hasAttachments', false);
-
- $return = [];
-
- //$buffer = $handleRequest->forwardRequest($requestID, $specialtyList, $this->userGroupId, $this->user->getUserId(), 15);
- //return $this->setRawJsonResponse('err', $buffer, ['log'=>$buffer]);
-
- if ($message == '') {
- return $this->setRawJsonResponse('err', _('The Comment text field cannot be empty.'), ['log'=>[]]);
- }
-
- $id = $this->db->insert('requests_comments', [
- 'request_id' => $requestID,
- 'user_id' => $this->user->getUserId(),
- 'comment' => $message,
- 'comment_guid' => $this->security->getGUID(),
- 'updated_at' => date('Y-m-d H:i:s'),
- 'created_at' => date('Y-m-d H:i:s')
- ]);
-
- if ($id) {
- $comments = $handleRequest->getCommentList($requestID, $centerID, true);
- $request = $this->db->where('id', $requestID)->getOne('requests');
-
- $html = $this->partial('Request/comment-list', ['comments'=>$comments]);
-
- $return['commentID'] = $id;
- $return['html'] = $html;
-
- $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_MSG', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestID]);
-
- //If the user is a referral, increment the comment counter (request_reports_counter table)
- if ($handleRequest->isReferralInRequest($requestID, $this->user->getUserId())) {
-
- //$handleRequest->setLog('position', 'dentro is referral in request');
-
- //Check whether moderator or referral has added new medical specialty and notify new referrals
- if ($handleRequest->forwardRequest($requestID, $specialtyList, $this->userGroupId, $request['user_id'], $request['center_id'])) {
-
- $handleRequest->setRequestStatus($requestID, $handleRequest::REQUEST_STATUS_PART_REPORTED, $this->user->getUserId());
-
- //$handleRequest->setLog('position', 'dentro forward');
-
- } else {
-
- //If previusly reported, just change the status to reported (closed)
- /*if ($handleRequest->isRequestPreviouslyReopened($requestID)) {
-
- $handleRequest->setLog('position', 'dentro is previuosly reopened');
-
- $handleRequest->setRequestStatus($requestID, $handleRequest::REQUEST_STATUS_REPORTED, $this->user->getUserId());
- //Notify the applicant (queue the message)
- $msgStructure = $handleRequest->queueMessage($requestID, $request['user_id'], $request['user_id'], 'PARTIALLY_REPORTED');
- } else {*/
-
- //$handleRequest->setLog('position', 'dentro il commento normale, incrementa il contatore');
-
- //If a referral comments again, doesn't add a new record in the table (see the table indexes)
- $handleRequest->incrementReferralCounter($requestID, $this->user->getUserId());
-
- //Change the request status
- if ($handleRequest->isRequestFullyReported($requestID) === true) {
- $handleRequest->setRequestStatus($requestID, $handleRequest::REQUEST_STATUS_REPORTED, $this->user->getUserId());
- $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_CLOSED_AUTO', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestID]);
- } else {
- $handleRequest->setRequestStatus($requestID, $handleRequest::REQUEST_STATUS_PART_REPORTED, $this->user->getUserId());
- }
-
- //Notify the applicant (queue the message)
- $msgStructure = $handleRequest->queueMessage($requestID, $request['user_id'], $request['user_id'], 'PARTIALLY_REPORTED');
-
- //}
-
- }
-
- }
-
- //TODO: check whether the comment has attachments (visible / not visible)
-
- //Applicant's comment: change the status to REOPENED
- if ($handleRequest->isApplicantInRequest($requestID, $this->user->getUserId())) {
- $handleRequest->setRequestStatus($requestID, $handleRequest::REQUEST_STATUS_REOPENED, $this->user->getUserId());
- $handleRequest->notifyAllReferrals($requestID, 'REQUEST_UPDATE');
- }
-
- //Force the new request status (Moderator)
- if ($newStatus != '') {
- $handleRequest->setRequestStatus($requestID, $newStatus, $this->user->getUserId());
-
- $isFwd = $handleRequest->forwardRequest($requestID, $specialtyList, $this->userGroupId, $request['user_id'], $request['center_id']);
-
- if ($newStatus == 'reopened') {
- //Notifiy all referrals
- $handleRequest->notifyAllReferrals($requestID, 'REQUEST_UPDATE');
- //Notify the applicant
- $handleRequest->queueMessage($requestID, $request['user_id'], $request['user_id'], 'REQUEST_UPDATE_APPLICANT');
- }
-
- if ($newStatus == 'referted') {
- //Notify the applicant
- $handleRequest->queueMessage($requestID, $request['user_id'], $request['user_id'], 'CLOSED_BY_MODERATOR');
- }
-
- $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_STATUS_CNG_MODERATOR', ['userId'=>$this->user->getUserId(), 'newStatus'=>$newStatus]);
- }
-
- //Update last update request field
- $handleRequest->updateDate($requestID);
-
- $return['action'] = 'refresh';
-
- return $this->setRawJsonResponse('ok', '', $return);
-
- } else {
- return $this->setRawJsonResponse('err', _('Unable to send the message right now. Please try again in a few minutes.'), ['log'=>[]]);
- }
-
- }
-
- //Ajax function to load all request comments
- public function requestLoadAllComments() {
- if (!$this->user->isLogged()) {
- return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
- }
-
- $requestID = $this->getPost('requestID', 0);
- $centerID = $this->getPost('centerID', 0);
-
- $comments = $handleRequest->getCommentList($requestID, $centerID, true);
-
- $html = $this->partial('Request/comment-list', ['comments'=>$comments]);
-
- return $this->setRawJsonResponse('ok', '', ['html'=>$html]);
- }
-
- //Ajax function to get the deaseses under a provided ICD10 category
- public function requestGetDeseases() {
- if (!$this->user->isLogged()) {
- return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
- }
-
- if(!$this->checkPermissions([ADMIN_ROLE_ID, APPLICANT_ROLE_ID])) {
- return $this->setRawJsonResponse('err', _('Permission denied.'));
- }
-
- $icd10Id = $this->getPost('icd10Id', null); //Parent category ID
-
- //If Draft mode some deseases could be selected
- $selectedDeseases = $this->getPost('selectedDeseases', []);
-
- $handleRequest = new HandleRequest();
-
- $deseases = $handleRequest->getDeseasesByICD10Category($icd10Id, $this->user->getUserLang(), $selectedDeseases);
-
- $html = $this->partial('Request/icd10-deseases-list', ['deseases'=>$deseases, 'checked'=>false]);
-
- return $this->setRawJsonResponse('ok', '', ['html'=>$html]);
- }
-
- public function requestSearchDesease() {
- if (!$this->user->isLogged()) {
- return $this->setRawJsonResponse('ok', '', ['html'=>'']);
- }
-
- if(!$this->checkPermissions([ADMIN_ROLE_ID, APPLICANT_ROLE_ID])) {
- return $this->setRawJsonResponse('ok', '', ['html'=>'']);
- }
-
- $handleRequest = new HandleRequest();
- $keyword = addslashes($this->getPost('keyword', null));
- $langCode = $this->getPost('lang', 'en');
- $selectedDeseases = $this->getPost('selectedDeseases', []);
-
- $deseases = $handleRequest->getDeseaseByKeyword($keyword, $langCode, $selectedDeseases);
-
- $html = $this->partial('Request/icd10-search-deseases-list', ['deseases'=>$deseases, 'langCode'=>$langCode]);
-
- return $this->setRawJsonResponse('ok', '', ['html'=>$html]);
- }
-
- //Ajax function to get all attachs by post code (used to render the attachs list after an Ajax call)
- public function requestAttachs() {
- if (!$this->user->isLogged()) {
- return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
- }
-
- if(!$this->checkPermissions([ADMIN_ROLE_ID, MODERATOR_ROLE_ID, APPLICANT_ROLE_ID])) {
- return $this->setRawJsonResponse('err', _('Permission denied.'));
- }
-
- $postCode = $this->getPost('postCode', null);
- $attachs = [];
- $request = null;
-
- if(!is_null($postCode)) {
- $request = $this->db
- ->where('r.unique_code', $postCode)
- ->join('requests_attachments ra', 'ra.request_id=r.id', 'INNER')
- ->get('requests r', null, ['ra.id attach_id', 'ra.file_name attach_name', 'ra.file_title attach_title', 'ra.file_ext attach_ext']);
-
- if (is_array($request)) {
-
- foreach($request as $index => $item) {
- $ext = trim($item['attach_ext']) != '' ? $item['attach_ext'] : pathinfo($item['attach_name'], PATHINFO_EXTENSION);
-
- $attachs[$index]['forceDownload'] = !in_array($ext, $this->config['settings']['preview-ext']) ? 1 : 0;
- $attachs[$index]['ext'] = $ext;
- $attachs[$index]['id'] = $item['attach_id'];
- $attachs[$index]['name'] = $item['attach_name'];
- $attachs[$index]['title'] = $this->helper->truncate($item['attach_title'], MAX_ATTACH_TITLE_LENGTH, '...'.$item['attach_ext']); }
- }
- }
-
- return $this->setRawJsonResponse('ok', '', ['attachData'=>$attachs]);
- }
-
- //Ajax function to delete the passed attachment id
- public function requestDeleteAttach() {
- if (!$this->user->isLogged()) {
- return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
- }
-
- if(!$this->checkPermissions([ADMIN_ROLE_ID, APPLICANT_ROLE_ID])) {
- return $this->setRawJsonResponse('err', _('Permission denied.'));
- }
-
- $attachId = $this->getPost('attachId', null);
- $attachName = $this->getPost('attachName', null);
- $delete = false;
-
- if (!is_null($attachId) && !is_null($attachName)) {
- $delete = $this->db->where('id', $attachId)->delete('requests_attachments');
- @unlink(ATTACH_DIR.$attachName);
- }
-
- if ($delete) {
- return $this->setRawJsonResponse('ok', '', ['attachId'=>$attachId]);
- } else {
- return $this->setRawJsonResponse('ok', '', ['attachId'=>0]);
- }
- }
-
- //Ajax function to delete the request by id
- public function requestDelete() {
- if (!$this->user->isLogged()) {
- return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
- }
-
- if(!$this->checkPermissions([APPLICANT_ROLE_ID, MODERATOR_ROLE_ID])) {
- return $this->setRawJsonResponse('err', _('Permission denied.'));
- }
-
- $scope = $this->user->is(APPLICANT_ROLE_ID) ? 'my' : 'moderations';
-
- $requestId = $this->getPost('requestId', 0);
-
- $handleRequest = new HandleRequest();
-
- $return = $handleRequest->deleteRequest($requestId);
-
- if ($return) {
- $handleRequest->setActivityLog($this->user->getUserId(), 'REQ_DELETED', ['userId'=>$this->user->getUserId(), 'requestId'=>$requestId]);
- return $this->setRawJsonResponse('ok', '', ['redirect'=>'requests/'.time().'/'.$scope.'/created_at/desc/1']);
- } else {
- return $this->setRawJsonResponse('err', _('Unable to delete the request right now, please try again in a few minutes.'));
- }
- }
-
- public function getRequestResponders() {
- if (!$this->user->isLogged()) {
- return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
- }
-
- if(!$this->checkPermissions([MODERATOR_ROLE_ID])) {
- return $this->setRawJsonResponse('err', _('Permission denied.'));
- }
-
- $handleRequest = new HandleRequest();
-
- $requestId = $this->getPost('requestId', 0);
-
- $recipients = $handleRequest->getRecipientsByRequestId($requestId);
-
- $html = $this->partial('Request/show-responders-list', ['recipients'=>$recipients]);
-
- return $this->setRawJsonResponse('ok', '', ['html'=>$html]);
- }
-
- //Activity log page
- public function logs() {
- if (!$this->user->isLogged()) {
- return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
- }
-
- if(!$this->checkPermissions([ADMIN_ROLE_ID])) {
- return $this->setRawJsonResponse('err', _('Permission denied.'));
- }
-
- $this->view->users = $this->db
- ->where('status', 1)
- ->where('group_id', $this->userGroupId)
- ->orderBy('surname', 'asc')
- ->get('users', null, ['id', 'username', 'name', 'surname']);
-
- $this->view->requests = $this->db
- ->where('u.status', 1)
- ->where('u.group_id', $this->userGroupId)
- ->join('users u', 'u.id=r.user_id', 'INNER')
- ->orderBy('r.created_at', 'desc')
- ->get('requests r', 100, ['r.id', 'r.created_at']);
-
- $this->actionTitle = _('Activity logs');
- return $this->setJsonView('logs');
- }
-
- //Sending Referral list preview (in a modal)
- public function requestPreview() {
- if (!$this->user->isLogged()) {
- return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
- }
-
- if(!$this->checkPermissions([ADMIN_ROLE_ID, APPLICANT_ROLE_ID])) {
- return $this->setRawJsonResponse('err', _('Permission denied.'));
- }
-
- $data = isset($_POST['data']) ? $_POST['data'] : null;
-
- $this->view->data = $data;
- $this->view->error = '';
- $userCount = 0;
- $request = new HandleRequest();
-
- $recipientList = $data['request_referral_list']['value'];
-
- if (!is_array($recipientList)) {
- if (!is_array($data['referral_ms']['value'])) {
- $this->view->error = _('Please provide at least one Responder Medical for this request.');
- return $this->setJsonView('requestPreview', true, '', ['userCount'=>$userCount]);
- }
-
- /*if (!is_array($data['referral_cc']['value'])) {
- $this->view->error = _('Please provide at least one Responder Clinical Center.');
- return $this->setJsonView('requestPreview', true, '', ['userCount'=>$userCount]);
- }
- */
-
- if (!is_array($data['referral_langs']['value'])) {
- $this->view->error = _('Please provide at least one Default Language for this request.');
- return $this->setJsonView('requestPreview', true, '', ['userCount'=>$userCount]);
- }
- }
-
- $referralMs = $data['referral_ms']['value'];
- $referralCc = isset($data['referral_cc']['value']) && !empty($data['referral_cc']['value']) ? $data['referral_cc']['value'] : null;
- $referralLangs = $data['referral_langs']['value'];
- $referralVisibility = $data['referral_ms']['referral_visibility'];
-
- //Recipients preview
- $this->view->referrals = $request->getRecipients([
- 'recipientList' => $recipientList,
- 'ms' => $referralMs,
- 'cc' => $referralCc,
- 'langs' => $referralLangs
- ]);
-
- $userCount = count($this->view->referrals);
-
- return $this->setJsonView('requestPreview', true, '', ['userCount'=>$userCount]);
- }
-
- public function generatePDF() {
- if (!$this->user->isLogged()) {
- return $this->setRawJsonResponse('err', _('Session expired, please log in again.'), [], ['button'=>'login']);
- }
-
- $context = $this->getPost('context');
- $operation = $this->getPost('operation');
- $htmlContent = '';
- $outputFilePath = '';
- $fileTitle = 'print_preview';
- $pdf = new PdfPrinter();
- $layout = new Layout();
- $destinationDir = DATA_TMP_DIR;
-
- $printFileURI = $this->config['settings']['http-protocol'].$this->config['settings']['site-domain'].'/print/';
-
- switch($context) {
-
- case 'requestview':
- $_POST['requestID'] = $this->getPost('requestId');
- $_POST['viewType'] = 'view';
- $this->requestEdit();
-
- // footer dinamico
- $headerURI = $printFileURI.'header-default.php?center_description='.rawurlencode($this->view->requestData['center_description'])
- .'¢er_continent='.rawurlencode($this->view->requestData['center_continent']).'¢er_country='.rawurlencode($this->view->requestData['center_country']).'¢er_address='.rawurlencode($this->view->requestData['center_address'])
- .'&companies_title='.rawurlencode($this->view->companies['title'])
- .'&head_title='._('Multidisciplinary teleconsultation service')
- .'&app_report_header='.$this->config['settings']['app-report-header'].'';
- $footerURI = $printFileURI.'footer-default.php?teleconsulto='.rawurlencode($this->actionTitle).'&paziente='.$this->view->requestData['patient_surname'].' '.$this->view->requestData['patient_name']
- .'&request_date='.$this->view->requestData['created_at'].'&patient='._('Patient_pdf').'&request_date_txt='._('Request date').'&print_date_txt='._('Print date')
- .'&request_date='.$this->view->requestData['created_at'].'';
-
- $htmlContent = $this->partial('Print/request-view', ['publicUri'=>$layout->getPublicUri()]);
- $outputFilePath = $destinationDir.'request_'.$this->user->getUserId().'.pdf';
- $fileTitle = 'request_'.$this->view->requestData['id'];
- break;
-
- }
-
- //Pass the HTML to $pdf object
- $pdfContent = $pdf->convertHtmlToPdf($htmlContent, $headerURI, $footerURI);
-
- //file_put_contents($destinationDir.'html.html', $htmlContent);
- file_put_contents($outputFilePath, $pdfContent);
-
- if ($operation == 'print') {
- return $this->setRawJsonResponse('ok', '', ['outputFilePath'=>$outputFilePath, 'fileTitle'=>$fileTitle,'debug'=>$this->view->companies]);
- } else {
-
- $hr = new HandleRequest();
- $request_id = $this->getPost('requestId');
- $attach_ids = $this->getPost('attach_ids');
- $delay = $this->getPost('delay', null);
- $delay_date = $this->utility->setDateToIsoFormat($delay);
- $attachs = [];
-
- //return $this->setRawJsonResponse('err', '-'.strlen($delay).'-');
-
- if (strlen($delay) > 0 && is_null($delay_date)) {
- return $this->setRawJsonResponse('err', "Impossibile concludere l'operazione, la data di spedizione deve essere indicata nel formato gg/mm/aaaa.");
- }
-
- if (!is_null($delay_date) && $this->utility->isDateInThePast($delay_date)) {
- return $this->setRawJsonResponse('err', "La data di spedizione non può essere corrente o nel passato.");
- }
-
- $survey = $this->db->where('request_id', $request_id)->getOne('sportellocura');
-
- if (isset($survey['survey_id']) || trim($this->view->requestData['cgemail']) != '') {
-
- $survey_data = json_decode($survey['survey_data'], true);
- $attachs_data = [];
-
- if (isset($survey['survey_id'])) {
- $recipient_email = $survey_data['email'];
- $recipient_name = $survey_data['name'];
- $recipient_surname = $survey_data['surname'];
- $mailcode = 'SURVEY_'.uniqid();
- $survey_id = $survey['survey_id'];
- } else {
- $recipient_email = trim($this->view->requestData['cgemail']);
- $recipient_name = '';
- $recipient_surname = trim($this->view->requestData['cgnamesurname']) != '' ? trim($this->view->requestData['cgnamesurname']) : 'Paziente';
- $mailcode = 'REPORT_'.uniqid();
- $survey_id = 0;
- }
-
- //$recipient_email = 'agodegi@gmail.com';
-
-
- if ($this->utility->validateEmail($recipient_email)) {
-
- if (is_array($attach_ids) && !empty($attach_ids)) {
- $attach_id_list = implode(',', $attach_ids);
- $attachs = $this->db->where("id IN($attach_id_list)")->get('requests_attachments');
-
- if (is_array($attachs) && !empty($attachs)) {
- foreach($attachs as $index => $attach) {
- $attachs_data[$index]['path'] = ATTACH_DIR.$attach['file_name'];
- $attachs_data[$index]['name'] = $attach['file_title'].'.'.$attach['file_ext'];
- }
- }
- }
-
- $pdf_path = ATTACH_DIR.$request_id.'.pdf';
- rename($outputFilePath, $pdf_path);
-
- //////
- $attachs_data[] = ['path'=>$pdf_path, 'name'=>'Risposta-Specialista.pdf'];
-
- $subject = 'Risposta del TeleAmbulatorio';
- $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>
- Cordiali Saluti,<br>Servizio di TeleAmbulatorio";
-
- //$nf = new Notification();
- //$mailcode = 'SURVEY_'.uniqid();
- //$nf->sendEmail($recipient_email, $subject, $body, $mailcode, [], $attachs_data);*/
- //////
-
- $hr->insertMsgInQueue([
- 'senderId' => $this->user->getUserId(),
- 'recipientId' => $this->user->getUserId(), //L'utente corrente deve avere l'invio delle email attivato
- 'requestId' => $request_id,
- 'mailId' => $mailcode,
- 'subject' => $subject,
- 'content' => $body,
- 'type' => 'email',
- 'recipient' => $recipient_email,
- 'senderStatus' => 1,
- 'attachments' => json_encode($attachs_data),
- 'delay' => $delay_date
- ]);
-
- //Log
- $this->db->insert('sportellocura_log', [
- 'request_id'=>$request_id,
- 'survey_id'=>$survey_id,
- 'mail_code'=>$mailcode,
- 'created_at'=>date('Y-m-d H:i:s')
- ]);
-
- $this->notifySendPdf($survey['survey_id']);
-
- return $this->setRawJsonResponse('ok', 'PDF inviato correttamente', ['log'=>null], ['button'=>'refresh-hash']);
-
- } else {
- return $this->setRawJsonResponse('err', _('Not valid recipient e-mail address'));
- }
-
- }
-
- //Send PDF
- return $this->setRawJsonResponse('err', _('Not valid request'));
- }
- }
-
- public function deleteSurveyMailQueue() {
- $mail_id = $this->getPost('mail_id', null);
- $request_id = $this->getPost('request_id', 0);
-
- $this->db
- ->where('request_id', $request_id)
- ->where('mail_id', $mail_id)
- ->delete('requests_messages_queue');
-
- return $this->setRawJsonResponse('ok', 'Il tentativo di cancellazione della ricezione programmata è stato eseguito con successo.');
- }
-
- public function getCitiesByProvince() {
- $province_id = $this->getPost('province_id', 0);
- $selected_city_id = $this->getPost('selected_city_id', 0);
- $options = ['<option value="0">...</option>'];
- $html = '';
-
- $cities = $this->db->where('province_id', $province_id)->orderBy('name', 'ASC')->get('italian_cities');
- if (is_array($cities) && !empty($cities)) {
- foreach($cities as $city) {
- $selected = $city['id'] == $selected_city_id ? 'selected' : '';
- $options[] = '<option value="'.$city['id'].'" '.$selected.'>'.$city['name'].'</option>';
- }
-
- $html = implode("\n", $options);
- }
-
-
- return $this->setRawJsonResponse('ok', '', ['html'=>$html]);
- }
-
- private function notifySendPdf($survey_id=0) {
- $endpoint = $this->config['settings']['sportellocura']['api']['endpoint'];
- $apikey = $this->config['settings']['sportellocura']['api']['key'];
- $vars = ['survey_id'=>$survey_id, 'cmd'=>'notify-pdf'];
-
- if ($survey_id < 1) return;
-
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $endpoint);
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_USERPWD, "dev:demo");
- curl_setopt($ch, CURLOPT_POSTFIELDS, $vars); //Post Fields
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
- curl_setopt($ch, CURLOPT_TIMEOUT, 30);
-
- $headers = [
- 'Api-Key: '.$apikey,
- ];
-
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
-
- $data = curl_exec($ch);
- //$output = json_decode($data, true);
-
- curl_close($ch);
-
- return $data;
- }
-
- public function getSportelloCura() {
- $endpoint = $this->config['settings']['sportellocura']['api']['endpoint'];
- $apikey = $this->config['settings']['sportellocura']['api']['key'];
- $survey_id = $this->getPost('survey_id', 0);
- $vars = ['survey_id'=>$survey_id, 'cmd'=>'get-survey'];
-
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $endpoint);
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_USERPWD, "dev:demo");
- curl_setopt($ch, CURLOPT_POSTFIELDS, $vars); //Post Fields
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
-
- $headers = [
- 'Api-Key: '.$apikey,
- ];
-
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
-
- $data = curl_exec($ch);
- $output = json_decode($data, true);
-
- curl_close($ch);
-
- $type_id = isset($output['survey']['type_id']) ? (int)$output['survey']['type_id'] : 0;
-
- $output['survey']['ms'] = 0;
-
- if ($type_id > 0) {
- $ms = $this->db->where('sportello_type_id', $type_id)->getOne('users_medical_specialties');
- if (isset($ms['id']) && (int)$ms['id']>0) {
- $output['survey']['ms'] = $ms['id'];
- }
- }
-
- return $this->setRawJsonResponse('ok', '', ['output'=>$output]);
- }
-
- public function getDreamItaly() {
-
- $endpoint = $this->config['settings']['api']['endpoint'];
- $apikey = $this->config['settings']['api']['key'];
- $code = $this->getPost('code', 0);
- $vars = ['request_id'=>$code];
-
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $endpoint);
- curl_setopt($ch, CURLOPT_POST, 1);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $vars); //Post Fields
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
-
- $headers = [
- 'Api-Key: '.$apikey,
- ];
-
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
-
- $data = curl_exec($ch);
-
- $output = json_decode($data, true);
-
- $output['r_citta_lcl_id'] = 0;
-
- $output['r_provincia_lcl_id'] = 0;
-
- curl_close ($ch);
-
- return $this->setRawJsonResponse('ok', '', ['output'=>$output]);
-
- }
-
- public function setViewerType() {
- $checked_value = $this->getPost('checked_value', -1);
- $user_id = $this->user->getUserId();
-
- if ((int)$checked_value > -1) {
- //$updt = $this->db->where('id', $user_id)->update('users', ['simple_viewer'=>$checked_value]);
- $updt = 0;
- }
-
- return $this->setRawJsonResponse('ok', '', ['output'=>$updt]);
- }
-
- public function allowAccess() {
- if (!$this->user->isLogged()) {
- return $this->redirect('login', 'index');
- }
-
- return false;
- }
- }
|