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