HomeController.php 96 KB

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