HomeController.php 22 KB

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