HomeController.php 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Lib\Backend;
  4. use App\Models\Appointment;
  5. use App\Models\AppointmentConfirmationDecision;
  6. use App\Models\AppSession;
  7. use App\Models\ClientMemo;
  8. use App\Models\ClientProChange;
  9. use App\Models\ClientSMS;
  10. use App\Models\Facility;
  11. use App\Models\IncomingReport;
  12. use App\Models\MBPayer;
  13. use App\Models\ProProAccess;
  14. use App\Models\SupplyOrder;
  15. use App\Models\Ticket;
  16. use DateTime;
  17. use App\Models\Client;
  18. use App\Models\Bill;
  19. use App\Models\Measurement;
  20. use App\Models\Note;
  21. use App\Models\Pro;
  22. use App\Models\ProTransaction;
  23. use GuzzleHttp\Cookie\CookieJar;
  24. use Illuminate\Http\Request;
  25. use Illuminate\Support\Facades\Cookie;
  26. use Illuminate\Support\Facades\DB;
  27. use Illuminate\Support\Facades\Http;
  28. class HomeController extends Controller
  29. {
  30. public function confirmSmsAuthToken(Request $request)
  31. {
  32. return view('app/confirm_sms_auth_token');
  33. }
  34. public function setPassword(Request $request)
  35. {
  36. return view('app/set_password');
  37. }
  38. public function setSecurityQuestions(Request $request)
  39. {
  40. return view('app/set_security_questions');
  41. }
  42. public function postConfirmSmsAuthToken(Request $request)
  43. {
  44. try {
  45. $url = config('stag.backendUrl') . '/session/confirmSmsAuthToken';
  46. $data = [
  47. 'cellNumber' => $request->input('cellNumber'),
  48. 'token' => $request->input('token'),
  49. ];
  50. $response = Http::asForm()
  51. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  52. ->post($url, $data)
  53. ->json();
  54. if (!isset($response['success']) || !$response['success']) {
  55. $message = 'API error';
  56. if (isset($response['error'])) {
  57. $message = $response['error'];
  58. if (isset($response['path'])) $message .= ': ' . $response['path'];
  59. } else if (isset($response['message'])) $message = $response['message'];
  60. return redirect('/confirm_sms_auth_token')
  61. ->withInput()
  62. ->with('message', $message);
  63. }
  64. return redirect('/');
  65. } catch (\Exception $e) {
  66. return redirect()->back()
  67. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  68. ->withInput($request->input());
  69. }
  70. }
  71. public function resendSmsAuthToken(Request $request)
  72. {
  73. try {
  74. $url = config('stag.backendUrl') . '/session/resendSmsAuthToken';
  75. $data = [];
  76. $response = Http::asForm()
  77. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  78. ->post($url, $data)
  79. ->json();
  80. if (!isset($response['success']) || !$response['success']) {
  81. $message = 'API error';
  82. if (isset($response['error'])) {
  83. $message = $response['error'];
  84. if (isset($response['path'])) $message .= ': ' . $response['path'];
  85. } else if (isset($response['message'])) $message = $response['message'];
  86. return redirect('/confirm_sms_auth_token')
  87. ->withInput()
  88. ->with('message', $message);
  89. }
  90. return redirect()->back()->withInput()->with('message', "SMS Auth Token sent.");
  91. } catch (\Exception $e) {
  92. return redirect()->back()
  93. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  94. ->withInput($request->input());
  95. }
  96. }
  97. public function postSetPassword(Request $request)
  98. {
  99. try {
  100. $url = config('stag.backendUrl') . '/pro/selfPutPassword';
  101. $data = [
  102. 'newPassword' => $request->input('newPassword'),
  103. 'newPasswordConfirmation' => $request->input('newPasswordConfirmation'),
  104. ];
  105. $response = Http::asForm()
  106. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  107. ->post($url, $data)
  108. ->json();
  109. if (!isset($response['success']) || !$response['success']) {
  110. $message = 'API error';
  111. if (isset($response['error'])) {
  112. $message = $response['error'];
  113. if (isset($response['path'])) $message .= ': ' . $response['path'];
  114. } else if (isset($response['message'])) $message = $response['message'];
  115. return redirect('/set_password')
  116. ->withInput()
  117. ->with('message', $message);
  118. }
  119. return redirect('/');
  120. } catch (\Exception $e) {
  121. return redirect()->back()
  122. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  123. ->withInput($request->input());
  124. }
  125. }
  126. public function postSetSecurityQuestions(Request $request)
  127. {
  128. try {
  129. $url = env('BACKEND_URL', 'http://localhost:8080/api') . '/pro/selfPutSecurityQuestions';
  130. $data = [
  131. 'securityQuestion1' => $request->input('securityQuestion1'),
  132. 'securityAnswer1' => $request->input('securityAnswer1'),
  133. 'securityQuestion2' => $request->input('securityQuestion2'),
  134. 'securityAnswer2' => $request->input('securityAnswer2'),
  135. ];
  136. $response = Http::asForm()
  137. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  138. ->post($url, $data)
  139. ->json();
  140. if (!isset($response['success']) || !$response['success']) {
  141. $message = 'API error';
  142. if (isset($response['error'])) {
  143. $message = $response['error'];
  144. if (isset($response['path'])) $message .= ': ' . $response['path'];
  145. } else if (isset($response['message'])) $message = $response['message'];
  146. return redirect('/set_password')
  147. ->withInput()
  148. ->with('message', $message);
  149. }
  150. return redirect('/');
  151. } catch (\Exception $e) {
  152. return redirect()->back()
  153. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  154. ->withInput($request->input());
  155. }
  156. }
  157. public function dashboard(Request $request)
  158. {
  159. //patients where performer is the mcp
  160. $performer = $this->performer();
  161. $performerProID = $performer->pro->id;
  162. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  163. $keyNumbers = [];
  164. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  165. $keyNumbers['totalPatients'] = $queryClients->count();
  166. // patientNotSeenYet
  167. $patientNotSeenYet = $queryClients
  168. ->where(function ($query) use ($performer) { // own patient and primary OB visit pending
  169. $query->where('mcp_pro_id', $performer->pro->id)
  170. ->where('has_mcp_done_onboarding_visit', '!=', 'YES');
  171. })
  172. // ->orWhere(function ($query) { // mcp of any client program and program OB pending
  173. // $query->where(function ($_query) {
  174. // $_query->select(DB::raw('COUNT(id)'))
  175. // ->from('client_program')
  176. // ->whereColumn('client_id', 'client.id')
  177. // ->where('has_mcp_done_onboarding_visit', '!=', 'YES');
  178. // }, '>=', 1);
  179. // })
  180. ->count();
  181. $keyNumbers['patientsNotSeenYet'] = $patientNotSeenYet;
  182. $pendingBillsToSign = Bill::where('bill_service_type', '<>', 'CARE_MONTH')->where(function ($query) use ($performerProID) {
  183. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false);
  184. })
  185. ->orWhere(function ($query) use ($performerProID) {
  186. $query->where('cm_pro_id', $performerProID)->where('is_signed_by_cm', false)->where('is_cancelled', false);;
  187. })->orWhere(function ($query) use ($performerProID) {
  188. $query->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false)->where('is_cancelled', false);;
  189. })->orWhere(function ($query) use ($performerProID) {
  190. $query->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false)->where('is_cancelled', false);;
  191. })->count();
  192. $keyNumbers['pendingBillsToSign'] = $pendingBillsToSign;
  193. $pendingNotesToSign = Note::where(function ($query) use ($performerProID) {
  194. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false);;
  195. })
  196. ->orWhere(function ($query) use ($performerProID) {
  197. $query->where('ally_pro_id', $performerProID)->where('is_signed_by_ally', false)->where('is_cancelled', false);;
  198. })->count();
  199. $keyNumbers['pendingNotesToSign'] = $pendingNotesToSign;
  200. $pendingNotesToSignAllySigned = Note::where(function ($query) use ($performerProID) {
  201. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_signed_by_ally', true)->where('is_cancelled', false);;
  202. })->count();
  203. $keyNumbers['pendingNotesToSignAllySigned'] = $pendingNotesToSignAllySigned;
  204. $signedNotesWithoutBills = Note::where(function ($query) use ($performerProID) {
  205. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', true)->where('is_cancelled', false);;
  206. })->whereDoesntHave('bills')->count();
  207. $keyNumbers['signedNotesWithoutBills'] = $signedNotesWithoutBills;
  208. // open tickets
  209. $keyNumbers['numOpenTickets'] = Ticket::where('is_open', true)
  210. ->where(function ($q) use ($performerProID) {
  211. $q->where('assigned_pro_id', $performerProID)
  212. ->orWhere('manager_pro_id', $performerProID)
  213. ->orWhere('ordering_pro_id', $performerProID)
  214. ->orWhere('initiating_pro_id', $performerProID);
  215. })
  216. ->count();
  217. // unacknowledged cancelled bills for authed pro
  218. $keyNumbers['unacknowledgedCancelledBills'] = Bill::where('hcp_pro_id', $performerProID)
  219. ->where('is_cancelled', true)
  220. ->where('is_cancellation_acknowledged', false)
  221. ->count();
  222. // unacknowledged cancelled supply orders for authed pro
  223. $keyNumbers['unacknowledgedCancelledSupplyOrders'] = SupplyOrder::where('signed_by_pro_id', $performerProID)
  224. ->where('is_cancelled', true)
  225. ->where('is_cancellation_acknowledged', false)
  226. ->count();
  227. // unsigned supply orders created by authed pro
  228. $keyNumbers['unsignedSupplyOrders'] = SupplyOrder
  229. ::where('is_cancelled', false)
  230. ->where('is_signed_by_pro', false)
  231. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$performerProID])
  232. ->count();
  233. // patientsHavingBirthdayToday
  234. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  235. $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
  236. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  237. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
  238. ->count();
  239. $reimbursement = [];
  240. $reimbursement["currentBalance"] = $performer->pro->balance;
  241. $reimbursement["nextPaymentDate"] = '--';
  242. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  243. if ($lastPayment) {
  244. $reimbursement["lastPayment"] = $lastPayment->amount;
  245. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  246. } else {
  247. $reimbursement["lastPayment"] = '--';
  248. $reimbursement["lastPaymentDate"] = '--';
  249. }
  250. //if today is < 15th, next payment is 15th, else nextPayment is
  251. $today = strtotime(date('Y-m-d'));
  252. $todayDate = date('j', $today);
  253. $todayMonth = date('m', $today);
  254. $todayYear = date('Y', $today);
  255. if ($todayDate < 15) {
  256. $nextPaymentDate = new DateTime();
  257. $nextPaymentDate->setDate($todayYear, $todayMonth, 15);
  258. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  259. } else {
  260. $nextPaymentDate = new \DateTime();
  261. $lastDayOfMonth = date('t', $today);
  262. $nextPaymentDate->setDate($todayYear, $todayMonth, $lastDayOfMonth);
  263. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  264. }
  265. //expectedPay
  266. $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;
  267. $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;
  268. $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;
  269. $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;
  270. $expectedForNa = DB::select(DB::raw("SELECT coalesce(SUM(generic_pro_expected_payment_amount),0) as expected_pay FROM bill WHERE generic_pro_id = :performerProID AND has_generic_pro_been_paid = false AND is_signed_by_generic_pro IS TRUE AND is_cancelled = false"), ['performerProID' => $performerProID])[0]->expected_pay;
  271. $totalExpectedAmount = $expectedForHcp + $expectedForCm + $expectedForRme + $expectedForRmm + $expectedForNa;
  272. $reimbursement['nextPaymentAmount'] = $totalExpectedAmount;
  273. $milliseconds = strtotime(date('Y-m-d')) . '000';
  274. // bills & claims
  275. $businessNumbers = [];
  276. // Notes with bills to resolve
  277. $businessNumbers['notesWithBillsToResolve'] = Note::where('is_cancelled', '!=', true)
  278. ->where('is_bill_closed', '!=', true)
  279. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND is_cancelled = false AND is_verified = false) > 0')
  280. ->count();
  281. // Notes pending bill closure
  282. $businessNumbers['notesPendingBillingClosure'] = Note::where('is_cancelled', '!=', true)
  283. ->where('is_bill_closed', '!=', true)
  284. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND (is_cancelled = true OR is_verified = true)) = 0')
  285. ->count();
  286. // incoming reports not signed
  287. $incomingReports = IncomingReport::where('hcp_pro_id', $performerProID)
  288. ->where('has_hcp_pro_signed', false)
  289. ->where('is_entry_error', false)
  290. ->orderBy('created_at', 'ASC')
  291. ->get();
  292. // erx, labs & imaging that are not closed
  293. $tickets = Ticket::where('ordering_pro_id', $performerProID)
  294. ->where('is_entry_error', false)
  295. ->where('is_open', true)
  296. ->orderBy('created_at', 'ASC')
  297. ->get();
  298. $supplyOrders = 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. ->orderBy('created_at', 'ASC')
  302. ->get();
  303. $numERx = Ticket::where('ordering_pro_id', $performerProID)
  304. ->where('category', 'erx')
  305. ->where('is_entry_error', false)
  306. ->where('is_open', true)
  307. ->count();
  308. $numLabs = Ticket::where('ordering_pro_id', $performerProID)
  309. ->where('category', 'lab')
  310. ->where('is_entry_error', false)
  311. ->where('is_open', true)
  312. ->count();
  313. $numImaging = Ticket::where('ordering_pro_id', $performerProID)
  314. ->where('category', 'imaging')
  315. ->where('is_entry_error', false)
  316. ->where('is_open', true)
  317. ->count();
  318. $numSupplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  319. ->where('is_cancelled', false)
  320. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  321. ->count();
  322. $newMCPAssociations = ClientProChange
  323. ::where('new_pro_id', $performerProID)
  324. ->where('responsibility_type', 'MCP')
  325. ->whereNull('current_client_pro_change_decision_id')
  326. ->get();
  327. $newNAAssociations = ClientProChange
  328. ::where('new_pro_id', $performerProID)
  329. ->where('responsibility_type', 'DEFAULT_NA')
  330. ->whereNull('current_client_pro_change_decision_id')
  331. ->get();
  332. $proApptUpdates = AppointmentConfirmationDecision
  333. ::select('appointment_confirmation_decision.uid', 'client.name_first', 'client.name_last', 'appointment.start_time')
  334. ->rightJoin('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  335. ->rightJoin('client', 'client.id', '=', 'appointment.client_id')
  336. ->where('appointment_confirmation_decision.was_acknowledged_by_appointment_pro', false)
  337. ->where('appointment.status', '!=', 'CREATED')
  338. ->where('appointment.status', '!=', 'COMPLETED')
  339. ->where('appointment.status', '!=', 'ABANDONED')
  340. ->where('appointment.pro_id', $performerProID)
  341. ->where('client.mcp_pro_id', $performerProID)
  342. ->orderBy('appointment.start_time', 'DESC')
  343. ->get();
  344. $naApptUpdates = AppointmentConfirmationDecision
  345. ::select('appointment_confirmation_decision.uid', 'client.name_first', 'client.name_last', 'pro.name_first as pro_name_first', 'pro.name_last as pro_name_last', 'appointment.start_time')
  346. ->rightJoin('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  347. ->rightJoin('client', 'client.id', '=', 'appointment.client_id')
  348. ->rightJoin('pro', 'pro.id', '=', 'appointment.pro_id')
  349. ->where('appointment_confirmation_decision.was_acknowledged_by_client_default_na', false)
  350. ->where('appointment.status', '!=', 'CREATED')
  351. ->where('appointment.status', '!=', 'COMPLETED')
  352. ->where('appointment.status', '!=', 'ABANDONED')
  353. ->where('client.default_na_pro_id', $performerProID)
  354. ->orderBy('appointment.start_time', 'DESC')
  355. ->get();
  356. // $naApptUpdates = AppointmentConfirmationDecision
  357. // ::join('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  358. // ->join('client', 'client.id', '=', 'appointment.client_id')
  359. // ->where('client.default_na_pro_id', $performerProID)
  360. // ->where('appointment_confirmation_decision.was_acknowledged_by_client_default_na', false)
  361. // ->orderBy('appointment.start_time DESC')
  362. // ->get();
  363. // unstamped client memos
  364. // for mcp
  365. $mcpClientMemos = DB::select(
  366. DB::raw("
  367. SELECT c.uid as client_uid, c.name_first, c.name_last,
  368. cm.uid, cm.content, cm.created_at
  369. FROM client c join client_memo cm on c.id = cm.client_id
  370. WHERE
  371. c.mcp_pro_id = {$performerProID} AND
  372. cm.mcp_stamp_id IS NULL
  373. ORDER BY cm.created_at DESC
  374. ")
  375. );
  376. // for na
  377. $naClientMemos = DB::select(
  378. DB::raw("
  379. SELECT c.uid as client_uid, c.name_first, c.name_last,
  380. cm.uid, cm.content, cm.created_at
  381. FROM client c join client_memo cm on c.id = cm.client_id
  382. WHERE
  383. c.default_na_pro_id = {$performerProID} AND
  384. cm.default_na_stamp_id IS NULL
  385. ORDER BY cm.created_at DESC
  386. ")
  387. );
  388. $naBillableSignedNotes = DB::select(DB::raw("
  389. SELECT count(note.id) as na_billable_notes
  390. FROM note
  391. WHERE
  392. note.is_signed_by_hcp = TRUE AND
  393. note.ally_pro_id = :pro_id AND
  394. note.is_cancelled = FALSE AND
  395. (
  396. SELECT count(bill.id)
  397. FROM bill
  398. WHERE
  399. bill.is_cancelled = FALSE AND
  400. bill.generic_pro_id = :pro_id AND
  401. bill.note_id = note.id
  402. ) = 0
  403. "), ["pro_id" => $performerProID]);
  404. if(!$naBillableSignedNotes || !count($naBillableSignedNotes)) {
  405. $naBillableSignedNotes = 0;
  406. }
  407. else {
  408. $naBillableSignedNotes = $naBillableSignedNotes[0]->na_billable_notes;
  409. }
  410. $keyNumbers['naBillableSignedNotes'] = $naBillableSignedNotes;
  411. $keyNumbers['rmBillsToSign'] = Bill
  412. ::where('is_cancelled', false)
  413. ->where('cm_or_rm', 'RM')
  414. ->where(function ($q) use ($performerProID) {
  415. $q
  416. ->where(function ($q2) use ($performerProID) {
  417. $q2->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false);
  418. })
  419. ->orWhere(function ($q2) use ($performerProID) {
  420. $q2->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false);
  421. })
  422. ->orWhere(function ($q2) use ($performerProID) {
  423. $q2->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false);
  424. })
  425. ->orWhere(function ($q2) use ($performerProID) {
  426. $q2->where('generic_pro_id', $performerProID)->where('is_signed_by_generic_pro', false);
  427. });
  428. })
  429. ->count();
  430. $count = DB::select(
  431. DB::raw(
  432. "
  433. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  434. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  435. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  436. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  437. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  438. AND (care_month.number_of_days_with_remote_measurements < 16 OR care_month.number_of_days_with_remote_measurements IS NULL)
  439. "
  440. )
  441. );
  442. $keyNumbers['rmPatientsWithLT16MD'] = $count[0]->cnt;
  443. $count = DB::select(
  444. DB::raw(
  445. "
  446. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  447. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  448. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  449. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  450. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  451. AND (care_month.number_of_days_with_remote_measurements >= 16 AND care_month.number_of_days_with_remote_measurements IS NOT NULL)
  452. "
  453. )
  454. );
  455. $keyNumbers['rmPatientsWithGTE16MD'] = $count[0]->cnt;
  456. $count = DB::select(
  457. DB::raw(
  458. "
  459. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  460. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  461. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  462. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  463. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  464. AND (care_month.has_anyone_interacted_with_client_about_rm_outside_note = TRUE AND care_month.has_anyone_interacted_with_client_about_rm_outside_note IS NOT NULL)
  465. "
  466. )
  467. );
  468. $keyNumbers['rmPatientsWithWhomCommDone'] = $count[0]->cnt;
  469. $count = DB::select(
  470. DB::raw(
  471. "
  472. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  473. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  474. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  475. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  476. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  477. AND (care_month.has_anyone_interacted_with_client_about_rm_outside_note = FALSE OR care_month.has_anyone_interacted_with_client_about_rm_outside_note IS NULL)
  478. "
  479. )
  480. );
  481. $keyNumbers['rmPatientsWithWhomCommNotDone'] = $count[0]->cnt;
  482. // num measurements that need stamping
  483. $keyNumbers['measurementsToBeStamped'] = $this->performer()->pro->getUnstampedMeasurementsFromCurrentMonth(true, null, null);
  484. return view('app/dashboard', compact('keyNumbers', 'reimbursement', 'milliseconds',
  485. 'businessNumbers',
  486. 'incomingReports', 'tickets', 'supplyOrders',
  487. 'numERx', 'numLabs', 'numImaging', 'numSupplyOrders',
  488. 'newMCPAssociations', 'newNAAssociations',
  489. 'mcpClientMemos', 'naClientMemos',
  490. 'proApptUpdates', 'naApptUpdates'));
  491. }
  492. public function dashboardMeasurementsTab(Request $request, $page = 1) {
  493. $performer = $this->performer();
  494. $myClientIDs = [];
  495. if ($performer->pro->pro_type != 'ADMIN') {
  496. $myClientIDs = $this->getMyClientIds();
  497. $myClientIDs = implode(", ", $myClientIDs);
  498. }
  499. $ifNotAdmin = " AND (
  500. client.mcp_pro_id = {$performer->pro->id}
  501. OR client.rmm_pro_id = {$performer->pro->id}
  502. OR client.rme_pro_id = {$performer->pro->id}
  503. OR client.physician_pro_id = {$performer->pro->id}
  504. OR client.id in (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = {$performer->pro->id})
  505. OR client.id in (SELECT client_id FROM appointment WHERE status NOT IN ('CANCELLED', 'ABANDONED') AND pro_id = {$performer->pro->id})
  506. )";
  507. $numMeasurements = DB::select(
  508. DB::raw(
  509. "
  510. SELECT count(measurement.id) as cnt
  511. FROM measurement
  512. join client on measurement.client_id = client.id
  513. join care_month on client.id = care_month.client_id
  514. WHERE measurement.label NOT IN ('SBP', 'DBP')
  515. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  516. AND measurement.is_removed IS FALSE
  517. AND measurement.ts IS NOT NULL
  518. AND measurement.client_bdt_measurement_id IS NOT NULL
  519. AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
  520. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  521. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  522. " .
  523. (
  524. $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
  525. )
  526. )
  527. );
  528. $numMeasurements = $numMeasurements[0]->cnt;
  529. $measurements = DB::select(
  530. DB::raw(
  531. "
  532. SELECT measurement.uid as uid,
  533. care_month.uid as care_month_uid,
  534. care_month.start_date as care_month_start_date,
  535. measurement.label,
  536. measurement.value,
  537. measurement.sbp_mm_hg,
  538. measurement.dbp_mm_hg,
  539. measurement.numeric_value,
  540. measurement.value_pulse,
  541. measurement.value_irregular,
  542. measurement.ts,
  543. client.id as client_id,
  544. client.mcp_pro_id,
  545. client.default_na_pro_id,
  546. client.rmm_pro_id,
  547. client.rme_pro_id,
  548. client.uid as client_uid,
  549. client.name_last,
  550. client.name_first,
  551. care_month.rm_total_time_in_seconds
  552. FROM measurement
  553. join client on measurement.client_id = client.id
  554. join care_month on client.id = care_month.client_id
  555. WHERE measurement.label NOT IN ('SBP', 'DBP')
  556. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  557. AND measurement.is_removed IS FALSE
  558. AND measurement.has_been_stamped_by_mcp IS FALSE
  559. AND measurement.ts IS NOT NULL
  560. AND measurement.client_bdt_measurement_id IS NOT NULL
  561. AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
  562. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  563. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  564. " .
  565. (
  566. $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
  567. )
  568. ) .
  569. " ORDER BY measurement.ts DESC LIMIT 20 OFFSET " . (($page - 1) * 20)
  570. );
  571. return view('app.dashboard.measurements', compact('numMeasurements', 'measurements', 'page'));
  572. }
  573. public function dashboardAppointmentDates(Request $request, $from, $to) {
  574. $performer = $this->performer();
  575. $performerProID = $performer->pro->id;
  576. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  577. $results = DB::table('appointment')->select('raw_date')->distinct()->where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  578. if(!$isAdmin) {
  579. $results = $results->where("pro_id", $performerProID);
  580. }
  581. $results = $results->get();
  582. $dates = [];
  583. foreach ($results as $result) {
  584. // $dates[] = strtotime($result->raw_date) . '000';
  585. $dates[] = $result->raw_date;
  586. }
  587. // foreach ($results as $result) {
  588. // $results->dateYMD = date('Y-m-d', strtotime($result->raw_date));
  589. // }
  590. return json_encode($dates);
  591. }
  592. public function dashboardAppointments(Request $request, $from, $to) {
  593. $performer = $this->performer();
  594. $performerProID = $performer->pro->id;
  595. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  596. // $appointments = Appointment::where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  597. $appointments = Appointment::where("raw_date", '=', $from);
  598. if(!$isAdmin) {
  599. $appointments = $appointments->where("pro_id", $performerProID);
  600. }
  601. $appointments = $appointments
  602. ->orderBy('start_time', 'asc')
  603. ->get();
  604. foreach ($appointments as $appointment) {
  605. $date = explode(" ", $appointment->start_time)[0];
  606. $appointment->milliseconds = strtotime($date) . '000';
  607. $appointment->newStatus = $appointment->status;
  608. $appointment->dateYMD = date('Y-m-d', strtotime($appointment->raw_date));
  609. $appointment->clientName = $appointment->client->displayName();
  610. $appointment->clientInitials = substr($appointment->client->name_first, 0, 1) . substr($appointment->client->name_last, 0, 1);
  611. $appointment->isClientShadowOfPro = $appointment->client->shadow_pro_id ? true : false;
  612. $appointment->proInitials = substr($appointment->pro->name_first, 0, 1) . substr($appointment->pro->name_last, 0, 1);
  613. $appointment->friendlyStartTime = friendly_time($appointment->raw_start_time);
  614. $appointment->friendlyEndTime = friendly_time($appointment->raw_end_time);
  615. $appointment->clientSummary = friendly_date_time($appointment->client->dob, false) . ' (' .
  616. $appointment->client->age_in_years . ' y.o' .
  617. ($appointment->client->sex ? ' ' . $appointment->client->sex : '') .
  618. ')';
  619. $appointment->started = false;
  620. $appointment->inHowManyHours = date_diff(date_create('now'), date_create($appointment->start_time), false)
  621. ->format('%R%h h, %i m');
  622. if ($appointment->inHowManyHours[0] === '-') {
  623. $appointment->inHowManyHours = substr($appointment->inHowManyHours, 1) . ' ago';
  624. $appointment->started = true;
  625. } else {
  626. $appointment->inHowManyHours = 'Appt. in ' . substr($appointment->inHowManyHours, 1);
  627. }
  628. $appointment->clientUid = $appointment->client->uid;
  629. $appointment->proUid = $appointment->pro->uid;
  630. $appointment->proName = $appointment->pro->displayName();
  631. unset($appointment->client);
  632. unset($appointment->pro);
  633. unset($appointment->detail_json);
  634. }
  635. return json_encode($appointments);
  636. }
  637. public function dashboardMeasurements(Request $request, $filter) {
  638. $measurements = $this->performer()->pro->getMeasurements($filter === 'NEED_ACK');
  639. return json_encode($measurements);
  640. }
  641. public function patients(Request $request, $filter = '')
  642. {
  643. $performer = $this->performer();
  644. $query = $performer->pro->getAccessibleClientsQuery();
  645. $q = trim($request->input('q'));
  646. if(!empty($q)) {
  647. $query = $query->where(function ($query) use ($q) {
  648. $query->where('name_first', 'ILIKE', "%$q%")
  649. ->orWhere('name_last', 'ILIKE', "%$q%")
  650. ->orWhere('email_address', 'ILIKE', "%$q%")
  651. ->orWhere('tags', 'ILIKE', "%$q%");
  652. });
  653. }
  654. switch ($filter) {
  655. case 'not-yet-seen':
  656. $query = $query
  657. ->where(function ($query) use ($performer) {
  658. $query
  659. ->where(function ($query) use ($performer) { // own patient and primary OB visit pending
  660. $query->where('mcp_pro_id', $performer->pro->id)
  661. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  662. })
  663. ->orWhere(function ($query) use ($performer) { // mcp of any client program and program OB pending
  664. $query->select(DB::raw('COUNT(id)'))
  665. ->from('client_program')
  666. ->whereColumn('client_id', 'client.id')
  667. ->where('mcp_pro_id', $performer->pro->id)
  668. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  669. }, '>=', 1);
  670. });
  671. break;
  672. case 'having-birthday-today':
  673. $query = $query
  674. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  675. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')]);
  676. break;
  677. // more cases can be added as needed
  678. default:
  679. break;
  680. }
  681. $patients = $query->orderBy('id', 'desc')->paginate(50);
  682. // patient acquisition chart (admin only)
  683. $patientAcquisitionData = null;
  684. if($performer->pro->pro_type === 'ADMIN') {
  685. $startDate = date_sub(date_create(), date_interval_create_from_date_string("1 month"));
  686. $startDate = date_format($startDate, "Y-m-d");
  687. $patientAcquisitionData = DB::select(DB::raw(
  688. "SELECT count(id) as count, DATE(created_at at time zone 'utc' at time zone 'est') as date " .
  689. "FROM client " .
  690. "WHERE shadow_pro_id IS NULL " .
  691. "GROUP BY DATE(created_at at time zone 'utc' at time zone 'est') " .
  692. "ORDER BY DATE(created_at at time zone 'utc' at time zone 'est') DESC " .
  693. "LIMIT 30"));
  694. }
  695. return view('app/patients', compact('patients', 'filter', 'patientAcquisitionData'));
  696. }
  697. public function patientsSuggest(Request $request)
  698. {
  699. $pro = $this->pro;
  700. $term = $request->input('term') ? trim($request->input('term')) : '';
  701. $originalTerm = $term;
  702. if (empty($term)) return '';
  703. // if multiple words in query, check for all (max 2)
  704. $term2 = '';
  705. if(strpos($term, ' ') !== FALSE) {
  706. $terms = explode(' ', $term);
  707. $term = trim($terms[0]);
  708. $term2 = trim($terms[1]);
  709. }
  710. $phoneNumberTerm = preg_replace("/[^0-9]/", "", $originalTerm );
  711. if($phoneNumberTerm == ""){ //to avoid search with blank string
  712. $phoneNumberTerm = $term;
  713. }
  714. $clientQuery= Client::whereNull('shadow_pro_id')
  715. ->where(function ($q) use ($term, $phoneNumberTerm) {
  716. $q->where('name_first', 'ILIKE', '%' . $term . '%')
  717. ->orWhere('name_last', 'ILIKE', '%' . $term . '%')
  718. ->orWhere('cell_number', 'ILIKE', '%' . $phoneNumberTerm . '%')
  719. ->orWhere('phone_home', 'ILIKE', '%' . $phoneNumberTerm . '%');
  720. });
  721. if(!empty($term2)) {
  722. $clientQuery = $clientQuery->where(function ($q) use ($term2, $phoneNumberTerm) {
  723. $q->where('name_first', 'ILIKE', '%' . $term2 . '%')
  724. ->orWhere('name_last', 'ILIKE', '%' . $term2 . '%')
  725. ->orWhere('cell_number', 'ILIKE', '%' . $phoneNumberTerm . '%')
  726. ->orWhere('phone_home', 'ILIKE', '%' . $phoneNumberTerm . '%');
  727. });
  728. }
  729. if(!($pro->pro_type === 'ADMIN' && $pro->can_see_any_client_via_search)) {
  730. $clientQuery->where(function ($q) use ($pro) {
  731. if($pro->pro_type === 'ADMIN') {
  732. $q->whereIn('id', $pro->getMyClientIds(true))->orWhereNull('mcp_pro_id');
  733. }
  734. else {
  735. $q->whereIn('id', $pro->getMyClientIds(true));
  736. }
  737. });
  738. }
  739. $clients = $clientQuery->get();
  740. return view('app/patient-suggest', compact('clients'));
  741. }
  742. public function pharmacySuggest(Request $request)
  743. {
  744. $term = $request->input('term') ? trim($request->input('term')) : '';
  745. if (empty($term)) return '';
  746. $term = strtolower($term);
  747. $pharmacies = Facility::where('facility_type', 'Pharmacy')
  748. ->where(function ($q) use ($term) {
  749. $q->orWhereRaw('LOWER(name::text) LIKE ?', ['%' . $term . '%'])
  750. ->orWhereRaw('LOWER(address_line1::text) LIKE ?', ['%' . $term . '%'])
  751. ->orWhereRaw('LOWER(address_line2::text) LIKE ?', ['%' . $term . '%'])
  752. ->orWhereRaw('LOWER(address_city::text) LIKE ?', ['%' . $term . '%'])
  753. ->orWhereRaw('LOWER(address_state::text) LIKE ?', ['%' . $term . '%'])
  754. ->orWhereRaw('LOWER(phone::text) LIKE ?', ['%' . $term . '%'])
  755. ->orWhereRaw('LOWER(address_zip::text) LIKE ?', ['%' . $term . '%']);
  756. });
  757. if($request->input('city')) {
  758. $pharmacies = $pharmacies->whereRaw('LOWER(address_city::text) LIKE ?', ['%' . strtolower($request->input('city')) . '%']);
  759. }
  760. if($request->input('state')) {
  761. $pharmacies = $pharmacies->whereRaw('LOWER(address_state::text) LIKE ?', ['%' . strtolower($request->input('state')) . '%']);
  762. }
  763. if($request->input('zip')) {
  764. $pharmacies = $pharmacies->whereRaw('LOWER(address_zip::text) LIKE ?', ['%' . strtolower($request->input('zip')) . '%']);
  765. }
  766. $pharmacies = $pharmacies
  767. ->orderBy('name', 'asc')
  768. ->orderBy('address_line1', 'asc')
  769. ->orderBy('address_city', 'asc')
  770. ->orderBy('address_state', 'asc')
  771. ->get();
  772. return view('app/pharmacy-suggest', compact('pharmacies'));
  773. }
  774. public function proSuggest(Request $request) {
  775. $term = $request->input('term') ? trim($request->input('term')) : '';
  776. if (empty($term)) return '';
  777. $term = strtolower($term);
  778. $pros = Pro::where(function ($q) use ($term) {
  779. $q->orWhereRaw('LOWER(name_first::text) LIKE ?', ['%' . $term . '%'])
  780. ->orWhereRaw('LOWER(name_last::text) LIKE ?', ['%' . $term . '%'])
  781. ->orWhereRaw('cell_number LIKE ?', ['%' . $term . '%']);
  782. });
  783. if($this->performer->pro && $this->performer->pro->pro_type != 'ADMIN'){
  784. $accessiblePros = ProProAccess::where('owner_pro_id', $this->performer->pro->id);
  785. $accessibleProIds = [];
  786. foreach($accessiblePros as $accessiblePro){
  787. $accessibleProIds[] = $accessiblePro->id;
  788. }
  789. $accessibleProIds[] = $this->performer->pro->id;
  790. $pros->whereIn('id', $accessibleProIds);
  791. }
  792. $suggestedPros = $pros->orderBy('name_last')->orderBy('name_first')->get();
  793. // for calendar select2
  794. if($request->input('json')) {
  795. $jsonPros = $suggestedPros->map(function($_pro) {
  796. return [
  797. "uid" => $_pro->uid,
  798. "id" => $_pro->id,
  799. "text" => $_pro->displayName(),
  800. "initials" => $_pro->initials(),
  801. ];
  802. });
  803. return json_encode([
  804. "results" => $jsonPros
  805. ]);
  806. }
  807. return view('app/pro-suggest', compact('suggestedPros'));
  808. }
  809. public function proDisplayName(Request $request, Pro $pro) {
  810. return $pro ? $pro->displayName() : '';
  811. }
  812. public function unmappedSMS(Request $request, $filter = '')
  813. {
  814. $proID = $this->performer()->pro->id;
  815. if ($this->performer()->pro->pro_type === 'ADMIN') {
  816. $query = Client::where('id', '>', 0);
  817. } else {
  818. $query = Client::where(function ($q) use ($proID) {
  819. $q->where('mcp_pro_id', $proID)
  820. ->orWhere('cm_pro_id', $proID)
  821. ->orWhere('rmm_pro_id', $proID)
  822. ->orWhere('rme_pro_id', $proID)
  823. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID]);
  824. });
  825. }
  826. $patients = $query->orderBy('name_last', 'asc')->orderBy('name_first', 'asc')->get();
  827. $unmappedSMS = ClientSMS::where('client_id', null)->where('incoming_or_outgoing', 'INCOMING')->paginate(20);
  828. return view('app/unmapped-sms', compact('unmappedSMS', 'patients'));
  829. }
  830. public function newPatient(Request $request)
  831. {
  832. $mbPayers = MBPayer::all();
  833. return view('app/new-patient', compact('mbPayers'));
  834. }
  835. public function newNonMcnPatient(Request $request)
  836. {
  837. $mbPayers = MBPayer::all();
  838. return view('app/new-non-mcn-patient', compact('mbPayers'));
  839. }
  840. public function mc(Request $request, $fragment = "")
  841. {
  842. $page = "/";
  843. if ($fragment) {
  844. $page = '/' . $fragment;
  845. }
  846. return view('app/mc', compact('page'));
  847. }
  848. public function blank(Request $request)
  849. {
  850. return view('app/blank');
  851. }
  852. public function noteTemplateSet(Request $request, $section, $template)
  853. {
  854. return view('app/patient/note/_template', [
  855. "sectionInternalName" => $section,
  856. "templateName" => $template
  857. ]);
  858. }
  859. public function noteExamTemplateSet(Request $request, $exam, $template)
  860. {
  861. return view('app/patient/note/_template-exam', [
  862. "exam" => $exam,
  863. "sectionInternalName" => 'exam-' . $exam . '-detail',
  864. "templateName" => $template
  865. ]);
  866. }
  867. public function logInAs(Request $request)
  868. {
  869. if($this->pro->pro_type != 'ADMIN'){
  870. return redirect()->to(route('dashboard'));
  871. }
  872. $pros = Pro::where('pro_type', '!=', 'ADMIN');
  873. if($request->input('q')) {
  874. $nameQuery = '%' . $request->input('q') . '%';
  875. $pros = $pros->where(function ($query) use ($nameQuery) {
  876. $query->where('name_first', 'ILIKE', $nameQuery)
  877. ->orWhere('name_last', 'ILIKE', $nameQuery)
  878. ->orWhere('email_address', 'ILIKE', $nameQuery)
  879. ->orWhere('cell_number', 'ILIKE', $nameQuery);
  880. });
  881. }
  882. if($request->input('sort') && $request->input('dir')) {
  883. $pros = $pros->orderBy($request->input('sort'), $request->input('dir'));
  884. }
  885. else {
  886. $pros = $pros->orderBy('name_last', 'asc');
  887. }
  888. $pros = $pros->paginate(20);
  889. return view('app/log-in-as', ['logInAsPros' => $pros]);
  890. }
  891. public function processLogInAs(Request $request)
  892. {
  893. $api = new Backend();
  894. try {
  895. $apiResponse = $api->post('session/proLogInAs', [
  896. 'proUid' => $request->post('proUid')
  897. ],
  898. [
  899. 'sessionKey'=>$this->performer()->session_key
  900. ]);
  901. $data = json_decode($apiResponse->getContents());
  902. if (!property_exists($data, 'success') || !$data->success) {
  903. return redirect()->to(route('log-in-as'))->with('message', $data->message)
  904. ->withInput($request->input());
  905. }
  906. Cookie::queue('sessionKey', $data->data->sessionKey);
  907. return redirect('/mc');
  908. } catch (\Exception $e) {
  909. return redirect()->to(route('log-in-as'))
  910. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  911. ->withInput($request->input());
  912. }
  913. }
  914. public function backToAdminPro(Request $request){
  915. $adminPerformerId = $this->performer->logged_in_as_pro_from_admin_pro_app_session_id;
  916. $adminPerformer = AppSession::where('id', $adminPerformerId)->first();
  917. $url = "/session/pro_log_in_with_session_key/".$adminPerformer->session_key;
  918. $api = new Backend();
  919. try {
  920. $apiResponse = $api->post($url, []);
  921. $data = json_decode($apiResponse->getContents());
  922. if (!property_exists($data, 'success') || !$data->success) {
  923. return redirect()->to(route('logout'));
  924. }
  925. Cookie::queue('sessionKey', $data->data->sessionKey);
  926. return redirect(route('dashboard'));
  927. } catch (\Exception $e) {
  928. return redirect(route('dashboard'));
  929. }
  930. }
  931. public function getTicket(Request $request, Ticket $ticket) {
  932. $ticket->data = json_decode($ticket->data);
  933. // $ticket->created_at = friendly_date_time($ticket->created_at);
  934. $ticket->assignedPro;
  935. $ticket->managerPro;
  936. $ticket->orderingPro;
  937. $ticket->initiatingPro;
  938. return json_encode($ticket);
  939. }
  940. public function genericBill(Request $request, $entityType, $entityUid) {
  941. $patient = null;
  942. if ($entityType && $entityUid) {
  943. try {
  944. $entityClass = "\\App\\Models\\" . $entityType;
  945. $entity = $entityClass::where('uid', $entityUid)->first();
  946. if ($entity->client) {
  947. $patient = $entity->client;
  948. }
  949. } catch (\Exception $e) {
  950. }
  951. }
  952. return view('app.generic-bills.inline', ['class' => 'p-3 border-top mt-3', 'entityType' => $entityType, 'entityUid' => $entityUid, 'patient' => $patient]);
  953. }
  954. }