HomeController.php 100 KB

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