HomeController.php 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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 patients(Request $request, $filter = '')
  278. {
  279. $performer = $this->performer();
  280. $query = $performer->pro->getAccessibleClientsQuery();
  281. switch ($filter) {
  282. case 'not-yet-seen':
  283. $query = $query
  284. ->where(function ($query) use ($performer) {
  285. $query
  286. ->where(function ($query) use ($performer) { // own patient and primary OB visit pending
  287. $query->where('mcp_pro_id', $performer->pro->id)
  288. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  289. })
  290. ->orWhere(function ($query) use ($performer) { // mcp of any client program and program OB pending
  291. $query->select(DB::raw('COUNT(id)'))
  292. ->from('client_program')
  293. ->whereColumn('client_id', 'client.id')
  294. ->where('mcp_pro_id', $performer->pro->id)
  295. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  296. }, '>=', 1);
  297. });
  298. break;
  299. // more cases can be added as needed
  300. default:
  301. break;
  302. }
  303. $patients = $query->orderBy('id', 'desc')->paginate(500);
  304. return view('app/patients', compact('patients', 'filter'));
  305. }
  306. public function patientsSuggest(Request $request)
  307. {
  308. $pro = $this->pro;
  309. $term = $request->input('term') ? trim($request->input('term')) : '';
  310. if (empty($term)) return '';
  311. $clientQuery= Client::where(function ($q) use ($term) {
  312. $q->where('name_first', 'ILIKE', '%' . $term . '%')
  313. ->orWhere('name_last', 'ILIKE', '%' . $term . '%')
  314. ->orWhere('cell_number', 'ILIKE', '%' . $term . '%');
  315. });
  316. if($pro->pro_type != 'ADMIN'){
  317. $clientQuery->whereIn('id', $pro->getMyClientIds());
  318. }
  319. $clients = $clientQuery->get();
  320. return view('app/patient-suggest', compact('clients'));
  321. }
  322. public function pharmacySuggest(Request $request)
  323. {
  324. $term = $request->input('term') ? trim($request->input('term')) : '';
  325. if (empty($term)) return '';
  326. $term = strtolower($term);
  327. $pharmacies = Facility::where('facility_type', 'Pharmacy')
  328. ->where(function ($q) use ($term) {
  329. $q->orWhereRaw('LOWER(name::text) LIKE ?', ['%' . $term . '%'])
  330. ->orWhereRaw('LOWER(address_line1::text) LIKE ?', ['%' . $term . '%'])
  331. ->orWhereRaw('LOWER(address_line2::text) LIKE ?', ['%' . $term . '%'])
  332. ->orWhereRaw('LOWER(address_city::text) LIKE ?', ['%' . $term . '%'])
  333. ->orWhereRaw('LOWER(address_state::text) LIKE ?', ['%' . $term . '%'])
  334. ->orWhereRaw('LOWER(phone::text) LIKE ?', ['%' . $term . '%'])
  335. ->orWhereRaw('LOWER(address_zip::text) LIKE ?', ['%' . $term . '%']);
  336. })
  337. ->orderBy('name', 'asc')
  338. ->orderBy('address_line1', 'asc')
  339. ->orderBy('address_city', 'asc')
  340. ->orderBy('address_state', 'asc')
  341. ->get();
  342. return view('app/pharmacy-suggest', compact('pharmacies'));
  343. }
  344. public function unmappedSMS(Request $request, $filter = '')
  345. {
  346. $proID = $this->performer()->pro->id;
  347. if ($this->performer()->pro->pro_type === 'ADMIN') {
  348. $query = Client::where('id', '>', 0);
  349. } else {
  350. $query = Client::where(function ($q) use ($proID) {
  351. $q->where('mcp_pro_id', $proID)
  352. ->orWhere('cm_pro_id', $proID)
  353. ->orWhere('rmm_pro_id', $proID)
  354. ->orWhere('rme_pro_id', $proID)
  355. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID]);
  356. });
  357. }
  358. $patients = $query->orderBy('name_last', 'asc')->orderBy('name_first', 'asc')->get();
  359. $unmappedSMS = ClientSMS::where('client_id', null)->where('incoming_or_outgoing', 'INCOMING')->get();
  360. return view('app/unmapped-sms', compact('unmappedSMS', 'patients'));
  361. }
  362. public function newPatient(Request $request)
  363. {
  364. return view('app/new-patient');
  365. }
  366. public function mc(Request $request, $fragment = "")
  367. {
  368. $page = "/";
  369. if ($fragment) {
  370. $page = '/' . $fragment;
  371. }
  372. return view('app/mc', compact('page'));
  373. }
  374. public function blank(Request $request)
  375. {
  376. return view('app/blank');
  377. }
  378. public function noteTemplateSet(Request $request, $section, $template)
  379. {
  380. return view('app/patient/note/_template', [
  381. "sectionInternalName" => $section,
  382. "templateName" => $template
  383. ]);
  384. }
  385. public function noteExamTemplateSet(Request $request, $exam, $template)
  386. {
  387. return view('app/patient/note/_template-exam', [
  388. "exam" => $exam,
  389. "sectionInternalName" => 'exam-' . $exam . '-detail',
  390. "templateName" => $template
  391. ]);
  392. }
  393. public function logInAs(Request $request)
  394. {
  395. if($this->pro->pro_type != 'ADMIN'){
  396. return redirect()->to(route('dashboard'));
  397. }
  398. $pros = Pro
  399. ::where('pro_type', '!=', 'ADMIN')
  400. ->orWhereNull('pro_type')
  401. ->orderBy('name_last', 'asc')
  402. ->orderBy('name_first', 'asc')
  403. ->get();
  404. return view('app/log-in-as', compact('pros'));
  405. }
  406. public function processLogInAs(Request $request)
  407. {
  408. $api = new Backend();
  409. try {
  410. $apiResponse = $api->post('session/proLogInAs', [
  411. 'proUid' => $request->post('proUid')
  412. ],
  413. [
  414. 'sessionKey'=>$this->performer()->session_key
  415. ]);
  416. $data = json_decode($apiResponse->getContents());
  417. if (!property_exists($data, 'success') || !$data->success) {
  418. return redirect()->to(route('log-in-as'))->with('message', $data->message)
  419. ->withInput($request->input());
  420. }
  421. Cookie::queue('sessionKey', $data->data->sessionKey);
  422. return redirect('/mc');
  423. } catch (\Exception $e) {
  424. return redirect()->to(route('log-in-as'))
  425. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  426. ->withInput($request->input());
  427. }
  428. }
  429. public function backToAdminPro(Request $request){
  430. $adminPerformerId = $this->performer->logged_in_as_pro_from_admin_pro_app_session_id;
  431. $adminPerformer = AppSession::where('id', $adminPerformerId)->first();
  432. $url = "/session/pro_log_in_with_session_key/".$adminPerformer->session_key;
  433. $api = new Backend();
  434. try {
  435. $apiResponse = $api->post($url, []);
  436. $data = json_decode($apiResponse->getContents());
  437. if (!property_exists($data, 'success') || !$data->success) {
  438. return redirect('/mc');
  439. }
  440. Cookie::queue('sessionKey', $data->data->sessionKey);
  441. return redirect(route('dashboard'));
  442. } catch (\Exception $e) {
  443. return redirect(route('dashboard'));
  444. }
  445. }
  446. }