HomeController.php 97 KB

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