HomeController.php 96 KB

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