HomeController.php 76 KB

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