HomeController.php 85 KB

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