HomeController.php 44 KB

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