HomeController.php 86 KB

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