HomeController.php 99 KB

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