HomeController.php 25 KB

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