HomeController.php 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Lib\Backend;
  4. use App\Models\Appointment;
  5. use App\Models\AppSession;
  6. use App\Models\ClientSMS;
  7. use App\Models\Facility;
  8. use App\Models\Ticket;
  9. use DateTime;
  10. use App\Models\Client;
  11. use App\Models\Bill;
  12. use App\Models\Measurement;
  13. use App\Models\Note;
  14. use App\Models\Pro;
  15. use App\Models\ProTransaction;
  16. use GuzzleHttp\Cookie\CookieJar;
  17. use Illuminate\Http\Request;
  18. use Illuminate\Support\Facades\Cookie;
  19. use Illuminate\Support\Facades\DB;
  20. use Illuminate\Support\Facades\Http;
  21. class HomeController extends Controller
  22. {
  23. public function confirmSmsAuthToken(Request $request)
  24. {
  25. return view('app/confirm_sms_auth_token');
  26. }
  27. public function setPassword(Request $request)
  28. {
  29. return view('app/set_password');
  30. }
  31. public function setSecurityQuestions(Request $request)
  32. {
  33. return view('app/set_security_questions');
  34. }
  35. public function postConfirmSmsAuthToken(Request $request)
  36. {
  37. try {
  38. $url = config('stag.backendUrl') . '/session/confirmSmsAuthToken';
  39. $data = [
  40. 'cellNumber' => $request->input('cellNumber'),
  41. 'token' => $request->input('token'),
  42. ];
  43. $response = Http::asForm()
  44. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  45. ->post($url, $data)
  46. ->json();
  47. if (!isset($response['success']) || !$response['success']) {
  48. $message = 'API error';
  49. if (isset($response['error'])) {
  50. $message = $response['error'];
  51. if (isset($response['path'])) $message .= ': ' . $response['path'];
  52. } else if (isset($response['message'])) $message = $response['message'];
  53. return redirect('/confirm_sms_auth_token')
  54. ->withInput()
  55. ->with('message', $message);
  56. }
  57. return redirect('/');
  58. } catch (\Exception $e) {
  59. return redirect()->back()
  60. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  61. ->withInput($request->input());
  62. }
  63. }
  64. public function resendSmsAuthToken(Request $request)
  65. {
  66. try {
  67. $url = config('stag.backendUrl') . '/session/resendSmsAuthToken';
  68. $data = [];
  69. $response = Http::asForm()
  70. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  71. ->post($url, $data)
  72. ->json();
  73. if (!isset($response['success']) || !$response['success']) {
  74. $message = 'API error';
  75. if (isset($response['error'])) {
  76. $message = $response['error'];
  77. if (isset($response['path'])) $message .= ': ' . $response['path'];
  78. } else if (isset($response['message'])) $message = $response['message'];
  79. return redirect('/confirm_sms_auth_token')
  80. ->withInput()
  81. ->with('message', $message);
  82. }
  83. return redirect()->back()->withInput()->with('message', "SMS Auth Token sent.");
  84. } catch (\Exception $e) {
  85. return redirect()->back()
  86. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  87. ->withInput($request->input());
  88. }
  89. }
  90. public function postSetPassword(Request $request)
  91. {
  92. try {
  93. $url = config('stag.backendUrl') . '/pro/selfPutPassword';
  94. $data = [
  95. 'newPassword' => $request->input('newPassword'),
  96. 'newPasswordConfirmation' => $request->input('newPasswordConfirmation'),
  97. ];
  98. $response = Http::asForm()
  99. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  100. ->post($url, $data)
  101. ->json();
  102. if (!isset($response['success']) || !$response['success']) {
  103. $message = 'API error';
  104. if (isset($response['error'])) {
  105. $message = $response['error'];
  106. if (isset($response['path'])) $message .= ': ' . $response['path'];
  107. } else if (isset($response['message'])) $message = $response['message'];
  108. return redirect('/set_password')
  109. ->withInput()
  110. ->with('message', $message);
  111. }
  112. return redirect('/');
  113. } catch (\Exception $e) {
  114. return redirect()->back()
  115. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  116. ->withInput($request->input());
  117. }
  118. }
  119. public function postSetSecurityQuestions(Request $request)
  120. {
  121. try {
  122. $url = env('BACKEND_URL', 'http://localhost:8080/api') . '/pro/selfPutSecurityQuestions';
  123. $data = [
  124. 'securityQuestion1' => $request->input('securityQuestion1'),
  125. 'securityAnswer1' => $request->input('securityAnswer1'),
  126. 'securityQuestion2' => $request->input('securityQuestion2'),
  127. 'securityAnswer2' => $request->input('securityAnswer2'),
  128. ];
  129. $response = Http::asForm()
  130. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  131. ->post($url, $data)
  132. ->json();
  133. if (!isset($response['success']) || !$response['success']) {
  134. $message = 'API error';
  135. if (isset($response['error'])) {
  136. $message = $response['error'];
  137. if (isset($response['path'])) $message .= ': ' . $response['path'];
  138. } else if (isset($response['message'])) $message = $response['message'];
  139. return redirect('/set_password')
  140. ->withInput()
  141. ->with('message', $message);
  142. }
  143. return redirect('/');
  144. } catch (\Exception $e) {
  145. return redirect()->back()
  146. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  147. ->withInput($request->input());
  148. }
  149. }
  150. public function dashboard(Request $request)
  151. {
  152. //patients where performer is the mcp
  153. $performer = $this->performer();
  154. $performerProID = $performer->pro->id;
  155. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  156. $keyNumbers = [];
  157. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  158. $keyNumbers['totalPatients'] = $queryClients->count();
  159. // patientNotSeenYet
  160. $patientNotSeenYet = $queryClients
  161. ->where(function ($query) use ($performer) { // own patient and primary OB visit pending
  162. $query->where('mcp_pro_id', $performer->pro->id)
  163. ->where('has_mcp_done_onboarding_visit', '!=', 'YES');
  164. })
  165. ->orWhere(function ($query) { // mcp of any client program and program OB pending
  166. $query->where(function ($_query) {
  167. $_query->select(DB::raw('COUNT(id)'))
  168. ->from('client_program')
  169. ->whereColumn('client_id', 'client.id')
  170. ->where('has_mcp_done_onboarding_visit', '!=', 'YES');
  171. }, '>=', 1);
  172. })->count();
  173. $keyNumbers['patientsNotSeenYet'] = $patientNotSeenYet;
  174. $pendingBillsToSign = Bill::where(function ($query) use ($performerProID) {
  175. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false);
  176. })
  177. ->orWhere(function ($query) use ($performerProID) {
  178. $query->where('cm_pro_id', $performerProID)->where('is_signed_by_cm', false)->where('is_cancelled', false);;
  179. })->orWhere(function ($query) use ($performerProID) {
  180. $query->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false)->where('is_cancelled', false);;
  181. })->orWhere(function ($query) use ($performerProID) {
  182. $query->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false)->where('is_cancelled', false);;
  183. })->count();
  184. $keyNumbers['pendingBillsToSign'] = $pendingBillsToSign;
  185. $pendingNotesToSign = Note::where(function ($query) use ($performerProID) {
  186. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false);;
  187. })
  188. ->orWhere(function ($query) use ($performerProID) {
  189. $query->where('ally_pro_id', $performerProID)->where('is_signed_by_ally', false)->where('is_cancelled', false);;
  190. })->count();
  191. $keyNumbers['pendingNotesToSign'] = $pendingNotesToSign;
  192. // open tickets
  193. $keyNumbers['numOpenTickets'] = Ticket::where('is_open', true)
  194. ->where(function ($q) use ($performerProID) {
  195. $q->where('assigned_pro_id', $performerProID)
  196. ->orWhere('manager_pro_id', $performerProID)
  197. ->orWhere('ordering_pro_id', $performerProID)
  198. ->orWhere('initiating_pro_id', $performerProID);
  199. })
  200. ->count();
  201. // num measurements that need stamping
  202. $keyNumbers['measurementsToBeStamped'] = ($this->performer()->pro->pro_type === 'ADMIN' ? '-' : count($this->performer()->pro->getMeasurements(true)));
  203. $reimbursement = [];
  204. $reimbursement["currentBalance"] = $performer->pro->balance;
  205. $reimbursement["nextPaymentDate"] = '--';
  206. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  207. if ($lastPayment) {
  208. $reimbursement["lastPayment"] = $lastPayment->amount;
  209. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  210. } else {
  211. $reimbursement["lastPayment"] = '--';
  212. $reimbursement["lastPaymentDate"] = '--';
  213. }
  214. //if today is < 15th, next payment is 15th, else nextPayment is
  215. $today = strtotime(date('Y-m-d'));
  216. $todayDate = date('j', $today);
  217. $todayMonth = date('m', $today);
  218. $todayYear = date('Y', $today);
  219. if ($todayDate < 15) {
  220. $nextPaymentDate = new DateTime();
  221. $nextPaymentDate->setDate($todayYear, $todayMonth, 15);
  222. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  223. } else {
  224. $nextPaymentDate = new \DateTime();
  225. $lastDayOfMonth = date('t', $today);
  226. $nextPaymentDate->setDate($todayYear, $todayMonth, $lastDayOfMonth);
  227. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  228. }
  229. //expectedPay
  230. $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;
  231. $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;
  232. $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;
  233. $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;
  234. $expectedForNa = DB::select(DB::raw("SELECT coalesce(SUM(na_expected_payment_amount),0) as expected_pay FROM bill WHERE na_pro_id = :performerProID AND has_na_been_paid = false AND is_signed_by_hcp IS TRUE AND is_cancelled = false"), ['performerProID' => $performerProID])[0]->expected_pay;
  235. $totalExpectedAmount = $expectedForHcp + $expectedForCm + $expectedForRme + $expectedForRmm + $expectedForNa;
  236. $reimbursement['nextPaymentAmount'] = $totalExpectedAmount;
  237. $milliseconds = strtotime(date('Y-m-d')) . '000';
  238. $measurements = $performer->pro->getMeasurements();
  239. return view('app/dashboard', compact('keyNumbers', 'reimbursement', 'milliseconds', 'measurements'));
  240. }
  241. public function dashboardAppointments(Request $request, $from, $to) {
  242. $performer = $this->performer();
  243. $performerProID = $performer->pro->id;
  244. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  245. $appointments = Appointment::where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  246. if(!$isAdmin) {
  247. $appointments = $appointments->where("pro_id", $performerProID);
  248. }
  249. $appointments = $appointments
  250. ->orderBy('start_time', 'asc')
  251. ->get();
  252. foreach ($appointments as $appointment) {
  253. $date = explode(" ", $appointment->start_time)[0];
  254. $appointment->milliseconds = strtotime($date) . '000';
  255. $appointment->newStatus = $appointment->status;
  256. $appointment->dateYMD = date('Y-m-d', strtotime($appointment->raw_date));
  257. $appointment->clientName = $appointment->client->displayName();
  258. $appointment->clientInitials = substr($appointment->client->name_first, 0, 1) . substr($appointment->client->name_last, 0, 1);
  259. $appointment->proInitials = substr($appointment->pro->name_first, 0, 1) . substr($appointment->pro->name_last, 0, 1);
  260. $appointment->friendlyStartTime = friendly_time($appointment->raw_start_time);
  261. $appointment->friendlyEndTime = friendly_time($appointment->raw_end_time);
  262. $appointment->clientSummary = friendly_date_time($appointment->client->dob, false) . ' (' .
  263. $appointment->client->age_in_years . ' y.o' .
  264. ($appointment->client->sex ? ' ' . $appointment->client->sex : '') .
  265. ')';
  266. $appointment->started = false;
  267. $appointment->inHowManyHours = date_diff(date_create('now'), date_create($appointment->start_time), false)
  268. ->format('%R%h h, %i m');
  269. if ($appointment->inHowManyHours[0] === '-') {
  270. $appointment->inHowManyHours = substr($appointment->inHowManyHours, 1) . ' ago';
  271. $appointment->started = true;
  272. } else {
  273. $appointment->inHowManyHours = 'Appt. in ' . substr($appointment->inHowManyHours, 1);
  274. }
  275. $appointment->clientUid = $appointment->client->uid;
  276. $appointment->proUid = $appointment->pro->uid;
  277. $appointment->proName = $appointment->pro->displayName();
  278. }
  279. return json_encode($appointments);
  280. }
  281. public function dashboardMeasurements(Request $request, $filter) {
  282. $measurements = $this->performer()->pro->getMeasurements($filter === 'NEED_ACK');
  283. return json_encode($measurements);
  284. }
  285. public function patients(Request $request, $filter = '')
  286. {
  287. $performer = $this->performer();
  288. $query = $performer->pro->getAccessibleClientsQuery();
  289. switch ($filter) {
  290. case 'not-yet-seen':
  291. $query = $query
  292. ->where(function ($query) use ($performer) {
  293. $query
  294. ->where(function ($query) use ($performer) { // own patient and primary OB visit pending
  295. $query->where('mcp_pro_id', $performer->pro->id)
  296. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  297. })
  298. ->orWhere(function ($query) use ($performer) { // mcp of any client program and program OB pending
  299. $query->select(DB::raw('COUNT(id)'))
  300. ->from('client_program')
  301. ->whereColumn('client_id', 'client.id')
  302. ->where('mcp_pro_id', $performer->pro->id)
  303. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  304. }, '>=', 1);
  305. });
  306. break;
  307. // more cases can be added as needed
  308. default:
  309. break;
  310. }
  311. $patients = $query->orderBy('id', 'desc')->paginate(500);
  312. return view('app/patients', compact('patients', 'filter'));
  313. }
  314. public function patientsSuggest(Request $request)
  315. {
  316. $pro = $this->pro;
  317. $term = $request->input('term') ? trim($request->input('term')) : '';
  318. if (empty($term)) return '';
  319. $clientQuery= Client::where(function ($q) use ($term) {
  320. $q->where('name_first', 'ILIKE', '%' . $term . '%')
  321. ->orWhere('name_last', 'ILIKE', '%' . $term . '%')
  322. ->orWhere('cell_number', 'ILIKE', '%' . $term . '%');
  323. });
  324. if($pro->pro_type != 'ADMIN'){
  325. $clientQuery->whereIn('id', $pro->getMyClientIds());
  326. }
  327. $clients = $clientQuery->get();
  328. return view('app/patient-suggest', compact('clients'));
  329. }
  330. public function pharmacySuggest(Request $request)
  331. {
  332. $term = $request->input('term') ? trim($request->input('term')) : '';
  333. if (empty($term)) return '';
  334. $term = strtolower($term);
  335. $pharmacies = Facility::where('facility_type', 'Pharmacy')
  336. ->where(function ($q) use ($term) {
  337. $q->orWhereRaw('LOWER(name::text) LIKE ?', ['%' . $term . '%'])
  338. ->orWhereRaw('LOWER(address_line1::text) LIKE ?', ['%' . $term . '%'])
  339. ->orWhereRaw('LOWER(address_line2::text) LIKE ?', ['%' . $term . '%'])
  340. ->orWhereRaw('LOWER(address_city::text) LIKE ?', ['%' . $term . '%'])
  341. ->orWhereRaw('LOWER(address_state::text) LIKE ?', ['%' . $term . '%'])
  342. ->orWhereRaw('LOWER(phone::text) LIKE ?', ['%' . $term . '%'])
  343. ->orWhereRaw('LOWER(address_zip::text) LIKE ?', ['%' . $term . '%']);
  344. })
  345. ->orderBy('name', 'asc')
  346. ->orderBy('address_line1', 'asc')
  347. ->orderBy('address_city', 'asc')
  348. ->orderBy('address_state', 'asc')
  349. ->get();
  350. return view('app/pharmacy-suggest', compact('pharmacies'));
  351. }
  352. public function unmappedSMS(Request $request, $filter = '')
  353. {
  354. $proID = $this->performer()->pro->id;
  355. if ($this->performer()->pro->pro_type === 'ADMIN') {
  356. $query = Client::where('id', '>', 0);
  357. } else {
  358. $query = Client::where(function ($q) use ($proID) {
  359. $q->where('mcp_pro_id', $proID)
  360. ->orWhere('cm_pro_id', $proID)
  361. ->orWhere('rmm_pro_id', $proID)
  362. ->orWhere('rme_pro_id', $proID)
  363. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID]);
  364. });
  365. }
  366. $patients = $query->orderBy('name_last', 'asc')->orderBy('name_first', 'asc')->get();
  367. $unmappedSMS = ClientSMS::where('client_id', null)->where('incoming_or_outgoing', 'INCOMING')->get();
  368. return view('app/unmapped-sms', compact('unmappedSMS', 'patients'));
  369. }
  370. public function newPatient(Request $request)
  371. {
  372. return view('app/new-patient');
  373. }
  374. public function mc(Request $request, $fragment = "")
  375. {
  376. $page = "/";
  377. if ($fragment) {
  378. $page = '/' . $fragment;
  379. }
  380. return view('app/mc', compact('page'));
  381. }
  382. public function blank(Request $request)
  383. {
  384. return view('app/blank');
  385. }
  386. public function noteTemplateSet(Request $request, $section, $template)
  387. {
  388. return view('app/patient/note/_template', [
  389. "sectionInternalName" => $section,
  390. "templateName" => $template
  391. ]);
  392. }
  393. public function noteExamTemplateSet(Request $request, $exam, $template)
  394. {
  395. return view('app/patient/note/_template-exam', [
  396. "exam" => $exam,
  397. "sectionInternalName" => 'exam-' . $exam . '-detail',
  398. "templateName" => $template
  399. ]);
  400. }
  401. public function logInAs(Request $request)
  402. {
  403. if($this->pro->pro_type != 'ADMIN'){
  404. return redirect()->to(route('dashboard'));
  405. }
  406. $pros = Pro
  407. ::where('pro_type', '!=', 'ADMIN')
  408. ->orWhereNull('pro_type')
  409. ->orderBy('name_last', 'asc')
  410. ->orderBy('name_first', 'asc')
  411. ->get();
  412. return view('app/log-in-as', compact('pros'));
  413. }
  414. public function processLogInAs(Request $request)
  415. {
  416. $api = new Backend();
  417. try {
  418. $apiResponse = $api->post('session/proLogInAs', [
  419. 'proUid' => $request->post('proUid')
  420. ],
  421. [
  422. 'sessionKey'=>$this->performer()->session_key
  423. ]);
  424. $data = json_decode($apiResponse->getContents());
  425. if (!property_exists($data, 'success') || !$data->success) {
  426. return redirect()->to(route('log-in-as'))->with('message', $data->message)
  427. ->withInput($request->input());
  428. }
  429. Cookie::queue('sessionKey', $data->data->sessionKey);
  430. return redirect('/mc');
  431. } catch (\Exception $e) {
  432. return redirect()->to(route('log-in-as'))
  433. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  434. ->withInput($request->input());
  435. }
  436. }
  437. public function backToAdminPro(Request $request){
  438. $adminPerformerId = $this->performer->logged_in_as_pro_from_admin_pro_app_session_id;
  439. $adminPerformer = AppSession::where('id', $adminPerformerId)->first();
  440. $url = "/session/pro_log_in_with_session_key/".$adminPerformer->session_key;
  441. $api = new Backend();
  442. try {
  443. $apiResponse = $api->post($url, []);
  444. $data = json_decode($apiResponse->getContents());
  445. if (!property_exists($data, 'success') || !$data->success) {
  446. return redirect()->to(route('logout'));
  447. }
  448. Cookie::queue('sessionKey', $data->data->sessionKey);
  449. return redirect(route('dashboard'));
  450. } catch (\Exception $e) {
  451. return redirect(route('dashboard'));
  452. }
  453. }
  454. }