HomeController.php 92 KB

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