HomeController.php 87 KB

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