HomeController.php 21 KB

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