HomeController.php 101 KB

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