HomeController.php 100 KB

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