HomeController.php 98 KB

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