HomeController.php 49 KB

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