HomeController.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  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. $pendingBillsToSign = Bill::where(function ($query) use ($performerProID) {
  163. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false);
  164. })
  165. ->orWhere(function ($query) use ($performerProID) {
  166. $query->where('cm_pro_id', $performerProID)->where('is_signed_by_cm', false)->where('is_cancelled', false);;
  167. })->orWhere(function ($query) use ($performerProID) {
  168. $query->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false)->where('is_cancelled', false);;
  169. })->orWhere(function ($query) use ($performerProID) {
  170. $query->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false)->where('is_cancelled', false);;
  171. })->count();
  172. $keyNumbers['pendingBillsToSign'] = $pendingBillsToSign;
  173. $pendingNotesToSign = Note::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('ally_pro_id', $performerProID)->where('is_signed_by_ally', false)->where('is_cancelled', false);;
  178. })->count();
  179. $keyNumbers['pendingNotesToSign'] = $pendingNotesToSign;
  180. $reimbursement = [];
  181. $reimbursement["currentBalance"] = $performer->pro->balance;
  182. $reimbursement["nextPaymentDate"] = '--';
  183. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  184. if ($lastPayment) {
  185. $reimbursement["lastPayment"] = $lastPayment->amount;
  186. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  187. } else {
  188. $reimbursement["lastPayment"] = '--';
  189. $reimbursement["lastPaymentDate"] = '--';
  190. }
  191. //if today is < 15th, next payment is 15th, else nextPayment is
  192. $today = strtotime(date('Y-m-d'));
  193. $todayDate = date('j', $today);
  194. $todayMonth = date('m', $today);
  195. $todayYear = date('Y', $today);
  196. if ($todayDate < 15) {
  197. $nextPaymentDate = new DateTime();
  198. $nextPaymentDate->setDate($todayYear, $todayMonth, 15);
  199. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  200. } else {
  201. $nextPaymentDate = new \DateTime();
  202. $lastDayOfMonth = date('t', $today);
  203. $nextPaymentDate->setDate($todayYear, $todayMonth, $lastDayOfMonth);
  204. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  205. }
  206. //expectedPay
  207. $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_cancelled = false"), ['performerProID' => $performerProID])[0]->expected_pay;
  208. $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_cancelled = false"), ['performerProID' => $performerProID])[0]->expected_pay;
  209. $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_cancelled = false"), ['performerProID' => $performerProID])[0]->expected_pay;
  210. $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_cancelled = false"), ['performerProID' => $performerProID])[0]->expected_pay;
  211. $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_cancelled = false"), ['performerProID' => $performerProID])[0]->expected_pay;
  212. $totalExpectedAmount = $expectedForHcp + $expectedForCm + $expectedForRme + $expectedForRmm + $expectedForNa;
  213. $reimbursement['nextPaymentAmount'] = $totalExpectedAmount;
  214. $milliseconds = strtotime(date('Y-m-d')) . '000';
  215. return view('app/dashboard', compact('keyNumbers', 'reimbursement', 'milliseconds'));
  216. }
  217. public function dashboardAppointments(Request $request, $from, $to) {
  218. $performer = $this->performer();
  219. $performerProID = $performer->pro->id;
  220. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  221. $appointments = Appointment::where("start_time", '>=', $from)->where("start_time", '<=', $to);
  222. if(!$isAdmin) {
  223. $appointments = $appointments->where("pro_id", $performerProID);
  224. }
  225. $appointments = $appointments
  226. ->orderBy('start_time', 'asc')
  227. ->get();
  228. foreach ($appointments as $appointment) {
  229. $date = explode(" ", $appointment->start_time)[0];
  230. $appointment->milliseconds = strtotime($date) . '000';
  231. $appointment->newStatus = $appointment->status;
  232. $appointment->dateYMD = date('Y-m-d', strtotime($appointment->start_time));
  233. $appointment->clientName = $appointment->client->displayName();
  234. $appointment->clientInitials = substr($appointment->client->name_first, 0, 1) . substr($appointment->client->name_last, 0, 1);
  235. $appointment->proInitials = substr($appointment->pro->name_first, 0, 1) . substr($appointment->pro->name_last, 0, 1);
  236. $appointment->friendlyStartTime = friendly_time($appointment->raw_start_time);
  237. $appointment->friendlyEndTime = friendly_time($appointment->raw_end_time);
  238. $appointment->clientSummary = friendly_date_time($appointment->client->dob, false) . ' (' .
  239. $appointment->client->age_in_years . ' y.o' .
  240. ($appointment->client->sex ? ' ' . $appointment->client->sex : '') .
  241. ')';
  242. $appointment->started = false;
  243. $appointment->inHowManyHours = date_diff(date_create('now'), date_create($appointment->start_time), false)
  244. ->format('%R%h h, %i m');
  245. if ($appointment->inHowManyHours[0] === '-') {
  246. $appointment->inHowManyHours = substr($appointment->inHowManyHours, 1) . ' ago';
  247. $appointment->started = true;
  248. } else {
  249. $appointment->inHowManyHours = 'Appt. in ' . substr($appointment->inHowManyHours, 1);
  250. }
  251. $appointment->clientUid = $appointment->client->uid;
  252. $appointment->proUid = $appointment->pro->uid;
  253. $appointment->proName = $appointment->pro->displayName();
  254. }
  255. return json_encode($appointments);
  256. }
  257. public function patients(Request $request, $filter = '')
  258. {
  259. $proID = $this->performer()->pro->id;
  260. if ($this->performer()->pro->pro_type === 'ADMIN') {
  261. $query = Client::where('id', '>', 0);
  262. } else {
  263. $query = Client::where(function ($q) use ($proID) {
  264. $q->where('mcp_pro_id', $proID)
  265. ->orWhere('cm_pro_id', $proID)
  266. ->orWhere('rmm_pro_id', $proID)
  267. ->orWhere('rme_pro_id', $proID)
  268. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID]);
  269. });
  270. }
  271. switch ($filter) {
  272. case 'not-yet-seen':
  273. $query = $query->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  274. break;
  275. // more cases can be added as needed
  276. default:
  277. break;
  278. }
  279. $patients = $query->orderBy('created_at', 'asc')->orderBy('name_last', 'asc')->orderBy('name_first', 'asc')->paginate(500);
  280. return view('app/patients', compact('patients', 'filter'));
  281. }
  282. public function patientsSuggest(Request $request)
  283. {
  284. $term = $request->input('term') ? trim($request->input('term')) : '';
  285. if (empty($term)) return '';
  286. $clients = Client::where(function ($q) use ($term) {
  287. $q->where('name_first', 'ILIKE', '%' . $term . '%')
  288. ->orWhere('name_last', 'ILIKE', '%' . $term . '%');
  289. })->get();
  290. return view('app/patient-suggest', compact('clients'));
  291. }
  292. public function unmappedSMS(Request $request, $filter = '')
  293. {
  294. $proID = $this->performer()->pro->id;
  295. if ($this->performer()->pro->pro_type === 'ADMIN') {
  296. $query = Client::where('id', '>', 0);
  297. } else {
  298. $query = Client::where(function ($q) use ($proID) {
  299. $q->where('mcp_pro_id', $proID)
  300. ->orWhere('cm_pro_id', $proID)
  301. ->orWhere('rmm_pro_id', $proID)
  302. ->orWhere('rme_pro_id', $proID)
  303. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID]);
  304. });
  305. }
  306. $patients = $query->orderBy('name_last', 'asc')->orderBy('name_first', 'asc')->get();
  307. $unmappedSMS = ClientSMS::where('client_id', null)->where('incoming_or_outgoing', 'INCOMING')->get();
  308. return view('app/unmapped-sms', compact('unmappedSMS', 'patients'));
  309. }
  310. public function newPatient(Request $request)
  311. {
  312. return view('app/new-patient');
  313. }
  314. public function mc(Request $request, $fragment = "")
  315. {
  316. $page = "/";
  317. if ($fragment) {
  318. $page = '/' . $fragment;
  319. }
  320. return view('app/mc', compact('page'));
  321. }
  322. public function blank(Request $request)
  323. {
  324. return view('app/blank');
  325. }
  326. public function noteTemplateSet(Request $request, $section, $template)
  327. {
  328. return view('app/patient/note/_template', [
  329. "sectionInternalName" => $section,
  330. "templateName" => $template
  331. ]);
  332. }
  333. public function noteExamTemplateSet(Request $request, $exam, $template)
  334. {
  335. return view('app/patient/note/_template-exam', [
  336. "exam" => $exam,
  337. "sectionInternalName" => 'exam-' . $exam . '-detail',
  338. "templateName" => $template
  339. ]);
  340. }
  341. public function logInAs(Request $request)
  342. {
  343. if($this->pro->pro_type != 'ADMIN'){
  344. return redirect()->to(route('dashboard'));
  345. }
  346. $pros = Pro::where('pro_type', '!=', 'ADMIN')->orWhereNull('pro_type')->get();
  347. return view('app/log-in-as', compact('pros'));
  348. }
  349. public function processLogInAs(Request $request)
  350. {
  351. $api = new Backend();
  352. try {
  353. $apiResponse = $api->post('session/proLogInAs', [
  354. 'proUid' => $request->post('proUid')
  355. ],
  356. [
  357. 'sessionKey'=>$this->performer()->session_key
  358. ]);
  359. $data = json_decode($apiResponse->getContents());
  360. if (!property_exists($data, 'success') || !$data->success) {
  361. return redirect()->to(route('log-in-as'))->with('message', $data->message)
  362. ->withInput($request->input());
  363. }
  364. Cookie::queue('sessionKey', $data->data->sessionKey);
  365. return redirect('/mc');
  366. } catch (\Exception $e) {
  367. return redirect()->to(route('log-in-as'))
  368. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  369. ->withInput($request->input());
  370. }
  371. }
  372. public function backToAdminPro(Request $request){
  373. $adminPerformerId = $this->performer->logged_in_as_pro_from_admin_pro_app_session_id;
  374. $adminPerformer = AppSession::where('id', $adminPerformerId)->first();
  375. $url = "/session/pro_log_in_with_session_key/".$adminPerformer->session_key;
  376. $api = new Backend();
  377. try {
  378. $apiResponse = $api->post($url, []);
  379. $data = json_decode($apiResponse->getContents());
  380. if (!property_exists($data, 'success') || !$data->success) {
  381. return redirect('/mc');
  382. }
  383. Cookie::queue('sessionKey', $data->data->sessionKey);
  384. return redirect(route('dashboard'));
  385. } catch (\Exception $e) {
  386. return redirect(route('dashboard'));
  387. }
  388. }
  389. }