HomeController.php 91 KB

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