HomeController.php 101 KB

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