HomeController.php 42 KB

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