HomeController.php 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873
  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)->where('is_core_note', 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)->where('is_core_note', 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)->where('is_core_note', 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)->where('is_core_note', 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. // unstamped client memos
  325. // for mcp
  326. $mcpClientMemos = DB::select(
  327. DB::raw("
  328. SELECT c.uid as client_uid, c.name_first, c.name_last,
  329. cm.uid, cm.content, cm.created_at
  330. FROM client c join client_memo cm on c.id = cm.client_id
  331. WHERE
  332. c.mcp_pro_id = {$performerProID} AND
  333. cm.mcp_stamp_id IS NULL
  334. AND (is_admin_only IS FALSE OR is_admin_only IS NULL)
  335. ORDER BY cm.created_at DESC
  336. OFFSET 0 LIMIT 10
  337. ")
  338. );
  339. $mcpClientMemosCount = DB::select(
  340. DB::raw("
  341. SELECT count(c.uid)
  342. FROM client c join client_memo cm on c.id = cm.client_id
  343. WHERE
  344. c.mcp_pro_id = {$performerProID} AND
  345. cm.mcp_stamp_id IS NULL
  346. AND (is_admin_only IS FALSE OR is_admin_only IS NULL)
  347. ")
  348. );
  349. if($mcpClientMemosCount && count($mcpClientMemosCount)) {
  350. $mcpClientMemosCount = $mcpClientMemosCount[0]->count;
  351. }
  352. // for na
  353. $naClientMemos = DB::select(
  354. DB::raw("
  355. SELECT c.uid as client_uid, c.name_first, c.name_last,
  356. cm.uid, cm.content, cm.created_at
  357. FROM client c join client_memo cm on c.id = cm.client_id
  358. WHERE
  359. c.default_na_pro_id = {$performerProID} AND
  360. cm.default_na_stamp_id IS NULL
  361. ORDER BY cm.created_at DESC
  362. ")
  363. );
  364. $keyNumbers['rmBillsToSign'] = Bill
  365. ::where('is_cancelled', false)
  366. ->where('cm_or_rm', 'RM')
  367. ->where(function ($q) use ($performerProID) {
  368. $q
  369. ->where(function ($q2) use ($performerProID) {
  370. $q2->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false);
  371. })
  372. ->orWhere(function ($q2) use ($performerProID) {
  373. $q2->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false);
  374. })
  375. ->orWhere(function ($q2) use ($performerProID) {
  376. $q2->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false);
  377. })
  378. ->orWhere(function ($q2) use ($performerProID) {
  379. $q2->where('generic_pro_id', $performerProID)->where('is_signed_by_generic_pro', false);
  380. });
  381. })
  382. ->count();
  383. $count = DB::select(
  384. DB::raw(
  385. "
  386. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  387. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  388. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  389. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  390. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  391. AND (care_month.number_of_days_with_remote_measurements < 16 OR care_month.number_of_days_with_remote_measurements IS NULL)
  392. "
  393. )
  394. );
  395. $keyNumbers['rmPatientsWithLT16MD'] = $count[0]->cnt;
  396. $count = DB::select(
  397. DB::raw(
  398. "
  399. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  400. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  401. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  402. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  403. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  404. AND (care_month.number_of_days_with_remote_measurements >= 16 AND care_month.number_of_days_with_remote_measurements IS NOT NULL)
  405. "
  406. )
  407. );
  408. $keyNumbers['rmPatientsWithGTE16MD'] = $count[0]->cnt;
  409. $count = DB::select(
  410. DB::raw(
  411. "
  412. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  413. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  414. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  415. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  416. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  417. 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)
  418. "
  419. )
  420. );
  421. $keyNumbers['rmPatientsWithWhomCommDone'] = $count[0]->cnt;
  422. $count = DB::select(
  423. DB::raw(
  424. "
  425. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  426. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  427. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  428. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  429. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  430. 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)
  431. "
  432. )
  433. );
  434. $keyNumbers['rmPatientsWithWhomCommNotDone'] = $count[0]->cnt;
  435. // num measurements that need stamping
  436. $keyNumbers['measurementsToBeStamped'] = $this->performer()->pro->getUnstampedMeasurementsFromCurrentMonth(true, null, null);
  437. if($performer->pro->pro_type === 'ADMIN') {
  438. // patients without coverage information
  439. $keyNumbers['patientsWithoutCoverageInformation'] = DB::select(DB::raw("
  440. SELECT count(DISTINCT (cl.id)) as cnt
  441. FROM client cl
  442. WHERE cl.shadow_pro_id IS NULL AND cl.latest_client_primary_coverage_id IS NULL -- no coverage record"
  443. ))[0]->cnt;
  444. // patients pending coverage verification
  445. $keyNumbers['patientsPendingCoverageVerification'] = DB::select(DB::raw("
  446. SELECT count(DISTINCT (cl.id)) as cnt
  447. FROM client cl
  448. LEFT JOIN client_primary_coverage cpc ON cl.latest_client_primary_coverage_id = cpc.id
  449. WHERE cl.shadow_pro_id IS NULL
  450. AND (cl.latest_client_primary_coverage_id IS NOT NULL -- coverage exists, but status is null or unknown
  451. AND (
  452. (cpc.plan_type = 'MEDICARE' AND (cpc.is_partbprimary = 'UNKNOWN' OR cpc.is_partbprimary IS NULL))
  453. OR
  454. (cpc.plan_type != 'MEDICARE' AND
  455. (cpc.manual_determination_category = 'UNKNOWN' OR cpc.manual_determination_category IS NULL))
  456. ))"
  457. ))[0]->cnt;
  458. }
  459. $incomingSmsMessagesPendingReply = DB::select("
  460. SELECT cs.* ,c.uid as client_uid, c.name_first as client_name_first, c.name_last as client_name_last FROM client_sms cs LEFT JOIN client c ON c.id = cs.client_id
  461. WHERE cs.is_reply_needed = 'YES' AND c.mcp_pro_id = :mcp_pro_id AND incoming_or_outgoing = 'INCOMING'
  462. AND (cs.created_at > c.last_sms_sent_to_client_at OR c.last_sms_sent_to_client_at IS NULL)
  463. ORDER BY created_at DESC
  464. ", ['mcp_pro_id' => $performer->pro->id]);
  465. return view('app/dashboard-mcp', compact('keyNumbers', 'reimbursement', 'milliseconds',
  466. 'businessNumbers',
  467. 'incomingReports', 'tickets', 'supplyOrders',
  468. 'numERx', 'numLabs', 'numImaging', 'numSupplyOrders',
  469. 'newMCPAssociations', 'newNAAssociations',
  470. 'mcpClientMemos', 'mcpClientMemosCount', 'naClientMemos', 'incomingSmsMessagesPendingReply'));
  471. }
  472. private function dashboard_DNA(Request $request){
  473. $performer = $this->performer();
  474. $pro = $performer->pro;
  475. $keyNumbers = [];
  476. // Patients // SELECT * FROM client WHERE mcp_pro_id = :me.id;
  477. // New Patients Awaiting Visit // SELECT * FROM client WHERE mcp_pro_id = :me.id AND hasMcpDoneOnboardingVisit != 'YES';
  478. // 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;
  479. // 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;
  480. // Reports Pending Signature // SELECT * FROM incoming_report WHERE hcp_pro_id = :me.id AND isEntryError IS NOT TRUE AND hasHcpProSigned IS NOT TRUE;
  481. // Patients w/o Appointments // SELECT * FROM client WHERE mcp_pro_id = :me.id AND client.next_mcp_appointment_date < today();
  482. // Patients Overdue for Visit // SELECT * FROM client WHERE mcp_pro_id = :me.id AND client.next_expected_mcp_visit_date < today();
  483. // Cancelled Appts. Pending Review // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  484. // Cancelled Bills Pending Review // SELECT * FROM bill WHERE bill_service_type = 'NOTE' AND is_cancelled IS TRUE AND isCancellationAcknowledged IS FALSE;
  485. // 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;
  486. // ERx & Orders Pending Signature // SELECT * FROM erx WHERE hcp_pro_id = :me.id AND pro_declared_status <> 'CANCELLED' AND hasHcpProSigned IS NOT TRUE;
  487. // 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;
  488. $performer = $this->performer();
  489. $pro = $performer->pro;
  490. $performerProID = $performer->pro->id;
  491. $keyNumbers = [];
  492. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  493. $keyNumbers['patients'] = $queryClients->count();
  494. $pendingNotesToSign = Note::where('ally_pro_id', $performerProID)->where('is_signed_by_ally', false)->where('is_cancelled', false)->where('is_core_note', false)->count();
  495. $keyNumbers['pendingNotesToSign'] = $pendingNotesToSign;
  496. // notes pending mcp sign (applicable to dnas only)
  497. $pendingNotesToSignMCP = Note::where('ally_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false)->where('is_core_note', false)->count();
  498. $keyNumbers['$pendingNotesToSignMCP'] = $pendingNotesToSignMCP;
  499. $pendingNotesToSignAllySigned = Note::where(function ($query) use ($performerProID) {
  500. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_signed_by_ally', true)->where('is_cancelled', false)->where('is_core_note', false);
  501. })->count();
  502. $keyNumbers['pendingNotesToSignAllySigned'] = $pendingNotesToSignAllySigned;
  503. $signedNotesWithoutBills = Note::where(function ($query) use ($performerProID) {
  504. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', true)->where('is_cancelled', false);
  505. })->whereDoesntHave('bills')->count();
  506. $keyNumbers['signedNotesWithoutBills'] = $signedNotesWithoutBills;
  507. // open tickets
  508. $keyNumbers['numOpenTickets'] = Ticket::where('is_open', true)
  509. ->where(function ($q) use ($performerProID) {
  510. $q->where('assigned_pro_id', $performerProID)
  511. ->orWhere('manager_pro_id', $performerProID)
  512. ->orWhere('ordering_pro_id', $performerProID)
  513. ->orWhere('initiating_pro_id', $performerProID);
  514. })
  515. ->count();
  516. // unacknowledged cancelled bills for authed pro
  517. $keyNumbers['unacknowledgedCancelledBills'] = Bill::where('na_pro_id', $performerProID)
  518. ->where('is_cancelled', true)
  519. ->where('is_cancellation_acknowledged', false)
  520. ->count();
  521. // unacknowledged cancelled supply orders for authed pro
  522. $keyNumbers['unacknowledgedCancelledSupplyOrders'] = SupplyOrder::where('signed_by_pro_id', $performerProID)
  523. ->where('is_cancelled', true)
  524. ->where('is_cancellation_acknowledged', false)
  525. ->count();
  526. // unsigned supply orders created by authed pro
  527. $keyNumbers['unsignedSupplyOrders'] = SupplyOrder
  528. ::where('is_cancelled', false)
  529. ->where('is_signed_by_pro', false)
  530. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$performerProID])
  531. ->count();
  532. // patientsHavingBirthdayToday
  533. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  534. $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
  535. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  536. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
  537. ->count();
  538. $reimbursement = [];
  539. $reimbursement["currentBalance"] = $performer->pro->balance;
  540. $reimbursement["nextPaymentDate"] = '--';
  541. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  542. if ($lastPayment) {
  543. $reimbursement["lastPayment"] = $lastPayment->amount;
  544. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  545. } else {
  546. $reimbursement["lastPayment"] = '--';
  547. $reimbursement["lastPaymentDate"] = '--';
  548. }
  549. //if today is < 15th, next payment is 15th, else nextPayment is
  550. $today = strtotime(date('Y-m-d'));
  551. $todayDate = date('j', $today);
  552. $todayMonth = date('m', $today);
  553. $todayYear = date('Y', $today);
  554. if ($todayDate < 15) {
  555. $nextPaymentDate = new DateTime();
  556. $nextPaymentDate->setDate($todayYear, $todayMonth, 15);
  557. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  558. } else {
  559. $nextPaymentDate = new \DateTime();
  560. $lastDayOfMonth = date('t', $today);
  561. $nextPaymentDate->setDate($todayYear, $todayMonth, $lastDayOfMonth);
  562. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  563. }
  564. //expectedPay
  565. $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;
  566. $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;
  567. $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;
  568. $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;
  569. $totalExpectedAmount = $expectedForCm + $expectedForRme + $expectedForRmm + $expectedForNa;
  570. $reimbursement['nextPaymentAmount'] = $totalExpectedAmount;
  571. $milliseconds = strtotime(date('Y-m-d')) . '000';
  572. // bills & claims
  573. $businessNumbers = [];
  574. // Notes with bills to resolve
  575. $businessNumbers['notesWithBillsToResolve'] = Note::where('is_cancelled', '!=', true)
  576. ->where('is_bill_closed', '!=', true)
  577. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND is_cancelled = false AND is_verified = false) > 0')
  578. ->count();
  579. // Notes pending bill closure
  580. $businessNumbers['notesPendingBillingClosure'] = Note::where('is_cancelled', '!=', true)
  581. ->where('is_bill_closed', '!=', true)
  582. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND (is_cancelled = true OR is_verified = true)) = 0')
  583. ->count();
  584. // incoming reports not signed
  585. $incomingReports = IncomingReport::where('hcp_pro_id', $performerProID)
  586. ->where('has_hcp_pro_signed', false)
  587. ->where('is_entry_error', false)
  588. ->orderBy('created_at', 'ASC')
  589. ->get();
  590. // erx, labs & imaging that are not closed
  591. $tickets = Ticket::where('ordering_pro_id', $performerProID)
  592. ->where('is_entry_error', false)
  593. ->where('is_open', true)
  594. ->orderBy('created_at', 'ASC')
  595. ->get();
  596. $supplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  597. ->where('is_cancelled', false)
  598. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  599. ->orderBy('created_at', 'ASC')
  600. ->get();
  601. $numERx = Ticket::where('ordering_pro_id', $performerProID)
  602. ->where('category', 'erx')
  603. ->where('is_entry_error', false)
  604. ->where('is_open', true)
  605. ->count();
  606. $numLabs = Ticket::where('ordering_pro_id', $performerProID)
  607. ->where('category', 'lab')
  608. ->where('is_entry_error', false)
  609. ->where('is_open', true)
  610. ->count();
  611. $numImaging = Ticket::where('ordering_pro_id', $performerProID)
  612. ->where('category', 'imaging')
  613. ->where('is_entry_error', false)
  614. ->where('is_open', true)
  615. ->count();
  616. $numSupplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  617. ->where('is_cancelled', false)
  618. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  619. ->count();
  620. $newMCPAssociations = ClientProChange
  621. ::where('new_pro_id', $performerProID)
  622. ->where('responsibility_type', 'MCP')
  623. ->whereNull('current_client_pro_change_decision_id')
  624. ->get();
  625. $newNAAssociations = ClientProChange
  626. ::where('new_pro_id', $performerProID)
  627. ->where('responsibility_type', 'DEFAULT_NA')
  628. ->whereNull('current_client_pro_change_decision_id')
  629. ->get();
  630. // unstamped client memos
  631. // for mcp
  632. $mcpClientMemos = DB::select(
  633. DB::raw("
  634. SELECT c.uid as client_uid, c.name_first, c.name_last,
  635. cm.uid, cm.content, cm.created_at
  636. FROM client c join client_memo cm on c.id = cm.client_id
  637. WHERE
  638. c.mcp_pro_id = {$performerProID} AND
  639. cm.mcp_stamp_id IS NULL
  640. ORDER BY cm.created_at DESC
  641. ")
  642. );
  643. // for na
  644. $naClientMemos = DB::select(
  645. DB::raw("
  646. SELECT c.uid as client_uid, c.name_first, c.name_last,
  647. cm.uid, cm.content, cm.created_at
  648. FROM client c join client_memo cm on c.id = cm.client_id
  649. WHERE
  650. c.default_na_pro_id = {$performerProID} AND
  651. cm.default_na_stamp_id IS NULL
  652. ORDER BY cm.created_at DESC
  653. ")
  654. );
  655. $keyNumbers['rmBillsToSign'] = Bill
  656. ::where('is_cancelled', false)
  657. ->where('cm_or_rm', 'RM')
  658. ->where(function ($q) use ($performerProID) {
  659. $q
  660. ->where(function ($q2) use ($performerProID) {
  661. $q2->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false);
  662. })
  663. ->orWhere(function ($q2) use ($performerProID) {
  664. $q2->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false);
  665. })
  666. ->orWhere(function ($q2) use ($performerProID) {
  667. $q2->where('generic_pro_id', $performerProID)->where('is_signed_by_generic_pro', false);
  668. });
  669. })
  670. ->count();
  671. $count = DB::select(
  672. DB::raw(
  673. "
  674. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  675. WHERE ( (client.rmm_pro_id = {$performer->pro->id})
  676. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  677. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  678. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  679. AND (care_month.number_of_days_with_remote_measurements < 16 OR care_month.number_of_days_with_remote_measurements IS NULL)
  680. "
  681. )
  682. );
  683. $keyNumbers['rmPatientsWithLT16MD'] = $count[0]->cnt;
  684. $count = DB::select(
  685. DB::raw(
  686. "
  687. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  688. WHERE ((client.rmm_pro_id = {$performer->pro->id})
  689. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  690. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  691. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  692. AND (care_month.number_of_days_with_remote_measurements >= 16 AND care_month.number_of_days_with_remote_measurements IS NOT NULL)
  693. "
  694. )
  695. );
  696. $keyNumbers['rmPatientsWithGTE16MD'] = $count[0]->cnt;
  697. $count = DB::select(
  698. DB::raw(
  699. "
  700. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  701. WHERE ((client.rmm_pro_id = {$performer->pro->id})
  702. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  703. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  704. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  705. 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)
  706. "
  707. )
  708. );
  709. $keyNumbers['rmPatientsWithWhomCommDone'] = $count[0]->cnt;
  710. $count = DB::select(
  711. DB::raw(
  712. "
  713. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  714. WHERE ( (client.rmm_pro_id = {$performer->pro->id})
  715. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  716. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  717. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  718. 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)
  719. "
  720. )
  721. );
  722. $keyNumbers['rmPatientsWithWhomCommNotDone'] = $count[0]->cnt;
  723. // num measurements that need stamping
  724. $keyNumbers['measurementsToBeStamped'] = $this->performer()->pro->getUnstampedMeasurementsFromCurrentMonth(true, null, null);
  725. if($performer->pro->pro_type === 'ADMIN') {
  726. // patients without coverage information
  727. $keyNumbers['patientsWithoutCoverageInformation'] = DB::select(DB::raw("
  728. SELECT count(DISTINCT (cl.id)) as cnt
  729. FROM client cl
  730. WHERE cl.shadow_pro_id IS NULL AND cl.latest_client_primary_coverage_id IS NULL -- no coverage record"
  731. ))[0]->cnt;
  732. // patients pending coverage verification
  733. $keyNumbers['patientsPendingCoverageVerification'] = DB::select(DB::raw("
  734. SELECT count(DISTINCT (cl.id)) as cnt
  735. FROM client cl
  736. LEFT JOIN client_primary_coverage cpc ON cl.latest_client_primary_coverage_id = cpc.id
  737. WHERE cl.shadow_pro_id IS NULL
  738. AND (cl.latest_client_primary_coverage_id IS NOT NULL -- coverage exists, but status is null or unknown
  739. AND (
  740. (cpc.plan_type = 'MEDICARE' AND (cpc.is_partbprimary = 'UNKNOWN' OR cpc.is_partbprimary IS NULL))
  741. OR
  742. (cpc.plan_type != 'MEDICARE' AND
  743. (cpc.manual_determination_category = 'UNKNOWN' OR cpc.manual_determination_category IS NULL))
  744. ))"
  745. ))[0]->cnt;
  746. }
  747. return view('app/dashboard-dna', compact('keyNumbers', 'reimbursement', 'milliseconds',
  748. 'businessNumbers',
  749. 'incomingReports', 'tickets', 'supplyOrders',
  750. 'numERx', 'numLabs', 'numImaging', 'numSupplyOrders',
  751. 'newMCPAssociations', 'newNAAssociations',
  752. 'mcpClientMemos', 'naClientMemos'));
  753. }
  754. private function dashboard_ADMIN(Request $request){
  755. $keyNumbers = [];
  756. // Patients // SELECT * FROM client WHERE mcp_pro_id = :me.id;
  757. // New Patients Awaiting Visit // SELECT * FROM client WHERE mcp_pro_id = :me.id AND hasMcpDoneOnboardingVisit != 'YES';
  758. // 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;
  759. // 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;
  760. // Reports Pending Signature // SELECT * FROM incoming_report WHERE hcp_pro_id = :me.id AND isEntryError IS NOT TRUE AND hasHcpProSigned IS NOT TRUE;
  761. // Patients w/o Appointments // SELECT * FROM client WHERE mcp_pro_id = :me.id AND client.next_mcp_appointment_date < today();
  762. // Patients Overdue for Visit // SELECT * FROM client WHERE mcp_pro_id = :me.id AND client.next_expected_mcp_visit_date < today();
  763. // Cancelled Appts. Pending Review // SELECT * FROM appointment WHERE hcp_pro_id = :me.id AND status = 'REJECTED' AND wasAcknowledgedByAppointmentPro IS NOT TRUE;
  764. // Cancelled Bills Pending Review // SELECT * FROM bill WHERE bill_service_type = 'NOTE' AND is_cancelled IS TRUE AND isCancellationAcknowledged IS FALSE;
  765. // 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;
  766. // ERx & Orders Pending Signature // SELECT * FROM erx WHERE hcp_pro_id = :me.id AND pro_declared_status <> 'CANCELLED' AND hasHcpProSigned IS NOT TRUE;
  767. // 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;
  768. $performer = $this->performer();
  769. $pro = $performer->pro;
  770. $performerProID = $performer->pro->id;
  771. $keyNumbers = [];
  772. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  773. $pendingNotesToSign = Note
  774. ::where(function ($query) use ($performerProID) {
  775. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false)->where('is_core_note', false);
  776. })
  777. ->orWhere(function ($query) use ($performerProID) {
  778. $query->where('ally_pro_id', $performerProID)->where('is_signed_by_ally', false)->where('is_cancelled', false)->where('is_core_note', false);
  779. })
  780. ->count();
  781. $keyNumbers['pendingNotesToSign'] = $pendingNotesToSign;
  782. // notes pending mcp sign (applicable to dnas only)
  783. $pendingNotesToSignMCP = Note
  784. ::where(function ($query) use ($performerProID) {
  785. $query->where('ally_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false)->where('is_core_note', false);
  786. })
  787. ->count();
  788. $keyNumbers['$pendingNotesToSignMCP'] = $pendingNotesToSignMCP;
  789. $pendingNotesToSignAllySigned = Note::where(function ($query) use ($performerProID) {
  790. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_signed_by_ally', true)->where('is_cancelled', false)->where('is_core_note', false);;
  791. })->count();
  792. $keyNumbers['pendingNotesToSignAllySigned'] = $pendingNotesToSignAllySigned;
  793. $signedNotesWithoutBills = Note::where(function ($query) use ($performerProID) {
  794. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', true)->where('is_cancelled', false);
  795. })->whereDoesntHave('bills')->count();
  796. $keyNumbers['signedNotesWithoutBills'] = $signedNotesWithoutBills;
  797. // open tickets
  798. $keyNumbers['numOpenTickets'] = Ticket::where('is_open', true)
  799. ->where(function ($q) use ($performerProID) {
  800. $q->where('assigned_pro_id', $performerProID)
  801. ->orWhere('manager_pro_id', $performerProID)
  802. ->orWhere('ordering_pro_id', $performerProID)
  803. ->orWhere('initiating_pro_id', $performerProID);
  804. })
  805. ->count();
  806. // unacknowledged cancelled bills for authed pro
  807. $keyNumbers['unacknowledgedCancelledBills'] = Bill::where('hcp_pro_id', $performerProID)
  808. ->where('is_cancelled', true)
  809. ->where('is_cancellation_acknowledged', false)
  810. ->count();
  811. // unacknowledged cancelled supply orders for authed pro
  812. $keyNumbers['unacknowledgedCancelledSupplyOrders'] = SupplyOrder::where('signed_by_pro_id', $performerProID)
  813. ->where('is_cancelled', true)
  814. ->where('is_cancellation_acknowledged', false)
  815. ->count();
  816. // unsigned supply orders created by authed pro
  817. $keyNumbers['unsignedSupplyOrders'] = SupplyOrder
  818. ::where('is_cancelled', false)
  819. ->where('is_signed_by_pro', false)
  820. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$performerProID])
  821. ->count();
  822. // patientsHavingBirthdayToday
  823. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  824. $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
  825. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  826. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
  827. ->count();
  828. $reimbursement = [];
  829. $reimbursement["currentBalance"] = $performer->pro->balance;
  830. $reimbursement["nextPaymentDate"] = '--';
  831. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  832. if ($lastPayment) {
  833. $reimbursement["lastPayment"] = $lastPayment->amount;
  834. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  835. } else {
  836. $reimbursement["lastPayment"] = '--';
  837. $reimbursement["lastPaymentDate"] = '--';
  838. }
  839. //if today is < 15th, next payment is 15th, else nextPayment is
  840. $today = strtotime(date('Y-m-d'));
  841. $todayDate = date('j', $today);
  842. $todayMonth = date('m', $today);
  843. $todayYear = date('Y', $today);
  844. if ($todayDate < 15) {
  845. $nextPaymentDate = new DateTime();
  846. $nextPaymentDate->setDate($todayYear, $todayMonth, 15);
  847. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  848. } else {
  849. $nextPaymentDate = new \DateTime();
  850. $lastDayOfMonth = date('t', $today);
  851. $nextPaymentDate->setDate($todayYear, $todayMonth, $lastDayOfMonth);
  852. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  853. }
  854. //expectedPay
  855. $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;
  856. $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;
  857. $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;
  858. $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;
  859. $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;
  860. $totalExpectedAmount = $expectedForHcp + $expectedForCm + $expectedForRme + $expectedForRmm + $expectedForNa;
  861. $reimbursement['nextPaymentAmount'] = $totalExpectedAmount;
  862. $milliseconds = strtotime(date('Y-m-d')) . '000';
  863. // bills & claims
  864. $businessNumbers = [];
  865. // Notes with bills to resolve
  866. $businessNumbers['notesWithBillsToResolve'] = Note::where('is_cancelled', '!=', true)
  867. ->where('is_bill_closed', '!=', true)
  868. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND is_cancelled = false AND is_verified = false) > 0')
  869. ->count();
  870. // Notes pending bill closure
  871. $businessNumbers['notesPendingBillingClosure'] = Note::where('is_cancelled', '!=', true)
  872. ->where('is_bill_closed', '!=', true)
  873. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND (is_cancelled = true OR is_verified = true)) = 0')
  874. ->count();
  875. // incoming reports not signed
  876. $incomingReports = IncomingReport::where('hcp_pro_id', $performerProID)
  877. ->where('has_hcp_pro_signed', false)
  878. ->where('is_entry_error', false)
  879. ->orderBy('created_at', 'ASC')
  880. ->get();
  881. // erx, labs & imaging that are not closed
  882. $tickets = Ticket::where('ordering_pro_id', $performerProID)
  883. ->where('is_entry_error', false)
  884. ->where('is_open', true)
  885. ->orderBy('created_at', 'ASC')
  886. ->get();
  887. $supplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  888. ->where('is_cancelled', false)
  889. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  890. ->orderBy('created_at', 'ASC')
  891. ->get();
  892. $numERx = Ticket::where('ordering_pro_id', $performerProID)
  893. ->where('category', 'erx')
  894. ->where('is_entry_error', false)
  895. ->where('is_open', true)
  896. ->count();
  897. $numLabs = Ticket::where('ordering_pro_id', $performerProID)
  898. ->where('category', 'lab')
  899. ->where('is_entry_error', false)
  900. ->where('is_open', true)
  901. ->count();
  902. $numImaging = Ticket::where('ordering_pro_id', $performerProID)
  903. ->where('category', 'imaging')
  904. ->where('is_entry_error', false)
  905. ->where('is_open', true)
  906. ->count();
  907. $numSupplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  908. ->where('is_cancelled', false)
  909. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  910. ->count();
  911. $newMCPAssociations = ClientProChange
  912. ::where('new_pro_id', $performerProID)
  913. ->where('responsibility_type', 'MCP')
  914. ->whereNull('current_client_pro_change_decision_id')
  915. ->get();
  916. $newNAAssociations = ClientProChange
  917. ::where('new_pro_id', $performerProID)
  918. ->where('responsibility_type', 'DEFAULT_NA')
  919. ->whereNull('current_client_pro_change_decision_id')
  920. ->get();
  921. $proApptUpdates = AppointmentConfirmationDecision
  922. ::select('appointment_confirmation_decision.uid', 'client.name_first', 'client.name_last', 'appointment.start_time')
  923. ->rightJoin('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  924. ->rightJoin('client', 'client.id', '=', 'appointment.client_id')
  925. ->where('appointment_confirmation_decision.was_acknowledged_by_appointment_pro', false)
  926. ->where('appointment.status', '!=', 'CREATED')
  927. ->where('appointment.status', '!=', 'COMPLETED')
  928. ->where('appointment.status', '!=', 'ABANDONED')
  929. ->where('appointment.pro_id', $performerProID)
  930. ->where('client.mcp_pro_id', $performerProID)
  931. ->orderBy('appointment.start_time', 'DESC')
  932. ->get();
  933. $naApptUpdates = AppointmentConfirmationDecision
  934. ::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')
  935. ->rightJoin('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  936. ->rightJoin('client', 'client.id', '=', 'appointment.client_id')
  937. ->rightJoin('pro', 'pro.id', '=', 'appointment.pro_id')
  938. ->where('appointment_confirmation_decision.was_acknowledged_by_client_default_na', false)
  939. ->where('appointment.status', '!=', 'CREATED')
  940. ->where('appointment.status', '!=', 'COMPLETED')
  941. ->where('appointment.status', '!=', 'ABANDONED')
  942. ->where('client.default_na_pro_id', $performerProID)
  943. ->orderBy('appointment.start_time', 'DESC')
  944. ->get();
  945. // $naApptUpdates = AppointmentConfirmationDecision
  946. // ::join('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  947. // ->join('client', 'client.id', '=', 'appointment.client_id')
  948. // ->where('client.default_na_pro_id', $performerProID)
  949. // ->where('appointment_confirmation_decision.was_acknowledged_by_client_default_na', false)
  950. // ->orderBy('appointment.start_time DESC')
  951. // ->get();
  952. // unstamped client memos
  953. // for mcp
  954. $mcpClientMemos = DB::select(
  955. DB::raw("
  956. SELECT c.uid as client_uid, c.name_first, c.name_last,
  957. cm.uid, cm.content, cm.created_at
  958. FROM client c join client_memo cm on c.id = cm.client_id
  959. WHERE
  960. c.mcp_pro_id = {$performerProID} AND
  961. cm.mcp_stamp_id IS NULL
  962. ORDER BY cm.created_at DESC
  963. ")
  964. );
  965. // for na
  966. $naClientMemos = DB::select(
  967. DB::raw("
  968. SELECT c.uid as client_uid, c.name_first, c.name_last,
  969. cm.uid, cm.content, cm.created_at
  970. FROM client c join client_memo cm on c.id = cm.client_id
  971. WHERE
  972. c.default_na_pro_id = {$performerProID} AND
  973. cm.default_na_stamp_id IS NULL
  974. ORDER BY cm.created_at DESC
  975. ")
  976. );
  977. $keyNumbers['rmBillsToSign'] = Bill
  978. ::where('is_cancelled', false)
  979. ->where('cm_or_rm', 'RM')
  980. ->where(function ($q) use ($performerProID) {
  981. $q
  982. ->where(function ($q2) use ($performerProID) {
  983. $q2->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false);
  984. })
  985. ->orWhere(function ($q2) use ($performerProID) {
  986. $q2->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false);
  987. })
  988. ->orWhere(function ($q2) use ($performerProID) {
  989. $q2->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false);
  990. })
  991. ->orWhere(function ($q2) use ($performerProID) {
  992. $q2->where('generic_pro_id', $performerProID)->where('is_signed_by_generic_pro', false);
  993. });
  994. })
  995. ->count();
  996. $count = DB::select(
  997. DB::raw(
  998. "
  999. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  1000. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  1001. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  1002. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  1003. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  1004. AND (care_month.number_of_days_with_remote_measurements < 16 OR care_month.number_of_days_with_remote_measurements IS NULL)
  1005. "
  1006. )
  1007. );
  1008. $keyNumbers['rmPatientsWithLT16MD'] = $count[0]->cnt;
  1009. $count = DB::select(
  1010. DB::raw(
  1011. "
  1012. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  1013. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  1014. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  1015. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  1016. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  1017. AND (care_month.number_of_days_with_remote_measurements >= 16 AND care_month.number_of_days_with_remote_measurements IS NOT NULL)
  1018. "
  1019. )
  1020. );
  1021. $keyNumbers['rmPatientsWithGTE16MD'] = $count[0]->cnt;
  1022. $count = DB::select(
  1023. DB::raw(
  1024. "
  1025. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  1026. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  1027. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  1028. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  1029. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  1030. 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)
  1031. "
  1032. )
  1033. );
  1034. $keyNumbers['rmPatientsWithWhomCommDone'] = $count[0]->cnt;
  1035. $count = DB::select(
  1036. DB::raw(
  1037. "
  1038. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  1039. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  1040. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  1041. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  1042. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  1043. 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)
  1044. "
  1045. )
  1046. );
  1047. $keyNumbers['rmPatientsWithWhomCommNotDone'] = $count[0]->cnt;
  1048. // num measurements that need stamping
  1049. $keyNumbers['measurementsToBeStamped'] = $this->performer()->pro->getUnstampedMeasurementsFromCurrentMonth(true, null, null);
  1050. if($performer->pro->pro_type === 'ADMIN') {
  1051. // patients without coverage information
  1052. $keyNumbers['patientsWithoutCoverageInformation'] = DB::select(DB::raw("
  1053. SELECT count(DISTINCT (cl.id)) as cnt
  1054. FROM client cl
  1055. WHERE cl.shadow_pro_id IS NULL AND cl.latest_client_primary_coverage_id IS NULL -- no coverage record"
  1056. ))[0]->cnt;
  1057. // patients pending coverage verification
  1058. $keyNumbers['patientsPendingCoverageVerification'] = DB::select(DB::raw("
  1059. SELECT count(DISTINCT (cl.id)) as cnt
  1060. FROM client cl
  1061. LEFT JOIN client_primary_coverage cpc ON cl.latest_client_primary_coverage_id = cpc.id
  1062. WHERE cl.shadow_pro_id IS NULL
  1063. AND (cl.latest_client_primary_coverage_id IS NOT NULL -- coverage exists, but status is null or unknown
  1064. AND (
  1065. (cpc.plan_type = 'MEDICARE' AND (cpc.is_partbprimary = 'UNKNOWN' OR cpc.is_partbprimary IS NULL))
  1066. OR
  1067. (cpc.plan_type != 'MEDICARE' AND
  1068. (cpc.manual_determination_category = 'UNKNOWN' OR cpc.manual_determination_category IS NULL))
  1069. ))"
  1070. ))[0]->cnt;
  1071. }
  1072. return view('app/dashboard-admin', compact('keyNumbers', 'reimbursement', 'milliseconds',
  1073. 'businessNumbers',
  1074. 'incomingReports', 'tickets', 'supplyOrders',
  1075. 'numERx', 'numLabs', 'numImaging', 'numSupplyOrders',
  1076. 'newMCPAssociations', 'newNAAssociations',
  1077. 'mcpClientMemos', 'naClientMemos',
  1078. 'proApptUpdates', 'naApptUpdates'));
  1079. }
  1080. public function dashboard(Request $request)
  1081. {
  1082. $performer = $this->performer();
  1083. $pro = $performer->pro;
  1084. if($pro->is_enrolled_as_mcp){
  1085. return $this->dashboard_MCP($request);
  1086. }elseif($pro->pro_type === 'ADMIN'){
  1087. return $this->dashboard_ADMIN($request);
  1088. }else{
  1089. return $this->dashboard_DNA($request);
  1090. }
  1091. }
  1092. public function dashboardMeasurementsTab(Request $request, $page = 1) {
  1093. $performer = $this->performer();
  1094. $myClientIDs = [];
  1095. if ($performer->pro->pro_type != 'ADMIN') {
  1096. $myClientIDs = $this->getMyClientIds();
  1097. $myClientIDs = implode(", ", $myClientIDs);
  1098. }
  1099. $ifNotAdmin = " AND (
  1100. client.mcp_pro_id = {$performer->pro->id}
  1101. OR client.rmm_pro_id = {$performer->pro->id}
  1102. OR client.rme_pro_id = {$performer->pro->id}
  1103. OR client.physician_pro_id = {$performer->pro->id}
  1104. OR client.id in (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = {$performer->pro->id})
  1105. OR client.id in (SELECT client_id FROM appointment WHERE status NOT IN ('CANCELLED') AND pro_id = {$performer->pro->id})
  1106. )";
  1107. $numMeasurements = DB::select(
  1108. DB::raw(
  1109. "
  1110. SELECT count(measurement.id) as cnt
  1111. FROM measurement
  1112. join client on measurement.client_id = client.id
  1113. WHERE measurement.label NOT IN ('SBP', 'DBP')
  1114. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  1115. AND measurement.is_removed IS FALSE
  1116. AND measurement.has_been_stamped_by_mcp IS FALSE
  1117. AND measurement.ts IS NOT NULL
  1118. AND measurement.client_bdt_measurement_id IS NOT NULL
  1119. AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
  1120. AND EXTRACT(MONTH from measurement.created_at) = EXTRACT(MONTH from NOW())
  1121. AND EXTRACT(YEAR from measurement.created_at) = EXTRACT(YEAR from NOW())
  1122. " .
  1123. (
  1124. $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
  1125. )
  1126. )
  1127. );
  1128. $numMeasurements = $numMeasurements[0]->cnt;
  1129. $measurements = DB::select(
  1130. DB::raw(
  1131. "
  1132. SELECT measurement.uid as uid,
  1133. care_month.uid as care_month_uid,
  1134. care_month.start_date as care_month_start_date,
  1135. measurement.label,
  1136. measurement.value,
  1137. measurement.sbp_mm_hg,
  1138. measurement.dbp_mm_hg,
  1139. measurement.numeric_value,
  1140. measurement.value_pulse,
  1141. measurement.value_irregular,
  1142. measurement.ts,
  1143. client.id as client_id,
  1144. client.mcp_pro_id,
  1145. client.default_na_pro_id,
  1146. client.rmm_pro_id,
  1147. client.rme_pro_id,
  1148. client.uid as client_uid,
  1149. client.name_last,
  1150. client.name_first,
  1151. care_month.rm_total_time_in_seconds
  1152. FROM measurement
  1153. join client on measurement.client_id = client.id
  1154. join care_month on client.id = care_month.client_id
  1155. WHERE measurement.label NOT IN ('SBP', 'DBP')
  1156. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  1157. AND measurement.is_removed IS FALSE
  1158. AND measurement.has_been_stamped_by_mcp IS FALSE
  1159. AND measurement.ts IS NOT NULL
  1160. AND measurement.client_bdt_measurement_id IS NOT NULL
  1161. AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
  1162. AND EXTRACT(MONTH from measurement.created_at) = EXTRACT(MONTH from NOW())
  1163. AND EXTRACT(YEAR from measurement.created_at) = EXTRACT(YEAR from NOW())
  1164. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from NOW())
  1165. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from NOW())
  1166. " .
  1167. (
  1168. $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
  1169. )
  1170. ) .
  1171. " ORDER BY measurement.ts DESC LIMIT 20 OFFSET " . (($page - 1) * 20)
  1172. );
  1173. return view('app.dashboard.measurements', compact('numMeasurements', 'measurements', 'page'));
  1174. }
  1175. public function dashboardAppointmentDates(Request $request, $from, $to) {
  1176. $performer = $this->performer();
  1177. $performerProID = $performer->pro->id;
  1178. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  1179. $results = DB::table('appointment')->select('raw_date')->distinct()->where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  1180. if(!$isAdmin) {
  1181. $results = $results->where("pro_id", $performerProID);
  1182. }
  1183. $results = $results->get();
  1184. $dates = [];
  1185. foreach ($results as $result) {
  1186. // $dates[] = strtotime($result->raw_date) . '000';
  1187. $dates[] = $result->raw_date;
  1188. }
  1189. // foreach ($results as $result) {
  1190. // $results->dateYMD = date('Y-m-d', strtotime($result->raw_date));
  1191. // }
  1192. return json_encode($dates);
  1193. }
  1194. public function dashboardAppointments(Request $request, $from, $to) {
  1195. $performer = $this->performer();
  1196. $performerProID = $performer->pro->id;
  1197. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  1198. // $appointments = Appointment::where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  1199. $appointments = Appointment::where("raw_date", '=', $from);
  1200. if(!$isAdmin) {
  1201. $appointments = $appointments->where("pro_id", $performerProID);
  1202. }
  1203. $appointments = $appointments
  1204. // ->whereRaw('status NOT IN (\'CANCELLED\', \'COMPLETED\')')
  1205. ->orderBy('start_time', 'asc')
  1206. ->get();
  1207. foreach ($appointments as $appointment) {
  1208. $date = explode(" ", $appointment->start_time)[0];
  1209. $appointment->milliseconds = strtotime($date) . '000';
  1210. $appointment->newStatus = $appointment->status;
  1211. $appointment->dateYMD = date('Y-m-d', strtotime($appointment->raw_date));
  1212. $appointment->clientName = $appointment->client->displayName();
  1213. $appointment->clientInitials = substr($appointment->client->name_first, 0, 1) . substr($appointment->client->name_last, 0, 1);
  1214. $appointment->isClientShadowOfPro = $appointment->client->shadow_pro_id ? true : false;
  1215. $appointment->proInitials = substr($appointment->pro->name_first, 0, 1) . substr($appointment->pro->name_last, 0, 1);
  1216. $appointment->friendlyStartTime = friendly_time($appointment->raw_start_time);
  1217. $appointment->friendlyEndTime = friendly_time($appointment->raw_end_time);
  1218. $appointment->clientSummary = friendly_date_time($appointment->client->dob, false) . ' (' .
  1219. $appointment->client->age_in_years . ' y.o' .
  1220. ($appointment->client->sex ? ' ' . $appointment->client->sex : '') .
  1221. ')';
  1222. $appointment->clientAge = $appointment->client->age_in_years;
  1223. $appointment->clientSex = $appointment->client->sex;
  1224. $appointment->started = false;
  1225. $appointment->inHowManyHours = date_diff(date_create('now'), date_create($appointment->start_time), false)
  1226. ->format('%R%h h, %i m');
  1227. if ($appointment->inHowManyHours[0] === '-') {
  1228. $appointment->inHowManyHours = substr($appointment->inHowManyHours, 1) . ' ago';
  1229. $appointment->started = true;
  1230. } else {
  1231. $appointment->inHowManyHours = 'Appt. in ' . substr($appointment->inHowManyHours, 1);
  1232. }
  1233. $appointment->clientUid = $appointment->client->uid;
  1234. $appointment->proUid = $appointment->pro->uid;
  1235. $appointment->proName = $appointment->pro->displayName();
  1236. // insurance information
  1237. $appointment->coverage = $appointment->client->getPrimaryCoverageStatus();
  1238. unset($appointment->client);
  1239. unset($appointment->pro);
  1240. unset($appointment->detail_json);
  1241. }
  1242. return json_encode($appointments);
  1243. }
  1244. public function dashboardMeasurements(Request $request, $filter) {
  1245. $measurements = $this->performer()->pro->getMeasurements($filter === 'NEED_ACK');
  1246. return json_encode($measurements);
  1247. }
  1248. public function patients(Request $request, $filter = '')
  1249. {
  1250. $performer = $this->performer();
  1251. $query = $performer->pro->getAccessibleClientsQuery();
  1252. $q = trim($request->input('q'));
  1253. if(!empty($q)) {
  1254. $query = $query->where(function ($query) use ($q) {
  1255. $query->where('name_first', 'ILIKE', "%$q%")
  1256. ->orWhere('name_last', 'ILIKE', "%$q%")
  1257. ->orWhere('email_address', 'ILIKE', "%$q%")
  1258. ->orWhere('tags', 'ILIKE', "%$q%");
  1259. });
  1260. }
  1261. switch ($filter) {
  1262. case 'not-yet-seen':
  1263. $query = $query
  1264. ->where(function ($query) use ($performer) {
  1265. $query
  1266. ->where(function ($query) use ($performer) { // own patient and primary OB visit pending
  1267. $query->where('mcp_pro_id', $performer->pro->id)
  1268. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  1269. })
  1270. ->orWhere(function ($query) use ($performer) { // mcp of any client program and program OB pending
  1271. $query->select(DB::raw('COUNT(id)'))
  1272. ->from('client_program')
  1273. ->whereColumn('client_id', 'client.id')
  1274. ->where('mcp_pro_id', $performer->pro->id)
  1275. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  1276. }, '>=', 1);
  1277. });
  1278. break;
  1279. case 'having-birthday-today':
  1280. $query = $query
  1281. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  1282. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')]);
  1283. break;
  1284. // more cases can be added as needed
  1285. default:
  1286. break;
  1287. }
  1288. $patients = $query->orderBy('id', 'desc')->paginate(50);
  1289. // patient acquisition chart (admin only)
  1290. $patientAcquisitionData = null;
  1291. if($performer->pro->pro_type === 'ADMIN') {
  1292. $startDate = date_sub(date_create(), date_interval_create_from_date_string("1 month"));
  1293. $startDate = date_format($startDate, "Y-m-d");
  1294. $patientAcquisitionData = DB::select(DB::raw(
  1295. "SELECT count(id) as count, DATE(created_at at time zone 'utc' at time zone 'est') as date " .
  1296. "FROM client " .
  1297. "WHERE shadow_pro_id IS NULL " .
  1298. "GROUP BY DATE(created_at at time zone 'utc' at time zone 'est') " .
  1299. "ORDER BY DATE(created_at at time zone 'utc' at time zone 'est') DESC " .
  1300. "LIMIT 30"));
  1301. }
  1302. return view('app/patients', compact('patients', 'filter', 'patientAcquisitionData'));
  1303. }
  1304. public function patientsSuggest(Request $request)
  1305. {
  1306. $pro = $this->pro;
  1307. $term = $request->input('term') ? trim($request->input('term')) : '';
  1308. $originalTerm = $term;
  1309. if (empty($term)) return '';
  1310. // if multiple words in query, check for all (max 2)
  1311. $term2 = '';
  1312. if(strpos($term, ' ') !== FALSE) {
  1313. $terms = explode(' ', $term);
  1314. $term = trim($terms[0]);
  1315. $term2 = trim($terms[1]);
  1316. }
  1317. $phoneNumberTerm = preg_replace("/[^0-9]/", "", $originalTerm );
  1318. if($phoneNumberTerm == ""){ //to avoid search with blank string
  1319. $phoneNumberTerm = $term;
  1320. }
  1321. $clientQuery= Client::whereNull('shadow_pro_id')
  1322. ->where(function ($q) use ($term, $phoneNumberTerm) {
  1323. $q->where('name_first', 'ILIKE', '%' . $term . '%')
  1324. ->orWhere('name_last', 'ILIKE', '%' . $term . '%')
  1325. ->orWhere('cell_number', 'ILIKE', '%' . $phoneNumberTerm . '%')
  1326. ->orWhere('phone_home', 'ILIKE', '%' . $phoneNumberTerm . '%');
  1327. });
  1328. if(!empty($term2)) {
  1329. $clientQuery = $clientQuery->where(function ($q) use ($term2, $phoneNumberTerm) {
  1330. $q->where('name_first', 'ILIKE', '%' . $term2 . '%')
  1331. ->orWhere('name_last', 'ILIKE', '%' . $term2 . '%')
  1332. ->orWhere('cell_number', 'ILIKE', '%' . $phoneNumberTerm . '%')
  1333. ->orWhere('phone_home', 'ILIKE', '%' . $phoneNumberTerm . '%');
  1334. });
  1335. }
  1336. if(!($pro->pro_type === 'ADMIN' && $pro->can_see_any_client_via_search)) {
  1337. $clientQuery->where(function ($q) use ($pro) {
  1338. if($pro->pro_type === 'ADMIN') {
  1339. $q->whereIn('id', $pro->getMyClientIds(true))->orWhereNull('mcp_pro_id');
  1340. }
  1341. else {
  1342. $q->whereIn('id', $pro->getMyClientIds(true));
  1343. }
  1344. });
  1345. }
  1346. $clients = $clientQuery->get();
  1347. return view('app/patient-suggest', compact('clients'));
  1348. }
  1349. public function pharmacySuggest(Request $request)
  1350. {
  1351. $term = $request->input('term') ? trim($request->input('term')) : '';
  1352. if (empty($term)) return '';
  1353. $term = strtolower($term);
  1354. $pharmacies = Facility::where('facility_type', 'Pharmacy')
  1355. ->where(function ($q) use ($term) {
  1356. $q->orWhereRaw('LOWER(name::text) LIKE ?', ['%' . $term . '%'])
  1357. ->orWhereRaw('LOWER(address_line1::text) LIKE ?', ['%' . $term . '%'])
  1358. ->orWhereRaw('LOWER(address_line2::text) LIKE ?', ['%' . $term . '%'])
  1359. ->orWhereRaw('LOWER(address_city::text) LIKE ?', ['%' . $term . '%'])
  1360. ->orWhereRaw('LOWER(address_state::text) LIKE ?', ['%' . $term . '%'])
  1361. ->orWhereRaw('LOWER(phone::text) LIKE ?', ['%' . $term . '%'])
  1362. ->orWhereRaw('LOWER(address_zip::text) LIKE ?', ['%' . $term . '%']);
  1363. });
  1364. if($request->input('city')) {
  1365. $pharmacies = $pharmacies->whereRaw('LOWER(address_city::text) LIKE ?', ['%' . strtolower($request->input('city')) . '%']);
  1366. }
  1367. if($request->input('state')) {
  1368. $pharmacies = $pharmacies->whereRaw('LOWER(address_state::text) LIKE ?', ['%' . strtolower($request->input('state')) . '%']);
  1369. }
  1370. if($request->input('zip')) {
  1371. $pharmacies = $pharmacies->whereRaw('LOWER(address_zip::text) LIKE ?', ['%' . strtolower($request->input('zip')) . '%']);
  1372. }
  1373. $pharmacies = $pharmacies
  1374. ->orderBy('name', 'asc')
  1375. ->orderBy('address_line1', 'asc')
  1376. ->orderBy('address_city', 'asc')
  1377. ->orderBy('address_state', 'asc')
  1378. ->get();
  1379. return view('app/pharmacy-suggest', compact('pharmacies'));
  1380. }
  1381. public function facilitySuggestJSON(Request $request)
  1382. {
  1383. $term = $request->input('term') ? trim($request->input('term')) : '';
  1384. if (empty($term)) return '';
  1385. $terms = explode(' ', $term);
  1386. $terms = array_filter($terms, function($_x) {
  1387. return !!trim($_x);
  1388. });
  1389. $whereCondition = [];
  1390. $whereParams = [];
  1391. for ($i = 0; $i < count($terms); $i++) {
  1392. $whereCondition[] = "(name ILIKE :term{$i} OR address_city ILIKE :term{$i} OR address_state ILIKE :term{$i} OR address_zip ILIKE :term{$i})";
  1393. $whereParams["term{$i}"] = '%' . $terms[$i] . '%';
  1394. }
  1395. $whereCondition = implode(" AND ", $whereCondition);
  1396. $matches = DB::select(
  1397. "SELECT (name || ' ' || address_city || ' ' || address_state || ' ' || address_zip) as text,
  1398. address_line1 as text2,
  1399. name, address_city as city, address_state as state, address_zip as zip, phone, fax FROM facility
  1400. WHERE {$whereCondition} ORDER BY name", $whereParams);
  1401. return json_encode([
  1402. "success" => true,
  1403. "data" => $matches
  1404. ]);
  1405. }
  1406. public function proSuggest(Request $request) {
  1407. $term = $request->input('term') ? trim($request->input('term')) : '';
  1408. if (empty($term)) return '';
  1409. $term = strtolower($term);
  1410. $pros = Pro::where(function ($q) use ($term) {
  1411. $q->orWhereRaw('LOWER(name_first::text) LIKE ?', ['%' . $term . '%'])
  1412. ->orWhereRaw('LOWER(name_last::text) LIKE ?', ['%' . $term . '%'])
  1413. ->orWhereRaw('cell_number LIKE ?', ['%' . $term . '%']);
  1414. });
  1415. $type = $request->input('type') ? trim($request->input('type')) : '';
  1416. if(!!$type) {
  1417. switch(strtolower($type)) {
  1418. case 'hcp':
  1419. $pros->where('is_hcp', true);
  1420. break;
  1421. case 'default-na': // TODO: fix condition for NA
  1422. $pros->where('is_hcp', false)->where('pro_type', '!=', 'ADMIN');
  1423. break;
  1424. case 'admin':
  1425. $pros->where('pro_type', 'ADMIN');
  1426. break;
  1427. case 'non-admin':
  1428. $pros->where('pro_type', '!=', 'ADMIN');
  1429. break;
  1430. }
  1431. }
  1432. if($this->performer->pro && $this->performer->pro->pro_type != 'ADMIN'){
  1433. $accessiblePros = ProProAccess::where('owner_pro_id', $this->performer->pro->id);
  1434. $accessibleProIds = [];
  1435. foreach($accessiblePros as $accessiblePro){
  1436. $accessibleProIds[] = $accessiblePro->id;
  1437. }
  1438. $accessibleProIds[] = $this->performer->pro->id;
  1439. // for dna, add pros accessible via pro teams
  1440. if($this->performer->pro->isDefaultNA()) {
  1441. $teams = $this->performer->pro->teamsWhereAssistant;
  1442. foreach ($teams as $team) {
  1443. if(!in_array($team->mcp_pro_id, $accessibleProIds)) {
  1444. $accessibleProIds[] = $team->mcp_pro_id;
  1445. }
  1446. }
  1447. }
  1448. $pros->whereIn('id', $accessibleProIds);
  1449. }
  1450. $suggestedPros = $pros->orderBy('name_last')->orderBy('name_first')->get();
  1451. // for calendar select2
  1452. if($request->input('json')) {
  1453. $jsonPros = $suggestedPros->map(function($_pro) {
  1454. return [
  1455. "uid" => $_pro->uid,
  1456. "id" => $_pro->id,
  1457. "text" => $_pro->displayName(),
  1458. "initials" => $_pro->initials(),
  1459. ];
  1460. });
  1461. return json_encode([
  1462. "results" => $jsonPros
  1463. ]);
  1464. }
  1465. return view('app/pro-suggest', compact('suggestedPros'));
  1466. }
  1467. public function canAccessPatient(Request $request, $uid) {
  1468. return json_encode([
  1469. "success" => true,
  1470. "data" => $this->performer->pro->canAccess($uid)
  1471. ]);
  1472. }
  1473. public function proDisplayName(Request $request, Pro $pro) {
  1474. return $pro ? $pro->displayName() : '';
  1475. }
  1476. public function unmappedSMS(Request $request, $filter = '')
  1477. {
  1478. $proID = $this->performer()->pro->id;
  1479. if ($this->performer()->pro->pro_type === 'ADMIN') {
  1480. $query = Client::where('id', '>', 0);
  1481. } else {
  1482. $query = Client::where(function ($q) use ($proID) {
  1483. $q->where('mcp_pro_id', $proID)
  1484. ->orWhere('cm_pro_id', $proID)
  1485. ->orWhere('rmm_pro_id', $proID)
  1486. ->orWhere('rme_pro_id', $proID)
  1487. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID]);
  1488. });
  1489. }
  1490. $patients = $query->orderBy('name_last', 'asc')->orderBy('name_first', 'asc')->get();
  1491. $unmappedSMS = ClientSMS::where('client_id', null)->where('incoming_or_outgoing', 'INCOMING')->paginate(20);
  1492. return view('app/unmapped-sms', compact('unmappedSMS', 'patients'));
  1493. }
  1494. public function newPatient(Request $request)
  1495. {
  1496. $mbPayers = MBPayer::all();
  1497. return view('app/new-patient', compact('mbPayers'));
  1498. }
  1499. public function newNonMcnPatient(Request $request)
  1500. {
  1501. $mbPayers = MBPayer::all();
  1502. return view('app/new-non-mcn-patient', compact('mbPayers'));
  1503. }
  1504. public function mc(Request $request, $fragment = "")
  1505. {
  1506. $page = "/";
  1507. if ($fragment) {
  1508. $page = '/' . $fragment;
  1509. }
  1510. return view('app/mc', compact('page'));
  1511. }
  1512. public function blank(Request $request)
  1513. {
  1514. return view('app/blank');
  1515. }
  1516. public function noteTemplateSet(Request $request, $section, $template)
  1517. {
  1518. return view('app/patient/note/_template', [
  1519. "sectionInternalName" => $section,
  1520. "templateName" => $template
  1521. ]);
  1522. }
  1523. public function noteExamTemplateSet(Request $request, $exam, $template)
  1524. {
  1525. return view('app/patient/note/_template-exam', [
  1526. "exam" => $exam,
  1527. "sectionInternalName" => 'exam-' . $exam . '-detail',
  1528. "templateName" => $template
  1529. ]);
  1530. }
  1531. public function logInAs(Request $request)
  1532. {
  1533. if($this->pro->pro_type != 'ADMIN'){
  1534. return redirect()->to(route('dashboard'));
  1535. }
  1536. // dummy condition to get the chain-ability going
  1537. $pros = Pro::where('id', '>', 0);
  1538. if($request->input('q')) {
  1539. $nameQuery = '%' . $request->input('q') . '%';
  1540. $pros = $pros->where(function ($query) use ($nameQuery) {
  1541. $query->where('name_first', 'ILIKE', $nameQuery)
  1542. ->orWhere('name_last', 'ILIKE', $nameQuery)
  1543. ->orWhere('email_address', 'ILIKE', $nameQuery)
  1544. ->orWhere('cell_number', 'ILIKE', $nameQuery);
  1545. });
  1546. }
  1547. if($request->input('sort') && $request->input('dir')) {
  1548. $pros = $pros->orderBy($request->input('sort'), $request->input('dir'));
  1549. }
  1550. else {
  1551. $pros = $pros->orderBy('name_last', 'asc');
  1552. }
  1553. $pros = $pros->paginate(20);
  1554. return view('app/log-in-as', ['logInAsPros' => $pros]);
  1555. }
  1556. public function processLogInAs(Request $request)
  1557. {
  1558. $api = new Backend();
  1559. try {
  1560. $apiResponse = $api->post('session/proLogInAs', [
  1561. 'proUid' => $request->post('proUid')
  1562. ],
  1563. [
  1564. 'sessionKey'=>$this->performer()->session_key
  1565. ]);
  1566. $data = json_decode($apiResponse->getContents());
  1567. if (!property_exists($data, 'success') || !$data->success) {
  1568. return redirect()->to(route('log-in-as'))->with('message', $data->message)
  1569. ->withInput($request->input());
  1570. }
  1571. Cookie::queue('sessionKey', $data->data->sessionKey);
  1572. return redirect('/mc');
  1573. } catch (\Exception $e) {
  1574. return redirect()->to(route('log-in-as'))
  1575. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  1576. ->withInput($request->input());
  1577. }
  1578. }
  1579. public function backToAdminPro(Request $request){
  1580. $adminPerformerId = $this->performer->logged_in_as_pro_from_admin_pro_app_session_id;
  1581. $adminPerformer = AppSession::where('id', $adminPerformerId)->first();
  1582. $url = "/session/pro_log_in_with_session_key/".$adminPerformer->session_key;
  1583. $api = new Backend();
  1584. try {
  1585. $apiResponse = $api->post($url, []);
  1586. $data = json_decode($apiResponse->getContents());
  1587. if (!property_exists($data, 'success') || !$data->success) {
  1588. return redirect()->to(route('logout'));
  1589. }
  1590. Cookie::queue('sessionKey', $data->data->sessionKey);
  1591. return redirect(route('dashboard'));
  1592. } catch (\Exception $e) {
  1593. return redirect(route('dashboard'));
  1594. }
  1595. }
  1596. public function getTicket(Request $request, Ticket $ticket) {
  1597. $ticket->data = json_decode($ticket->data);
  1598. // $ticket->created_at = friendly_date_time($ticket->created_at);
  1599. $ticket->assignedPro;
  1600. $ticket->managerPro;
  1601. $ticket->orderingPro;
  1602. $ticket->initiatingPro;
  1603. return json_encode($ticket);
  1604. }
  1605. public function genericBill(Request $request, $entityType, $entityUid) {
  1606. $patient = null;
  1607. if ($entityType && $entityUid) {
  1608. try {
  1609. $entityClass = "\\App\\Models\\" . $entityType;
  1610. $entity = $entityClass::where('uid', $entityUid)->first();
  1611. if ($entity->client) {
  1612. $patient = $entity->client;
  1613. }
  1614. } catch (\Exception $e) {
  1615. }
  1616. }
  1617. return view('app.generic-bills.inline', ['class' => 'p-3 border-top mt-3', 'entityType' => $entityType, 'entityUid' => $entityUid, 'patient' => $patient]);
  1618. }
  1619. }