HomeController.php 96 KB

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