HomeController.php 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  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. ")
  342. );
  343. // for na
  344. $naClientMemos = DB::select(
  345. DB::raw("
  346. SELECT c.uid as client_uid, c.name_first, c.name_last,
  347. cm.uid, cm.content, cm.created_at
  348. FROM client c join client_memo cm on c.id = cm.client_id
  349. WHERE
  350. c.default_na_pro_id = {$performerProID} AND
  351. cm.default_na_stamp_id IS NULL;
  352. ")
  353. );
  354. $naBillableSignedNotes = DB::select(DB::raw("
  355. SELECT count(note.id) as na_billable_notes
  356. FROM note
  357. WHERE
  358. note.is_signed_by_hcp = TRUE AND
  359. note.ally_pro_id = :pro_id AND
  360. note.is_cancelled = FALSE AND
  361. (
  362. SELECT count(bill.id)
  363. FROM bill
  364. WHERE
  365. bill.is_cancelled = FALSE AND
  366. bill.generic_pro_id = :pro_id AND
  367. bill.note_id = note.id
  368. ) = 0
  369. "), ["pro_id" => $performerProID]);
  370. if(!$naBillableSignedNotes || !count($naBillableSignedNotes)) {
  371. $naBillableSignedNotes = 0;
  372. }
  373. else {
  374. $naBillableSignedNotes = $naBillableSignedNotes[0]->na_billable_notes;
  375. }
  376. $keyNumbers['naBillableSignedNotes'] = $naBillableSignedNotes;
  377. $keyNumbers['rmBillsToSign'] = Bill
  378. ::where('is_cancelled', false)
  379. ->where('cm_or_rm', 'RM')
  380. ->where(function ($q) use ($performerProID) {
  381. $q
  382. ->where(function ($q2) use ($performerProID) {
  383. $q2->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false);
  384. })
  385. ->orWhere(function ($q2) use ($performerProID) {
  386. $q2->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false);
  387. })
  388. ->orWhere(function ($q2) use ($performerProID) {
  389. $q2->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false);
  390. })
  391. ->orWhere(function ($q2) use ($performerProID) {
  392. $q2->where('generic_pro_id', $performerProID)->where('is_signed_by_generic_pro', false);
  393. });
  394. })
  395. ->count();
  396. $count = DB::select(
  397. DB::raw(
  398. "
  399. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  400. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  401. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  402. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  403. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  404. AND (care_month.number_of_days_with_remote_measurements < 16 OR care_month.number_of_days_with_remote_measurements IS NULL)
  405. "
  406. )
  407. );
  408. $keyNumbers['rmPatientsWithLT16MD'] = $count[0]->cnt;
  409. $count = DB::select(
  410. DB::raw(
  411. "
  412. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  413. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  414. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  415. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  416. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  417. AND (care_month.number_of_days_with_remote_measurements >= 16 AND care_month.number_of_days_with_remote_measurements IS NOT NULL)
  418. "
  419. )
  420. );
  421. $keyNumbers['rmPatientsWithGTE16MD'] = $count[0]->cnt;
  422. $count = DB::select(
  423. DB::raw(
  424. "
  425. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  426. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  427. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  428. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  429. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  430. AND (care_month.has_non_hcp_communicated_to_patient_about_rm = TRUE AND care_month.has_non_hcp_communicated_to_patient_about_rm IS NOT NULL)
  431. "
  432. )
  433. );
  434. $keyNumbers['rmPatientsWithWhomCommDone'] = $count[0]->cnt;
  435. $count = DB::select(
  436. DB::raw(
  437. "
  438. SELECT count(client.id) as cnt FROM client join care_month on care_month.client_id = client.id
  439. WHERE ((client.mcp_pro_id = {$performer->pro->id}) OR (client.rmm_pro_id = {$performer->pro->id})
  440. OR (client.rme_pro_id = {$performer->pro->id}) OR (client.default_na_pro_id = {$performer->pro->id}))
  441. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  442. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  443. AND (care_month.has_non_hcp_communicated_to_patient_about_rm = FALSE OR care_month.has_non_hcp_communicated_to_patient_about_rm IS NULL)
  444. "
  445. )
  446. );
  447. $keyNumbers['rmPatientsWithWhomCommNotDone'] = $count[0]->cnt;
  448. // num measurements that need stamping
  449. $keyNumbers['measurementsToBeStamped'] = $this->performer()->pro->getUnstampedMeasurementsFromCurrentMonth(true, null, null);
  450. return view('app/dashboard', compact('keyNumbers', 'reimbursement', 'milliseconds',
  451. 'businessNumbers',
  452. 'incomingReports', 'tickets', 'supplyOrders',
  453. 'numERx', 'numLabs', 'numImaging', 'numSupplyOrders',
  454. 'newMCPAssociations', 'newNAAssociations',
  455. 'mcpClientMemos', 'naClientMemos'));
  456. }
  457. public function dashboardMeasurementsTab(Request $request, $page = 1) {
  458. $performer = $this->performer();
  459. $myClientIDs = [];
  460. if ($performer->pro->pro_type != 'ADMIN') {
  461. $myClientIDs = $this->getMyClientIds();
  462. $myClientIDs = implode(", ", $myClientIDs);
  463. }
  464. $ifNotAdmin = " AND (
  465. client.mcp_pro_id = {$performer->pro->id}
  466. OR client.rmm_pro_id = {$performer->pro->id}
  467. OR client.rme_pro_id = {$performer->pro->id}
  468. OR client.physician_pro_id = {$performer->pro->id}
  469. OR client.id in (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = {$performer->pro->id})
  470. OR client.id in (SELECT client_id FROM appointment WHERE status NOT IN ('CANCELLED', 'ABANDONED') AND pro_id = {$performer->pro->id})
  471. )";
  472. $numMeasurements = DB::select(
  473. DB::raw(
  474. "
  475. SELECT count(measurement.id) as cnt
  476. FROM measurement
  477. join client on measurement.client_id = client.id
  478. join care_month on client.id = care_month.client_id
  479. WHERE measurement.label NOT IN ('SBP', 'DBP')
  480. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  481. AND measurement.is_removed IS FALSE
  482. AND measurement.ts IS NOT NULL
  483. AND measurement.client_bdt_measurement_id IS NOT NULL
  484. AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
  485. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  486. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  487. " .
  488. (
  489. $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
  490. )
  491. )
  492. );
  493. $numMeasurements = $numMeasurements[0]->cnt;
  494. $measurements = DB::select(
  495. DB::raw(
  496. "
  497. SELECT measurement.uid as uid,
  498. care_month.uid as care_month_uid,
  499. measurement.label,
  500. measurement.value,
  501. measurement.sbp_mm_hg,
  502. measurement.dbp_mm_hg,
  503. measurement.numeric_value,
  504. measurement.ts,
  505. client.uid as client_uid,
  506. client.name_last,
  507. client.name_first,
  508. care_month.rm_total_time_in_seconds
  509. FROM measurement
  510. join client on measurement.client_id = client.id
  511. join care_month on client.id = care_month.client_id
  512. WHERE measurement.label NOT IN ('SBP', 'DBP')
  513. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  514. AND measurement.is_removed IS FALSE
  515. AND measurement.ts IS NOT NULL
  516. AND measurement.client_bdt_measurement_id IS NOT NULL
  517. AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
  518. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  519. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  520. " .
  521. (
  522. $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
  523. )
  524. ) .
  525. " ORDER BY measurement.ts DESC LIMIT 20 OFFSET " . (($page - 1) * 20)
  526. );
  527. return view('app.dashboard.measurements', compact('numMeasurements', 'measurements', 'page'));
  528. }
  529. public function dashboardAppointmentDates(Request $request, $from, $to) {
  530. $performer = $this->performer();
  531. $performerProID = $performer->pro->id;
  532. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  533. $results = DB::table('appointment')->select('raw_date')->distinct()->where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  534. if(!$isAdmin) {
  535. $results = $results->where("pro_id", $performerProID);
  536. }
  537. $results = $results->get();
  538. $dates = [];
  539. foreach ($results as $result) {
  540. // $dates[] = strtotime($result->raw_date) . '000';
  541. $dates[] = $result->raw_date;
  542. }
  543. // foreach ($results as $result) {
  544. // $results->dateYMD = date('Y-m-d', strtotime($result->raw_date));
  545. // }
  546. return json_encode($dates);
  547. }
  548. public function dashboardAppointments(Request $request, $from, $to) {
  549. $performer = $this->performer();
  550. $performerProID = $performer->pro->id;
  551. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  552. // $appointments = Appointment::where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  553. $appointments = Appointment::where("raw_date", '=', $from);
  554. if(!$isAdmin) {
  555. $appointments = $appointments->where("pro_id", $performerProID);
  556. }
  557. $appointments = $appointments
  558. ->orderBy('start_time', 'asc')
  559. ->get();
  560. foreach ($appointments as $appointment) {
  561. $date = explode(" ", $appointment->start_time)[0];
  562. $appointment->milliseconds = strtotime($date) . '000';
  563. $appointment->newStatus = $appointment->status;
  564. $appointment->dateYMD = date('Y-m-d', strtotime($appointment->raw_date));
  565. $appointment->clientName = $appointment->client->displayName();
  566. $appointment->clientInitials = substr($appointment->client->name_first, 0, 1) . substr($appointment->client->name_last, 0, 1);
  567. $appointment->isClientShadowOfPro = $appointment->client->shadow_pro_id ? true : false;
  568. $appointment->proInitials = substr($appointment->pro->name_first, 0, 1) . substr($appointment->pro->name_last, 0, 1);
  569. $appointment->friendlyStartTime = friendly_time($appointment->raw_start_time);
  570. $appointment->friendlyEndTime = friendly_time($appointment->raw_end_time);
  571. $appointment->clientSummary = friendly_date_time($appointment->client->dob, false) . ' (' .
  572. $appointment->client->age_in_years . ' y.o' .
  573. ($appointment->client->sex ? ' ' . $appointment->client->sex : '') .
  574. ')';
  575. $appointment->started = false;
  576. $appointment->inHowManyHours = date_diff(date_create('now'), date_create($appointment->start_time), false)
  577. ->format('%R%h h, %i m');
  578. if ($appointment->inHowManyHours[0] === '-') {
  579. $appointment->inHowManyHours = substr($appointment->inHowManyHours, 1) . ' ago';
  580. $appointment->started = true;
  581. } else {
  582. $appointment->inHowManyHours = 'Appt. in ' . substr($appointment->inHowManyHours, 1);
  583. }
  584. $appointment->clientUid = $appointment->client->uid;
  585. $appointment->proUid = $appointment->pro->uid;
  586. $appointment->proName = $appointment->pro->displayName();
  587. unset($appointment->client);
  588. unset($appointment->pro);
  589. unset($appointment->detail_json);
  590. }
  591. return json_encode($appointments);
  592. }
  593. public function dashboardMeasurements(Request $request, $filter) {
  594. $measurements = $this->performer()->pro->getMeasurements($filter === 'NEED_ACK');
  595. return json_encode($measurements);
  596. }
  597. public function patients(Request $request, $filter = '')
  598. {
  599. $performer = $this->performer();
  600. $query = $performer->pro->getAccessibleClientsQuery();
  601. $q = trim($request->input('q'));
  602. if(!empty($q)) {
  603. $query = $query->where(function ($query) use ($q) {
  604. $query->where('name_first', 'ILIKE', "%$q%")
  605. ->orWhere('name_last', 'ILIKE', "%$q%")
  606. ->orWhere('email_address', 'ILIKE', "%$q%")
  607. ->orWhere('tags', 'ILIKE', "%$q%");
  608. });
  609. }
  610. switch ($filter) {
  611. case 'not-yet-seen':
  612. $query = $query
  613. ->where(function ($query) use ($performer) {
  614. $query
  615. ->where(function ($query) use ($performer) { // own patient and primary OB visit pending
  616. $query->where('mcp_pro_id', $performer->pro->id)
  617. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  618. })
  619. ->orWhere(function ($query) use ($performer) { // mcp of any client program and program OB pending
  620. $query->select(DB::raw('COUNT(id)'))
  621. ->from('client_program')
  622. ->whereColumn('client_id', 'client.id')
  623. ->where('mcp_pro_id', $performer->pro->id)
  624. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  625. }, '>=', 1);
  626. });
  627. break;
  628. case 'having-birthday-today':
  629. $query = $query
  630. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  631. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')]);
  632. break;
  633. // more cases can be added as needed
  634. default:
  635. break;
  636. }
  637. $patients = $query->orderBy('id', 'desc')->paginate(50);
  638. // patient acquisition chart (admin only)
  639. $patientAcquisitionData = null;
  640. if($performer->pro->pro_type === 'ADMIN') {
  641. $startDate = date_sub(date_create(), date_interval_create_from_date_string("1 month"));
  642. $startDate = date_format($startDate, "Y-m-d");
  643. $patientAcquisitionData = DB::select(DB::raw(
  644. "SELECT count(id) as count, DATE(created_at at time zone 'utc' at time zone 'est') as date " .
  645. "FROM client " .
  646. "WHERE shadow_pro_id IS NULL " .
  647. "GROUP BY DATE(created_at at time zone 'utc' at time zone 'est') " .
  648. "ORDER BY DATE(created_at at time zone 'utc' at time zone 'est') DESC " .
  649. "LIMIT 30"));
  650. }
  651. return view('app/patients', compact('patients', 'filter', 'patientAcquisitionData'));
  652. }
  653. public function patientsSuggest(Request $request)
  654. {
  655. $pro = $this->pro;
  656. $term = $request->input('term') ? trim($request->input('term')) : '';
  657. if (empty($term)) return '';
  658. $clientQuery= Client::whereNull('shadow_pro_id')
  659. ->where(function ($q) use ($term) {
  660. $q->where('name_first', 'ILIKE', '%' . $term . '%')
  661. ->orWhere('name_last', 'ILIKE', '%' . $term . '%')
  662. ->orWhere('cell_number', 'ILIKE', '%' . $term . '%')
  663. ->orWhere('phone_home', 'ILIKE', '%' . $term . '%');
  664. });
  665. if(!($pro->pro_type === 'ADMIN' && $pro->can_see_any_client_via_search)) {
  666. $clientQuery->where(function ($q) use ($pro) {
  667. $q->whereIn('id', $pro->getMyClientIds(true))
  668. ->orWhereNull('mcp_pro_id');
  669. });
  670. }
  671. $clients = $clientQuery->get();
  672. return view('app/patient-suggest', compact('clients'));
  673. }
  674. public function pharmacySuggest(Request $request)
  675. {
  676. $term = $request->input('term') ? trim($request->input('term')) : '';
  677. if (empty($term)) return '';
  678. $term = strtolower($term);
  679. $pharmacies = Facility::where('facility_type', 'Pharmacy')
  680. ->where(function ($q) use ($term) {
  681. $q->orWhereRaw('LOWER(name::text) LIKE ?', ['%' . $term . '%'])
  682. ->orWhereRaw('LOWER(address_line1::text) LIKE ?', ['%' . $term . '%'])
  683. ->orWhereRaw('LOWER(address_line2::text) LIKE ?', ['%' . $term . '%'])
  684. ->orWhereRaw('LOWER(address_city::text) LIKE ?', ['%' . $term . '%'])
  685. ->orWhereRaw('LOWER(address_state::text) LIKE ?', ['%' . $term . '%'])
  686. ->orWhereRaw('LOWER(phone::text) LIKE ?', ['%' . $term . '%'])
  687. ->orWhereRaw('LOWER(address_zip::text) LIKE ?', ['%' . $term . '%']);
  688. });
  689. if($request->input('city')) {
  690. $pharmacies = $pharmacies->whereRaw('LOWER(address_city::text) LIKE ?', ['%' . strtolower($request->input('city')) . '%']);
  691. }
  692. if($request->input('state')) {
  693. $pharmacies = $pharmacies->whereRaw('LOWER(address_state::text) LIKE ?', ['%' . strtolower($request->input('state')) . '%']);
  694. }
  695. if($request->input('zip')) {
  696. $pharmacies = $pharmacies->whereRaw('LOWER(address_zip::text) LIKE ?', ['%' . strtolower($request->input('zip')) . '%']);
  697. }
  698. $pharmacies = $pharmacies
  699. ->orderBy('name', 'asc')
  700. ->orderBy('address_line1', 'asc')
  701. ->orderBy('address_city', 'asc')
  702. ->orderBy('address_state', 'asc')
  703. ->get();
  704. return view('app/pharmacy-suggest', compact('pharmacies'));
  705. }
  706. public function proSuggest(Request $request) {
  707. $term = $request->input('term') ? trim($request->input('term')) : '';
  708. if (empty($term)) return '';
  709. $term = strtolower($term);
  710. $pros = Pro::where(function ($q) use ($term) {
  711. $q->orWhereRaw('LOWER(name_first::text) LIKE ?', ['%' . $term . '%'])
  712. ->orWhereRaw('LOWER(name_last::text) LIKE ?', ['%' . $term . '%'])
  713. ->orWhereRaw('cell_number LIKE ?', ['%' . $term . '%']);
  714. });
  715. if($this->performer->pro && $this->performer->pro->pro_type != 'ADMIN'){
  716. $accessiblePros = ProProAccess::where('owner_pro_id', $this->performer->pro->id);
  717. $accessibleProIds = [];
  718. foreach($accessiblePros as $accessiblePro){
  719. $accessibleProIds[] = $accessiblePro->id;
  720. }
  721. $accessibleProIds[] = $this->performer->pro->id;
  722. $pros->whereIn('id', $accessibleProIds);
  723. }
  724. $suggestedPros = $pros->orderBy('name_last')->orderBy('name_first')->get();
  725. // for calendar select2
  726. if($request->input('json')) {
  727. $jsonPros = $suggestedPros->map(function($_pro) {
  728. return [
  729. "uid" => $_pro->uid,
  730. "id" => $_pro->id,
  731. "text" => $_pro->displayName(),
  732. "initials" => $_pro->initials(),
  733. ];
  734. });
  735. return json_encode([
  736. "results" => $jsonPros
  737. ]);
  738. }
  739. return view('app/pro-suggest', compact('suggestedPros'));
  740. }
  741. public function proDisplayName(Request $request, Pro $pro) {
  742. return $pro ? $pro->displayName() : '';
  743. }
  744. public function unmappedSMS(Request $request, $filter = '')
  745. {
  746. $proID = $this->performer()->pro->id;
  747. if ($this->performer()->pro->pro_type === 'ADMIN') {
  748. $query = Client::where('id', '>', 0);
  749. } else {
  750. $query = Client::where(function ($q) use ($proID) {
  751. $q->where('mcp_pro_id', $proID)
  752. ->orWhere('cm_pro_id', $proID)
  753. ->orWhere('rmm_pro_id', $proID)
  754. ->orWhere('rme_pro_id', $proID)
  755. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID]);
  756. });
  757. }
  758. $patients = $query->orderBy('name_last', 'asc')->orderBy('name_first', 'asc')->get();
  759. $unmappedSMS = ClientSMS::where('client_id', null)->where('incoming_or_outgoing', 'INCOMING')->get();
  760. return view('app/unmapped-sms', compact('unmappedSMS', 'patients'));
  761. }
  762. public function newPatient(Request $request)
  763. {
  764. $mbPayers = MBPayer::all();
  765. return view('app/new-patient', compact('mbPayers'));
  766. }
  767. public function newNonMcnPatient(Request $request)
  768. {
  769. $mbPayers = MBPayer::all();
  770. return view('app/new-non-mcn-patient', compact('mbPayers'));
  771. }
  772. public function mc(Request $request, $fragment = "")
  773. {
  774. $page = "/";
  775. if ($fragment) {
  776. $page = '/' . $fragment;
  777. }
  778. return view('app/mc', compact('page'));
  779. }
  780. public function blank(Request $request)
  781. {
  782. return view('app/blank');
  783. }
  784. public function noteTemplateSet(Request $request, $section, $template)
  785. {
  786. return view('app/patient/note/_template', [
  787. "sectionInternalName" => $section,
  788. "templateName" => $template
  789. ]);
  790. }
  791. public function noteExamTemplateSet(Request $request, $exam, $template)
  792. {
  793. return view('app/patient/note/_template-exam', [
  794. "exam" => $exam,
  795. "sectionInternalName" => 'exam-' . $exam . '-detail',
  796. "templateName" => $template
  797. ]);
  798. }
  799. public function logInAs(Request $request)
  800. {
  801. if($this->pro->pro_type != 'ADMIN'){
  802. return redirect()->to(route('dashboard'));
  803. }
  804. $pros = Pro::where('pro_type', '!=', 'ADMIN');
  805. if($request->input('q')) {
  806. $nameQuery = '%' . $request->input('q') . '%';
  807. $pros = $pros->where(function ($query) use ($nameQuery) {
  808. $query->where('name_first', 'ILIKE', $nameQuery)
  809. ->orWhere('name_last', 'ILIKE', $nameQuery)
  810. ->orWhere('email_address', 'ILIKE', $nameQuery)
  811. ->orWhere('cell_number', 'ILIKE', $nameQuery);
  812. });
  813. }
  814. if($request->input('sort') && $request->input('dir')) {
  815. $pros = $pros->orderBy($request->input('sort'), $request->input('dir'));
  816. }
  817. else {
  818. $pros = $pros->orderBy('name_last', 'asc');
  819. }
  820. $pros = $pros->paginate(20);
  821. return view('app/log-in-as', ['logInAsPros' => $pros]);
  822. }
  823. public function processLogInAs(Request $request)
  824. {
  825. $api = new Backend();
  826. try {
  827. $apiResponse = $api->post('session/proLogInAs', [
  828. 'proUid' => $request->post('proUid')
  829. ],
  830. [
  831. 'sessionKey'=>$this->performer()->session_key
  832. ]);
  833. $data = json_decode($apiResponse->getContents());
  834. if (!property_exists($data, 'success') || !$data->success) {
  835. return redirect()->to(route('log-in-as'))->with('message', $data->message)
  836. ->withInput($request->input());
  837. }
  838. Cookie::queue('sessionKey', $data->data->sessionKey);
  839. return redirect('/mc');
  840. } catch (\Exception $e) {
  841. return redirect()->to(route('log-in-as'))
  842. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  843. ->withInput($request->input());
  844. }
  845. }
  846. public function backToAdminPro(Request $request){
  847. $adminPerformerId = $this->performer->logged_in_as_pro_from_admin_pro_app_session_id;
  848. $adminPerformer = AppSession::where('id', $adminPerformerId)->first();
  849. $url = "/session/pro_log_in_with_session_key/".$adminPerformer->session_key;
  850. $api = new Backend();
  851. try {
  852. $apiResponse = $api->post($url, []);
  853. $data = json_decode($apiResponse->getContents());
  854. if (!property_exists($data, 'success') || !$data->success) {
  855. return redirect()->to(route('logout'));
  856. }
  857. Cookie::queue('sessionKey', $data->data->sessionKey);
  858. return redirect(route('dashboard'));
  859. } catch (\Exception $e) {
  860. return redirect(route('dashboard'));
  861. }
  862. }
  863. public function getTicket(Request $request, Ticket $ticket) {
  864. $ticket->data = json_decode($ticket->data);
  865. // $ticket->created_at = friendly_date_time($ticket->created_at);
  866. $ticket->assignedPro;
  867. $ticket->managerPro;
  868. $ticket->orderingPro;
  869. $ticket->initiatingPro;
  870. return json_encode($ticket);
  871. }
  872. public function genericBill(Request $request, $entityType, $entityUid) {
  873. return view('app.generic-bills.inline', ['class' => 'p-3 border-top mt-3', 'entityType' => $entityType, 'entityUid' => $entityUid]);
  874. }
  875. }