HomeController.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911
  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. // num measurements that need stamping
  216. $keyNumbers['measurementsToBeStamped'] = count($this->performer()->pro->getMeasurements(true));
  217. // unacknowledged cancelled bills for authed pro
  218. $keyNumbers['unacknowledgedCancelledBills'] = Bill::where('hcp_pro_id', $performerProID)
  219. ->where('is_cancelled', true)
  220. ->where('is_cancellation_acknowledged', false)
  221. ->count();
  222. // unacknowledged cancelled supply orders for authed pro
  223. $keyNumbers['unacknowledgedCancelledSupplyOrders'] = SupplyOrder::where('signed_by_pro_id', $performerProID)
  224. ->where('is_cancelled', true)
  225. ->where('is_cancellation_acknowledged', false)
  226. ->count();
  227. // unsigned supply orders created by authed pro
  228. $keyNumbers['unsignedSupplyOrders'] = SupplyOrder
  229. ::where('is_cancelled', false)
  230. ->where('is_signed_by_pro', false)
  231. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$performerProID])
  232. ->count();
  233. // patientsHavingBirthdayToday
  234. $queryClients = $this->performer()->pro->getAccessibleClientsQuery();
  235. $keyNumbers['patientsHavingBirthdayToday'] = $queryClients
  236. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  237. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')])
  238. ->count();
  239. $reimbursement = [];
  240. $reimbursement["currentBalance"] = $performer->pro->balance;
  241. $reimbursement["nextPaymentDate"] = '--';
  242. $lastPayment = ProTransaction::where('pro_id', $performerProID)->where('plus_or_minus', 'PLUS')->orderBy('created_at', 'DESC')->first();
  243. if ($lastPayment) {
  244. $reimbursement["lastPayment"] = $lastPayment->amount;
  245. $reimbursement["lastPaymentDate"] = $lastPayment->created_at;
  246. } else {
  247. $reimbursement["lastPayment"] = '--';
  248. $reimbursement["lastPaymentDate"] = '--';
  249. }
  250. //if today is < 15th, next payment is 15th, else nextPayment is
  251. $today = strtotime(date('Y-m-d'));
  252. $todayDate = date('j', $today);
  253. $todayMonth = date('m', $today);
  254. $todayYear = date('Y', $today);
  255. if ($todayDate < 15) {
  256. $nextPaymentDate = new DateTime();
  257. $nextPaymentDate->setDate($todayYear, $todayMonth, 15);
  258. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  259. } else {
  260. $nextPaymentDate = new \DateTime();
  261. $lastDayOfMonth = date('t', $today);
  262. $nextPaymentDate->setDate($todayYear, $todayMonth, $lastDayOfMonth);
  263. $reimbursement['nextPaymentDate'] = $nextPaymentDate->format('m/d/Y');
  264. }
  265. //expectedPay
  266. $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;
  267. $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;
  268. $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;
  269. $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;
  270. $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;
  271. $totalExpectedAmount = $expectedForHcp + $expectedForCm + $expectedForRme + $expectedForRmm + $expectedForNa;
  272. $reimbursement['nextPaymentAmount'] = $totalExpectedAmount;
  273. $milliseconds = strtotime(date('Y-m-d')) . '000';
  274. // bills & claims
  275. $businessNumbers = [];
  276. // Notes with bills to resolve
  277. $businessNumbers['notesWithBillsToResolve'] = Note::where('is_cancelled', '!=', true)
  278. ->where('is_bill_closed', '!=', true)
  279. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND is_cancelled = false AND is_verified = false) > 0')
  280. ->count();
  281. // Notes pending bill closure
  282. $businessNumbers['notesPendingBillingClosure'] = Note::where('is_cancelled', '!=', true)
  283. ->where('is_bill_closed', '!=', true)
  284. ->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND (is_cancelled = true OR is_verified = true)) = 0')
  285. ->count();
  286. // incoming reports not signed
  287. $incomingReports = IncomingReport::where('hcp_pro_id', $performerProID)
  288. ->where('has_hcp_pro_signed', false)
  289. ->where('is_entry_error', false)
  290. ->orderBy('created_at', 'ASC')
  291. ->get();
  292. // erx, labs & imaging that are not closed
  293. $tickets = Ticket::where('ordering_pro_id', $performerProID)
  294. ->where('is_entry_error', false)
  295. ->where('is_open', true)
  296. ->orderBy('created_at', 'ASC')
  297. ->get();
  298. $supplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  299. ->where('is_cancelled', false)
  300. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  301. ->orderBy('created_at', 'ASC')
  302. ->get();
  303. $numERx = Ticket::where('ordering_pro_id', $performerProID)
  304. ->where('category', 'erx')
  305. ->where('is_entry_error', false)
  306. ->where('is_open', true)
  307. ->count();
  308. $numLabs = Ticket::where('ordering_pro_id', $performerProID)
  309. ->where('category', 'lab')
  310. ->where('is_entry_error', false)
  311. ->where('is_open', true)
  312. ->count();
  313. $numImaging = Ticket::where('ordering_pro_id', $performerProID)
  314. ->where('category', 'imaging')
  315. ->where('is_entry_error', false)
  316. ->where('is_open', true)
  317. ->count();
  318. $numSupplyOrders = SupplyOrder::where('is_cleared_for_shipment', false)
  319. ->where('is_cancelled', false)
  320. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session where pro_id = ?)', [$performer->pro->id])
  321. ->count();
  322. $newMCPAssociations = ClientProChange
  323. ::where('new_pro_id', $performerProID)
  324. ->where('responsibility_type', 'MCP')
  325. ->whereNull('current_client_pro_change_decision_id')
  326. ->get();
  327. $newNAAssociations = ClientProChange
  328. ::where('new_pro_id', $performerProID)
  329. ->where('responsibility_type', 'DEFAULT_NA')
  330. ->whereNull('current_client_pro_change_decision_id')
  331. ->get();
  332. $naBillableSignedNotes = DB::select(DB::raw("
  333. SELECT count(note.id) as na_billable_notes
  334. FROM note
  335. WHERE
  336. note.is_signed_by_hcp = TRUE AND
  337. note.ally_pro_id = :pro_id AND
  338. note.is_cancelled = FALSE AND
  339. (
  340. SELECT count(bill.id)
  341. FROM bill
  342. WHERE
  343. bill.is_cancelled = FALSE AND
  344. bill.generic_pro_id = :pro_id AND
  345. bill.note_id = note.id
  346. ) = 0
  347. "), ["pro_id" => $performerProID]);
  348. if(!$naBillableSignedNotes || !count($naBillableSignedNotes)) {
  349. $naBillableSignedNotes = 0;
  350. }
  351. else {
  352. $naBillableSignedNotes = $naBillableSignedNotes[0]->na_billable_notes;
  353. }
  354. $keyNumbers['naBillableSignedNotes'] = $naBillableSignedNotes;
  355. return view('app/dashboard', compact('keyNumbers', 'reimbursement', 'milliseconds',
  356. 'businessNumbers',
  357. 'incomingReports', 'tickets', 'supplyOrders',
  358. 'numERx', 'numLabs', 'numImaging', 'numSupplyOrders',
  359. 'newMCPAssociations', 'newNAAssociations'));
  360. }
  361. public function dashboardMeasurementsTab(Request $request, $page = 1) {
  362. $performer = $this->performer();
  363. $myClientIDs = [];
  364. if ($performer->pro->pro_type != 'ADMIN') {
  365. $myClientIDs = $this->getMyClientIds();
  366. $myClientIDs = implode(", ", $myClientIDs);
  367. }
  368. $ifNotAdmin = " AND (
  369. client.mcp_pro_id = {$performer->pro->id}
  370. OR client.rmm_pro_id = {$performer->pro->id}
  371. OR client.rme_pro_id = {$performer->pro->id}
  372. OR client.physician_pro_id = {$performer->pro->id}
  373. OR client.id in (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = {$performer->pro->id})
  374. OR client.id in (SELECT client_id FROM appointment WHERE status NOT IN ('CANCELLED', 'ABANDONED') AND pro_id = {$performer->pro->id})
  375. )";
  376. $numMeasurements = DB::select(
  377. DB::raw(
  378. "
  379. SELECT count(measurement.id) as cnt
  380. FROM measurement
  381. join client on measurement.client_id = client.id
  382. join care_month on client.id = care_month.client_id
  383. WHERE measurement.label NOT IN ('SBP', 'DBP')
  384. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  385. AND measurement.is_removed IS FALSE
  386. AND measurement.ts IS NOT NULL
  387. AND measurement.client_bdt_measurement_id IS NOT NULL
  388. AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
  389. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  390. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  391. " .
  392. (
  393. $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
  394. )
  395. )
  396. );
  397. $numMeasurements = $numMeasurements[0]->cnt;
  398. $measurements = DB::select(
  399. DB::raw(
  400. "
  401. SELECT measurement.uid as uid,
  402. care_month.uid as care_month_uid,
  403. measurement.label,
  404. measurement.value,
  405. measurement.sbp_mm_hg,
  406. measurement.dbp_mm_hg,
  407. measurement.numeric_value,
  408. measurement.ts,
  409. client.uid as client_uid,
  410. client.name_last,
  411. client.name_first,
  412. care_month.rm_total_time_in_seconds
  413. FROM measurement
  414. join client on measurement.client_id = client.id
  415. join care_month on client.id = care_month.client_id
  416. WHERE measurement.label NOT IN ('SBP', 'DBP')
  417. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  418. AND measurement.is_removed IS FALSE
  419. AND measurement.ts IS NOT NULL
  420. AND measurement.client_bdt_measurement_id IS NOT NULL
  421. AND (measurement.status IS NULL OR (measurement.status <> 'ACK' AND measurement.status <> 'INVALID_ACK'))
  422. AND EXTRACT(MONTH from care_month.start_date) = EXTRACT(MONTH from now())
  423. AND EXTRACT(YEAR from care_month.start_date) = EXTRACT(YEAR from now())
  424. " .
  425. (
  426. $performer->pro->pro_type != 'ADMIN' ? $ifNotAdmin : ''
  427. )
  428. ) .
  429. " ORDER BY measurement.ts DESC LIMIT 20 OFFSET " . (($page - 1) * 20)
  430. );
  431. return view('app.dashboard.measurements', compact('numMeasurements', 'measurements', 'page'));
  432. }
  433. public function dashboardAppointmentDates(Request $request, $from, $to) {
  434. $performer = $this->performer();
  435. $performerProID = $performer->pro->id;
  436. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  437. $results = DB::table('appointment')->select('raw_date')->distinct()->where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  438. if(!$isAdmin) {
  439. $results = $results->where("pro_id", $performerProID);
  440. }
  441. $results = $results->get();
  442. $dates = [];
  443. foreach ($results as $result) {
  444. // $dates[] = strtotime($result->raw_date) . '000';
  445. $dates[] = $result->raw_date;
  446. }
  447. // foreach ($results as $result) {
  448. // $results->dateYMD = date('Y-m-d', strtotime($result->raw_date));
  449. // }
  450. return json_encode($dates);
  451. }
  452. public function dashboardAppointments(Request $request, $from, $to) {
  453. $performer = $this->performer();
  454. $performerProID = $performer->pro->id;
  455. $isAdmin = ($performer->pro->pro_type === 'ADMIN');
  456. // $appointments = Appointment::where("start_time", '>=', $from)->where("start_time", '<=', $to.' 23:59:00+00');
  457. $appointments = Appointment::where("raw_date", '=', $from);
  458. if(!$isAdmin) {
  459. $appointments = $appointments->where("pro_id", $performerProID);
  460. }
  461. $appointments = $appointments
  462. ->orderBy('start_time', 'asc')
  463. ->get();
  464. foreach ($appointments as $appointment) {
  465. $date = explode(" ", $appointment->start_time)[0];
  466. $appointment->milliseconds = strtotime($date) . '000';
  467. $appointment->newStatus = $appointment->status;
  468. $appointment->dateYMD = date('Y-m-d', strtotime($appointment->raw_date));
  469. $appointment->clientName = $appointment->client->displayName();
  470. $appointment->clientInitials = substr($appointment->client->name_first, 0, 1) . substr($appointment->client->name_last, 0, 1);
  471. $appointment->isClientShadowOfPro = $appointment->client->shadow_pro_id ? true : false;
  472. $appointment->proInitials = substr($appointment->pro->name_first, 0, 1) . substr($appointment->pro->name_last, 0, 1);
  473. $appointment->friendlyStartTime = friendly_time($appointment->raw_start_time);
  474. $appointment->friendlyEndTime = friendly_time($appointment->raw_end_time);
  475. $appointment->clientSummary = friendly_date_time($appointment->client->dob, false) . ' (' .
  476. $appointment->client->age_in_years . ' y.o' .
  477. ($appointment->client->sex ? ' ' . $appointment->client->sex : '') .
  478. ')';
  479. $appointment->started = false;
  480. $appointment->inHowManyHours = date_diff(date_create('now'), date_create($appointment->start_time), false)
  481. ->format('%R%h h, %i m');
  482. if ($appointment->inHowManyHours[0] === '-') {
  483. $appointment->inHowManyHours = substr($appointment->inHowManyHours, 1) . ' ago';
  484. $appointment->started = true;
  485. } else {
  486. $appointment->inHowManyHours = 'Appt. in ' . substr($appointment->inHowManyHours, 1);
  487. }
  488. $appointment->clientUid = $appointment->client->uid;
  489. $appointment->proUid = $appointment->pro->uid;
  490. $appointment->proName = $appointment->pro->displayName();
  491. unset($appointment->client);
  492. unset($appointment->pro);
  493. unset($appointment->detail_json);
  494. }
  495. return json_encode($appointments);
  496. }
  497. public function dashboardMeasurements(Request $request, $filter) {
  498. $measurements = $this->performer()->pro->getMeasurements($filter === 'NEED_ACK');
  499. return json_encode($measurements);
  500. }
  501. public function patients(Request $request, $filter = '')
  502. {
  503. $performer = $this->performer();
  504. $query = $performer->pro->getAccessibleClientsQuery();
  505. $q = trim($request->input('q'));
  506. if(!empty($q)) {
  507. $query = $query->where(function ($query) use ($q) {
  508. $query->where('name_first', 'ILIKE', "%$q%")
  509. ->orWhere('name_last', 'ILIKE', "%$q%")
  510. ->orWhere('email_address', 'ILIKE', "%$q%")
  511. ->orWhere('tags', 'ILIKE', "%$q%");
  512. });
  513. }
  514. switch ($filter) {
  515. case 'not-yet-seen':
  516. $query = $query
  517. ->where(function ($query) use ($performer) {
  518. $query
  519. ->where(function ($query) use ($performer) { // own patient and primary OB visit pending
  520. $query->where('mcp_pro_id', $performer->pro->id)
  521. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  522. })
  523. ->orWhere(function ($query) use ($performer) { // mcp of any client program and program OB pending
  524. $query->select(DB::raw('COUNT(id)'))
  525. ->from('client_program')
  526. ->whereColumn('client_id', 'client.id')
  527. ->where('mcp_pro_id', $performer->pro->id)
  528. ->where('has_mcp_done_onboarding_visit', '<>', 'YES');
  529. }, '>=', 1);
  530. });
  531. break;
  532. case 'having-birthday-today':
  533. $query = $query
  534. ->whereRaw('EXTRACT(DAY from dob) = ?', [date('d')])
  535. ->whereRaw('EXTRACT(MONTH from dob) = ?', [date('m')]);
  536. break;
  537. // more cases can be added as needed
  538. default:
  539. break;
  540. }
  541. $patients = $query->orderBy('id', 'desc')->paginate(50);
  542. // patient acquisition chart (admin only)
  543. $patientAcquisitionData = null;
  544. if($performer->pro->pro_type === 'ADMIN') {
  545. $startDate = date_sub(date_create(), date_interval_create_from_date_string("1 month"));
  546. $startDate = date_format($startDate, "Y-m-d");
  547. $patientAcquisitionData = DB::select(DB::raw(
  548. "SELECT count(id) as count, DATE(created_at at time zone 'utc' at time zone 'est') as date " .
  549. "FROM client " .
  550. "WHERE shadow_pro_id IS NULL " .
  551. "GROUP BY DATE(created_at at time zone 'utc' at time zone 'est') " .
  552. "ORDER BY DATE(created_at at time zone 'utc' at time zone 'est') DESC " .
  553. "LIMIT 30"));
  554. }
  555. return view('app/patients', compact('patients', 'filter', 'patientAcquisitionData'));
  556. }
  557. public function patientsSuggest(Request $request)
  558. {
  559. $pro = $this->pro;
  560. $term = $request->input('term') ? trim($request->input('term')) : '';
  561. if (empty($term)) return '';
  562. $clientQuery= Client::whereNull('shadow_pro_id')
  563. ->where(function ($q) use ($term) {
  564. $q->where('name_first', 'ILIKE', '%' . $term . '%')
  565. ->orWhere('name_last', 'ILIKE', '%' . $term . '%')
  566. ->orWhere('cell_number', 'ILIKE', '%' . $term . '%')
  567. ->orWhere('phone_home', 'ILIKE', '%' . $term . '%');
  568. });
  569. if(!($pro->pro_type === 'ADMIN' && $pro->can_see_any_client_via_search)) {
  570. $clientQuery->where(function ($q) use ($pro) {
  571. $q->whereIn('id', $pro->getMyClientIds(true))
  572. ->orWhereNull('mcp_pro_id');
  573. });
  574. }
  575. $clients = $clientQuery->get();
  576. return view('app/patient-suggest', compact('clients'));
  577. }
  578. public function pharmacySuggest(Request $request)
  579. {
  580. $term = $request->input('term') ? trim($request->input('term')) : '';
  581. if (empty($term)) return '';
  582. $term = strtolower($term);
  583. $pharmacies = Facility::where('facility_type', 'Pharmacy')
  584. ->where(function ($q) use ($term) {
  585. $q->orWhereRaw('LOWER(name::text) LIKE ?', ['%' . $term . '%'])
  586. ->orWhereRaw('LOWER(address_line1::text) LIKE ?', ['%' . $term . '%'])
  587. ->orWhereRaw('LOWER(address_line2::text) LIKE ?', ['%' . $term . '%'])
  588. ->orWhereRaw('LOWER(address_city::text) LIKE ?', ['%' . $term . '%'])
  589. ->orWhereRaw('LOWER(address_state::text) LIKE ?', ['%' . $term . '%'])
  590. ->orWhereRaw('LOWER(phone::text) LIKE ?', ['%' . $term . '%'])
  591. ->orWhereRaw('LOWER(address_zip::text) LIKE ?', ['%' . $term . '%']);
  592. })
  593. ->orderBy('name', 'asc')
  594. ->orderBy('address_line1', 'asc')
  595. ->orderBy('address_city', 'asc')
  596. ->orderBy('address_state', 'asc')
  597. ->get();
  598. return view('app/pharmacy-suggest', compact('pharmacies'));
  599. }
  600. public function proSuggest(Request $request) {
  601. $term = $request->input('term') ? trim($request->input('term')) : '';
  602. if (empty($term)) return '';
  603. $term = strtolower($term);
  604. $pros = Pro::where(function ($q) use ($term) {
  605. $q->orWhereRaw('LOWER(name_first::text) LIKE ?', ['%' . $term . '%'])
  606. ->orWhereRaw('LOWER(name_last::text) LIKE ?', ['%' . $term . '%'])
  607. ->orWhereRaw('cell_number LIKE ?', ['%' . $term . '%']);
  608. });
  609. if($this->performer->pro && $this->performer->pro->pro_type != 'ADMIN'){
  610. $accessiblePros = ProProAccess::where('owner_pro_id', $this->performer->pro->id);
  611. $accessibleProIds = [];
  612. foreach($accessiblePros as $accessiblePro){
  613. $accessibleProIds[] = $accessiblePro->id;
  614. }
  615. $accessibleProIds[] = $this->performer->pro->id;
  616. $pros->whereIn('id', $accessibleProIds);
  617. }
  618. $suggestedPros = $pros->orderBy('name_last')->orderBy('name_first')->get();
  619. // for calendar select2
  620. if($request->input('json')) {
  621. $jsonPros = $suggestedPros->map(function($_pro) {
  622. return [
  623. "uid" => $_pro->uid,
  624. "id" => $_pro->id,
  625. "text" => $_pro->displayName(),
  626. "initials" => $_pro->initials(),
  627. ];
  628. });
  629. return json_encode([
  630. "results" => $jsonPros
  631. ]);
  632. }
  633. return view('app/pro-suggest', compact('suggestedPros'));
  634. }
  635. public function proDisplayName(Request $request, Pro $pro) {
  636. return $pro ? $pro->displayName() : '';
  637. }
  638. public function unmappedSMS(Request $request, $filter = '')
  639. {
  640. $proID = $this->performer()->pro->id;
  641. if ($this->performer()->pro->pro_type === 'ADMIN') {
  642. $query = Client::where('id', '>', 0);
  643. } else {
  644. $query = Client::where(function ($q) use ($proID) {
  645. $q->where('mcp_pro_id', $proID)
  646. ->orWhere('cm_pro_id', $proID)
  647. ->orWhere('rmm_pro_id', $proID)
  648. ->orWhere('rme_pro_id', $proID)
  649. ->orWhereRaw('id IN (SELECT client_id FROM client_pro_access WHERE is_active AND pro_id = ?)', [$proID]);
  650. });
  651. }
  652. $patients = $query->orderBy('name_last', 'asc')->orderBy('name_first', 'asc')->get();
  653. $unmappedSMS = ClientSMS::where('client_id', null)->where('incoming_or_outgoing', 'INCOMING')->get();
  654. return view('app/unmapped-sms', compact('unmappedSMS', 'patients'));
  655. }
  656. public function newPatient(Request $request)
  657. {
  658. $mbPayers = MBPayer::all();
  659. return view('app/new-patient', compact('mbPayers'));
  660. }
  661. public function newNonMcnPatient(Request $request)
  662. {
  663. $mbPayers = MBPayer::all();
  664. return view('app/new-non-mcn-patient', compact('mbPayers'));
  665. }
  666. public function mc(Request $request, $fragment = "")
  667. {
  668. $page = "/";
  669. if ($fragment) {
  670. $page = '/' . $fragment;
  671. }
  672. return view('app/mc', compact('page'));
  673. }
  674. public function blank(Request $request)
  675. {
  676. return view('app/blank');
  677. }
  678. public function noteTemplateSet(Request $request, $section, $template)
  679. {
  680. return view('app/patient/note/_template', [
  681. "sectionInternalName" => $section,
  682. "templateName" => $template
  683. ]);
  684. }
  685. public function noteExamTemplateSet(Request $request, $exam, $template)
  686. {
  687. return view('app/patient/note/_template-exam', [
  688. "exam" => $exam,
  689. "sectionInternalName" => 'exam-' . $exam . '-detail',
  690. "templateName" => $template
  691. ]);
  692. }
  693. public function logInAs(Request $request)
  694. {
  695. if($this->pro->pro_type != 'ADMIN'){
  696. return redirect()->to(route('dashboard'));
  697. }
  698. $pros = Pro::where('pro_type', '!=', 'ADMIN');
  699. if($request->input('q')) {
  700. $nameQuery = '%' . $request->input('q') . '%';
  701. $pros = $pros->where(function ($query) use ($nameQuery) {
  702. $query->where('name_first', 'ILIKE', $nameQuery)
  703. ->orWhere('name_last', 'ILIKE', $nameQuery)
  704. ->orWhere('email_address', 'ILIKE', $nameQuery)
  705. ->orWhere('cell_number', 'ILIKE', $nameQuery);
  706. });
  707. }
  708. if($request->input('sort') && $request->input('dir')) {
  709. $pros = $pros->orderBy($request->input('sort'), $request->input('dir'));
  710. }
  711. else {
  712. $pros = $pros->orderBy('name_last', 'asc');
  713. }
  714. $pros = $pros->paginate(20);
  715. return view('app/log-in-as', ['logInAsPros' => $pros]);
  716. }
  717. public function processLogInAs(Request $request)
  718. {
  719. $api = new Backend();
  720. try {
  721. $apiResponse = $api->post('session/proLogInAs', [
  722. 'proUid' => $request->post('proUid')
  723. ],
  724. [
  725. 'sessionKey'=>$this->performer()->session_key
  726. ]);
  727. $data = json_decode($apiResponse->getContents());
  728. if (!property_exists($data, 'success') || !$data->success) {
  729. return redirect()->to(route('log-in-as'))->with('message', $data->message)
  730. ->withInput($request->input());
  731. }
  732. Cookie::queue('sessionKey', $data->data->sessionKey);
  733. return redirect('/mc');
  734. } catch (\Exception $e) {
  735. return redirect()->to(route('log-in-as'))
  736. ->with('message', 'Unable to process your request at the moment. Please try again later.')
  737. ->withInput($request->input());
  738. }
  739. }
  740. public function backToAdminPro(Request $request){
  741. $adminPerformerId = $this->performer->logged_in_as_pro_from_admin_pro_app_session_id;
  742. $adminPerformer = AppSession::where('id', $adminPerformerId)->first();
  743. $url = "/session/pro_log_in_with_session_key/".$adminPerformer->session_key;
  744. $api = new Backend();
  745. try {
  746. $apiResponse = $api->post($url, []);
  747. $data = json_decode($apiResponse->getContents());
  748. if (!property_exists($data, 'success') || !$data->success) {
  749. return redirect()->to(route('logout'));
  750. }
  751. Cookie::queue('sessionKey', $data->data->sessionKey);
  752. return redirect(route('dashboard'));
  753. } catch (\Exception $e) {
  754. return redirect(route('dashboard'));
  755. }
  756. }
  757. public function getTicket(Request $request, Ticket $ticket) {
  758. $ticket->data = json_decode($ticket->data);
  759. // $ticket->created_at = friendly_date_time($ticket->created_at);
  760. $ticket->assignedPro;
  761. $ticket->managerPro;
  762. $ticket->orderingPro;
  763. $ticket->initiatingPro;
  764. return json_encode($ticket);
  765. }
  766. public function genericBill(Request $request, $entityType, $entityUid) {
  767. return view('app.generic-bills.inline', ['class' => 'p-3 border-top mt-3', 'entityType' => $entityType, 'entityUid' => $entityUid]);
  768. }
  769. }