HomeController.php 50 KB

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