HomeController.php 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534
  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. $keyNumbers = [];
  489. // Patients // SELECT * FROM client WHERE mcp_pro_id = :me.id;
  490. // New Patients Awaiting Visit // SELECT * FROM client WHERE mcp_pro_id = :me.id AND hasMcpDoneOnboardingVisit != 'YES';
  491. // 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;
  492. // 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;
  493. // Reports Pending Signature // SELECT * FROM incoming_report WHERE hcp_pro_id = :me.id AND isEntryError IS NOT TRUE AND hasHcpProSigned IS NOT TRUE;
  494. // Patients w/o Appointments // SELECT * FROM client WHERE mcp_pro_id = :me.id AND client.next_mcp_appointment_date < today();
  495. // Patients Overdue for Visit // SELECT * FROM client WHERE mcp_pro_id = :me.id AND client.next_expected_mcp_visit_date < today();
  496. // Cancelled Appts. Pending Review // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  497. // Cancelled Bills Pending Review // SELECT * FROM bill WHERE bill_service_type = 'NOTE' AND is_cancelled IS TRUE AND isCancellationAcknowledged IS FALSE;
  498. // 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;
  499. // ERx & Orders Pending Signature // SELECT * FROM erx WHERE hcp_pro_id = :me.id AND pro_declared_status <> 'CANCELLED' AND hasHcpProSigned IS NOT TRUE;
  500. // 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;
  501. $performer = $this->performer();
  502. $pro = $performer->pro;
  503. $performerProID = $performer->pro->id;
  504. $keyNumbers = [];
  505. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  506. $pendingNotesToSign = Note
  507. ::where(function ($query) use ($performerProID) {
  508. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false);
  509. })
  510. ->orWhere(function ($query) use ($performerProID) {
  511. $query->where('ally_pro_id', $performerProID)->where('is_signed_by_ally', false)->where('is_cancelled', false);
  512. })
  513. ->count();
  514. $keyNumbers['pendingNotesToSign'] = $pendingNotesToSign;
  515. // notes pending mcp sign (applicable to dnas only)
  516. $pendingNotesToSignMCP = Note
  517. ::where(function ($query) use ($performerProID) {
  518. $query->where('ally_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false);
  519. })
  520. ->count();
  521. $keyNumbers['$pendingNotesToSignMCP'] = $pendingNotesToSignMCP;
  522. $pendingNotesToSignAllySigned = Note::where(function ($query) use ($performerProID) {
  523. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_signed_by_ally', true)->where('is_cancelled', false);;
  524. })->count();
  525. $keyNumbers['pendingNotesToSignAllySigned'] = $pendingNotesToSignAllySigned;
  526. $signedNotesWithoutBills = Note::where(function ($query) use ($performerProID) {
  527. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', true)->where('is_cancelled', false);
  528. })->whereDoesntHave('bills')->count();
  529. $keyNumbers['signedNotesWithoutBills'] = $signedNotesWithoutBills;
  530. // open tickets
  531. $keyNumbers['numOpenTickets'] = Ticket::where('is_open', true)
  532. ->where(function ($q) use ($performerProID) {
  533. $q->where('assigned_pro_id', $performerProID)
  534. ->orWhere('manager_pro_id', $performerProID)
  535. ->orWhere('ordering_pro_id', $performerProID)
  536. ->orWhere('initiating_pro_id', $performerProID);
  537. })
  538. ->count();
  539. // unacknowledged cancelled bills for authed pro
  540. $keyNumbers['unacknowledgedCancelledBills'] = Bill::where('hcp_pro_id', $performerProID)
  541. ->where('is_cancelled', true)
  542. ->where('is_cancellation_acknowledged', false)
  543. ->count();
  544. // unacknowledged cancelled supply orders for authed pro
  545. $keyNumbers['unacknowledgedCancelledSupplyOrders'] = SupplyOrder::where('signed_by_pro_id', $performerProID)
  546. ->where('is_cancelled', true)
  547. ->where('is_cancellation_acknowledged', false)
  548. ->count();
  549. // unsigned supply orders created by authed pro
  550. $keyNumbers['unsignedSupplyOrders'] = SupplyOrder
  551. ::where('is_cancelled', false)
  552. ->where('is_signed_by_pro', false)
  553. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$performerProID])
  554. ->count();
  555. // patientsHavingBirthdayToday
  556. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  557. $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
  558. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  559. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
  560. ->count();
  561. $reimbursement = [];
  562. $reimbursement["currentBalance"] = $performer->pro->balance;
  563. $reimbursement["nextPaymentDate"] = '--';
  564. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  565. if ($lastPayment) {
  566. $reimbursement["lastPayment"] = $lastPayment->amount;
  567. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  568. } else {
  569. $reimbursement["lastPayment"] = '--';
  570. $reimbursement["lastPaymentDate"] = '--';
  571. }
  572. //if today is < 15th, next payment is 15th, else nextPayment is
  573. $today = strtotime(date('Y-m-d'));
  574. $todayDate = date('j', $today);
  575. $todayMonth = date('m', $today);
  576. $todayYear = date('Y', $today);
  577. if ($todayDate < 15) {
  578. $nextPaymentDate = new DateTime();
  579. $nextPaymentDate->setDate($todayYear, $todayMonth, 15);
  580. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  581. } else {
  582. $nextPaymentDate = new \DateTime();
  583. $lastDayOfMonth = date('t', $today);
  584. $nextPaymentDate->setDate($todayYear, $todayMonth, $lastDayOfMonth);
  585. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  586. }
  587. //expectedPay
  588. $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;
  589. $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;
  590. $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;
  591. $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;
  592. $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;
  593. $totalExpectedAmount = $expectedForHcp + $expectedForCm + $expectedForRme + $expectedForRmm + $expectedForNa;
  594. $reimbursement['nextPaymentAmount'] = $totalExpectedAmount;
  595. $milliseconds = strtotime(date('Y-m-d')) . '000';
  596. // bills & claims
  597. $businessNumbers = [];
  598. // Notes with bills to resolve
  599. $businessNumbers['notesWithBillsToResolve'] = Note::where('is_cancelled', '!=', true)
  600. ->where('is_bill_closed', '!=', true)
  601. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND is_cancelled = false AND is_verified = false) > 0')
  602. ->count();
  603. // Notes pending bill closure
  604. $businessNumbers['notesPendingBillingClosure'] = Note::where('is_cancelled', '!=', true)
  605. ->where('is_bill_closed', '!=', true)
  606. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND (is_cancelled = true OR is_verified = true)) = 0')
  607. ->count();
  608. // incoming reports not signed
  609. $incomingReports = IncomingReport::where('hcp_pro_id', $performerProID)
  610. ->where('has_hcp_pro_signed', false)
  611. ->where('is_entry_error', false)
  612. ->orderBy('created_at', 'ASC')
  613. ->get();
  614. // erx, labs & imaging that are not closed
  615. $tickets = Ticket::where('ordering_pro_id', $performerProID)
  616. ->where('is_entry_error', false)
  617. ->where('is_open', true)
  618. ->orderBy('created_at', 'ASC')
  619. ->get();
  620. $supplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  621. ->where('is_cancelled', false)
  622. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  623. ->orderBy('created_at', 'ASC')
  624. ->get();
  625. $numERx = Ticket::where('ordering_pro_id', $performerProID)
  626. ->where('category', 'erx')
  627. ->where('is_entry_error', false)
  628. ->where('is_open', true)
  629. ->count();
  630. $numLabs = Ticket::where('ordering_pro_id', $performerProID)
  631. ->where('category', 'lab')
  632. ->where('is_entry_error', false)
  633. ->where('is_open', true)
  634. ->count();
  635. $numImaging = Ticket::where('ordering_pro_id', $performerProID)
  636. ->where('category', 'imaging')
  637. ->where('is_entry_error', false)
  638. ->where('is_open', true)
  639. ->count();
  640. $numSupplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  641. ->where('is_cancelled', false)
  642. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  643. ->count();
  644. $newMCPAssociations = ClientProChange
  645. ::where('new_pro_id', $performerProID)
  646. ->where('responsibility_type', 'MCP')
  647. ->whereNull('current_client_pro_change_decision_id')
  648. ->get();
  649. $newNAAssociations = ClientProChange
  650. ::where('new_pro_id', $performerProID)
  651. ->where('responsibility_type', 'DEFAULT_NA')
  652. ->whereNull('current_client_pro_change_decision_id')
  653. ->get();
  654. $proApptUpdates = AppointmentConfirmationDecision
  655. ::select('appointment_confirmation_decision.uid', 'client.name_first', 'client.name_last', 'appointment.start_time')
  656. ->rightJoin('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  657. ->rightJoin('client', 'client.id', '=', 'appointment.client_id')
  658. ->where('appointment_confirmation_decision.was_acknowledged_by_appointment_pro', false)
  659. ->where('appointment.status', '!=', 'CREATED')
  660. ->where('appointment.status', '!=', 'COMPLETED')
  661. ->where('appointment.status', '!=', 'ABANDONED')
  662. ->where('appointment.pro_id', $performerProID)
  663. ->where('client.mcp_pro_id', $performerProID)
  664. ->orderBy('appointment.start_time', 'DESC')
  665. ->get();
  666. $naApptUpdates = AppointmentConfirmationDecision
  667. ::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')
  668. ->rightJoin('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  669. ->rightJoin('client', 'client.id', '=', 'appointment.client_id')
  670. ->rightJoin('pro', 'pro.id', '=', 'appointment.pro_id')
  671. ->where('appointment_confirmation_decision.was_acknowledged_by_client_default_na', false)
  672. ->where('appointment.status', '!=', 'CREATED')
  673. ->where('appointment.status', '!=', 'COMPLETED')
  674. ->where('appointment.status', '!=', 'ABANDONED')
  675. ->where('client.default_na_pro_id', $performerProID)
  676. ->orderBy('appointment.start_time', 'DESC')
  677. ->get();
  678. // $naApptUpdates = AppointmentConfirmationDecision
  679. // ::join('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  680. // ->join('client', 'client.id', '=', 'appointment.client_id')
  681. // ->where('client.default_na_pro_id', $performerProID)
  682. // ->where('appointment_confirmation_decision.was_acknowledged_by_client_default_na', false)
  683. // ->orderBy('appointment.start_time DESC')
  684. // ->get();
  685. // unstamped client memos
  686. // for mcp
  687. $mcpClientMemos = DB::select(
  688. DB::raw("
  689. SELECT c.uid as client_uid, c.name_first, c.name_last,
  690. cm.uid, cm.content, cm.created_at
  691. FROM client c join client_memo cm on c.id = cm.client_id
  692. WHERE
  693. c.mcp_pro_id = {$performerProID} AND
  694. cm.mcp_stamp_id IS NULL
  695. ORDER BY cm.created_at DESC
  696. ")
  697. );
  698. // for na
  699. $naClientMemos = DB::select(
  700. DB::raw("
  701. SELECT c.uid as client_uid, c.name_first, c.name_last,
  702. cm.uid, cm.content, cm.created_at
  703. FROM client c join client_memo cm on c.id = cm.client_id
  704. WHERE
  705. c.default_na_pro_id = {$performerProID} AND
  706. cm.default_na_stamp_id IS NULL
  707. ORDER BY cm.created_at DESC
  708. ")
  709. );
  710. $keyNumbers['rmBillsToSign'] = Bill
  711. ::where('is_cancelled', false)
  712. ->where('cm_or_rm', 'RM')
  713. ->where(function ($q) use ($performerProID) {
  714. $q
  715. ->where(function ($q2) use ($performerProID) {
  716. $q2->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false);
  717. })
  718. ->orWhere(function ($q2) use ($performerProID) {
  719. $q2->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false);
  720. })
  721. ->orWhere(function ($q2) use ($performerProID) {
  722. $q2->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false);
  723. })
  724. ->orWhere(function ($q2) use ($performerProID) {
  725. $q2->where('generic_pro_id', $performerProID)->where('is_signed_by_generic_pro', false);
  726. });
  727. })
  728. ->count();
  729. $count = DB::select(
  730. DB::raw(
  731. "
  732. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  733. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  734. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  735. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  736. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  737. AND (care_month.number_of_days_with_remote_measurements < 16 OR care_month.number_of_days_with_remote_measurements IS NULL)
  738. "
  739. )
  740. );
  741. $keyNumbers['rmPatientsWithLT16MD'] = $count[0]->cnt;
  742. $count = DB::select(
  743. DB::raw(
  744. "
  745. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  746. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  747. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  748. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  749. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  750. AND (care_month.number_of_days_with_remote_measurements >= 16 AND care_month.number_of_days_with_remote_measurements IS NOT NULL)
  751. "
  752. )
  753. );
  754. $keyNumbers['rmPatientsWithGTE16MD'] = $count[0]->cnt;
  755. $count = DB::select(
  756. DB::raw(
  757. "
  758. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  759. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  760. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  761. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  762. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  763. 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)
  764. "
  765. )
  766. );
  767. $keyNumbers['rmPatientsWithWhomCommDone'] = $count[0]->cnt;
  768. $count = DB::select(
  769. DB::raw(
  770. "
  771. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  772. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  773. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  774. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  775. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  776. 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)
  777. "
  778. )
  779. );
  780. $keyNumbers['rmPatientsWithWhomCommNotDone'] = $count[0]->cnt;
  781. // num measurements that need stamping
  782. $keyNumbers['measurementsToBeStamped'] = $this->performer()->pro->getUnstampedMeasurementsFromCurrentMonth(true, null, null);
  783. if($performer->pro->pro_type === 'ADMIN') {
  784. // patients without coverage information
  785. $keyNumbers['patientsWithoutCoverageInformation'] = DB::select(DB::raw("
  786. SELECT count(DISTINCT (cl.id)) as cnt
  787. FROM client cl
  788. WHERE cl.shadow_pro_id IS NULL AND cl.latest_client_primary_coverage_id IS NULL -- no coverage record"
  789. ))[0]->cnt;
  790. // patients pending coverage verification
  791. $keyNumbers['patientsPendingCoverageVerification'] = DB::select(DB::raw("
  792. SELECT count(DISTINCT (cl.id)) as cnt
  793. FROM client cl
  794. LEFT JOIN client_primary_coverage cpc ON cl.latest_client_primary_coverage_id = cpc.id
  795. WHERE cl.shadow_pro_id IS NULL
  796. AND (cl.latest_client_primary_coverage_id IS NOT NULL -- coverage exists, but status is null or unknown
  797. AND (
  798. (cpc.plan_type = 'MEDICARE' AND (cpc.is_partbprimary = 'UNKNOWN' OR cpc.is_partbprimary IS NULL))
  799. OR
  800. (cpc.plan_type != 'MEDICARE' AND
  801. (cpc.manual_determination_category = 'UNKNOWN' OR cpc.manual_determination_category IS NULL))
  802. ))"
  803. ))[0]->cnt;
  804. }
  805. return view('app/dashboard-admin', compact('keyNumbers', 'reimbursement', 'milliseconds',
  806. 'businessNumbers',
  807. 'incomingReports', 'tickets', 'supplyOrders',
  808. 'numERx', 'numLabs', 'numImaging', 'numSupplyOrders',
  809. 'newMCPAssociations', 'newNAAssociations',
  810. 'mcpClientMemos', 'naClientMemos',
  811. 'proApptUpdates', 'naApptUpdates'));
  812. }
  813. public function dashboard(Request $request)
  814. {
  815. $performer = $this->performer();
  816. $pro = $performer->pro;
  817. if($pro->is_enrolled_as_mcp){
  818. return $this->dashboard_MCP($request);
  819. }elseif($pro->pro_type === 'ADMIN'){
  820. return $this->dashboard_ADMIN($request);
  821. }else{
  822. return $this->dashboard_DNA($request);
  823. }
  824. }
  825. public function dashboardMeasurementsTab(Request $request, $page = 1) {
  826. $performer = $this->performer();
  827. $myClientIDs = [];
  828. if ($performer->pro->pro_type != 'ADMIN') {
  829. $myClientIDs = $this->getMyClientIds();
  830. $myClientIDs = implode(", ", $myClientIDs);
  831. }
  832. $ifNotAdmin = " AND (
  833. client.mcp_pro_id = {$performer->pro->id}
  834. OR client.rmm_pro_id = {$performer->pro->id}
  835. OR client.rme_pro_id = {$performer->pro->id}
  836. OR client.physician_pro_id = {$performer->pro->id}
  837. OR client.id in (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = {$performer->pro->id})
  838. OR client.id in (SELECT client_id FROM appointment WHERE status NOT IN ('CANCELLED', 'ABANDONED') AND pro_id = {$performer->pro->id})
  839. )";
  840. $numMeasurements = DB::select(
  841. DB::raw(
  842. "
  843. SELECT count(measurement.id) as cnt
  844. FROM measurement
  845. join client on measurement.client_id = client.id
  846. WHERE measurement.label NOT IN ('SBP', 'DBP')
  847. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  848. AND measurement.is_removed IS FALSE
  849. AND measurement.has_been_stamped_by_mcp IS FALSE
  850. AND measurement.ts IS NOT NULL
  851. AND measurement.client_bdt_measurement_id IS NOT NULL
  852. AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
  853. AND EXTRACT(MONTH from measurement.created_at) = EXTRACT(MONTH from NOW())
  854. AND EXTRACT(YEAR from measurement.created_at) = EXTRACT(YEAR from NOW())
  855. " .
  856. (
  857. $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
  858. )
  859. )
  860. );
  861. $numMeasurements = $numMeasurements[0]->cnt;
  862. $measurements = DB::select(
  863. DB::raw(
  864. "
  865. SELECT measurement.uid as uid,
  866. care_month.uid as care_month_uid,
  867. care_month.start_date as care_month_start_date,
  868. measurement.label,
  869. measurement.value,
  870. measurement.sbp_mm_hg,
  871. measurement.dbp_mm_hg,
  872. measurement.numeric_value,
  873. measurement.value_pulse,
  874. measurement.value_irregular,
  875. measurement.ts,
  876. client.id as client_id,
  877. client.mcp_pro_id,
  878. client.default_na_pro_id,
  879. client.rmm_pro_id,
  880. client.rme_pro_id,
  881. client.uid as client_uid,
  882. client.name_last,
  883. client.name_first,
  884. care_month.rm_total_time_in_seconds
  885. FROM measurement
  886. join client on measurement.client_id = client.id
  887. join care_month on client.id = care_month.client_id
  888. WHERE measurement.label NOT IN ('SBP', 'DBP')
  889. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  890. AND measurement.is_removed IS FALSE
  891. AND measurement.has_been_stamped_by_mcp IS FALSE
  892. AND measurement.ts IS NOT NULL
  893. AND measurement.client_bdt_measurement_id IS NOT NULL
  894. AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
  895. AND EXTRACT(MONTH from measurement.created_at) = EXTRACT(MONTH from NOW())
  896. AND EXTRACT(YEAR from measurement.created_at) = EXTRACT(YEAR from NOW())
  897. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from NOW())
  898. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from NOW())
  899. " .
  900. (
  901. $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
  902. )
  903. ) .
  904. " ORDER BY measurement.ts DESC LIMIT 20 OFFSET " . (($page - 1) * 20)
  905. );
  906. return view('app.dashboard.measurements', compact('numMeasurements', 'measurements', 'page'));
  907. }
  908. public function dashboardAppointmentDates(Request $request, $from, $to) {
  909. $performer = $this->performer();
  910. $performerProID = $performer->pro->id;
  911. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  912. $results = DB::table('appointment')->select('raw_date')->distinct()->where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  913. if(!$isAdmin) {
  914. $results = $results->where("pro_id", $performerProID);
  915. }
  916. $results = $results->get();
  917. $dates = [];
  918. foreach ($results as $result) {
  919. // $dates[] = strtotime($result->raw_date) . '000';
  920. $dates[] = $result->raw_date;
  921. }
  922. // foreach ($results as $result) {
  923. // $results->dateYMD = date('Y-m-d', strtotime($result->raw_date));
  924. // }
  925. return json_encode($dates);
  926. }
  927. public function dashboardAppointments(Request $request, $from, $to) {
  928. $performer = $this->performer();
  929. $performerProID = $performer->pro->id;
  930. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  931. // $appointments = Appointment::where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  932. $appointments = Appointment::where("raw_date", '=', $from);
  933. if(!$isAdmin) {
  934. $appointments = $appointments->where("pro_id", $performerProID);
  935. }
  936. $appointments = $appointments
  937. ->orderBy('start_time', 'asc')
  938. ->get();
  939. foreach ($appointments as $appointment) {
  940. $date = explode(" ", $appointment->start_time)[0];
  941. $appointment->milliseconds = strtotime($date) . '000';
  942. $appointment->newStatus = $appointment->status;
  943. $appointment->dateYMD = date('Y-m-d', strtotime($appointment->raw_date));
  944. $appointment->clientName = $appointment->client->displayName();
  945. $appointment->clientInitials = substr($appointment->client->name_first, 0, 1) . substr($appointment->client->name_last, 0, 1);
  946. $appointment->isClientShadowOfPro = $appointment->client->shadow_pro_id ? true : false;
  947. $appointment->proInitials = substr($appointment->pro->name_first, 0, 1) . substr($appointment->pro->name_last, 0, 1);
  948. $appointment->friendlyStartTime = friendly_time($appointment->raw_start_time);
  949. $appointment->friendlyEndTime = friendly_time($appointment->raw_end_time);
  950. $appointment->clientSummary = friendly_date_time($appointment->client->dob, false) . ' (' .
  951. $appointment->client->age_in_years . ' y.o' .
  952. ($appointment->client->sex ? ' ' . $appointment->client->sex : '') .
  953. ')';
  954. $appointment->clientAge = $appointment->client->age_in_years;
  955. $appointment->clientSex = $appointment->client->sex;
  956. $appointment->started = false;
  957. $appointment->inHowManyHours = date_diff(date_create('now'), date_create($appointment->start_time), false)
  958. ->format('%R%h h, %i m');
  959. if ($appointment->inHowManyHours[0] === '-') {
  960. $appointment->inHowManyHours = substr($appointment->inHowManyHours, 1) . ' ago';
  961. $appointment->started = true;
  962. } else {
  963. $appointment->inHowManyHours = 'Appt. in ' . substr($appointment->inHowManyHours, 1);
  964. }
  965. $appointment->clientUid = $appointment->client->uid;
  966. $appointment->proUid = $appointment->pro->uid;
  967. $appointment->proName = $appointment->pro->displayName();
  968. // insurance information
  969. $appointment->coverage = $appointment->client->getPrimaryCoverageStatus();
  970. unset($appointment->client);
  971. unset($appointment->pro);
  972. unset($appointment->detail_json);
  973. }
  974. return json_encode($appointments);
  975. }
  976. public function dashboardMeasurements(Request $request, $filter) {
  977. $measurements = $this->performer()->pro->getMeasurements($filter === 'NEED_ACK');
  978. return json_encode($measurements);
  979. }
  980. public function patients(Request $request, $filter = '')
  981. {
  982. $performer = $this->performer();
  983. $query = $performer->pro->getAccessibleClientsQuery();
  984. $q = trim($request->input('q'));
  985. if(!empty($q)) {
  986. $query = $query->where(function ($query) use ($q) {
  987. $query->where('name_first', 'ILIKE', "%$q%")
  988. ->orWhere('name_last', 'ILIKE', "%$q%")
  989. ->orWhere('email_address', 'ILIKE', "%$q%")
  990. ->orWhere('tags', 'ILIKE', "%$q%");
  991. });
  992. }
  993. switch ($filter) {
  994. case 'not-yet-seen':
  995. $query = $query
  996. ->where(function ($query) use ($performer) {
  997. $query
  998. ->where(function ($query) use ($performer) { // own patient and primary OB visit pending
  999. $query->where('mcp_pro_id', $performer->pro->id)
  1000. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  1001. })
  1002. ->orWhere(function ($query) use ($performer) { // mcp of any client program and program OB pending
  1003. $query->select(DB::raw('COUNT(id)'))
  1004. ->from('client_program')
  1005. ->whereColumn('client_id', 'client.id')
  1006. ->where('mcp_pro_id', $performer->pro->id)
  1007. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  1008. }, '>=', 1);
  1009. });
  1010. break;
  1011. case 'having-birthday-today':
  1012. $query = $query
  1013. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  1014. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')]);
  1015. break;
  1016. // more cases can be added as needed
  1017. default:
  1018. break;
  1019. }
  1020. $patients = $query->orderBy('id', 'desc')->paginate(50);
  1021. // patient acquisition chart (admin only)
  1022. $patientAcquisitionData = null;
  1023. if($performer->pro->pro_type === 'ADMIN') {
  1024. $startDate = date_sub(date_create(), date_interval_create_from_date_string("1 month"));
  1025. $startDate = date_format($startDate, "Y-m-d");
  1026. $patientAcquisitionData = DB::select(DB::raw(
  1027. "SELECT count(id) as count, DATE(created_at at time zone 'utc' at time zone 'est') as date " .
  1028. "FROM client " .
  1029. "WHERE shadow_pro_id IS NULL " .
  1030. "GROUP BY DATE(created_at at time zone 'utc' at time zone 'est') " .
  1031. "ORDER BY DATE(created_at at time zone 'utc' at time zone 'est') DESC " .
  1032. "LIMIT 30"));
  1033. }
  1034. return view('app/patients', compact('patients', 'filter', 'patientAcquisitionData'));
  1035. }
  1036. public function patientsSuggest(Request $request)
  1037. {
  1038. $pro = $this->pro;
  1039. $term = $request->input('term') ? trim($request->input('term')) : '';
  1040. $originalTerm = $term;
  1041. if (empty($term)) return '';
  1042. // if multiple words in query, check for all (max 2)
  1043. $term2 = '';
  1044. if(strpos($term, ' ') !== FALSE) {
  1045. $terms = explode(' ', $term);
  1046. $term = trim($terms[0]);
  1047. $term2 = trim($terms[1]);
  1048. }
  1049. $phoneNumberTerm = preg_replace("/[^0-9]/", "", $originalTerm );
  1050. if($phoneNumberTerm == ""){ //to avoid search with blank string
  1051. $phoneNumberTerm = $term;
  1052. }
  1053. $clientQuery= Client::whereNull('shadow_pro_id')
  1054. ->where(function ($q) use ($term, $phoneNumberTerm) {
  1055. $q->where('name_first', 'ILIKE', '%' . $term . '%')
  1056. ->orWhere('name_last', 'ILIKE', '%' . $term . '%')
  1057. ->orWhere('cell_number', 'ILIKE', '%' . $phoneNumberTerm . '%')
  1058. ->orWhere('phone_home', 'ILIKE', '%' . $phoneNumberTerm . '%');
  1059. });
  1060. if(!empty($term2)) {
  1061. $clientQuery = $clientQuery->where(function ($q) use ($term2, $phoneNumberTerm) {
  1062. $q->where('name_first', 'ILIKE', '%' . $term2 . '%')
  1063. ->orWhere('name_last', 'ILIKE', '%' . $term2 . '%')
  1064. ->orWhere('cell_number', 'ILIKE', '%' . $phoneNumberTerm . '%')
  1065. ->orWhere('phone_home', 'ILIKE', '%' . $phoneNumberTerm . '%');
  1066. });
  1067. }
  1068. if(!($pro->pro_type === 'ADMIN' && $pro->can_see_any_client_via_search)) {
  1069. $clientQuery->where(function ($q) use ($pro) {
  1070. if($pro->pro_type === 'ADMIN') {
  1071. $q->whereIn('id', $pro->getMyClientIds(true))->orWhereNull('mcp_pro_id');
  1072. }
  1073. else {
  1074. $q->whereIn('id', $pro->getMyClientIds(true));
  1075. }
  1076. });
  1077. }
  1078. $clients = $clientQuery->get();
  1079. return view('app/patient-suggest', compact('clients'));
  1080. }
  1081. public function pharmacySuggest(Request $request)
  1082. {
  1083. $term = $request->input('term') ? trim($request->input('term')) : '';
  1084. if (empty($term)) return '';
  1085. $term = strtolower($term);
  1086. $pharmacies = Facility::where('facility_type', 'Pharmacy')
  1087. ->where(function ($q) use ($term) {
  1088. $q->orWhereRaw('LOWER(name::text) LIKE ?', ['%' . $term . '%'])
  1089. ->orWhereRaw('LOWER(address_line1::text) LIKE ?', ['%' . $term . '%'])
  1090. ->orWhereRaw('LOWER(address_line2::text) LIKE ?', ['%' . $term . '%'])
  1091. ->orWhereRaw('LOWER(address_city::text) LIKE ?', ['%' . $term . '%'])
  1092. ->orWhereRaw('LOWER(address_state::text) LIKE ?', ['%' . $term . '%'])
  1093. ->orWhereRaw('LOWER(phone::text) LIKE ?', ['%' . $term . '%'])
  1094. ->orWhereRaw('LOWER(address_zip::text) LIKE ?', ['%' . $term . '%']);
  1095. });
  1096. if($request->input('city')) {
  1097. $pharmacies = $pharmacies->whereRaw('LOWER(address_city::text) LIKE ?', ['%' . strtolower($request->input('city')) . '%']);
  1098. }
  1099. if($request->input('state')) {
  1100. $pharmacies = $pharmacies->whereRaw('LOWER(address_state::text) LIKE ?', ['%' . strtolower($request->input('state')) . '%']);
  1101. }
  1102. if($request->input('zip')) {
  1103. $pharmacies = $pharmacies->whereRaw('LOWER(address_zip::text) LIKE ?', ['%' . strtolower($request->input('zip')) . '%']);
  1104. }
  1105. $pharmacies = $pharmacies
  1106. ->orderBy('name', 'asc')
  1107. ->orderBy('address_line1', 'asc')
  1108. ->orderBy('address_city', 'asc')
  1109. ->orderBy('address_state', 'asc')
  1110. ->get();
  1111. return view('app/pharmacy-suggest', compact('pharmacies'));
  1112. }
  1113. public function proSuggest(Request $request) {
  1114. $term = $request->input('term') ? trim($request->input('term')) : '';
  1115. if (empty($term)) return '';
  1116. $term = strtolower($term);
  1117. $pros = Pro::where(function ($q) use ($term) {
  1118. $q->orWhereRaw('LOWER(name_first::text) LIKE ?', ['%' . $term . '%'])
  1119. ->orWhereRaw('LOWER(name_last::text) LIKE ?', ['%' . $term . '%'])
  1120. ->orWhereRaw('cell_number LIKE ?', ['%' . $term . '%']);
  1121. });
  1122. $type = $request->input('type') ? trim($request->input('type')) : '';
  1123. if(!!$type) {
  1124. switch(strtolower($type)) {
  1125. case 'hcp':
  1126. $pros->where('is_hcp', true);
  1127. break;
  1128. case 'default-na': // TODO: fix condition for NA
  1129. $pros->where('is_hcp', false)->where('pro_type', '!=', 'ADMIN');
  1130. break;
  1131. case 'admin':
  1132. $pros->where('pro_type', 'ADMIN');
  1133. break;
  1134. case 'non-admin':
  1135. $pros->where('pro_type', '!=', 'ADMIN');
  1136. break;
  1137. }
  1138. }
  1139. if($this->performer->pro && $this->performer->pro->pro_type != 'ADMIN'){
  1140. $accessiblePros = ProProAccess::where('owner_pro_id', $this->performer->pro->id);
  1141. $accessibleProIds = [];
  1142. foreach($accessiblePros as $accessiblePro){
  1143. $accessibleProIds[] = $accessiblePro->id;
  1144. }
  1145. $accessibleProIds[] = $this->performer->pro->id;
  1146. // for dna, add pros accessible via pro teams
  1147. if($this->performer->pro->isDefaultNA()) {
  1148. $teams = $this->performer->pro->teamsWhereAssistant;
  1149. foreach ($teams as $team) {
  1150. if(!in_array($team->mcp_pro_id, $accessibleProIds)) {
  1151. $accessibleProIds[] = $team->mcp_pro_id;
  1152. }
  1153. }
  1154. }
  1155. $pros->whereIn('id', $accessibleProIds);
  1156. }
  1157. $suggestedPros = $pros->orderBy('name_last')->orderBy('name_first')->get();
  1158. // for calendar select2
  1159. if($request->input('json')) {
  1160. $jsonPros = $suggestedPros->map(function($_pro) {
  1161. return [
  1162. "uid" => $_pro->uid,
  1163. "id" => $_pro->id,
  1164. "text" => $_pro->displayName(),
  1165. "initials" => $_pro->initials(),
  1166. ];
  1167. });
  1168. return json_encode([
  1169. "results" => $jsonPros
  1170. ]);
  1171. }
  1172. return view('app/pro-suggest', compact('suggestedPros'));
  1173. }
  1174. public function canAccessPatient(Request $request, $uid) {
  1175. return json_encode([
  1176. "success" => true,
  1177. "data" => $this->performer->pro->canAccess($uid)
  1178. ]);
  1179. }
  1180. public function proDisplayName(Request $request, Pro $pro) {
  1181. return $pro ? $pro->displayName() : '';
  1182. }
  1183. public function unmappedSMS(Request $request, $filter = '')
  1184. {
  1185. $proID = $this->performer()->pro->id;
  1186. if ($this->performer()->pro->pro_type === 'ADMIN') {
  1187. $query = Client::where('id', '>', 0);
  1188. } else {
  1189. $query = Client::where(function ($q) use ($proID) {
  1190. $q->where('mcp_pro_id', $proID)
  1191. ->orWhere('cm_pro_id', $proID)
  1192. ->orWhere('rmm_pro_id', $proID)
  1193. ->orWhere('rme_pro_id', $proID)
  1194. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID]);
  1195. });
  1196. }
  1197. $patients = $query->orderBy('name_last', 'asc')->orderBy('name_first', 'asc')->get();
  1198. $unmappedSMS = ClientSMS::where('client_id', null)->where('incoming_or_outgoing', 'INCOMING')->paginate(20);
  1199. return view('app/unmapped-sms', compact('unmappedSMS', 'patients'));
  1200. }
  1201. public function newPatient(Request $request)
  1202. {
  1203. $mbPayers = MBPayer::all();
  1204. return view('app/new-patient', compact('mbPayers'));
  1205. }
  1206. public function newNonMcnPatient(Request $request)
  1207. {
  1208. $mbPayers = MBPayer::all();
  1209. return view('app/new-non-mcn-patient', compact('mbPayers'));
  1210. }
  1211. public function mc(Request $request, $fragment = "")
  1212. {
  1213. $page = "/";
  1214. if ($fragment) {
  1215. $page = '/' . $fragment;
  1216. }
  1217. return view('app/mc', compact('page'));
  1218. }
  1219. public function blank(Request $request)
  1220. {
  1221. return view('app/blank');
  1222. }
  1223. public function noteTemplateSet(Request $request, $section, $template)
  1224. {
  1225. return view('app/patient/note/_template', [
  1226. "sectionInternalName" => $section,
  1227. "templateName" => $template
  1228. ]);
  1229. }
  1230. public function noteExamTemplateSet(Request $request, $exam, $template)
  1231. {
  1232. return view('app/patient/note/_template-exam', [
  1233. "exam" => $exam,
  1234. "sectionInternalName" => 'exam-' . $exam . '-detail',
  1235. "templateName" => $template
  1236. ]);
  1237. }
  1238. public function logInAs(Request $request)
  1239. {
  1240. if($this->pro->pro_type != 'ADMIN'){
  1241. return redirect()->to(route('dashboard'));
  1242. }
  1243. // dummy condition to get the chain-ability going
  1244. $pros = Pro::where('id', '>', 0);
  1245. if($request->input('q')) {
  1246. $nameQuery = '%' . $request->input('q') . '%';
  1247. $pros = $pros->where(function ($query) use ($nameQuery) {
  1248. $query->where('name_first', 'ILIKE', $nameQuery)
  1249. ->orWhere('name_last', 'ILIKE', $nameQuery)
  1250. ->orWhere('email_address', 'ILIKE', $nameQuery)
  1251. ->orWhere('cell_number', 'ILIKE', $nameQuery);
  1252. });
  1253. }
  1254. if($request->input('sort') && $request->input('dir')) {
  1255. $pros = $pros->orderBy($request->input('sort'), $request->input('dir'));
  1256. }
  1257. else {
  1258. $pros = $pros->orderBy('name_last', 'asc');
  1259. }
  1260. $pros = $pros->paginate(20);
  1261. return view('app/log-in-as', ['logInAsPros' => $pros]);
  1262. }
  1263. public function processLogInAs(Request $request)
  1264. {
  1265. $api = new Backend();
  1266. try {
  1267. $apiResponse = $api->post('session/proLogInAs', [
  1268. 'proUid' => $request->post('proUid')
  1269. ],
  1270. [
  1271. 'sessionKey'=>$this->performer()->session_key
  1272. ]);
  1273. $data = json_decode($apiResponse->getContents());
  1274. if (!property_exists($data, 'success') || !$data->success) {
  1275. return redirect()->to(route('log-in-as'))->with('message', $data->message)
  1276. ->withInput($request->input());
  1277. }
  1278. Cookie::queue('sessionKey', $data->data->sessionKey);
  1279. return redirect('/mc');
  1280. } catch (\Exception $e) {
  1281. return redirect()->to(route('log-in-as'))
  1282. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  1283. ->withInput($request->input());
  1284. }
  1285. }
  1286. public function backToAdminPro(Request $request){
  1287. $adminPerformerId = $this->performer->logged_in_as_pro_from_admin_pro_app_session_id;
  1288. $adminPerformer = AppSession::where('id', $adminPerformerId)->first();
  1289. $url = "/session/pro_log_in_with_session_key/".$adminPerformer->session_key;
  1290. $api = new Backend();
  1291. try {
  1292. $apiResponse = $api->post($url, []);
  1293. $data = json_decode($apiResponse->getContents());
  1294. if (!property_exists($data, 'success') || !$data->success) {
  1295. return redirect()->to(route('logout'));
  1296. }
  1297. Cookie::queue('sessionKey', $data->data->sessionKey);
  1298. return redirect(route('dashboard'));
  1299. } catch (\Exception $e) {
  1300. return redirect(route('dashboard'));
  1301. }
  1302. }
  1303. public function getTicket(Request $request, Ticket $ticket) {
  1304. $ticket->data = json_decode($ticket->data);
  1305. // $ticket->created_at = friendly_date_time($ticket->created_at);
  1306. $ticket->assignedPro;
  1307. $ticket->managerPro;
  1308. $ticket->orderingPro;
  1309. $ticket->initiatingPro;
  1310. return json_encode($ticket);
  1311. }
  1312. public function genericBill(Request $request, $entityType, $entityUid) {
  1313. $patient = null;
  1314. if ($entityType && $entityUid) {
  1315. try {
  1316. $entityClass = "\\App\\Models\\" . $entityType;
  1317. $entity = $entityClass::where('uid', $entityUid)->first();
  1318. if ($entity->client) {
  1319. $patient = $entity->client;
  1320. }
  1321. } catch (\Exception $e) {
  1322. }
  1323. }
  1324. return view('app.generic-bills.inline', ['class' => 'p-3 border-top mt-3', 'entityType' => $entityType, 'entityUid' => $entityUid, 'patient' => $patient]);
  1325. }
  1326. }