HomeController.php 98 KB

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