HomeController.php 20 KB

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