HomeController.php 97 KB

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