HomeController.php 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Lib\Backend;
  4. use App\Models\Appointment;
  5. use App\Models\AppointmentConfirmationDecision;
  6. use App\Models\AppSession;
  7. use App\Models\ClientMemo;
  8. use App\Models\ClientProChange;
  9. use App\Models\ClientSMS;
  10. use App\Models\Facility;
  11. use App\Models\IncomingReport;
  12. use App\Models\MBPayer;
  13. use App\Models\ProProAccess;
  14. use App\Models\SupplyOrder;
  15. use App\Models\Ticket;
  16. use DateTime;
  17. use App\Models\Client;
  18. use App\Models\Bill;
  19. use App\Models\Measurement;
  20. use App\Models\Note;
  21. use App\Models\Pro;
  22. use App\Models\ProTransaction;
  23. use GuzzleHttp\Cookie\CookieJar;
  24. use Illuminate\Http\Request;
  25. use Illuminate\Support\Facades\Cookie;
  26. use Illuminate\Support\Facades\DB;
  27. use Illuminate\Support\Facades\Http;
  28. class HomeController extends Controller
  29. {
  30. public function confirmSmsAuthToken(Request $request)
  31. {
  32. return view('app/confirm_sms_auth_token');
  33. }
  34. public function setPassword(Request $request)
  35. {
  36. return view('app/set_password');
  37. }
  38. public function setSecurityQuestions(Request $request)
  39. {
  40. return view('app/set_security_questions');
  41. }
  42. public function postConfirmSmsAuthToken(Request $request)
  43. {
  44. try {
  45. $url = config('stag.backendUrl') . '/session/confirmSmsAuthToken';
  46. $data = [
  47. 'cellNumber' => $request->input('cellNumber'),
  48. 'token' => $request->input('token'),
  49. ];
  50. $response = Http::asForm()
  51. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  52. ->post($url, $data)
  53. ->json();
  54. if (!isset($response['success']) || !$response['success']) {
  55. $message = 'API error';
  56. if (isset($response['error'])) {
  57. $message = $response['error'];
  58. if (isset($response['path'])) $message .= ': ' . $response['path'];
  59. } else if (isset($response['message'])) $message = $response['message'];
  60. return redirect('/confirm_sms_auth_token')
  61. ->withInput()
  62. ->with('message', $message);
  63. }
  64. return redirect('/');
  65. } catch (\Exception $e) {
  66. return redirect()->back()
  67. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  68. ->withInput($request->input());
  69. }
  70. }
  71. public function resendSmsAuthToken(Request $request)
  72. {
  73. try {
  74. $url = config('stag.backendUrl') . '/session/resendSmsAuthToken';
  75. $data = [];
  76. $response = Http::asForm()
  77. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  78. ->post($url, $data)
  79. ->json();
  80. if (!isset($response['success']) || !$response['success']) {
  81. $message = 'API error';
  82. if (isset($response['error'])) {
  83. $message = $response['error'];
  84. if (isset($response['path'])) $message .= ': ' . $response['path'];
  85. } else if (isset($response['message'])) $message = $response['message'];
  86. return redirect('/confirm_sms_auth_token')
  87. ->withInput()
  88. ->with('message', $message);
  89. }
  90. return redirect()->back()->withInput()->with('message', "SMS Auth Token sent.");
  91. } catch (\Exception $e) {
  92. return redirect()->back()
  93. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  94. ->withInput($request->input());
  95. }
  96. }
  97. public function postSetPassword(Request $request)
  98. {
  99. try {
  100. $url = config('stag.backendUrl') . '/pro/selfPutPassword';
  101. $data = [
  102. 'newPassword' => $request->input('newPassword'),
  103. 'newPasswordConfirmation' => $request->input('newPasswordConfirmation'),
  104. ];
  105. $response = Http::asForm()
  106. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  107. ->post($url, $data)
  108. ->json();
  109. if (!isset($response['success']) || !$response['success']) {
  110. $message = 'API error';
  111. if (isset($response['error'])) {
  112. $message = $response['error'];
  113. if (isset($response['path'])) $message .= ': ' . $response['path'];
  114. } else if (isset($response['message'])) $message = $response['message'];
  115. return redirect('/set_password')
  116. ->withInput()
  117. ->with('message', $message);
  118. }
  119. return redirect('/');
  120. } catch (\Exception $e) {
  121. return redirect()->back()
  122. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  123. ->withInput($request->input());
  124. }
  125. }
  126. public function postSetSecurityQuestions(Request $request)
  127. {
  128. try {
  129. $url = env('BACKEND_URL', 'http://localhost:8080/api') . '/pro/selfPutSecurityQuestions';
  130. $data = [
  131. 'securityQuestion1' => $request->input('securityQuestion1'),
  132. 'securityAnswer1' => $request->input('securityAnswer1'),
  133. 'securityQuestion2' => $request->input('securityQuestion2'),
  134. 'securityAnswer2' => $request->input('securityAnswer2'),
  135. ];
  136. $response = Http::asForm()
  137. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  138. ->post($url, $data)
  139. ->json();
  140. if (!isset($response['success']) || !$response['success']) {
  141. $message = 'API error';
  142. if (isset($response['error'])) {
  143. $message = $response['error'];
  144. if (isset($response['path'])) $message .= ': ' . $response['path'];
  145. } else if (isset($response['message'])) $message = $response['message'];
  146. return redirect('/set_password')
  147. ->withInput()
  148. ->with('message', $message);
  149. }
  150. return redirect('/');
  151. } catch (\Exception $e) {
  152. return redirect()->back()
  153. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  154. ->withInput($request->input());
  155. }
  156. }
  157. private function dashboard_MCP(Request $request){
  158. $performer = $this->performer();
  159. $pro = $performer->pro;
  160. $performerProID = $performer->pro->id;
  161. $keyNumbers = [];
  162. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  163. $pendingNotesToSign = Note
  164. ::where(function ($query) use ($performerProID) {
  165. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false);
  166. })
  167. ->orWhere(function ($query) use ($performerProID) {
  168. $query->where('ally_pro_id', $performerProID)->where('is_signed_by_ally', false)->where('is_cancelled', false);
  169. })
  170. ->count();
  171. $keyNumbers['pendingNotesToSign'] = $pendingNotesToSign;
  172. // notes pending mcp sign (applicable to dnas only)
  173. $pendingNotesToSignMCP = Note
  174. ::where(function ($query) use ($performerProID) {
  175. $query->where('ally_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_cancelled', false);
  176. })
  177. ->count();
  178. $keyNumbers['$pendingNotesToSignMCP'] = $pendingNotesToSignMCP;
  179. $pendingNotesToSignAllySigned = Note::where(function ($query) use ($performerProID) {
  180. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false)->where('is_signed_by_ally', true)->where('is_cancelled', false);;
  181. })->count();
  182. $keyNumbers['pendingNotesToSignAllySigned'] = $pendingNotesToSignAllySigned;
  183. $signedNotesWithoutBills = Note::where(function ($query) use ($performerProID) {
  184. $query->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', true)->where('is_cancelled', false);
  185. })->whereDoesntHave('bills')->count();
  186. $keyNumbers['signedNotesWithoutBills'] = $signedNotesWithoutBills;
  187. // open tickets
  188. $keyNumbers['numOpenTickets'] = Ticket::where('is_open', true)
  189. ->where(function ($q) use ($performerProID) {
  190. $q->where('assigned_pro_id', $performerProID)
  191. ->orWhere('manager_pro_id', $performerProID)
  192. ->orWhere('ordering_pro_id', $performerProID)
  193. ->orWhere('initiating_pro_id', $performerProID);
  194. })
  195. ->count();
  196. // unacknowledged cancelled bills for authed pro
  197. $keyNumbers['unacknowledgedCancelledBills'] = Bill::where('hcp_pro_id', $performerProID)
  198. ->where('is_cancelled', true)
  199. ->where('is_cancellation_acknowledged', false)
  200. ->count();
  201. // unacknowledged cancelled supply orders for authed pro
  202. $keyNumbers['unacknowledgedCancelledSupplyOrders'] = SupplyOrder::where('signed_by_pro_id', $performerProID)
  203. ->where('is_cancelled', true)
  204. ->where('is_cancellation_acknowledged', false)
  205. ->count();
  206. // unsigned supply orders created by authed pro
  207. $keyNumbers['unsignedSupplyOrders'] = SupplyOrder
  208. ::where('is_cancelled', false)
  209. ->where('is_signed_by_pro', false)
  210. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$performerProID])
  211. ->count();
  212. // patientsHavingBirthdayToday
  213. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  214. $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
  215. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  216. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
  217. ->count();
  218. $reimbursement = [];
  219. $reimbursement["currentBalance"] = $performer->pro->balance;
  220. $reimbursement["nextPaymentDate"] = '--';
  221. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  222. if ($lastPayment) {
  223. $reimbursement["lastPayment"] = $lastPayment->amount;
  224. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  225. } else {
  226. $reimbursement["lastPayment"] = '--';
  227. $reimbursement["lastPaymentDate"] = '--';
  228. }
  229. //if today is < 15th, next payment is 15th, else nextPayment is
  230. $today = strtotime(date('Y-m-d'));
  231. $todayDate = date('j', $today);
  232. $todayMonth = date('m', $today);
  233. $todayYear = date('Y', $today);
  234. if ($todayDate < 15) {
  235. $nextPaymentDate = new DateTime();
  236. $nextPaymentDate->setDate($todayYear, $todayMonth, 15);
  237. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  238. } else {
  239. $nextPaymentDate = new \DateTime();
  240. $lastDayOfMonth = date('t', $today);
  241. $nextPaymentDate->setDate($todayYear, $todayMonth, $lastDayOfMonth);
  242. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  243. }
  244. //expectedPay
  245. $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;
  246. $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;
  247. $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;
  248. $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;
  249. $expectedForNa = DB::select(DB::raw("SELECT coalesce(SUM(generic_pro_expected_payment_amount),0) as expected_pay FROM bill WHERE generic_pro_id = :performerProID AND has_generic_pro_been_paid = false AND is_signed_by_generic_pro IS TRUE AND is_cancelled = false"), ['performerProID' => $performerProID])[0]->expected_pay;
  250. $totalExpectedAmount = $expectedForHcp + $expectedForCm + $expectedForRme + $expectedForRmm + $expectedForNa;
  251. $reimbursement['nextPaymentAmount'] = $totalExpectedAmount;
  252. $milliseconds = strtotime(date('Y-m-d')) . '000';
  253. // bills & claims
  254. $businessNumbers = [];
  255. // Notes with bills to resolve
  256. $businessNumbers['notesWithBillsToResolve'] = Note::where('is_cancelled', '!=', true)
  257. ->where('is_bill_closed', '!=', true)
  258. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND is_cancelled = false AND is_verified = false) > 0')
  259. ->count();
  260. // Notes pending bill closure
  261. $businessNumbers['notesPendingBillingClosure'] = Note::where('is_cancelled', '!=', true)
  262. ->where('is_bill_closed', '!=', true)
  263. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND (is_cancelled = true OR is_verified = true)) = 0')
  264. ->count();
  265. // incoming reports not signed
  266. $incomingReports = IncomingReport::where('hcp_pro_id', $performerProID)
  267. ->where('has_hcp_pro_signed', false)
  268. ->where('is_entry_error', false)
  269. ->orderBy('created_at', 'ASC')
  270. ->get();
  271. // erx, labs & imaging that are not closed
  272. $tickets = Ticket::where('ordering_pro_id', $performerProID)
  273. ->where('is_entry_error', false)
  274. ->where('is_open', true)
  275. ->orderBy('created_at', 'ASC')
  276. ->get();
  277. $supplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  278. ->where('is_cancelled', false)
  279. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  280. ->orderBy('created_at', 'ASC')
  281. ->get();
  282. $numERx = Ticket::where('ordering_pro_id', $performerProID)
  283. ->where('category', 'erx')
  284. ->where('is_entry_error', false)
  285. ->where('is_open', true)
  286. ->count();
  287. $numLabs = Ticket::where('ordering_pro_id', $performerProID)
  288. ->where('category', 'lab')
  289. ->where('is_entry_error', false)
  290. ->where('is_open', true)
  291. ->count();
  292. $numImaging = Ticket::where('ordering_pro_id', $performerProID)
  293. ->where('category', 'imaging')
  294. ->where('is_entry_error', false)
  295. ->where('is_open', true)
  296. ->count();
  297. $numSupplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  298. ->where('is_cancelled', false)
  299. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  300. ->count();
  301. $newMCPAssociations = ClientProChange
  302. ::where('new_pro_id', $performerProID)
  303. ->where('responsibility_type', 'MCP')
  304. ->whereNull('current_client_pro_change_decision_id')
  305. ->get();
  306. $newNAAssociations = ClientProChange
  307. ::where('new_pro_id', $performerProID)
  308. ->where('responsibility_type', 'DEFAULT_NA')
  309. ->whereNull('current_client_pro_change_decision_id')
  310. ->get();
  311. $proApptUpdates = AppointmentConfirmationDecision
  312. ::select('appointment_confirmation_decision.uid', 'client.name_first', 'client.name_last', 'appointment.start_time')
  313. ->rightJoin('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  314. ->rightJoin('client', 'client.id', '=', 'appointment.client_id')
  315. ->where('appointment_confirmation_decision.was_acknowledged_by_appointment_pro', false)
  316. ->where('appointment.status', '!=', 'CREATED')
  317. ->where('appointment.status', '!=', 'COMPLETED')
  318. ->where('appointment.status', '!=', 'ABANDONED')
  319. ->where('appointment.pro_id', $performerProID)
  320. ->where('client.mcp_pro_id', $performerProID)
  321. ->orderBy('appointment.start_time', 'DESC')
  322. ->get();
  323. $naApptUpdates = AppointmentConfirmationDecision
  324. ::select('appointment_confirmation_decision.uid', 'client.name_first', 'client.name_last', 'pro.name_first as pro_name_first', 'pro.name_last as pro_name_last', 'appointment.start_time')
  325. ->rightJoin('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  326. ->rightJoin('client', 'client.id', '=', 'appointment.client_id')
  327. ->rightJoin('pro', 'pro.id', '=', 'appointment.pro_id')
  328. ->where('appointment_confirmation_decision.was_acknowledged_by_client_default_na', false)
  329. ->where('appointment.status', '!=', 'CREATED')
  330. ->where('appointment.status', '!=', 'COMPLETED')
  331. ->where('appointment.status', '!=', 'ABANDONED')
  332. ->where('client.default_na_pro_id', $performerProID)
  333. ->orderBy('appointment.start_time', 'DESC')
  334. ->get();
  335. // $naApptUpdates = AppointmentConfirmationDecision
  336. // ::join('appointment', 'appointment.id', '=', 'appointment_confirmation_decision.appointment_id')
  337. // ->join('client', 'client.id', '=', 'appointment.client_id')
  338. // ->where('client.default_na_pro_id', $performerProID)
  339. // ->where('appointment_confirmation_decision.was_acknowledged_by_client_default_na', false)
  340. // ->orderBy('appointment.start_time DESC')
  341. // ->get();
  342. // unstamped client memos
  343. // for mcp
  344. $mcpClientMemos = DB::select(
  345. DB::raw("
  346. SELECT c.uid as client_uid, c.name_first, c.name_last,
  347. cm.uid, cm.content, cm.created_at
  348. FROM client c join client_memo cm on c.id = cm.client_id
  349. WHERE
  350. c.mcp_pro_id = {$performerProID} AND
  351. cm.mcp_stamp_id IS NULL
  352. ORDER BY cm.created_at DESC
  353. ")
  354. );
  355. // for na
  356. $naClientMemos = DB::select(
  357. DB::raw("
  358. SELECT c.uid as client_uid, c.name_first, c.name_last,
  359. cm.uid, cm.content, cm.created_at
  360. FROM client c join client_memo cm on c.id = cm.client_id
  361. WHERE
  362. c.default_na_pro_id = {$performerProID} AND
  363. cm.default_na_stamp_id IS NULL
  364. ORDER BY cm.created_at DESC
  365. ")
  366. );
  367. $keyNumbers['rmBillsToSign'] = Bill
  368. ::where('is_cancelled', false)
  369. ->where('cm_or_rm', 'RM')
  370. ->where(function ($q) use ($performerProID) {
  371. $q
  372. ->where(function ($q2) use ($performerProID) {
  373. $q2->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false);
  374. })
  375. ->orWhere(function ($q2) use ($performerProID) {
  376. $q2->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false);
  377. })
  378. ->orWhere(function ($q2) use ($performerProID) {
  379. $q2->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false);
  380. })
  381. ->orWhere(function ($q2) use ($performerProID) {
  382. $q2->where('generic_pro_id', $performerProID)->where('is_signed_by_generic_pro', false);
  383. });
  384. })
  385. ->count();
  386. $count = DB::select(
  387. DB::raw(
  388. "
  389. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  390. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  391. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  392. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  393. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  394. AND (care_month.number_of_days_with_remote_measurements < 16 OR care_month.number_of_days_with_remote_measurements IS NULL)
  395. "
  396. )
  397. );
  398. $keyNumbers['rmPatientsWithLT16MD'] = $count[0]->cnt;
  399. $count = DB::select(
  400. DB::raw(
  401. "
  402. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  403. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  404. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  405. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  406. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  407. AND (care_month.number_of_days_with_remote_measurements >= 16 AND care_month.number_of_days_with_remote_measurements IS NOT NULL)
  408. "
  409. )
  410. );
  411. $keyNumbers['rmPatientsWithGTE16MD'] = $count[0]->cnt;
  412. $count = DB::select(
  413. DB::raw(
  414. "
  415. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  416. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  417. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  418. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  419. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  420. AND (care_month.has_anyone_interacted_with_client_about_rm_outside_note = TRUE AND care_month.has_anyone_interacted_with_client_about_rm_outside_note IS NOT NULL)
  421. "
  422. )
  423. );
  424. $keyNumbers['rmPatientsWithWhomCommDone'] = $count[0]->cnt;
  425. $count = DB::select(
  426. DB::raw(
  427. "
  428. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  429. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  430. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  431. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  432. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  433. AND (care_month.has_anyone_interacted_with_client_about_rm_outside_note = FALSE OR care_month.has_anyone_interacted_with_client_about_rm_outside_note IS NULL)
  434. "
  435. )
  436. );
  437. $keyNumbers['rmPatientsWithWhomCommNotDone'] = $count[0]->cnt;
  438. // num measurements that need stamping
  439. $keyNumbers['measurementsToBeStamped'] = $this->performer()->pro->getUnstampedMeasurementsFromCurrentMonth(true, null, null);
  440. if($performer->pro->pro_type === 'ADMIN') {
  441. // patients without coverage information
  442. $keyNumbers['patientsWithoutCoverageInformation'] = DB::select(DB::raw("
  443. SELECT count(DISTINCT (cl.id)) as cnt
  444. FROM client cl
  445. WHERE cl.shadow_pro_id IS NULL AND cl.latest_client_primary_coverage_id IS NULL -- no coverage record"
  446. ))[0]->cnt;
  447. // patients pending coverage verification
  448. $keyNumbers['patientsPendingCoverageVerification'] = DB::select(DB::raw("
  449. SELECT count(DISTINCT (cl.id)) as cnt
  450. FROM client cl
  451. LEFT JOIN client_primary_coverage cpc ON cl.latest_client_primary_coverage_id = cpc.id
  452. WHERE cl.shadow_pro_id IS NULL
  453. AND (cl.latest_client_primary_coverage_id IS NOT NULL -- coverage exists, but status is null or unknown
  454. AND (
  455. (cpc.plan_type = 'MEDICARE' AND (cpc.is_partbprimary = 'UNKNOWN' OR cpc.is_partbprimary IS NULL))
  456. OR
  457. (cpc.plan_type != 'MEDICARE' AND
  458. (cpc.manual_determination_category = 'UNKNOWN' OR cpc.manual_determination_category IS NULL))
  459. ))"
  460. ))[0]->cnt;
  461. }
  462. return view('app/dashboard-mcp', compact('keyNumbers', 'reimbursement', 'milliseconds',
  463. 'businessNumbers',
  464. 'incomingReports', 'tickets', 'supplyOrders',
  465. 'numERx', 'numLabs', 'numImaging', 'numSupplyOrders',
  466. 'newMCPAssociations', 'newNAAssociations',
  467. 'mcpClientMemos', 'naClientMemos',
  468. 'proApptUpdates', 'naApptUpdates'));
  469. }
  470. private function dashboard_DNA(Request $request){
  471. $performer = $this->performer();
  472. $pro = $performer->pro;
  473. }
  474. private function dashboard_ADMIN(Request $request){
  475. $performer = $this->performer();
  476. $pro = $performer->pro;
  477. }
  478. public function dashboard(Request $request)
  479. {
  480. $performer = $this->performer();
  481. $pro = $performer->pro;
  482. if($pro->is_enrolled_as_mcp){
  483. return $this->dashboard_MCP($request);
  484. }elseif($pro->pro_type === 'ADMIN'){
  485. return $this->dashboard_ADMIN($request);
  486. }else{
  487. return $this->dashboard_DNA($request);
  488. }
  489. }
  490. public function dashboardMeasurementsTab(Request $request, $page = 1) {
  491. $performer = $this->performer();
  492. $myClientIDs = [];
  493. if ($performer->pro->pro_type != 'ADMIN') {
  494. $myClientIDs = $this->getMyClientIds();
  495. $myClientIDs = implode(", ", $myClientIDs);
  496. }
  497. $ifNotAdmin = " AND (
  498. client.mcp_pro_id = {$performer->pro->id}
  499. OR client.rmm_pro_id = {$performer->pro->id}
  500. OR client.rme_pro_id = {$performer->pro->id}
  501. OR client.physician_pro_id = {$performer->pro->id}
  502. OR client.id in (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = {$performer->pro->id})
  503. OR client.id in (SELECT client_id FROM appointment WHERE status NOT IN ('CANCELLED', 'ABANDONED') AND pro_id = {$performer->pro->id})
  504. )";
  505. $numMeasurements = DB::select(
  506. DB::raw(
  507. "
  508. SELECT count(measurement.id) as cnt
  509. FROM measurement
  510. join client on measurement.client_id = client.id
  511. WHERE measurement.label NOT IN ('SBP', 'DBP')
  512. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  513. AND measurement.is_removed IS FALSE
  514. AND measurement.has_been_stamped_by_mcp IS FALSE
  515. AND measurement.ts IS NOT NULL
  516. AND measurement.client_bdt_measurement_id IS NOT NULL
  517. AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
  518. AND EXTRACT(MONTH from measurement.created_at) = EXTRACT(MONTH from NOW())
  519. AND EXTRACT(YEAR from measurement.created_at) = EXTRACT(YEAR from NOW())
  520. " .
  521. (
  522. $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
  523. )
  524. )
  525. );
  526. $numMeasurements = $numMeasurements[0]->cnt;
  527. $measurements = DB::select(
  528. DB::raw(
  529. "
  530. SELECT measurement.uid as uid,
  531. care_month.uid as care_month_uid,
  532. care_month.start_date as care_month_start_date,
  533. measurement.label,
  534. measurement.value,
  535. measurement.sbp_mm_hg,
  536. measurement.dbp_mm_hg,
  537. measurement.numeric_value,
  538. measurement.value_pulse,
  539. measurement.value_irregular,
  540. measurement.ts,
  541. client.id as client_id,
  542. client.mcp_pro_id,
  543. client.default_na_pro_id,
  544. client.rmm_pro_id,
  545. client.rme_pro_id,
  546. client.uid as client_uid,
  547. client.name_last,
  548. client.name_first,
  549. care_month.rm_total_time_in_seconds
  550. FROM measurement
  551. join client on measurement.client_id = client.id
  552. join care_month on client.id = care_month.client_id
  553. WHERE measurement.label NOT IN ('SBP', 'DBP')
  554. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  555. AND measurement.is_removed IS FALSE
  556. AND measurement.has_been_stamped_by_mcp IS FALSE
  557. AND measurement.ts IS NOT NULL
  558. AND measurement.client_bdt_measurement_id IS NOT NULL
  559. AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
  560. AND EXTRACT(MONTH from measurement.created_at) = EXTRACT(MONTH from NOW())
  561. AND EXTRACT(YEAR from measurement.created_at) = EXTRACT(YEAR from NOW())
  562. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from NOW())
  563. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from NOW())
  564. " .
  565. (
  566. $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
  567. )
  568. ) .
  569. " ORDER BY measurement.ts DESC LIMIT 20 OFFSET " . (($page - 1) * 20)
  570. );
  571. return view('app.dashboard.measurements', compact('numMeasurements', 'measurements', 'page'));
  572. }
  573. public function dashboardAppointmentDates(Request $request, $from, $to) {
  574. $performer = $this->performer();
  575. $performerProID = $performer->pro->id;
  576. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  577. $results = DB::table('appointment')->select('raw_date')->distinct()->where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  578. if(!$isAdmin) {
  579. $results = $results->where("pro_id", $performerProID);
  580. }
  581. $results = $results->get();
  582. $dates = [];
  583. foreach ($results as $result) {
  584. // $dates[] = strtotime($result->raw_date) . '000';
  585. $dates[] = $result->raw_date;
  586. }
  587. // foreach ($results as $result) {
  588. // $results->dateYMD = date('Y-m-d', strtotime($result->raw_date));
  589. // }
  590. return json_encode($dates);
  591. }
  592. public function dashboardAppointments(Request $request, $from, $to) {
  593. $performer = $this->performer();
  594. $performerProID = $performer->pro->id;
  595. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  596. // $appointments = Appointment::where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  597. $appointments = Appointment::where("raw_date", '=', $from);
  598. if(!$isAdmin) {
  599. $appointments = $appointments->where("pro_id", $performerProID);
  600. }
  601. $appointments = $appointments
  602. ->orderBy('start_time', 'asc')
  603. ->get();
  604. foreach ($appointments as $appointment) {
  605. $date = explode(" ", $appointment->start_time)[0];
  606. $appointment->milliseconds = strtotime($date) . '000';
  607. $appointment->newStatus = $appointment->status;
  608. $appointment->dateYMD = date('Y-m-d', strtotime($appointment->raw_date));
  609. $appointment->clientName = $appointment->client->displayName();
  610. $appointment->clientInitials = substr($appointment->client->name_first, 0, 1) . substr($appointment->client->name_last, 0, 1);
  611. $appointment->isClientShadowOfPro = $appointment->client->shadow_pro_id ? true : false;
  612. $appointment->proInitials = substr($appointment->pro->name_first, 0, 1) . substr($appointment->pro->name_last, 0, 1);
  613. $appointment->friendlyStartTime = friendly_time($appointment->raw_start_time);
  614. $appointment->friendlyEndTime = friendly_time($appointment->raw_end_time);
  615. $appointment->clientSummary = friendly_date_time($appointment->client->dob, false) . ' (' .
  616. $appointment->client->age_in_years . ' y.o' .
  617. ($appointment->client->sex ? ' ' . $appointment->client->sex : '') .
  618. ')';
  619. $appointment->clientAge = $appointment->client->age_in_years;
  620. $appointment->clientSex = $appointment->client->sex;
  621. $appointment->started = false;
  622. $appointment->inHowManyHours = date_diff(date_create('now'), date_create($appointment->start_time), false)
  623. ->format('%R%h h, %i m');
  624. if ($appointment->inHowManyHours[0] === '-') {
  625. $appointment->inHowManyHours = substr($appointment->inHowManyHours, 1) . ' ago';
  626. $appointment->started = true;
  627. } else {
  628. $appointment->inHowManyHours = 'Appt. in ' . substr($appointment->inHowManyHours, 1);
  629. }
  630. $appointment->clientUid = $appointment->client->uid;
  631. $appointment->proUid = $appointment->pro->uid;
  632. $appointment->proName = $appointment->pro->displayName();
  633. // insurance information
  634. $appointment->coverage = $appointment->client->getPrimaryCoverageStatus();
  635. unset($appointment->client);
  636. unset($appointment->pro);
  637. unset($appointment->detail_json);
  638. }
  639. return json_encode($appointments);
  640. }
  641. public function dashboardMeasurements(Request $request, $filter) {
  642. $measurements = $this->performer()->pro->getMeasurements($filter === 'NEED_ACK');
  643. return json_encode($measurements);
  644. }
  645. public function patients(Request $request, $filter = '')
  646. {
  647. $performer = $this->performer();
  648. $query = $performer->pro->getAccessibleClientsQuery();
  649. $q = trim($request->input('q'));
  650. if(!empty($q)) {
  651. $query = $query->where(function ($query) use ($q) {
  652. $query->where('name_first', 'ILIKE', "%$q%")
  653. ->orWhere('name_last', 'ILIKE', "%$q%")
  654. ->orWhere('email_address', 'ILIKE', "%$q%")
  655. ->orWhere('tags', 'ILIKE', "%$q%");
  656. });
  657. }
  658. switch ($filter) {
  659. case 'not-yet-seen':
  660. $query = $query
  661. ->where(function ($query) use ($performer) {
  662. $query
  663. ->where(function ($query) use ($performer) { // own patient and primary OB visit pending
  664. $query->where('mcp_pro_id', $performer->pro->id)
  665. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  666. })
  667. ->orWhere(function ($query) use ($performer) { // mcp of any client program and program OB pending
  668. $query->select(DB::raw('COUNT(id)'))
  669. ->from('client_program')
  670. ->whereColumn('client_id', 'client.id')
  671. ->where('mcp_pro_id', $performer->pro->id)
  672. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  673. }, '>=', 1);
  674. });
  675. break;
  676. case 'having-birthday-today':
  677. $query = $query
  678. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  679. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')]);
  680. break;
  681. // more cases can be added as needed
  682. default:
  683. break;
  684. }
  685. $patients = $query->orderBy('id', 'desc')->paginate(50);
  686. // patient acquisition chart (admin only)
  687. $patientAcquisitionData = null;
  688. if($performer->pro->pro_type === 'ADMIN') {
  689. $startDate = date_sub(date_create(), date_interval_create_from_date_string("1 month"));
  690. $startDate = date_format($startDate, "Y-m-d");
  691. $patientAcquisitionData = DB::select(DB::raw(
  692. "SELECT count(id) as count, DATE(created_at at time zone 'utc' at time zone 'est') as date " .
  693. "FROM client " .
  694. "WHERE shadow_pro_id IS NULL " .
  695. "GROUP BY DATE(created_at at time zone 'utc' at time zone 'est') " .
  696. "ORDER BY DATE(created_at at time zone 'utc' at time zone 'est') DESC " .
  697. "LIMIT 30"));
  698. }
  699. return view('app/patients', compact('patients', 'filter', 'patientAcquisitionData'));
  700. }
  701. public function patientsSuggest(Request $request)
  702. {
  703. $pro = $this->pro;
  704. $term = $request->input('term') ? trim($request->input('term')) : '';
  705. $originalTerm = $term;
  706. if (empty($term)) return '';
  707. // if multiple words in query, check for all (max 2)
  708. $term2 = '';
  709. if(strpos($term, ' ') !== FALSE) {
  710. $terms = explode(' ', $term);
  711. $term = trim($terms[0]);
  712. $term2 = trim($terms[1]);
  713. }
  714. $phoneNumberTerm = preg_replace("/[^0-9]/", "", $originalTerm );
  715. if($phoneNumberTerm == ""){ //to avoid search with blank string
  716. $phoneNumberTerm = $term;
  717. }
  718. $clientQuery= Client::whereNull('shadow_pro_id')
  719. ->where(function ($q) use ($term, $phoneNumberTerm) {
  720. $q->where('name_first', 'ILIKE', '%' . $term . '%')
  721. ->orWhere('name_last', 'ILIKE', '%' . $term . '%')
  722. ->orWhere('cell_number', 'ILIKE', '%' . $phoneNumberTerm . '%')
  723. ->orWhere('phone_home', 'ILIKE', '%' . $phoneNumberTerm . '%');
  724. });
  725. if(!empty($term2)) {
  726. $clientQuery = $clientQuery->where(function ($q) use ($term2, $phoneNumberTerm) {
  727. $q->where('name_first', 'ILIKE', '%' . $term2 . '%')
  728. ->orWhere('name_last', 'ILIKE', '%' . $term2 . '%')
  729. ->orWhere('cell_number', 'ILIKE', '%' . $phoneNumberTerm . '%')
  730. ->orWhere('phone_home', 'ILIKE', '%' . $phoneNumberTerm . '%');
  731. });
  732. }
  733. if(!($pro->pro_type === 'ADMIN' && $pro->can_see_any_client_via_search)) {
  734. $clientQuery->where(function ($q) use ($pro) {
  735. if($pro->pro_type === 'ADMIN') {
  736. $q->whereIn('id', $pro->getMyClientIds(true))->orWhereNull('mcp_pro_id');
  737. }
  738. else {
  739. $q->whereIn('id', $pro->getMyClientIds(true));
  740. }
  741. });
  742. }
  743. $clients = $clientQuery->get();
  744. return view('app/patient-suggest', compact('clients'));
  745. }
  746. public function pharmacySuggest(Request $request)
  747. {
  748. $term = $request->input('term') ? trim($request->input('term')) : '';
  749. if (empty($term)) return '';
  750. $term = strtolower($term);
  751. $pharmacies = Facility::where('facility_type', 'Pharmacy')
  752. ->where(function ($q) use ($term) {
  753. $q->orWhereRaw('LOWER(name::text) LIKE ?', ['%' . $term . '%'])
  754. ->orWhereRaw('LOWER(address_line1::text) LIKE ?', ['%' . $term . '%'])
  755. ->orWhereRaw('LOWER(address_line2::text) LIKE ?', ['%' . $term . '%'])
  756. ->orWhereRaw('LOWER(address_city::text) LIKE ?', ['%' . $term . '%'])
  757. ->orWhereRaw('LOWER(address_state::text) LIKE ?', ['%' . $term . '%'])
  758. ->orWhereRaw('LOWER(phone::text) LIKE ?', ['%' . $term . '%'])
  759. ->orWhereRaw('LOWER(address_zip::text) LIKE ?', ['%' . $term . '%']);
  760. });
  761. if($request->input('city')) {
  762. $pharmacies = $pharmacies->whereRaw('LOWER(address_city::text) LIKE ?', ['%' . strtolower($request->input('city')) . '%']);
  763. }
  764. if($request->input('state')) {
  765. $pharmacies = $pharmacies->whereRaw('LOWER(address_state::text) LIKE ?', ['%' . strtolower($request->input('state')) . '%']);
  766. }
  767. if($request->input('zip')) {
  768. $pharmacies = $pharmacies->whereRaw('LOWER(address_zip::text) LIKE ?', ['%' . strtolower($request->input('zip')) . '%']);
  769. }
  770. $pharmacies = $pharmacies
  771. ->orderBy('name', 'asc')
  772. ->orderBy('address_line1', 'asc')
  773. ->orderBy('address_city', 'asc')
  774. ->orderBy('address_state', 'asc')
  775. ->get();
  776. return view('app/pharmacy-suggest', compact('pharmacies'));
  777. }
  778. public function proSuggest(Request $request) {
  779. $term = $request->input('term') ? trim($request->input('term')) : '';
  780. if (empty($term)) return '';
  781. $term = strtolower($term);
  782. $pros = Pro::where(function ($q) use ($term) {
  783. $q->orWhereRaw('LOWER(name_first::text) LIKE ?', ['%' . $term . '%'])
  784. ->orWhereRaw('LOWER(name_last::text) LIKE ?', ['%' . $term . '%'])
  785. ->orWhereRaw('cell_number LIKE ?', ['%' . $term . '%']);
  786. });
  787. $type = $request->input('type') ? trim($request->input('type')) : '';
  788. if(!!$type) {
  789. switch(strtolower($type)) {
  790. case 'hcp':
  791. $pros->where('is_hcp', true);
  792. break;
  793. case 'default-na': // TODO: fix condition for NA
  794. $pros->where('is_hcp', false)->where('pro_type', '!=', 'ADMIN');
  795. break;
  796. case 'admin':
  797. $pros->where('pro_type', 'ADMIN');
  798. break;
  799. case 'non-admin':
  800. $pros->where('pro_type', '!=', 'ADMIN');
  801. break;
  802. }
  803. }
  804. if($this->performer->pro && $this->performer->pro->pro_type != 'ADMIN'){
  805. $accessiblePros = ProProAccess::where('owner_pro_id', $this->performer->pro->id);
  806. $accessibleProIds = [];
  807. foreach($accessiblePros as $accessiblePro){
  808. $accessibleProIds[] = $accessiblePro->id;
  809. }
  810. $accessibleProIds[] = $this->performer->pro->id;
  811. // for dna, add pros accessible via pro teams
  812. if($this->performer->pro->isDefaultNA()) {
  813. $teams = $this->performer->pro->teamsWhereAssistant;
  814. foreach ($teams as $team) {
  815. if(!in_array($team->mcp_pro_id, $accessibleProIds)) {
  816. $accessibleProIds[] = $team->mcp_pro_id;
  817. }
  818. }
  819. }
  820. $pros->whereIn('id', $accessibleProIds);
  821. }
  822. $suggestedPros = $pros->orderBy('name_last')->orderBy('name_first')->get();
  823. // for calendar select2
  824. if($request->input('json')) {
  825. $jsonPros = $suggestedPros->map(function($_pro) {
  826. return [
  827. "uid" => $_pro->uid,
  828. "id" => $_pro->id,
  829. "text" => $_pro->displayName(),
  830. "initials" => $_pro->initials(),
  831. ];
  832. });
  833. return json_encode([
  834. "results" => $jsonPros
  835. ]);
  836. }
  837. return view('app/pro-suggest', compact('suggestedPros'));
  838. }
  839. public function canAccessPatient(Request $request, $uid) {
  840. return json_encode([
  841. "success" => true,
  842. "data" => $this->performer->pro->canAccess($uid)
  843. ]);
  844. }
  845. public function proDisplayName(Request $request, Pro $pro) {
  846. return $pro ? $pro->displayName() : '';
  847. }
  848. public function unmappedSMS(Request $request, $filter = '')
  849. {
  850. $proID = $this->performer()->pro->id;
  851. if ($this->performer()->pro->pro_type === 'ADMIN') {
  852. $query = Client::where('id', '>', 0);
  853. } else {
  854. $query = Client::where(function ($q) use ($proID) {
  855. $q->where('mcp_pro_id', $proID)
  856. ->orWhere('cm_pro_id', $proID)
  857. ->orWhere('rmm_pro_id', $proID)
  858. ->orWhere('rme_pro_id', $proID)
  859. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID]);
  860. });
  861. }
  862. $patients = $query->orderBy('name_last', 'asc')->orderBy('name_first', 'asc')->get();
  863. $unmappedSMS = ClientSMS::where('client_id', null)->where('incoming_or_outgoing', 'INCOMING')->paginate(20);
  864. return view('app/unmapped-sms', compact('unmappedSMS', 'patients'));
  865. }
  866. public function newPatient(Request $request)
  867. {
  868. $mbPayers = MBPayer::all();
  869. return view('app/new-patient', compact('mbPayers'));
  870. }
  871. public function newNonMcnPatient(Request $request)
  872. {
  873. $mbPayers = MBPayer::all();
  874. return view('app/new-non-mcn-patient', compact('mbPayers'));
  875. }
  876. public function mc(Request $request, $fragment = "")
  877. {
  878. $page = "/";
  879. if ($fragment) {
  880. $page = '/' . $fragment;
  881. }
  882. return view('app/mc', compact('page'));
  883. }
  884. public function blank(Request $request)
  885. {
  886. return view('app/blank');
  887. }
  888. public function noteTemplateSet(Request $request, $section, $template)
  889. {
  890. return view('app/patient/note/_template', [
  891. "sectionInternalName" => $section,
  892. "templateName" => $template
  893. ]);
  894. }
  895. public function noteExamTemplateSet(Request $request, $exam, $template)
  896. {
  897. return view('app/patient/note/_template-exam', [
  898. "exam" => $exam,
  899. "sectionInternalName" => 'exam-' . $exam . '-detail',
  900. "templateName" => $template
  901. ]);
  902. }
  903. public function logInAs(Request $request)
  904. {
  905. if($this->pro->pro_type != 'ADMIN'){
  906. return redirect()->to(route('dashboard'));
  907. }
  908. // dummy condition to get the chain-ability going
  909. $pros = Pro::where('id', '>', 0);
  910. if($request->input('q')) {
  911. $nameQuery = '%' . $request->input('q') . '%';
  912. $pros = $pros->where(function ($query) use ($nameQuery) {
  913. $query->where('name_first', 'ILIKE', $nameQuery)
  914. ->orWhere('name_last', 'ILIKE', $nameQuery)
  915. ->orWhere('email_address', 'ILIKE', $nameQuery)
  916. ->orWhere('cell_number', 'ILIKE', $nameQuery);
  917. });
  918. }
  919. if($request->input('sort') && $request->input('dir')) {
  920. $pros = $pros->orderBy($request->input('sort'), $request->input('dir'));
  921. }
  922. else {
  923. $pros = $pros->orderBy('name_last', 'asc');
  924. }
  925. $pros = $pros->paginate(20);
  926. return view('app/log-in-as', ['logInAsPros' => $pros]);
  927. }
  928. public function processLogInAs(Request $request)
  929. {
  930. $api = new Backend();
  931. try {
  932. $apiResponse = $api->post('session/proLogInAs', [
  933. 'proUid' => $request->post('proUid')
  934. ],
  935. [
  936. 'sessionKey'=>$this->performer()->session_key
  937. ]);
  938. $data = json_decode($apiResponse->getContents());
  939. if (!property_exists($data, 'success') || !$data->success) {
  940. return redirect()->to(route('log-in-as'))->with('message', $data->message)
  941. ->withInput($request->input());
  942. }
  943. Cookie::queue('sessionKey', $data->data->sessionKey);
  944. return redirect('/mc');
  945. } catch (\Exception $e) {
  946. return redirect()->to(route('log-in-as'))
  947. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  948. ->withInput($request->input());
  949. }
  950. }
  951. public function backToAdminPro(Request $request){
  952. $adminPerformerId = $this->performer->logged_in_as_pro_from_admin_pro_app_session_id;
  953. $adminPerformer = AppSession::where('id', $adminPerformerId)->first();
  954. $url = "/session/pro_log_in_with_session_key/".$adminPerformer->session_key;
  955. $api = new Backend();
  956. try {
  957. $apiResponse = $api->post($url, []);
  958. $data = json_decode($apiResponse->getContents());
  959. if (!property_exists($data, 'success') || !$data->success) {
  960. return redirect()->to(route('logout'));
  961. }
  962. Cookie::queue('sessionKey', $data->data->sessionKey);
  963. return redirect(route('dashboard'));
  964. } catch (\Exception $e) {
  965. return redirect(route('dashboard'));
  966. }
  967. }
  968. public function getTicket(Request $request, Ticket $ticket) {
  969. $ticket->data = json_decode($ticket->data);
  970. // $ticket->created_at = friendly_date_time($ticket->created_at);
  971. $ticket->assignedPro;
  972. $ticket->managerPro;
  973. $ticket->orderingPro;
  974. $ticket->initiatingPro;
  975. return json_encode($ticket);
  976. }
  977. public function genericBill(Request $request, $entityType, $entityUid) {
  978. $patient = null;
  979. if ($entityType && $entityUid) {
  980. try {
  981. $entityClass = "\\App\\Models\\" . $entityType;
  982. $entity = $entityClass::where('uid', $entityUid)->first();
  983. if ($entity->client) {
  984. $patient = $entity->client;
  985. }
  986. } catch (\Exception $e) {
  987. }
  988. }
  989. return view('app.generic-bills.inline', ['class' => 'p-3 border-top mt-3', 'entityType' => $entityType, 'entityUid' => $entityUid, 'patient' => $patient]);
  990. }
  991. }