HomeController.php 99 KB

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