HomeController.php 21 KB

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