HomeController.php 50 KB

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