HomeController.php 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169
  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. private function dashboard_MCP(Request $request){
  158. $keyNumbers = [];
  159. // Patients // SELECT * FROM client WHERE mcp_pro_id = :me.id;
  160. // New Patients Awaiting Visit // SELECT * FROM client WHERE mcp_pro_id = :me.id AND hasMcpDoneOnboardingVisit != 'YES';
  161. // Notes Pending Signature // SELECT * FROM note WHERE hcp_pro_id = :me.id AND is_cancelled IS NOT TRUE AND has_hcp_signed IS NOT TRUE;
  162. // Notes Pending Billing // SELECT * FROM note WHERE hcp_pro_id = :me.id AND is_cancelled IS NOT TRUE AND has_hcp_signed IS TRUE AND is_billing_marked_done IS FALSE;
  163. // Reports Pending Signature // SELECT * FROM incoming_report WHERE hcp_pro_id = :me.id AND isEntryError IS NOT TRUE AND hasHcpProSigned IS NOT TRUE;
  164. // Patients w/o Appointments // SELECT * FROM client WHERE mcp_pro_id = :me.id AND client.next_mcp_appointment_date < today();
  165. // Patients Overdue for Visit // SELECT * FROM client WHERE mcp_pro_id = :me.id AND client.next_expected_mcp_visit_date < today();
  166. // Cancelled Appts. Pending Review // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  167. // Cancelled Bills Pending Review // SELECT * FROM bill WHERE bill_service_type = 'NOTE' AND is_cancelled IS TRUE AND isCancellationAcknowledged IS FALSE;
  168. // Cancelled Supply Orders Pending Review // SELECT * FROM supply_order WHERE signed_by_pro_id = :me.id AND is_cancelled IS TRUE AND isCancellationAcknowledged IS NOT TRUE;
  169. // ERx & Orders Pending Signature // SELECT * FROM erx WHERE hcp_pro_id = :me.id AND pro_declared_status <> 'CANCELLED' AND hasHcpProSigned IS NOT TRUE;
  170. // Supply Orders Pending Signature // SELECT supply_order.id FROM supply_order WHERE signed_by_pro_id IS NOT TRUE AND is_cancelled IS NOT TRUE AND created_by_pro_id = :me.id;
  171. $performer = $this->performer();
  172. $pro = $performer->pro;
  173. $performerProID = $performer->pro->id;
  174. $keyNumbers = [];
  175. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  176. $pendingNotesToSign = Note
  177. ::where(function ($query) use ($performerProID) {
  178. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false);
  179. })
  180. ->orWhere(function ($query) use ($performerProID) {
  181. $query->where('ally_pro_id', $performerProID)->where('is_signed_by_ally', false)->where('is_cancelled', false);
  182. })
  183. ->count();
  184. $keyNumbers['pendingNotesToSign'] = $pendingNotesToSign;
  185. // notes pending mcp sign (applicable to dnas only)
  186. $pendingNotesToSignMCP = Note
  187. ::where(function ($query) use ($performerProID) {
  188. $query->where('ally_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false);
  189. })
  190. ->count();
  191. $keyNumbers['$pendingNotesToSignMCP'] = $pendingNotesToSignMCP;
  192. $pendingNotesToSignAllySigned = Note::where(function ($query) use ($performerProID) {
  193. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_signed_by_ally', true)->where('is_cancelled', false);;
  194. })->count();
  195. $keyNumbers['pendingNotesToSignAllySigned'] = $pendingNotesToSignAllySigned;
  196. $signedNotesWithoutBills = Note::where(function ($query) use ($performerProID) {
  197. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', true)->where('is_cancelled', false);
  198. })->whereDoesntHave('bills')->count();
  199. $keyNumbers['signedNotesWithoutBills'] = $signedNotesWithoutBills;
  200. // open tickets
  201. $keyNumbers['numOpenTickets'] = Ticket::where('is_open', true)
  202. ->where(function ($q) use ($performerProID) {
  203. $q->where('assigned_pro_id', $performerProID)
  204. ->orWhere('manager_pro_id', $performerProID)
  205. ->orWhere('ordering_pro_id', $performerProID)
  206. ->orWhere('initiating_pro_id', $performerProID);
  207. })
  208. ->count();
  209. // unacknowledged cancelled bills for authed pro
  210. $keyNumbers['unacknowledgedCancelledBills'] = Bill::where('hcp_pro_id', $performerProID)
  211. ->where('is_cancelled', true)
  212. ->where('is_cancellation_acknowledged', false)
  213. ->count();
  214. // unacknowledged cancelled supply orders for authed pro
  215. $keyNumbers['unacknowledgedCancelledSupplyOrders'] = SupplyOrder::where('signed_by_pro_id', $performerProID)
  216. ->where('is_cancelled', true)
  217. ->where('is_cancellation_acknowledged', false)
  218. ->count();
  219. // unsigned supply orders created by authed pro
  220. $keyNumbers['unsignedSupplyOrders'] = SupplyOrder
  221. ::where('is_cancelled', false)
  222. ->where('is_signed_by_pro', false)
  223. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$performerProID])
  224. ->count();
  225. // patientsHavingBirthdayToday
  226. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  227. $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
  228. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  229. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
  230. ->count();
  231. $reimbursement = [];
  232. $reimbursement["currentBalance"] = $performer->pro->balance;
  233. $reimbursement["nextPaymentDate"] = '--';
  234. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  235. if ($lastPayment) {
  236. $reimbursement["lastPayment"] = $lastPayment->amount;
  237. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  238. } else {
  239. $reimbursement["lastPayment"] = '--';
  240. $reimbursement["lastPaymentDate"] = '--';
  241. }
  242. //if today is < 15th, next payment is 15th, else nextPayment is
  243. $today = strtotime(date('Y-m-d'));
  244. $todayDate = date('j', $today);
  245. $todayMonth = date('m', $today);
  246. $todayYear = date('Y', $today);
  247. if ($todayDate < 15) {
  248. $nextPaymentDate = new DateTime();
  249. $nextPaymentDate->setDate($todayYear, $todayMonth, 15);
  250. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  251. } else {
  252. $nextPaymentDate = new \DateTime();
  253. $lastDayOfMonth = date('t', $today);
  254. $nextPaymentDate->setDate($todayYear, $todayMonth, $lastDayOfMonth);
  255. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  256. }
  257. //expectedPay
  258. $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;
  259. $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;
  260. $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;
  261. $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;
  262. $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;
  263. $totalExpectedAmount = $expectedForHcp + $expectedForCm + $expectedForRme + $expectedForRmm + $expectedForNa;
  264. $reimbursement['nextPaymentAmount'] = $totalExpectedAmount;
  265. $milliseconds = strtotime(date('Y-m-d')) . '000';
  266. // bills & claims
  267. $businessNumbers = [];
  268. // Notes with bills to resolve
  269. $businessNumbers['notesWithBillsToResolve'] = Note::where('is_cancelled', '!=', true)
  270. ->where('is_bill_closed', '!=', true)
  271. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND is_cancelled = false AND is_verified = false) > 0')
  272. ->count();
  273. // Notes pending bill closure
  274. $businessNumbers['notesPendingBillingClosure'] = Note::where('is_cancelled', '!=', true)
  275. ->where('is_bill_closed', '!=', true)
  276. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND (is_cancelled = true OR is_verified = true)) = 0')
  277. ->count();
  278. // incoming reports not signed
  279. $incomingReports = IncomingReport::where('hcp_pro_id', $performerProID)
  280. ->where('has_hcp_pro_signed', false)
  281. ->where('is_entry_error', false)
  282. ->orderBy('created_at', 'ASC')
  283. ->get();
  284. // erx, labs & imaging that are not closed
  285. $tickets = Ticket::where('ordering_pro_id', $performerProID)
  286. ->where('is_entry_error', false)
  287. ->where('is_open', true)
  288. ->orderBy('created_at', 'ASC')
  289. ->get();
  290. $supplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  291. ->where('is_cancelled', false)
  292. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  293. ->orderBy('created_at', 'ASC')
  294. ->get();
  295. $numERx = Ticket::where('ordering_pro_id', $performerProID)
  296. ->where('category', 'erx')
  297. ->where('is_entry_error', false)
  298. ->where('is_open', true)
  299. ->count();
  300. $numLabs = Ticket::where('ordering_pro_id', $performerProID)
  301. ->where('category', 'lab')
  302. ->where('is_entry_error', false)
  303. ->where('is_open', true)
  304. ->count();
  305. $numImaging = Ticket::where('ordering_pro_id', $performerProID)
  306. ->where('category', 'imaging')
  307. ->where('is_entry_error', false)
  308. ->where('is_open', true)
  309. ->count();
  310. $numSupplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  311. ->where('is_cancelled', false)
  312. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  313. ->count();
  314. $newMCPAssociations = ClientProChange
  315. ::where('new_pro_id', $performerProID)
  316. ->where('responsibility_type', 'MCP')
  317. ->whereNull('current_client_pro_change_decision_id')
  318. ->get();
  319. $newNAAssociations = ClientProChange
  320. ::where('new_pro_id', $performerProID)
  321. ->where('responsibility_type', 'DEFAULT_NA')
  322. ->whereNull('current_client_pro_change_decision_id')
  323. ->get();
  324. $proApptUpdates = AppointmentConfirmationDecision
  325. ::select('appointment_confirmation_decision.uid', 'client.name_first', 'client.name_last', 'appointment.start_time')
  326. ->rightJoin('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  327. ->rightJoin('client', 'client.id', '=', 'appointment.client_id')
  328. ->where('appointment_confirmation_decision.was_acknowledged_by_appointment_pro', false)
  329. ->where('appointment.status', '!=', 'CREATED')
  330. ->where('appointment.status', '!=', 'COMPLETED')
  331. ->where('appointment.status', '!=', 'ABANDONED')
  332. ->where('appointment.pro_id', $performerProID)
  333. ->where('client.mcp_pro_id', $performerProID)
  334. ->orderBy('appointment.start_time', 'DESC')
  335. ->get();
  336. $naApptUpdates = AppointmentConfirmationDecision
  337. ::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')
  338. ->rightJoin('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  339. ->rightJoin('client', 'client.id', '=', 'appointment.client_id')
  340. ->rightJoin('pro', 'pro.id', '=', 'appointment.pro_id')
  341. ->where('appointment_confirmation_decision.was_acknowledged_by_client_default_na', false)
  342. ->where('appointment.status', '!=', 'CREATED')
  343. ->where('appointment.status', '!=', 'COMPLETED')
  344. ->where('appointment.status', '!=', 'ABANDONED')
  345. ->where('client.default_na_pro_id', $performerProID)
  346. ->orderBy('appointment.start_time', 'DESC')
  347. ->get();
  348. // $naApptUpdates = AppointmentConfirmationDecision
  349. // ::join('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  350. // ->join('client', 'client.id', '=', 'appointment.client_id')
  351. // ->where('client.default_na_pro_id', $performerProID)
  352. // ->where('appointment_confirmation_decision.was_acknowledged_by_client_default_na', false)
  353. // ->orderBy('appointment.start_time DESC')
  354. // ->get();
  355. // unstamped client memos
  356. // for mcp
  357. $mcpClientMemos = DB::select(
  358. DB::raw("
  359. SELECT c.uid as client_uid, c.name_first, c.name_last,
  360. cm.uid, cm.content, cm.created_at
  361. FROM client c join client_memo cm on c.id = cm.client_id
  362. WHERE
  363. c.mcp_pro_id = {$performerProID} AND
  364. cm.mcp_stamp_id IS NULL
  365. ORDER BY cm.created_at DESC
  366. ")
  367. );
  368. // for na
  369. $naClientMemos = DB::select(
  370. DB::raw("
  371. SELECT c.uid as client_uid, c.name_first, c.name_last,
  372. cm.uid, cm.content, cm.created_at
  373. FROM client c join client_memo cm on c.id = cm.client_id
  374. WHERE
  375. c.default_na_pro_id = {$performerProID} AND
  376. cm.default_na_stamp_id IS NULL
  377. ORDER BY cm.created_at DESC
  378. ")
  379. );
  380. $keyNumbers['rmBillsToSign'] = Bill
  381. ::where('is_cancelled', false)
  382. ->where('cm_or_rm', 'RM')
  383. ->where(function ($q) use ($performerProID) {
  384. $q
  385. ->where(function ($q2) use ($performerProID) {
  386. $q2->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false);
  387. })
  388. ->orWhere(function ($q2) use ($performerProID) {
  389. $q2->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false);
  390. })
  391. ->orWhere(function ($q2) use ($performerProID) {
  392. $q2->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false);
  393. })
  394. ->orWhere(function ($q2) use ($performerProID) {
  395. $q2->where('generic_pro_id', $performerProID)->where('is_signed_by_generic_pro', false);
  396. });
  397. })
  398. ->count();
  399. $count = DB::select(
  400. DB::raw(
  401. "
  402. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  403. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  404. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  405. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  406. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  407. AND (care_month.number_of_days_with_remote_measurements < 16 OR care_month.number_of_days_with_remote_measurements IS NULL)
  408. "
  409. )
  410. );
  411. $keyNumbers['rmPatientsWithLT16MD'] = $count[0]->cnt;
  412. $count = DB::select(
  413. DB::raw(
  414. "
  415. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  416. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  417. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  418. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  419. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  420. AND (care_month.number_of_days_with_remote_measurements >= 16 AND care_month.number_of_days_with_remote_measurements IS NOT NULL)
  421. "
  422. )
  423. );
  424. $keyNumbers['rmPatientsWithGTE16MD'] = $count[0]->cnt;
  425. $count = DB::select(
  426. DB::raw(
  427. "
  428. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  429. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  430. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  431. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  432. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  433. 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)
  434. "
  435. )
  436. );
  437. $keyNumbers['rmPatientsWithWhomCommDone'] = $count[0]->cnt;
  438. $count = DB::select(
  439. DB::raw(
  440. "
  441. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  442. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  443. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  444. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  445. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  446. 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)
  447. "
  448. )
  449. );
  450. $keyNumbers['rmPatientsWithWhomCommNotDone'] = $count[0]->cnt;
  451. // num measurements that need stamping
  452. $keyNumbers['measurementsToBeStamped'] = $this->performer()->pro->getUnstampedMeasurementsFromCurrentMonth(true, null, null);
  453. if($performer->pro->pro_type === 'ADMIN') {
  454. // patients without coverage information
  455. $keyNumbers['patientsWithoutCoverageInformation'] = DB::select(DB::raw("
  456. SELECT count(DISTINCT (cl.id)) as cnt
  457. FROM client cl
  458. WHERE cl.shadow_pro_id IS NULL AND cl.latest_client_primary_coverage_id IS NULL -- no coverage record"
  459. ))[0]->cnt;
  460. // patients pending coverage verification
  461. $keyNumbers['patientsPendingCoverageVerification'] = DB::select(DB::raw("
  462. SELECT count(DISTINCT (cl.id)) as cnt
  463. FROM client cl
  464. LEFT JOIN client_primary_coverage cpc ON cl.latest_client_primary_coverage_id = cpc.id
  465. WHERE cl.shadow_pro_id IS NULL
  466. AND (cl.latest_client_primary_coverage_id IS NOT NULL -- coverage exists, but status is null or unknown
  467. AND (
  468. (cpc.plan_type = 'MEDICARE' AND (cpc.is_partbprimary = 'UNKNOWN' OR cpc.is_partbprimary IS NULL))
  469. OR
  470. (cpc.plan_type != 'MEDICARE' AND
  471. (cpc.manual_determination_category = 'UNKNOWN' OR cpc.manual_determination_category IS NULL))
  472. ))"
  473. ))[0]->cnt;
  474. }
  475. return view('app/dashboard-mcp', compact('keyNumbers', 'reimbursement', 'milliseconds',
  476. 'businessNumbers',
  477. 'incomingReports', 'tickets', 'supplyOrders',
  478. 'numERx', 'numLabs', 'numImaging', 'numSupplyOrders',
  479. 'newMCPAssociations', 'newNAAssociations',
  480. 'mcpClientMemos', 'naClientMemos',
  481. 'proApptUpdates', 'naApptUpdates'));
  482. }
  483. private function dashboard_DNA(Request $request){
  484. $performer = $this->performer();
  485. $pro = $performer->pro;
  486. }
  487. private function dashboard_ADMIN(Request $request){
  488. $performer = $this->performer();
  489. $pro = $performer->pro;
  490. }
  491. public function dashboard(Request $request)
  492. {
  493. $performer = $this->performer();
  494. $pro = $performer->pro;
  495. if($pro->is_enrolled_as_mcp){
  496. return $this->dashboard_MCP($request);
  497. }elseif($pro->pro_type === 'ADMIN'){
  498. return $this->dashboard_ADMIN($request);
  499. }else{
  500. return $this->dashboard_DNA($request);
  501. }
  502. }
  503. public function dashboardMeasurementsTab(Request $request, $page = 1) {
  504. $performer = $this->performer();
  505. $myClientIDs = [];
  506. if ($performer->pro->pro_type != 'ADMIN') {
  507. $myClientIDs = $this->getMyClientIds();
  508. $myClientIDs = implode(", ", $myClientIDs);
  509. }
  510. $ifNotAdmin = " AND (
  511. client.mcp_pro_id = {$performer->pro->id}
  512. OR client.rmm_pro_id = {$performer->pro->id}
  513. OR client.rme_pro_id = {$performer->pro->id}
  514. OR client.physician_pro_id = {$performer->pro->id}
  515. OR client.id in (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = {$performer->pro->id})
  516. OR client.id in (SELECT client_id FROM appointment WHERE status NOT IN ('CANCELLED', 'ABANDONED') AND pro_id = {$performer->pro->id})
  517. )";
  518. $numMeasurements = DB::select(
  519. DB::raw(
  520. "
  521. SELECT count(measurement.id) as cnt
  522. FROM measurement
  523. join client on measurement.client_id = client.id
  524. WHERE measurement.label NOT IN ('SBP', 'DBP')
  525. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  526. AND measurement.is_removed IS FALSE
  527. AND measurement.has_been_stamped_by_mcp IS FALSE
  528. AND measurement.ts IS NOT NULL
  529. AND measurement.client_bdt_measurement_id IS NOT NULL
  530. AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
  531. AND EXTRACT(MONTH from measurement.created_at) = EXTRACT(MONTH from NOW())
  532. AND EXTRACT(YEAR from measurement.created_at) = EXTRACT(YEAR from NOW())
  533. " .
  534. (
  535. $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
  536. )
  537. )
  538. );
  539. $numMeasurements = $numMeasurements[0]->cnt;
  540. $measurements = DB::select(
  541. DB::raw(
  542. "
  543. SELECT measurement.uid as uid,
  544. care_month.uid as care_month_uid,
  545. care_month.start_date as care_month_start_date,
  546. measurement.label,
  547. measurement.value,
  548. measurement.sbp_mm_hg,
  549. measurement.dbp_mm_hg,
  550. measurement.numeric_value,
  551. measurement.value_pulse,
  552. measurement.value_irregular,
  553. measurement.ts,
  554. client.id as client_id,
  555. client.mcp_pro_id,
  556. client.default_na_pro_id,
  557. client.rmm_pro_id,
  558. client.rme_pro_id,
  559. client.uid as client_uid,
  560. client.name_last,
  561. client.name_first,
  562. care_month.rm_total_time_in_seconds
  563. FROM measurement
  564. join client on measurement.client_id = client.id
  565. join care_month on client.id = care_month.client_id
  566. WHERE measurement.label NOT IN ('SBP', 'DBP')
  567. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  568. AND measurement.is_removed IS FALSE
  569. AND measurement.has_been_stamped_by_mcp IS FALSE
  570. AND measurement.ts IS NOT NULL
  571. AND measurement.client_bdt_measurement_id IS NOT NULL
  572. AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
  573. AND EXTRACT(MONTH from measurement.created_at) = EXTRACT(MONTH from NOW())
  574. AND EXTRACT(YEAR from measurement.created_at) = EXTRACT(YEAR from NOW())
  575. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from NOW())
  576. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from NOW())
  577. " .
  578. (
  579. $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
  580. )
  581. ) .
  582. " ORDER BY measurement.ts DESC LIMIT 20 OFFSET " . (($page - 1) * 20)
  583. );
  584. return view('app.dashboard.measurements', compact('numMeasurements', 'measurements', 'page'));
  585. }
  586. public function dashboardAppointmentDates(Request $request, $from, $to) {
  587. $performer = $this->performer();
  588. $performerProID = $performer->pro->id;
  589. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  590. $results = DB::table('appointment')->select('raw_date')->distinct()->where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  591. if(!$isAdmin) {
  592. $results = $results->where("pro_id", $performerProID);
  593. }
  594. $results = $results->get();
  595. $dates = [];
  596. foreach ($results as $result) {
  597. // $dates[] = strtotime($result->raw_date) . '000';
  598. $dates[] = $result->raw_date;
  599. }
  600. // foreach ($results as $result) {
  601. // $results->dateYMD = date('Y-m-d', strtotime($result->raw_date));
  602. // }
  603. return json_encode($dates);
  604. }
  605. public function dashboardAppointments(Request $request, $from, $to) {
  606. $performer = $this->performer();
  607. $performerProID = $performer->pro->id;
  608. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  609. // $appointments = Appointment::where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  610. $appointments = Appointment::where("raw_date", '=', $from);
  611. if(!$isAdmin) {
  612. $appointments = $appointments->where("pro_id", $performerProID);
  613. }
  614. $appointments = $appointments
  615. ->orderBy('start_time', 'asc')
  616. ->get();
  617. foreach ($appointments as $appointment) {
  618. $date = explode(" ", $appointment->start_time)[0];
  619. $appointment->milliseconds = strtotime($date) . '000';
  620. $appointment->newStatus = $appointment->status;
  621. $appointment->dateYMD = date('Y-m-d', strtotime($appointment->raw_date));
  622. $appointment->clientName = $appointment->client->displayName();
  623. $appointment->clientInitials = substr($appointment->client->name_first, 0, 1) . substr($appointment->client->name_last, 0, 1);
  624. $appointment->isClientShadowOfPro = $appointment->client->shadow_pro_id ? true : false;
  625. $appointment->proInitials = substr($appointment->pro->name_first, 0, 1) . substr($appointment->pro->name_last, 0, 1);
  626. $appointment->friendlyStartTime = friendly_time($appointment->raw_start_time);
  627. $appointment->friendlyEndTime = friendly_time($appointment->raw_end_time);
  628. $appointment->clientSummary = friendly_date_time($appointment->client->dob, false) . ' (' .
  629. $appointment->client->age_in_years . ' y.o' .
  630. ($appointment->client->sex ? ' ' . $appointment->client->sex : '') .
  631. ')';
  632. $appointment->clientAge = $appointment->client->age_in_years;
  633. $appointment->clientSex = $appointment->client->sex;
  634. $appointment->started = false;
  635. $appointment->inHowManyHours = date_diff(date_create('now'), date_create($appointment->start_time), false)
  636. ->format('%R%h h, %i m');
  637. if ($appointment->inHowManyHours[0] === '-') {
  638. $appointment->inHowManyHours = substr($appointment->inHowManyHours, 1) . ' ago';
  639. $appointment->started = true;
  640. } else {
  641. $appointment->inHowManyHours = 'Appt. in ' . substr($appointment->inHowManyHours, 1);
  642. }
  643. $appointment->clientUid = $appointment->client->uid;
  644. $appointment->proUid = $appointment->pro->uid;
  645. $appointment->proName = $appointment->pro->displayName();
  646. // insurance information
  647. $appointment->coverage = $appointment->client->getPrimaryCoverageStatus();
  648. unset($appointment->client);
  649. unset($appointment->pro);
  650. unset($appointment->detail_json);
  651. }
  652. return json_encode($appointments);
  653. }
  654. public function dashboardMeasurements(Request $request, $filter) {
  655. $measurements = $this->performer()->pro->getMeasurements($filter === 'NEED_ACK');
  656. return json_encode($measurements);
  657. }
  658. public function patients(Request $request, $filter = '')
  659. {
  660. $performer = $this->performer();
  661. $query = $performer->pro->getAccessibleClientsQuery();
  662. $q = trim($request->input('q'));
  663. if(!empty($q)) {
  664. $query = $query->where(function ($query) use ($q) {
  665. $query->where('name_first', 'ILIKE', "%$q%")
  666. ->orWhere('name_last', 'ILIKE', "%$q%")
  667. ->orWhere('email_address', 'ILIKE', "%$q%")
  668. ->orWhere('tags', 'ILIKE', "%$q%");
  669. });
  670. }
  671. switch ($filter) {
  672. case 'not-yet-seen':
  673. $query = $query
  674. ->where(function ($query) use ($performer) {
  675. $query
  676. ->where(function ($query) use ($performer) { // own patient and primary OB visit pending
  677. $query->where('mcp_pro_id', $performer->pro->id)
  678. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  679. })
  680. ->orWhere(function ($query) use ($performer) { // mcp of any client program and program OB pending
  681. $query->select(DB::raw('COUNT(id)'))
  682. ->from('client_program')
  683. ->whereColumn('client_id', 'client.id')
  684. ->where('mcp_pro_id', $performer->pro->id)
  685. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  686. }, '>=', 1);
  687. });
  688. break;
  689. case 'having-birthday-today':
  690. $query = $query
  691. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  692. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')]);
  693. break;
  694. // more cases can be added as needed
  695. default:
  696. break;
  697. }
  698. $patients = $query->orderBy('id', 'desc')->paginate(50);
  699. // patient acquisition chart (admin only)
  700. $patientAcquisitionData = null;
  701. if($performer->pro->pro_type === 'ADMIN') {
  702. $startDate = date_sub(date_create(), date_interval_create_from_date_string("1 month"));
  703. $startDate = date_format($startDate, "Y-m-d");
  704. $patientAcquisitionData = DB::select(DB::raw(
  705. "SELECT count(id) as count, DATE(created_at at time zone 'utc' at time zone 'est') as date " .
  706. "FROM client " .
  707. "WHERE shadow_pro_id IS NULL " .
  708. "GROUP BY DATE(created_at at time zone 'utc' at time zone 'est') " .
  709. "ORDER BY DATE(created_at at time zone 'utc' at time zone 'est') DESC " .
  710. "LIMIT 30"));
  711. }
  712. return view('app/patients', compact('patients', 'filter', 'patientAcquisitionData'));
  713. }
  714. public function patientsSuggest(Request $request)
  715. {
  716. $pro = $this->pro;
  717. $term = $request->input('term') ? trim($request->input('term')) : '';
  718. $originalTerm = $term;
  719. if (empty($term)) return '';
  720. // if multiple words in query, check for all (max 2)
  721. $term2 = '';
  722. if(strpos($term, ' ') !== FALSE) {
  723. $terms = explode(' ', $term);
  724. $term = trim($terms[0]);
  725. $term2 = trim($terms[1]);
  726. }
  727. $phoneNumberTerm = preg_replace("/[^0-9]/", "", $originalTerm );
  728. if($phoneNumberTerm == ""){ //to avoid search with blank string
  729. $phoneNumberTerm = $term;
  730. }
  731. $clientQuery= Client::whereNull('shadow_pro_id')
  732. ->where(function ($q) use ($term, $phoneNumberTerm) {
  733. $q->where('name_first', 'ILIKE', '%' . $term . '%')
  734. ->orWhere('name_last', 'ILIKE', '%' . $term . '%')
  735. ->orWhere('cell_number', 'ILIKE', '%' . $phoneNumberTerm . '%')
  736. ->orWhere('phone_home', 'ILIKE', '%' . $phoneNumberTerm . '%');
  737. });
  738. if(!empty($term2)) {
  739. $clientQuery = $clientQuery->where(function ($q) use ($term2, $phoneNumberTerm) {
  740. $q->where('name_first', 'ILIKE', '%' . $term2 . '%')
  741. ->orWhere('name_last', 'ILIKE', '%' . $term2 . '%')
  742. ->orWhere('cell_number', 'ILIKE', '%' . $phoneNumberTerm . '%')
  743. ->orWhere('phone_home', 'ILIKE', '%' . $phoneNumberTerm . '%');
  744. });
  745. }
  746. if(!($pro->pro_type === 'ADMIN' && $pro->can_see_any_client_via_search)) {
  747. $clientQuery->where(function ($q) use ($pro) {
  748. if($pro->pro_type === 'ADMIN') {
  749. $q->whereIn('id', $pro->getMyClientIds(true))->orWhereNull('mcp_pro_id');
  750. }
  751. else {
  752. $q->whereIn('id', $pro->getMyClientIds(true));
  753. }
  754. });
  755. }
  756. $clients = $clientQuery->get();
  757. return view('app/patient-suggest', compact('clients'));
  758. }
  759. public function pharmacySuggest(Request $request)
  760. {
  761. $term = $request->input('term') ? trim($request->input('term')) : '';
  762. if (empty($term)) return '';
  763. $term = strtolower($term);
  764. $pharmacies = Facility::where('facility_type', 'Pharmacy')
  765. ->where(function ($q) use ($term) {
  766. $q->orWhereRaw('LOWER(name::text) LIKE ?', ['%' . $term . '%'])
  767. ->orWhereRaw('LOWER(address_line1::text) LIKE ?', ['%' . $term . '%'])
  768. ->orWhereRaw('LOWER(address_line2::text) LIKE ?', ['%' . $term . '%'])
  769. ->orWhereRaw('LOWER(address_city::text) LIKE ?', ['%' . $term . '%'])
  770. ->orWhereRaw('LOWER(address_state::text) LIKE ?', ['%' . $term . '%'])
  771. ->orWhereRaw('LOWER(phone::text) LIKE ?', ['%' . $term . '%'])
  772. ->orWhereRaw('LOWER(address_zip::text) LIKE ?', ['%' . $term . '%']);
  773. });
  774. if($request->input('city')) {
  775. $pharmacies = $pharmacies->whereRaw('LOWER(address_city::text) LIKE ?', ['%' . strtolower($request->input('city')) . '%']);
  776. }
  777. if($request->input('state')) {
  778. $pharmacies = $pharmacies->whereRaw('LOWER(address_state::text) LIKE ?', ['%' . strtolower($request->input('state')) . '%']);
  779. }
  780. if($request->input('zip')) {
  781. $pharmacies = $pharmacies->whereRaw('LOWER(address_zip::text) LIKE ?', ['%' . strtolower($request->input('zip')) . '%']);
  782. }
  783. $pharmacies = $pharmacies
  784. ->orderBy('name', 'asc')
  785. ->orderBy('address_line1', 'asc')
  786. ->orderBy('address_city', 'asc')
  787. ->orderBy('address_state', 'asc')
  788. ->get();
  789. return view('app/pharmacy-suggest', compact('pharmacies'));
  790. }
  791. public function proSuggest(Request $request) {
  792. $term = $request->input('term') ? trim($request->input('term')) : '';
  793. if (empty($term)) return '';
  794. $term = strtolower($term);
  795. $pros = Pro::where(function ($q) use ($term) {
  796. $q->orWhereRaw('LOWER(name_first::text) LIKE ?', ['%' . $term . '%'])
  797. ->orWhereRaw('LOWER(name_last::text) LIKE ?', ['%' . $term . '%'])
  798. ->orWhereRaw('cell_number LIKE ?', ['%' . $term . '%']);
  799. });
  800. $type = $request->input('type') ? trim($request->input('type')) : '';
  801. if(!!$type) {
  802. switch(strtolower($type)) {
  803. case 'hcp':
  804. $pros->where('is_hcp', true);
  805. break;
  806. case 'default-na': // TODO: fix condition for NA
  807. $pros->where('is_hcp', false)->where('pro_type', '!=', 'ADMIN');
  808. break;
  809. case 'admin':
  810. $pros->where('pro_type', 'ADMIN');
  811. break;
  812. case 'non-admin':
  813. $pros->where('pro_type', '!=', 'ADMIN');
  814. break;
  815. }
  816. }
  817. if($this->performer->pro && $this->performer->pro->pro_type != 'ADMIN'){
  818. $accessiblePros = ProProAccess::where('owner_pro_id', $this->performer->pro->id);
  819. $accessibleProIds = [];
  820. foreach($accessiblePros as $accessiblePro){
  821. $accessibleProIds[] = $accessiblePro->id;
  822. }
  823. $accessibleProIds[] = $this->performer->pro->id;
  824. // for dna, add pros accessible via pro teams
  825. if($this->performer->pro->isDefaultNA()) {
  826. $teams = $this->performer->pro->teamsWhereAssistant;
  827. foreach ($teams as $team) {
  828. if(!in_array($team->mcp_pro_id, $accessibleProIds)) {
  829. $accessibleProIds[] = $team->mcp_pro_id;
  830. }
  831. }
  832. }
  833. $pros->whereIn('id', $accessibleProIds);
  834. }
  835. $suggestedPros = $pros->orderBy('name_last')->orderBy('name_first')->get();
  836. // for calendar select2
  837. if($request->input('json')) {
  838. $jsonPros = $suggestedPros->map(function($_pro) {
  839. return [
  840. "uid" => $_pro->uid,
  841. "id" => $_pro->id,
  842. "text" => $_pro->displayName(),
  843. "initials" => $_pro->initials(),
  844. ];
  845. });
  846. return json_encode([
  847. "results" => $jsonPros
  848. ]);
  849. }
  850. return view('app/pro-suggest', compact('suggestedPros'));
  851. }
  852. public function canAccessPatient(Request $request, $uid) {
  853. return json_encode([
  854. "success" => true,
  855. "data" => $this->performer->pro->canAccess($uid)
  856. ]);
  857. }
  858. public function proDisplayName(Request $request, Pro $pro) {
  859. return $pro ? $pro->displayName() : '';
  860. }
  861. public function unmappedSMS(Request $request, $filter = '')
  862. {
  863. $proID = $this->performer()->pro->id;
  864. if ($this->performer()->pro->pro_type === 'ADMIN') {
  865. $query = Client::where('id', '>', 0);
  866. } else {
  867. $query = Client::where(function ($q) use ($proID) {
  868. $q->where('mcp_pro_id', $proID)
  869. ->orWhere('cm_pro_id', $proID)
  870. ->orWhere('rmm_pro_id', $proID)
  871. ->orWhere('rme_pro_id', $proID)
  872. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID]);
  873. });
  874. }
  875. $patients = $query->orderBy('name_last', 'asc')->orderBy('name_first', 'asc')->get();
  876. $unmappedSMS = ClientSMS::where('client_id', null)->where('incoming_or_outgoing', 'INCOMING')->paginate(20);
  877. return view('app/unmapped-sms', compact('unmappedSMS', 'patients'));
  878. }
  879. public function newPatient(Request $request)
  880. {
  881. $mbPayers = MBPayer::all();
  882. return view('app/new-patient', compact('mbPayers'));
  883. }
  884. public function newNonMcnPatient(Request $request)
  885. {
  886. $mbPayers = MBPayer::all();
  887. return view('app/new-non-mcn-patient', compact('mbPayers'));
  888. }
  889. public function mc(Request $request, $fragment = "")
  890. {
  891. $page = "/";
  892. if ($fragment) {
  893. $page = '/' . $fragment;
  894. }
  895. return view('app/mc', compact('page'));
  896. }
  897. public function blank(Request $request)
  898. {
  899. return view('app/blank');
  900. }
  901. public function noteTemplateSet(Request $request, $section, $template)
  902. {
  903. return view('app/patient/note/_template', [
  904. "sectionInternalName" => $section,
  905. "templateName" => $template
  906. ]);
  907. }
  908. public function noteExamTemplateSet(Request $request, $exam, $template)
  909. {
  910. return view('app/patient/note/_template-exam', [
  911. "exam" => $exam,
  912. "sectionInternalName" => 'exam-' . $exam . '-detail',
  913. "templateName" => $template
  914. ]);
  915. }
  916. public function logInAs(Request $request)
  917. {
  918. if($this->pro->pro_type != 'ADMIN'){
  919. return redirect()->to(route('dashboard'));
  920. }
  921. // dummy condition to get the chain-ability going
  922. $pros = Pro::where('id', '>', 0);
  923. if($request->input('q')) {
  924. $nameQuery = '%' . $request->input('q') . '%';
  925. $pros = $pros->where(function ($query) use ($nameQuery) {
  926. $query->where('name_first', 'ILIKE', $nameQuery)
  927. ->orWhere('name_last', 'ILIKE', $nameQuery)
  928. ->orWhere('email_address', 'ILIKE', $nameQuery)
  929. ->orWhere('cell_number', 'ILIKE', $nameQuery);
  930. });
  931. }
  932. if($request->input('sort') && $request->input('dir')) {
  933. $pros = $pros->orderBy($request->input('sort'), $request->input('dir'));
  934. }
  935. else {
  936. $pros = $pros->orderBy('name_last', 'asc');
  937. }
  938. $pros = $pros->paginate(20);
  939. return view('app/log-in-as', ['logInAsPros' => $pros]);
  940. }
  941. public function processLogInAs(Request $request)
  942. {
  943. $api = new Backend();
  944. try {
  945. $apiResponse = $api->post('session/proLogInAs', [
  946. 'proUid' => $request->post('proUid')
  947. ],
  948. [
  949. 'sessionKey'=>$this->performer()->session_key
  950. ]);
  951. $data = json_decode($apiResponse->getContents());
  952. if (!property_exists($data, 'success') || !$data->success) {
  953. return redirect()->to(route('log-in-as'))->with('message', $data->message)
  954. ->withInput($request->input());
  955. }
  956. Cookie::queue('sessionKey', $data->data->sessionKey);
  957. return redirect('/mc');
  958. } catch (\Exception $e) {
  959. return redirect()->to(route('log-in-as'))
  960. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  961. ->withInput($request->input());
  962. }
  963. }
  964. public function backToAdminPro(Request $request){
  965. $adminPerformerId = $this->performer->logged_in_as_pro_from_admin_pro_app_session_id;
  966. $adminPerformer = AppSession::where('id', $adminPerformerId)->first();
  967. $url = "/session/pro_log_in_with_session_key/".$adminPerformer->session_key;
  968. $api = new Backend();
  969. try {
  970. $apiResponse = $api->post($url, []);
  971. $data = json_decode($apiResponse->getContents());
  972. if (!property_exists($data, 'success') || !$data->success) {
  973. return redirect()->to(route('logout'));
  974. }
  975. Cookie::queue('sessionKey', $data->data->sessionKey);
  976. return redirect(route('dashboard'));
  977. } catch (\Exception $e) {
  978. return redirect(route('dashboard'));
  979. }
  980. }
  981. public function getTicket(Request $request, Ticket $ticket) {
  982. $ticket->data = json_decode($ticket->data);
  983. // $ticket->created_at = friendly_date_time($ticket->created_at);
  984. $ticket->assignedPro;
  985. $ticket->managerPro;
  986. $ticket->orderingPro;
  987. $ticket->initiatingPro;
  988. return json_encode($ticket);
  989. }
  990. public function genericBill(Request $request, $entityType, $entityUid) {
  991. $patient = null;
  992. if ($entityType && $entityUid) {
  993. try {
  994. $entityClass = "\\App\\Models\\" . $entityType;
  995. $entity = $entityClass::where('uid', $entityUid)->first();
  996. if ($entity->client) {
  997. $patient = $entity->client;
  998. }
  999. } catch (\Exception $e) {
  1000. }
  1001. }
  1002. return view('app.generic-bills.inline', ['class' => 'p-3 border-top mt-3', 'entityType' => $entityType, 'entityUid' => $entityUid, 'patient' => $patient]);
  1003. }
  1004. }