HomeController.php 48 KB

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