HomeController.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Lib\Backend;
  4. use App\Models\Appointment;
  5. use App\Models\AppSession;
  6. use App\Models\ClientSMS;
  7. use App\Models\Facility;
  8. use App\Models\IncomingReport;
  9. use App\Models\MBPayer;
  10. use App\Models\ProProAccess;
  11. use App\Models\SupplyOrder;
  12. use App\Models\Ticket;
  13. use DateTime;
  14. use App\Models\Client;
  15. use App\Models\Bill;
  16. use App\Models\Measurement;
  17. use App\Models\Note;
  18. use App\Models\Pro;
  19. use App\Models\ProTransaction;
  20. use GuzzleHttp\Cookie\CookieJar;
  21. use Illuminate\Http\Request;
  22. use Illuminate\Support\Facades\Cookie;
  23. use Illuminate\Support\Facades\DB;
  24. use Illuminate\Support\Facades\Http;
  25. class HomeController extends Controller
  26. {
  27. public function confirmSmsAuthToken(Request $request)
  28. {
  29. return view('app/confirm_sms_auth_token');
  30. }
  31. public function setPassword(Request $request)
  32. {
  33. return view('app/set_password');
  34. }
  35. public function setSecurityQuestions(Request $request)
  36. {
  37. return view('app/set_security_questions');
  38. }
  39. public function postConfirmSmsAuthToken(Request $request)
  40. {
  41. try {
  42. $url = config('stag.backendUrl') . '/session/confirmSmsAuthToken';
  43. $data = [
  44. 'cellNumber' => $request->input('cellNumber'),
  45. 'token' => $request->input('token'),
  46. ];
  47. $response = Http::asForm()
  48. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  49. ->post($url, $data)
  50. ->json();
  51. if (!isset($response['success']) || !$response['success']) {
  52. $message = 'API error';
  53. if (isset($response['error'])) {
  54. $message = $response['error'];
  55. if (isset($response['path'])) $message .= ': ' . $response['path'];
  56. } else if (isset($response['message'])) $message = $response['message'];
  57. return redirect('/confirm_sms_auth_token')
  58. ->withInput()
  59. ->with('message', $message);
  60. }
  61. return redirect('/');
  62. } catch (\Exception $e) {
  63. return redirect()->back()
  64. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  65. ->withInput($request->input());
  66. }
  67. }
  68. public function resendSmsAuthToken(Request $request)
  69. {
  70. try {
  71. $url = config('stag.backendUrl') . '/session/resendSmsAuthToken';
  72. $data = [];
  73. $response = Http::asForm()
  74. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  75. ->post($url, $data)
  76. ->json();
  77. if (!isset($response['success']) || !$response['success']) {
  78. $message = 'API error';
  79. if (isset($response['error'])) {
  80. $message = $response['error'];
  81. if (isset($response['path'])) $message .= ': ' . $response['path'];
  82. } else if (isset($response['message'])) $message = $response['message'];
  83. return redirect('/confirm_sms_auth_token')
  84. ->withInput()
  85. ->with('message', $message);
  86. }
  87. return redirect()->back()->withInput()->with('message', "SMS Auth Token sent.");
  88. } catch (\Exception $e) {
  89. return redirect()->back()
  90. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  91. ->withInput($request->input());
  92. }
  93. }
  94. public function postSetPassword(Request $request)
  95. {
  96. try {
  97. $url = config('stag.backendUrl') . '/pro/selfPutPassword';
  98. $data = [
  99. 'newPassword' => $request->input('newPassword'),
  100. 'newPasswordConfirmation' => $request->input('newPasswordConfirmation'),
  101. ];
  102. $response = Http::asForm()
  103. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  104. ->post($url, $data)
  105. ->json();
  106. if (!isset($response['success']) || !$response['success']) {
  107. $message = 'API error';
  108. if (isset($response['error'])) {
  109. $message = $response['error'];
  110. if (isset($response['path'])) $message .= ': ' . $response['path'];
  111. } else if (isset($response['message'])) $message = $response['message'];
  112. return redirect('/set_password')
  113. ->withInput()
  114. ->with('message', $message);
  115. }
  116. return redirect('/');
  117. } catch (\Exception $e) {
  118. return redirect()->back()
  119. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  120. ->withInput($request->input());
  121. }
  122. }
  123. public function postSetSecurityQuestions(Request $request)
  124. {
  125. try {
  126. $url = env('BACKEND_URL', 'http://localhost:8080/api') . '/pro/selfPutSecurityQuestions';
  127. $data = [
  128. 'securityQuestion1' => $request->input('securityQuestion1'),
  129. 'securityAnswer1' => $request->input('securityAnswer1'),
  130. 'securityQuestion2' => $request->input('securityQuestion2'),
  131. 'securityAnswer2' => $request->input('securityAnswer2'),
  132. ];
  133. $response = Http::asForm()
  134. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  135. ->post($url, $data)
  136. ->json();
  137. if (!isset($response['success']) || !$response['success']) {
  138. $message = 'API error';
  139. if (isset($response['error'])) {
  140. $message = $response['error'];
  141. if (isset($response['path'])) $message .= ': ' . $response['path'];
  142. } else if (isset($response['message'])) $message = $response['message'];
  143. return redirect('/set_password')
  144. ->withInput()
  145. ->with('message', $message);
  146. }
  147. return redirect('/');
  148. } catch (\Exception $e) {
  149. return redirect()->back()
  150. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  151. ->withInput($request->input());
  152. }
  153. }
  154. public function dashboard(Request $request)
  155. {
  156. //patients where performer is the mcp
  157. $performer = $this->performer();
  158. $performerProID = $performer->pro->id;
  159. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  160. $keyNumbers = [];
  161. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  162. $keyNumbers['totalPatients'] = $queryClients->count();
  163. // patientNotSeenYet
  164. $patientNotSeenYet = $queryClients
  165. ->where(function ($query) use ($performer) { // own patient and primary OB visit pending
  166. $query->where('mcp_pro_id', $performer->pro->id)
  167. ->where('has_mcp_done_onboarding_visit', '!=', 'YES');
  168. })
  169. ->orWhere(function ($query) { // mcp of any client program and program OB pending
  170. $query->where(function ($_query) {
  171. $_query->select(DB::raw('COUNT(id)'))
  172. ->from('client_program')
  173. ->whereColumn('client_id', 'client.id')
  174. ->where('has_mcp_done_onboarding_visit', '!=', 'YES');
  175. }, '>=', 1);
  176. })->count();
  177. $keyNumbers['patientsNotSeenYet'] = $patientNotSeenYet;
  178. $pendingBillsToSign = Bill::where(function ($query) use ($performerProID) {
  179. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false);
  180. })
  181. ->orWhere(function ($query) use ($performerProID) {
  182. $query->where('cm_pro_id', $performerProID)->where('is_signed_by_cm', false)->where('is_cancelled', false);;
  183. })->orWhere(function ($query) use ($performerProID) {
  184. $query->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false)->where('is_cancelled', false);;
  185. })->orWhere(function ($query) use ($performerProID) {
  186. $query->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false)->where('is_cancelled', false);;
  187. })->count();
  188. $keyNumbers['pendingBillsToSign'] = $pendingBillsToSign;
  189. $pendingNotesToSign = Note::where(function ($query) use ($performerProID) {
  190. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false);;
  191. })
  192. ->orWhere(function ($query) use ($performerProID) {
  193. $query->where('ally_pro_id', $performerProID)->where('is_signed_by_ally', false)->where('is_cancelled', false);;
  194. })->count();
  195. $keyNumbers['pendingNotesToSign'] = $pendingNotesToSign;
  196. // open tickets
  197. $keyNumbers['numOpenTickets'] = Ticket::where('is_open', true)
  198. ->where(function ($q) use ($performerProID) {
  199. $q->where('assigned_pro_id', $performerProID)
  200. ->orWhere('manager_pro_id', $performerProID)
  201. ->orWhere('ordering_pro_id', $performerProID)
  202. ->orWhere('initiating_pro_id', $performerProID);
  203. })
  204. ->count();
  205. // num measurements that need stamping
  206. $keyNumbers['measurementsToBeStamped'] = ($this->performer()->pro->pro_type === 'ADMIN' ? '-' : count($this->performer()->pro->getMeasurements(true)));
  207. // unacknowledged cancelled bills for authed pro
  208. $keyNumbers['unacknowledgedCancelledBills'] = Bill::where('hcp_pro_id', $performerProID)
  209. ->where('is_cancelled', true)
  210. ->where('is_cancellation_acknowledged', false)
  211. ->count();
  212. // patientsHavingBirthdayToday
  213. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  214. $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
  215. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  216. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
  217. ->count();
  218. $reimbursement = [];
  219. $reimbursement["currentBalance"] = $performer->pro->balance;
  220. $reimbursement["nextPaymentDate"] = '--';
  221. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  222. if ($lastPayment) {
  223. $reimbursement["lastPayment"] = $lastPayment->amount;
  224. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  225. } else {
  226. $reimbursement["lastPayment"] = '--';
  227. $reimbursement["lastPaymentDate"] = '--';
  228. }
  229. //if today is < 15th, next payment is 15th, else nextPayment is
  230. $today = strtotime(date('Y-m-d'));
  231. $todayDate = date('j', $today);
  232. $todayMonth = date('m', $today);
  233. $todayYear = date('Y', $today);
  234. if ($todayDate < 15) {
  235. $nextPaymentDate = new DateTime();
  236. $nextPaymentDate->setDate($todayYear, $todayMonth, 15);
  237. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  238. } else {
  239. $nextPaymentDate = new \DateTime();
  240. $lastDayOfMonth = date('t', $today);
  241. $nextPaymentDate->setDate($todayYear, $todayMonth, $lastDayOfMonth);
  242. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  243. }
  244. //expectedPay
  245. $expectedForHcp = DB::select(DB::raw("SELECT coalesce(SUM(hcp_expected_payment_amount),0) as expected_pay FROM bill WHERE hcp_pro_id = :performerProID AND has_hcp_been_paid = false AND is_signed_by_hcp IS TRUE AND is_cancelled = false"), ['performerProID' => $performerProID])[0]->expected_pay;
  246. $expectedForCm = DB::select(DB::raw("SELECT coalesce(SUM(cm_expected_payment_amount),0) as expected_pay FROM bill WHERE cm_pro_id = :performerProID AND has_cm_been_paid = false AND is_signed_by_cm IS TRUE AND is_cancelled = false"), ['performerProID' => $performerProID])[0]->expected_pay;
  247. $expectedForRme = DB::select(DB::raw("SELECT coalesce(SUM(rme_expected_payment_amount),0) as expected_pay FROM bill WHERE rme_pro_id = :performerProID AND has_rme_been_paid = false AND is_signed_by_rme IS TRUE AND is_cancelled = false"), ['performerProID' => $performerProID])[0]->expected_pay;
  248. $expectedForRmm = DB::select(DB::raw("SELECT coalesce(SUM(rmm_expected_payment_amount),0) as expected_pay FROM bill WHERE rmm_pro_id = :performerProID AND has_rmm_been_paid = false AND is_signed_by_rmm IS TRUE AND is_cancelled = false"), ['performerProID' => $performerProID])[0]->expected_pay;
  249. $expectedForNa = DB::select(DB::raw("SELECT coalesce(SUM(na_expected_payment_amount),0) as expected_pay FROM bill WHERE na_pro_id = :performerProID AND has_na_been_paid = false AND is_signed_by_hcp IS TRUE AND is_cancelled = false"), ['performerProID' => $performerProID])[0]->expected_pay;
  250. $totalExpectedAmount = $expectedForHcp + $expectedForCm + $expectedForRme + $expectedForRmm + $expectedForNa;
  251. $reimbursement['nextPaymentAmount'] = $totalExpectedAmount;
  252. $milliseconds = strtotime(date('Y-m-d')) . '000';
  253. $measurements = $performer->pro->getMeasurements();
  254. // bills & claims
  255. $businessNumbers = [];
  256. // Notes with bills to resolve
  257. $businessNumbers['notesWithBillsToResolve'] = Note::where('is_cancelled', '!=', true)
  258. ->where('is_bill_closed', '!=', true)
  259. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND is_cancelled = false AND is_verified = false) > 0')
  260. ->count();
  261. // Notes pending bill closure
  262. $businessNumbers['notesPendingBillingClosure'] = Note::where('is_cancelled', '!=', true)
  263. ->where('is_bill_closed', '!=', true)
  264. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND (is_cancelled = true OR is_verified = true)) = 0')
  265. ->count();
  266. // incoming reports not signed
  267. $incomingReports = IncomingReport::where('hcp_pro_id', $performerProID)
  268. ->where('has_hcp_pro_signed', false)
  269. ->where('is_entry_error', false)
  270. ->orderBy('created_at', 'ASC')
  271. ->get();
  272. // erx, labs & imaging that are not closed
  273. $tickets = Ticket::where('ordering_pro_id', $performerProID)
  274. ->where('is_entry_error', false)
  275. ->where('is_open', true)
  276. ->orderBy('created_at', 'ASC')
  277. ->get();
  278. $supplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  279. ->where('is_cancelled', false)
  280. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  281. ->orderBy('created_at', 'ASC')
  282. ->get();
  283. $numERx = Ticket::where('ordering_pro_id', $performerProID)
  284. ->where('category', 'erx')
  285. ->where('is_entry_error', false)
  286. ->where('is_open', true)
  287. ->count();
  288. $numLabs = Ticket::where('ordering_pro_id', $performerProID)
  289. ->where('category', 'lab')
  290. ->where('is_entry_error', false)
  291. ->where('is_open', true)
  292. ->count();
  293. $numImaging = Ticket::where('ordering_pro_id', $performerProID)
  294. ->where('category', 'imaging')
  295. ->where('is_entry_error', false)
  296. ->where('is_open', true)
  297. ->count();
  298. $numSupplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  299. ->where('is_cancelled', false)
  300. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  301. ->count();
  302. return view('app/dashboard', compact('keyNumbers', 'reimbursement', 'milliseconds', 'measurements', 'businessNumbers',
  303. 'incomingReports', 'tickets', 'supplyOrders',
  304. 'numERx', 'numLabs', 'numImaging', 'numSupplyOrders'));
  305. }
  306. public function dashboardAppointments(Request $request, $from, $to) {
  307. $performer = $this->performer();
  308. $performerProID = $performer->pro->id;
  309. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  310. $appointments = Appointment::where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  311. if(!$isAdmin) {
  312. $appointments = $appointments->where("pro_id", $performerProID);
  313. }
  314. $appointments = $appointments
  315. ->orderBy('start_time', 'asc')
  316. ->get();
  317. foreach ($appointments as $appointment) {
  318. $date = explode(" ", $appointment->start_time)[0];
  319. $appointment->milliseconds = strtotime($date) . '000';
  320. $appointment->newStatus = $appointment->status;
  321. $appointment->dateYMD = date('Y-m-d', strtotime($appointment->raw_date));
  322. $appointment->clientName = $appointment->client->displayName();
  323. $appointment->clientInitials = substr($appointment->client->name_first, 0, 1) . substr($appointment->client->name_last, 0, 1);
  324. $appointment->proInitials = substr($appointment->pro->name_first, 0, 1) . substr($appointment->pro->name_last, 0, 1);
  325. $appointment->friendlyStartTime = friendly_time($appointment->raw_start_time);
  326. $appointment->friendlyEndTime = friendly_time($appointment->raw_end_time);
  327. $appointment->clientSummary = friendly_date_time($appointment->client->dob, false) . ' (' .
  328. $appointment->client->age_in_years . ' y.o' .
  329. ($appointment->client->sex ? ' ' . $appointment->client->sex : '') .
  330. ')';
  331. $appointment->started = false;
  332. $appointment->inHowManyHours = date_diff(date_create('now'), date_create($appointment->start_time), false)
  333. ->format('%R%h h, %i m');
  334. if ($appointment->inHowManyHours[0] === '-') {
  335. $appointment->inHowManyHours = substr($appointment->inHowManyHours, 1) . ' ago';
  336. $appointment->started = true;
  337. } else {
  338. $appointment->inHowManyHours = 'Appt. in ' . substr($appointment->inHowManyHours, 1);
  339. }
  340. $appointment->clientUid = $appointment->client->uid;
  341. $appointment->proUid = $appointment->pro->uid;
  342. $appointment->proName = $appointment->pro->displayName();
  343. unset($appointment->client);
  344. unset($appointment->pro);
  345. unset($appointment->detail_json);
  346. }
  347. return json_encode($appointments);
  348. }
  349. public function dashboardMeasurements(Request $request, $filter) {
  350. $measurements = $this->performer()->pro->getMeasurements($filter === 'NEED_ACK');
  351. return json_encode($measurements);
  352. }
  353. public function patients(Request $request, $filter = '')
  354. {
  355. $performer = $this->performer();
  356. $query = $performer->pro->getAccessibleClientsQuery();
  357. switch ($filter) {
  358. case 'not-yet-seen':
  359. $query = $query
  360. ->where(function ($query) use ($performer) {
  361. $query
  362. ->where(function ($query) use ($performer) { // own patient and primary OB visit pending
  363. $query->where('mcp_pro_id', $performer->pro->id)
  364. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  365. })
  366. ->orWhere(function ($query) use ($performer) { // mcp of any client program and program OB pending
  367. $query->select(DB::raw('COUNT(id)'))
  368. ->from('client_program')
  369. ->whereColumn('client_id', 'client.id')
  370. ->where('mcp_pro_id', $performer->pro->id)
  371. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  372. }, '>=', 1);
  373. });
  374. break;
  375. case 'having-birthday-today':
  376. $query = $query
  377. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  378. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')]);
  379. break;
  380. // more cases can be added as needed
  381. default:
  382. break;
  383. }
  384. $patients = $query->orderBy('id', 'desc')->paginate(50);
  385. return view('app/patients', compact('patients', 'filter'));
  386. }
  387. public function patientsSuggest(Request $request)
  388. {
  389. $pro = $this->pro;
  390. $term = $request->input('term') ? trim($request->input('term')) : '';
  391. if (empty($term)) return '';
  392. $clientQuery= Client::where(function ($q) use ($term) {
  393. $q->where('name_first', 'ILIKE', '%' . $term . '%')
  394. ->orWhere('name_last', 'ILIKE', '%' . $term . '%')
  395. ->orWhere('cell_number', 'ILIKE', '%' . $term . '%');
  396. });
  397. if($pro->pro_type != 'ADMIN') {
  398. $clientQuery->where(function ($q) use ($pro) {
  399. $q->whereIn('id', $pro->getMyClientIds())
  400. ->orWhereNull('mcp_pro_id');
  401. });
  402. }
  403. $clients = $clientQuery->get();
  404. return view('app/patient-suggest', compact('clients'));
  405. }
  406. public function pharmacySuggest(Request $request)
  407. {
  408. $term = $request->input('term') ? trim($request->input('term')) : '';
  409. if (empty($term)) return '';
  410. $term = strtolower($term);
  411. $pharmacies = Facility::where('facility_type', 'Pharmacy')
  412. ->where(function ($q) use ($term) {
  413. $q->orWhereRaw('LOWER(name::text) LIKE ?', ['%' . $term . '%'])
  414. ->orWhereRaw('LOWER(address_line1::text) LIKE ?', ['%' . $term . '%'])
  415. ->orWhereRaw('LOWER(address_line2::text) LIKE ?', ['%' . $term . '%'])
  416. ->orWhereRaw('LOWER(address_city::text) LIKE ?', ['%' . $term . '%'])
  417. ->orWhereRaw('LOWER(address_state::text) LIKE ?', ['%' . $term . '%'])
  418. ->orWhereRaw('LOWER(phone::text) LIKE ?', ['%' . $term . '%'])
  419. ->orWhereRaw('LOWER(address_zip::text) LIKE ?', ['%' . $term . '%']);
  420. })
  421. ->orderBy('name', 'asc')
  422. ->orderBy('address_line1', 'asc')
  423. ->orderBy('address_city', 'asc')
  424. ->orderBy('address_state', 'asc')
  425. ->get();
  426. return view('app/pharmacy-suggest', compact('pharmacies'));
  427. }
  428. public function proSuggest(Request $request) {
  429. $term = $request->input('term') ? trim($request->input('term')) : '';
  430. if (empty($term)) return '';
  431. $term = strtolower($term);
  432. $pros = Pro::where(function ($q) use ($term) {
  433. $q->orWhereRaw('LOWER(name_first::text) LIKE ?', ['%' . $term . '%'])
  434. ->orWhereRaw('LOWER(name_last::text) LIKE ?', ['%' . $term . '%'])
  435. ->orWhereRaw('cell_number LIKE ?', ['%' . $term . '%']);
  436. });
  437. if($this->performer->pro && $this->performer->pro->pro_type != 'ADMIN'){
  438. $accessiblePros = ProProAccess::where('owner_pro_id', $this->performer->pro->id);
  439. $accessibleProIds = [];
  440. foreach($accessiblePros as $accessiblePro){
  441. $accessibleProIds[] = $accessiblePro->id;
  442. }
  443. $accessibleProIds[] = $this->performer->pro->id;
  444. $pros->whereIn('id', $accessibleProIds);
  445. }
  446. $suggestedPros = $pros->orderBy('name_last')->orderBy('name_first')->get();
  447. return view('app/pro-suggest', compact('suggestedPros'));
  448. }
  449. public function proDisplayName(Request $request, Pro $pro) {
  450. return $pro ? $pro->displayName() : '';
  451. }
  452. public function unmappedSMS(Request $request, $filter = '')
  453. {
  454. $proID = $this->performer()->pro->id;
  455. if ($this->performer()->pro->pro_type === 'ADMIN') {
  456. $query = Client::where('id', '>', 0);
  457. } else {
  458. $query = Client::where(function ($q) use ($proID) {
  459. $q->where('mcp_pro_id', $proID)
  460. ->orWhere('cm_pro_id', $proID)
  461. ->orWhere('rmm_pro_id', $proID)
  462. ->orWhere('rme_pro_id', $proID)
  463. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID]);
  464. });
  465. }
  466. $patients = $query->orderBy('name_last', 'asc')->orderBy('name_first', 'asc')->get();
  467. $unmappedSMS = ClientSMS::where('client_id', null)->where('incoming_or_outgoing', 'INCOMING')->get();
  468. return view('app/unmapped-sms', compact('unmappedSMS', 'patients'));
  469. }
  470. public function newPatient(Request $request)
  471. {
  472. $mbPayers = MBPayer::all();
  473. return view('app/new-patient', compact('mbPayers'));
  474. }
  475. public function newNonMcnPatient(Request $request)
  476. {
  477. $mbPayers = MBPayer::all();
  478. return view('app/new-non-mcn-patient', compact('mbPayers'));
  479. }
  480. public function mc(Request $request, $fragment = "")
  481. {
  482. $page = "/";
  483. if ($fragment) {
  484. $page = '/' . $fragment;
  485. }
  486. return view('app/mc', compact('page'));
  487. }
  488. public function blank(Request $request)
  489. {
  490. return view('app/blank');
  491. }
  492. public function noteTemplateSet(Request $request, $section, $template)
  493. {
  494. return view('app/patient/note/_template', [
  495. "sectionInternalName" => $section,
  496. "templateName" => $template
  497. ]);
  498. }
  499. public function noteExamTemplateSet(Request $request, $exam, $template)
  500. {
  501. return view('app/patient/note/_template-exam', [
  502. "exam" => $exam,
  503. "sectionInternalName" => 'exam-' . $exam . '-detail',
  504. "templateName" => $template
  505. ]);
  506. }
  507. public function logInAs(Request $request)
  508. {
  509. if($this->pro->pro_type != 'ADMIN'){
  510. return redirect()->to(route('dashboard'));
  511. }
  512. $pros = Pro
  513. ::where('pro_type', '!=', 'ADMIN')
  514. ->orWhereNull('pro_type')
  515. ->orderBy('name_last', 'asc')
  516. ->orderBy('name_first', 'asc')
  517. ->get();
  518. return view('app/log-in-as', compact('pros'));
  519. }
  520. public function processLogInAs(Request $request)
  521. {
  522. $api = new Backend();
  523. try {
  524. $apiResponse = $api->post('session/proLogInAs', [
  525. 'proUid' => $request->post('proUid')
  526. ],
  527. [
  528. 'sessionKey'=>$this->performer()->session_key
  529. ]);
  530. $data = json_decode($apiResponse->getContents());
  531. if (!property_exists($data, 'success') || !$data->success) {
  532. return redirect()->to(route('log-in-as'))->with('message', $data->message)
  533. ->withInput($request->input());
  534. }
  535. Cookie::queue('sessionKey', $data->data->sessionKey);
  536. return redirect('/mc');
  537. } catch (\Exception $e) {
  538. return redirect()->to(route('log-in-as'))
  539. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  540. ->withInput($request->input());
  541. }
  542. }
  543. public function backToAdminPro(Request $request){
  544. $adminPerformerId = $this->performer->logged_in_as_pro_from_admin_pro_app_session_id;
  545. $adminPerformer = AppSession::where('id', $adminPerformerId)->first();
  546. $url = "/session/pro_log_in_with_session_key/".$adminPerformer->session_key;
  547. $api = new Backend();
  548. try {
  549. $apiResponse = $api->post($url, []);
  550. $data = json_decode($apiResponse->getContents());
  551. if (!property_exists($data, 'success') || !$data->success) {
  552. return redirect()->to(route('logout'));
  553. }
  554. Cookie::queue('sessionKey', $data->data->sessionKey);
  555. return redirect(route('dashboard'));
  556. } catch (\Exception $e) {
  557. return redirect(route('dashboard'));
  558. }
  559. }
  560. public function getTicket(Request $request, Ticket $ticket) {
  561. $ticket->data = json_decode($ticket->data);
  562. // $ticket->created_at = friendly_date_time($ticket->created_at);
  563. $ticket->assignedPro;
  564. $ticket->managerPro;
  565. $ticket->orderingPro;
  566. $ticket->initiatingPro;
  567. return json_encode($ticket);
  568. }
  569. }