HomeController.php 98 KB

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