HomeController.php 18 KB

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