HomeController.php 36 KB

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