HomeController.php 99 KB

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