HomeController.php 100 KB

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