HomeController.php 56 KB

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