PatientController.php 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Models\Appointment;
  4. use App\Models\BDTDevice;
  5. use App\Models\CareMonth;
  6. use App\Models\Client;
  7. use App\Models\ClientBDTDevice;
  8. use App\Models\ClientInfoLine;
  9. use App\Models\ClientMemoView;
  10. use App\Models\ClientPrimaryCoverage;
  11. use App\Models\ClientProAccess;
  12. use App\Models\Company;
  13. use App\Models\CompanyPro;
  14. use App\Models\CompanyClient;
  15. use App\Models\CompanyProDocument;
  16. use App\Models\Customer;
  17. use App\Models\Erx;
  18. use App\Models\Facility;
  19. use App\Models\Handout;
  20. use App\Models\HandoutClient;
  21. use App\Models\IncomingReport;
  22. use App\Models\Invoice;
  23. use App\Models\MBClaim;
  24. use App\Models\MBPayer;
  25. use App\Models\Note;
  26. use App\Models\NoteTemplate;
  27. use App\Models\Pro;
  28. use App\Models\Product;
  29. use App\Models\ProProAccess;
  30. use App\Models\SectionTemplate;
  31. use App\Models\Shipment;
  32. use App\Models\SupplyOrder;
  33. use App\Models\Ticket;
  34. use App\Models\PatientRequest;
  35. use Illuminate\Http\Request;
  36. use Illuminate\Support\Facades\DB;
  37. use Illuminate\Support\Facades\File;
  38. use App\Models\Measurement;
  39. use App\Models\ClientReviewRequest;
  40. use App\Models\Point;
  41. use App\Models\Survey;
  42. use App\Models\InsuranceCard;
  43. use Illuminate\Support\Facades\Http;
  44. use PDF;
  45. use Illuminate\Support\Facades\Validator;
  46. use App\Http\Services\SurveyService;
  47. class PatientController extends Controller
  48. {
  49. public function invoicingCompanies(Request $request, Client $patient) {
  50. return view('app.patient.invoicing.companies', compact('patient'));
  51. }
  52. public function invoicingInvoices(Request $request, Client $patient, Customer $customer) {
  53. return view('app.patient.invoicing.invoices', compact('patient', 'customer'));
  54. }
  55. public function invoicingCustomerTransactions(Request $request, Client $patient, Customer $customer) {
  56. return view('app.patient.invoicing.customer-transactions', compact('patient', 'customer'));
  57. }
  58. public function invoicingInvoiceTransactions(Request $request, Client $patient, Invoice $invoice) {
  59. $customer = $invoice->customer;
  60. return view('app.patient.invoicing.invoice-transactions', compact('patient', 'invoice', 'customer'));
  61. }
  62. public function invoicingInvoiceTransactionsInPopup(Request $request, Client $patient, Invoice $invoice) {
  63. $customer = $invoice->customer;
  64. return view('app.patient.invoicing.invoice-transactions-in-popup', compact('patient', 'invoice', 'customer'));
  65. }
  66. public function claimsResolver(Request $request, Client $patient)
  67. {
  68. $notes = $patient->notesAscending;
  69. $hcpSignedNotesCount = 0;
  70. foreach($notes as $note){
  71. if($note->is_signed_by_hcp){
  72. $hcpSignedNotesCount += 1;
  73. }
  74. }
  75. $data = [
  76. 'dog' => 'bark',
  77. 'patient' => $patient,
  78. 'hcpSignedNotesCount' => $hcpSignedNotesCount
  79. ];
  80. return view('app.patient.claims-resolver', $data);
  81. }
  82. public function dashboard(Request $request, Client $patient )
  83. {
  84. $mcpPros = Pro::where('is_enrolled_as_mcp', true)->get();
  85. $facilities = []; // Facility::where('is_active', true)->get();
  86. // get assigned devices
  87. $assignedDeviceIDs = DB::select(DB::raw("SELECT device_id from client_bdt_device where is_active = true"));
  88. $assignedDeviceIDs = array_map(function($_x) {
  89. return $_x->device_id;
  90. }, $assignedDeviceIDs);
  91. // get all except assigned ones
  92. $devices = BDTDevice::where('is_active', true)
  93. ->whereNotIn('id', $assignedDeviceIDs)
  94. ->orderBy('imei', 'asc')
  95. ->get();
  96. $assignedDeviceIDs = null;
  97. unset($assignedDeviceIDs);
  98. $availableDevices = count($devices);
  99. $patientDeviceIDs = ClientBDTDevice::select('id')->where('client_id', $patient->id)->where('is_active', true)->get()->toArray();
  100. $patientDeviceIDs = array_map(function ($_x) {
  101. return $_x["id"];
  102. }, $patientDeviceIDs);
  103. $dxInfoLines = ClientInfoLine::where('client_id', $patient->id)
  104. ->where('category', 'dx')
  105. ->where('is_removed', false)
  106. ->orderBy('content_text', 'asc')
  107. ->get();
  108. $clientMemos = ClientMemoView::where('client_id', $patient->id)->where('is_cancelled', false)->orderBy('created_at', 'DESC')->get();
  109. $shortCutsObject = [];
  110. foreach ($this->pro->allShortcuts() as $shortcut) {
  111. // %replaceables%
  112. $shortcut->text = str_replace("%AGE%", $patient->age_in_years, $shortcut->text);
  113. $shortcut->text = str_replace("%GENDER%", $patient->sex, $shortcut->text);
  114. $shortcut->text = str_replace("%NAME%", $patient->displayName(), $shortcut->text);
  115. $shortCutsObject[] = [
  116. "name" => $shortcut->shortcut,
  117. "value" => $shortcut->text
  118. ];
  119. }
  120. $recentMeasurements = $patient->recentMeasurements;
  121. $latestVitals = Point::where('client_id', $patient->id)->where('category', 'VITALS')->orderBy('id', 'DESC')->first();
  122. $nonCoreVisitNotes = $patient->nonCoreVisitNotes;
  123. $disallowPointEdits = $nonCoreVisitNotes && count($nonCoreVisitNotes);
  124. return view('app.patient.dashboard',
  125. compact('patient', 'facilities', 'devices', 'dxInfoLines', 'clientMemos', 'shortCutsObject', 'availableDevices', 'patientDeviceIDs', 'recentMeasurements', 'latestVitals', 'disallowPointEdits'));
  126. }
  127. public function canvasMigrate(Request $request, Client $patient )
  128. {
  129. $mcpPros = Pro::where('is_enrolled_as_mcp', true)->get();
  130. $facilities = []; // Facility::where('is_active', true)->get();
  131. // get assigned devices
  132. $assignedDeviceIDs = DB::select(DB::raw("SELECT device_id from client_bdt_device where is_active = true"));
  133. $assignedDeviceIDs = array_map(function($_x) {
  134. return $_x->device_id;
  135. }, $assignedDeviceIDs);
  136. // get all except assigned ones
  137. $devices = BDTDevice::where('is_active', true)
  138. ->whereNotIn('id', $assignedDeviceIDs)
  139. ->orderBy('imei', 'asc')
  140. ->get();
  141. $assignedDeviceIDs = null;
  142. unset($assignedDeviceIDs);
  143. $dxInfoLines = ClientInfoLine::where('client_id', $patient->id)
  144. ->where('category', 'dx')
  145. ->where('is_removed', false)
  146. ->orderBy('content_text', 'asc')
  147. ->get();
  148. return view('app.patient.canvas-migrate',
  149. compact('patient', 'facilities', 'devices', 'dxInfoLines'));
  150. }
  151. public function canvas(Request $request, Client $patient){
  152. return view('app.patient.canvas_dump', compact('patient'));
  153. }
  154. public function intake(Request $request, Client $patient )
  155. {
  156. $files = File::allFiles(resource_path('views/app/intake-templates'));
  157. $templates = [];
  158. foreach ($files as $file) {
  159. $templates[] = str_replace(".blade.php", "", $file->getFilename());
  160. }
  161. return view('app.patient.intake', compact('patient', 'templates'));
  162. }
  163. public function carePlan(Request $request, Client $patient )
  164. {
  165. return view('app.patient.care-plan', compact('patient'));
  166. }
  167. public function medications(Request $request, Client $patient )
  168. {
  169. $infoLines = ClientInfoLine::where('client_id', $patient->id)
  170. ->where('category', 'rx')
  171. ->where('is_removed', false)
  172. ->orderBy('content_text', 'asc')
  173. ->get();
  174. return view('app.patient.medications', compact('patient', 'infoLines'));
  175. }
  176. public function dxAndFocusAreas(Request $request, Client $patient )
  177. {
  178. $dxInfoLines = ClientInfoLine::where('client_id', $patient->id)
  179. ->where('category', 'dx')
  180. ->where('is_removed', false)
  181. ->orderBy('content_text', 'asc')
  182. ->get();
  183. return view('app.patient.dx-and-focus-areas', compact('patient', 'dxInfoLines'));
  184. }
  185. public function careTeam(Request $request, Client $patient )
  186. {
  187. $infoLines = ClientInfoLine::where('client_id', $patient->id)
  188. ->where('category', 'care_team')
  189. ->where('is_removed', false)
  190. ->get();
  191. return view('app.patient.care-team', compact('patient', 'infoLines'));
  192. }
  193. public function devices(Request $request, Client $patient )
  194. {
  195. // get assigned devices
  196. $assignedDeviceIDs = DB::select(DB::raw("SELECT device_id from client_bdt_device where is_active = true"));
  197. $assignedDeviceIDs = array_map(function($_x) {
  198. return $_x->device_id;
  199. }, $assignedDeviceIDs);
  200. // get all except assigned ones
  201. $devices = BDTDevice::where('is_active', true)
  202. ->whereNotIn('id', $assignedDeviceIDs)
  203. ->orderBy('imei', 'asc')
  204. ->get();
  205. $assignedDeviceIDs = null;
  206. unset($assignedDeviceIDs);
  207. return view('app.patient.devices', compact('patient', 'devices'));
  208. }
  209. public function measurements(Request $request, Client $patient )
  210. {
  211. $measurements = Measurement::where('client_id', $patient->id)->where('is_active', true)->orderByRaw('ts DESC NULLS LAST')->paginate(30);
  212. return view('app.patient.measurements', compact('patient', 'measurements'));
  213. }
  214. public function labsAndStudies(Request $request, Client $patient )
  215. {
  216. return view('app.patient.labs-and-studies', compact('patient'));
  217. }
  218. public function history(Request $request, Client $patient )
  219. {
  220. $infoLines = ClientInfoLine::where('client_id', $patient->id)
  221. ->where('category', 'LIKE', 'history_%')
  222. ->where('is_removed', false)
  223. ->get();
  224. return view('app.patient.history', compact('patient', 'infoLines'));
  225. }
  226. public function memos(Request $request, Client $patient )
  227. {
  228. return view('app.patient.memos', compact('patient'));
  229. }
  230. public function memosThread(Request $request, Client $patient )
  231. {
  232. return view('app.patient.memos-thread', compact('patient'));
  233. }
  234. public function messagesThread(Request $request, Client $patient )
  235. {
  236. return view('app.patient.messages-thread', compact('patient'));
  237. }
  238. public function sms(Request $request, Client $patient )
  239. {
  240. return view('app.patient.sms', compact('patient'));
  241. }
  242. public function outgoingSmsLog(Request $request, Client $patient )
  243. {
  244. return view('app.patient.outgoing-sms-log', compact('patient'));
  245. }
  246. public function reviewRequests(Request $request, Client $patient){
  247. $pro = $this->performer->pro;
  248. $reviewRequests = ClientReviewRequest::where('client_id', $patient->id);
  249. if($pro->pro_type !== 'ADMIN'){
  250. $reviewRequests = $reviewRequests->where('pro_id', $pro->id)->where('is_active', true);
  251. }
  252. $reviewRequests = $reviewRequests->orderBy('created_at', 'DESC')->paginate(50);
  253. return view('app.patient.review-requests.list', compact('patient', 'reviewRequests'));
  254. }
  255. public function smsNumbers(Request $request, Client $patient )
  256. {
  257. return view('app.patient.sms-numbers', compact('patient'));
  258. }
  259. public function immunizations(Request $request, Client $patient )
  260. {
  261. return view('app.patient.immunizations', compact('patient'));
  262. }
  263. public function allergies(Request $request, Client $patient )
  264. {
  265. $infoLines = ClientInfoLine::where('client_id', $patient->id)
  266. ->where('category', 'allergy')
  267. ->where('is_removed', false)
  268. ->get();
  269. return view('app.patient.allergies', compact('patient', 'infoLines'));
  270. }
  271. public function notes(Request $request, Client $patient, $filter = 'active')
  272. {
  273. $pros = $this->pros;
  274. return view('app.patient.notes', compact('patient','pros', 'filter'));
  275. }
  276. public function genericBills(Request $request, Client $patient)
  277. {
  278. return view('app.patient.generic-bills', compact('patient'));
  279. }
  280. public function rmSetup(Request $request, Client $patient)
  281. {
  282. // get assigned devices
  283. $assignedDeviceIDs = DB::select(DB::raw("SELECT device_id from client_bdt_device where is_active = true"));
  284. $assignedDeviceIDs = array_map(function($_x) {
  285. return $_x->device_id;
  286. }, $assignedDeviceIDs);
  287. // get all except assigned ones
  288. $devices = BDTDevice::where('is_active', true)
  289. ->whereNotIn('id', $assignedDeviceIDs)
  290. ->orderBy('imei', 'asc')
  291. ->get();
  292. $assignedDeviceIDs = null;
  293. unset($assignedDeviceIDs);
  294. return view('app.patient.rm-setup', compact('patient', 'devices'));
  295. }
  296. public function handouts(Request $request, Client $patient )
  297. {
  298. $clientHandouts = HandoutClient::where('client_id', $patient->id)->get();
  299. $handouts = Handout::where('is_active', true)->orderBy('display_name', 'ASC')->get();
  300. return view('app.patient.handouts', compact('patient', 'clientHandouts', 'handouts'));
  301. }
  302. public function settings(Request $request, Client $patient )
  303. {
  304. $companies = Company::all();
  305. return view('app.patient.settings', compact('patient', 'companies'));
  306. }
  307. public function smsReminders(Request $request, Client $patient )
  308. {
  309. return view('app.patient.sms-reminders', compact('patient'));
  310. }
  311. public function measurementConfirmationNumbers(Request $request, Client $patient )
  312. {
  313. return view('app.patient.measurement-confirmation-numbers', compact('patient'));
  314. }
  315. public function pros(Request $request, Client $patient )
  316. {
  317. return view('app.patient.pros', compact('patient'));
  318. }
  319. public function proChanges(Request $request, Client $patient )
  320. {
  321. return view('app.patient.client-pro-changes', compact('patient'));
  322. }
  323. public function account(Request $request, Client $patient )
  324. {
  325. return view('app.patient.account', compact('patient'));
  326. }
  327. public function careChecklist(Request $request, Client $patient )
  328. {
  329. return view('app.patient.care-checklist', compact('patient'));
  330. }
  331. public function documents(Request $request, Client $patient )
  332. {
  333. return view('app.patient.documents', compact('patient'));
  334. }
  335. public function incomingReports(Request $request, Client $patient, IncomingReport $currentReport = null)
  336. {
  337. return view('app.patient.incoming-reports', compact('patient', 'currentReport'));
  338. }
  339. public function education(Request $request, Client $patient )
  340. {
  341. return view('app.patient.education', compact('patient'));
  342. }
  343. public function messaging(Request $request, Client $patient )
  344. {
  345. return view('app.patient.messaging', compact('patient'));
  346. }
  347. public function duplicate(Request $request, Client $patient )
  348. {
  349. return view('app.patient.duplicate', compact('patient'));
  350. }
  351. public function careMonths(Request $request, Client $patient )
  352. {
  353. if($request->input('ql')) DB::enableQueryLog();
  354. $careMonths = CareMonth
  355. ::select(
  356. 'id',
  357. 'uid',
  358. 'start_date',
  359. 'uid',
  360. 'was_rm_setup_performed',
  361. 'number_of_days_with_remote_measurements',
  362. 'rm_total_time_in_seconds',
  363. 'rm_total_time_in_seconds_by_mcp',
  364. 'rm_total_time_in_seconds_by_rme_pro',
  365. 'rm_total_time_in_seconds_by_rmm_pro',
  366. 'mcp_pro_id',
  367. 'rm_bill_id',
  368. 'cm_pro_id',
  369. 'rmm_pro_id',
  370. 'rme_pro_id',
  371. 'number_of_days_with_remote_measurements',
  372. 'rm_total_time_in_seconds_by_mcp',
  373. 'has_mcp_interacted_with_client_about_rm'
  374. )
  375. ->where('client_id', $patient->id)
  376. ->orderBy('start_date', 'desc')->get();
  377. $notes = [];
  378. if($patient->has_mcp_done_onboarding_visit !== 'YES') {
  379. $notes = Note
  380. ::select('uid', 'title', 'effective_dateest', 'hcp_pro_id')
  381. ->where('client_id', $patient->id)
  382. ->where('is_cancelled', false)
  383. ->get();
  384. }
  385. if($request->input('ql')) dd(DB::getQueryLog());
  386. return view('app.patient.care-months', compact('patient', 'careMonths', 'notes'));
  387. }
  388. public function presence(Request $request, Client $patient )
  389. {
  390. return json_encode([
  391. "online" => $patient->is_online
  392. ]);
  393. }
  394. public function embedSection(Request $request, Client $patient, $section, $selectable) {
  395. return view('app.patient.partials.' . $section, compact('patient', 'selectable'));
  396. }
  397. public function calendar(Request $request, Client $patient, Appointment $currentAppointment) {
  398. $pros = [];
  399. if($this->pro && $this->pro->pro_type != 'ADMIN') {
  400. $accessiblePros = ProProAccess::where('owner_pro_id', $this->pro->id)->get();
  401. $accessibleProIds = [];
  402. foreach($accessiblePros as $accessiblePro){
  403. $accessibleProIds[] = $accessiblePro->accessible_pro_id;
  404. }
  405. $accessibleProIds[] = $this->pro->id;
  406. // for dna, add pros accessible via pro teams
  407. if($this->performer->pro->isDefaultNA()) {
  408. $teams = $this->performer->pro->teamsWhereAssistant;
  409. foreach ($teams as $team) {
  410. if(!in_array($team->mcp_pro_id, $accessibleProIds)) {
  411. $accessibleProIds[] = $team->mcp_pro_id;
  412. }
  413. }
  414. }
  415. $pros = Pro::whereIn('id', $accessibleProIds)->get();
  416. }
  417. $dateLastWeek = date_sub(date_create(), date_interval_create_from_date_string("14 days"));
  418. $dateLastWeek = date_format($dateLastWeek, "Y-m-d");
  419. $appointments = Appointment::where('client_id', $patient->id)
  420. ->orderBy('raw_date', 'desc')->orderBy('raw_start_time', 'desc')
  421. ->where('raw_date', '>=', $dateLastWeek)
  422. ->get();
  423. $appointmentProIDs = $appointments->map(function($_item) {
  424. return $_item->pro_id;
  425. });
  426. $appointmentPros = Pro::whereIn('id', $appointmentProIDs)->get();
  427. return view('app.patient.appointment-calendar',
  428. compact('pros', 'patient', 'currentAppointment', 'appointments', 'appointmentPros'));
  429. }
  430. public function flowsheets(Request $request, Client $patient, $filter = '') {
  431. $pros = $this->pros;
  432. return view('app.patient.flowsheets', compact('patient', 'pros', 'filter'));
  433. }
  434. public function vitalsSettings(Request $request, Client $patient) {
  435. return view('app.patient.vitals-settings', compact('patient'));
  436. }
  437. public function vitalsGraph(Request $request, Client $patient, $filter = '') {
  438. $pros = $this->pros;
  439. return view('app.patient.vitals-graph', compact('patient', 'pros', 'filter'));
  440. }
  441. public function sleepStudy(Request $request, Client $patient) {
  442. return view('app.patient.sleep-study', compact('patient'));
  443. }
  444. public function sleepStudyStep(Request $request, Client $patient) {
  445. return view('app.patient.sleep-study.' . $request->input('step'), compact('patient'));
  446. }
  447. public function tickets(Request $request, Client $patient, $type = '', String $currentTicket = '') {
  448. $pros = $this->pros;
  449. $allPros = Pro::all();
  450. $qlTicket = $currentTicket;
  451. if(!!$currentTicket) {
  452. $qlTicket = Ticket::where('uid', $currentTicket)->first();
  453. if($qlTicket) {
  454. $currentTicket = $qlTicket;
  455. }
  456. }
  457. return view('app.patient.tickets', compact('patient', 'pros', 'allPros', 'type', 'currentTicket'));
  458. }
  459. protected function getDefaultFacility(){
  460. $defaultFacility = Facility::where('name', 'Ultra Care Pharmacy')->where('address_city', 'Baltimore')->first();
  461. return $defaultFacility;
  462. }
  463. public function prescriptions(Request $request, Client $patient, String $type = '', String $currentErx = '') {
  464. $this->updateDefaultPatientPharmacy($patient);
  465. if(!!$currentErx) {
  466. $currentErx = Erx::where('uid', $currentErx)->first();
  467. }
  468. $note = $patient->coreNote;
  469. $defaultFacility = $this->getDefaultFacility();
  470. $patient->refresh();
  471. return view('app.patient.prescriptions.index', compact('patient', 'type', 'currentErx', 'note', 'defaultFacility'));
  472. }
  473. protected function updateDefaultPatientPharmacy(Client $patient){
  474. $prescriptions = $patient->prescriptions;
  475. if(!count($prescriptions)) return;
  476. $defaultFacility = $this->getDefaultFacility();
  477. if(!$defaultFacility) return;
  478. foreach($prescriptions as $prescription){
  479. if($prescription->logistics_detail_json) continue;
  480. $this->setPrescriptionDefaultPharmacy($prescription, $defaultFacility);
  481. }
  482. }
  483. private function setPrescriptionDefaultPharmacy(Erx $prescription, Facility $facility){
  484. $data = [
  485. 'uid' => $prescription->uid,
  486. 'logisticsDetailJson' => json_encode([
  487. 'facilityName' => $facility->name,
  488. 'facilityCity' => $facility->address_city,
  489. 'facilityState' => $facility->address_state,
  490. 'facilityAddressMemo' => '',
  491. 'facilityPhone' => $facility->phone,
  492. 'facilityFax' => $facility->fax,
  493. 'facilityZip' => $facility->address_zip,
  494. ])
  495. ];
  496. $response = $this->callJavaApi('/erx/updateLogisticsDetail', $data);
  497. }
  498. public function prescriptionsPopup(Request $request, Client $patient, String $type = '', String $currentErx = '') {
  499. if(!!$currentErx) {
  500. $currentErx = Erx::where('uid', $currentErx)->first();
  501. }
  502. $note = null;
  503. if($request->input('noteUid')) {
  504. $note = Note::where('uid', $request->input('noteUid'))->first();
  505. }
  506. return view('app.patient.prescriptions-popup.list-popup', compact('patient', 'type', 'currentErx', 'note'));
  507. }
  508. public function prescriptionsList(Request $request, Client $patient, String $type = '', String $currentErx = '') {
  509. if(!!$currentErx) {
  510. $currentErx = Erx::where('uid', $currentErx)->first();
  511. }
  512. $note = null;
  513. if($request->input('noteUid')) {
  514. $note = Note::where('uid', $request->input('noteUid'))->first();
  515. }
  516. return view('app.patient.prescriptions.list', compact('patient', 'type', 'currentErx', 'note'));
  517. }
  518. public function downloadPrescriptionAsPdf(Request $request, Erx $prescription){
  519. if($request->input('html')) {
  520. return view('app.patient.prescriptions.pdf.pdf-preview', compact('prescription'));
  521. }
  522. else {
  523. $pdf = PDF::loadView('app.patient.prescriptions.pdf.pdf-preview', compact('prescription'));
  524. return $pdf->download($prescription->created_at .'_' . 'erx.pdf');
  525. }
  526. }
  527. public function transmitPrescription(Request $request, Erx $prescription){
  528. // re-generate pdf with cover sheet as first page and save it to FS
  529. $filePath = config('app.temp_dir') . "/{$prescription->uid}.pdf";
  530. $pdf = PDF::loadView('app.patient.prescriptions.pdf.pdf-preview-with-cover-sheet', compact('prescription'));
  531. $pdf->save($filePath);
  532. // send it along with the rest of the params to /api/erx/transmit [multi-part POST]
  533. $url = config('stag.backendUrl') . '/erx/transmit';
  534. $params = [
  535. "uid" => $request->input('uid'),
  536. "toWho" => $request->input('toWho'),
  537. "toEmail" => $request->input('toEmail'),
  538. "toFaxNumber" => $request->input('toFaxNumber'),
  539. "toFaxNumberAttentionLine" => $request->input('toFaxNumberAttentionLine'),
  540. "toFaxNumberCoverSheetMemo" => $request->input('toFaxNumberCoverSheetMemo'),
  541. ];
  542. if($request->input('copyToPatient')) {
  543. $params["copyToPatientFaxNumber"] = $request->input('copyToPatientFaxNumber');
  544. $params["copyToPatientEmail"] = $request->input('copyToPatientEmail');
  545. }
  546. $pdf = fopen($filePath, 'r');
  547. $response = Http
  548. ::attach('pdfSystemFile', $filePath, "{$prescription->uid}.pdf")
  549. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  550. ->post($url, $params)
  551. ->json();
  552. return $response;
  553. }
  554. public function supplyOrders(Request $request, Client $patient, SupplyOrder $supplyOrder = null)
  555. {
  556. $products = Product::where('is_active', true)->orderBy('created_at', 'desc')->get();
  557. return view('app.patient.supply-orders', compact('patient', 'supplyOrder', 'products'));
  558. }
  559. public function shipments(Request $request, Client $patient, Shipment $shipment = null)
  560. {
  561. return view('app.patient.shipments', compact('patient', 'shipment'));
  562. }
  563. public function appointments(Request $request, Client $patient, $forPro = 'all', $status = 'all') {
  564. $pros = $this->pros;
  565. $appointments = $patient->appointmentsForProByStatus($forPro, strtoupper($status));
  566. $appointmentProIDs = $appointments->map(function($_item) {
  567. return $_item->pro_id;
  568. });
  569. $appointmentPros = Pro::whereIn('id', $appointmentProIDs)->get();
  570. return view('app.patient.appointments',
  571. compact('patient', 'pros', 'appointments', 'appointmentPros', 'forPro', 'status'));
  572. }
  573. public function mcpRequests(Request $request, Client $patient) {
  574. return view('app.patient.mcp-requests', compact('patient'));
  575. }
  576. public function eligibleRefreshes(Request $request, Client $patient) {
  577. return view('app.patient.eligible-refreshes', compact('patient'));
  578. }
  579. public function insuranceCoverage(Request $request, Client $patient) {
  580. $mbPayers = MBPayer::all();
  581. return view('app.patient.insurance-coverage', compact('patient', 'mbPayers'));
  582. }
  583. public function clientPrimaryCoverages(Request $request, Client $patient) {
  584. $mbPayers = MBPayer::all();
  585. return view('app.patient.client-primary-coverages', compact('patient', 'mbPayers'));
  586. }
  587. public function primaryCoverage(Request $request, Client $patient) {
  588. $mbPayers = MBPayer::all();
  589. return view('app.patient.primary-coverage', compact('patient', 'mbPayers'));
  590. }
  591. public function primaryCoverageForm(Request $request, Client $patient) {
  592. $mbPayers = MBPayer::all();
  593. return view('app.patient.primary-coverage-form', compact('patient', 'mbPayers'));
  594. }
  595. public function primaryCoverageManualDeterminationModal(Request $request, Client $patient) {
  596. $coverageUid = $request->get('coverageUid');
  597. $coverage = ClientPrimaryCoverage::where('uid', $coverageUid)->first();
  598. if($patient->latestClientPrimaryCoverage->plan_type === 'MEDICARE'){
  599. return view('app.patient.primary-coverage-manual-determination-medicare-modal', compact('patient', 'coverage'));
  600. }
  601. if($patient->latestClientPrimaryCoverage->plan_type === 'MEDICAID'){
  602. return view('app.patient.primary-coverage-manual-determination-medicaid-modal', compact('patient', 'coverage'));
  603. }
  604. if($patient->latestClientPrimaryCoverage->plan_type === 'COMMERCIAL'){
  605. return view('app.patient.primary-coverage-manual-determination-commercial-modal', compact('patient', 'coverage'));
  606. }
  607. return "Plan Type is missing!";
  608. }
  609. public function mbClaim(Request $request, MBClaim $mbClaim) {
  610. return view('app.patient.mb-claim-single', compact('mbClaim'));
  611. }
  612. public function accounts(Request $request, Client $patient) {
  613. return view('app.patient.accounts', compact('patient'));
  614. }
  615. public function companies(Request $request, Client $patient) {
  616. $companies = Company::where('is_active', true)->get();
  617. $companyClientStatusMap = [];
  618. $companyClientStatusMap['NEW'] = 'New';
  619. $companyClientStatusMap['ELIGIBILITY_VERIFIED'] = 'Eligibility Verified';
  620. $companyClientStatusMap['ELIGIBILITY_PENDING'] = 'Eligibility Pending';
  621. $companyClientStatusMap['NOT_ELIGIBLE'] = 'Not Eligible';
  622. $companyClientStatusMap['INITIAL_CONSULT'] = 'Initial Consult';
  623. $companyClientStatusMap['HST_DELIVERED'] = 'HST Delivered';
  624. $companyClientStatusMap['STUDY_PENDING'] = 'Study Pending';
  625. $companyClientStatusMap['STUDY_COMPLETED'] = 'Study Completed';
  626. $companyClientStatusMap['STUDY_INTERPRETED'] = 'Study Interpreted';
  627. $companyClientStatusMap['POST_HST_VISIT'] = 'Post HST Visit';
  628. $companyClientStatusMap['CPAP_RX'] = 'CPAP Rx';
  629. $companyClientStatusMap['ORAL_APPLIANCE_RX'] = 'Oral Appliance Rx';
  630. $companyClientStatusMap['NOT_INTERESTED'] = 'Not Interested';
  631. $companyClientStatusMap['IN_LAB_STUDY'] = 'In Lab Study';
  632. $companyClientStatusMap['UNRESPONSIVE'] = 'Unresponsive';
  633. return view('app.patient.companies', compact('patient', 'companies', 'companyClientStatusMap'));
  634. }
  635. public function rtm(Request $request, Client $patient) {
  636. return view('app.patient.rtm', compact('patient'));
  637. }
  638. public function careMonthMatrix(Request $request, CareMonth $careMonth) {
  639. return view('app.patient.care-month.matrix', [
  640. 'patient' => $careMonth->patient,
  641. 'careMonth' => $careMonth,
  642. ]);
  643. }
  644. public function clientProAccess(Request $request, Client $patient) {
  645. $rows = ClientProAccess::where('client_id', $patient->id)->get();
  646. return view('app.patient.client-pro-access', compact('patient', 'rows'));
  647. }
  648. public function clientDocuments(Request $request, Client $patient){
  649. $templates = get_doc_templates();
  650. $companyProIDs = DB::select('SELECT company_pro_id FROM company_pro_document WHERE related_client_id = ?', [$patient->id]);
  651. $companyProIDInts = [];
  652. foreach($companyProIDs as $cpId){
  653. $companyProIDInts[] = $cpId->company_pro_id;
  654. }
  655. $companyPros = CompanyPro::whereIn('id', $companyProIDInts)->get();
  656. return view('app.patient.client-documents', compact('templates', 'companyPros', 'patient'));
  657. }
  658. public function clientDocumentsRequests(Request $request, Client $patient){
  659. $templates = $this->getTemplates();
  660. $companyClients = CompanyClient::where('client_id', $patient->id)->get();
  661. $companyClientsIds = CompanyClient::where('client_id', $patient->id)->pluck('id')->toArray();
  662. $documents = CompanyProDocument::whereIn('company_client_id', $companyClientsIds)->orderBy('created_at', 'DESC')->paginate(50);
  663. return view('app.patient.client-documents-requests', compact('templates', 'patient', 'companyClients', 'documents'));
  664. }
  665. private function getTemplates(){
  666. return get_doc_templates();
  667. }
  668. public function insuranceCards(Request $request, Client $patient){
  669. $insuranceCards = InsuranceCard::where('client_id', $patient->id)->orderBy('coverage_order', 'ASC')->get();
  670. return view('app.patient.insurance-cards', compact('patient', 'insuranceCards'));
  671. }
  672. public function insuranceCard(Request $request, Client $patient, InsuranceCard $card){
  673. return view('app.patient.insurance-card', compact('patient', 'card'));
  674. }
  675. public function insuranceCardPutInfo(Request $request, Client $patient, InsuranceCard $card){
  676. //Use java, but currently java is not updating card info columns
  677. $data = $request->except(['uid']);
  678. foreach($data as $key=>$value){
  679. if($key === 'frontImageUrl') $card->front_image_url = $value;
  680. if($key === 'backImageUrl') $card->back_image_url = $value;
  681. }
  682. $card->save();
  683. return $this->pass($card->uid);
  684. }
  685. public function insuranceCoverageHistory(Request $request, Client $patient){
  686. $insuranceCoverageHistory = ClientPrimaryCoverage::where('client_id', $patient->id)->orderBy('created_at', 'DESC')->get();
  687. return view('app.patient.insurance-coverage-history', compact('patient', 'insuranceCoverageHistory'));
  688. }
  689. public function protocolBuilder(Request $request, Client $patient) {
  690. return view('app.patient.rtm.protocol-builder', compact('patient'));
  691. }
  692. public function checkIfCptCodeIsSubmitted(Request $request){
  693. $clientUid = $request->get('clientUid');
  694. $cptCode = $request->get('code');
  695. if(!$clientUid || !$cptCode) return $this->fail('Error');
  696. $client = Client::where('uid', $clientUid)->first();
  697. $notes = $client->notes;
  698. $isCptSubmitted = false;
  699. foreach($notes as $note){
  700. $noteClaims = $note->claims;
  701. foreach($noteClaims as $noteClaim){
  702. foreach($noteClaim->lines as $claimLine){
  703. if($claimLine->cpt == $cptCode){
  704. if($noteClaim->status == 'SUBMITTED'){
  705. $isCptSubmitted = true;
  706. }
  707. }
  708. }
  709. }
  710. }
  711. if($isCptSubmitted) return $this->pass('SUBMITTED');
  712. return $this->pass('NOT_SUBMITTED');
  713. }
  714. public function surveys(Request $request, Client $patient)
  715. {
  716. $filters = $request->all();
  717. $entityTypes = Survey::ALLOWED_ENTITIES;
  718. $surveyFormsPath = resource_path(Survey::FORM_PATH);
  719. $filesInFolder = File::allFiles($surveyFormsPath);
  720. $forms = [];
  721. foreach ($filesInFolder as $path) {
  722. $file = pathinfo($path);
  723. $fileName = $file['filename'];
  724. $internalName = explode('.', $fileName)[0];
  725. $forms[] = $internalName;
  726. }
  727. $records = Survey::where('entity_uid', $patient->uid);
  728. $searchString = $request->get('string');
  729. if($searchString){
  730. $searchString = strtolower($searchString);
  731. $records = $records->where(function ($q) use ($searchString) {
  732. return $q->orWhereRaw('LOWER(title::text) ILIKE ?', ['%' . $searchString . '%'])
  733. ->orWhereRaw('LOWER(internal_name::text) ILIKE ?', ['%' . $searchString . '%'])
  734. ->orWhereRaw('survey_data ILIKE ?', ['%' . $searchString . '%']);
  735. });
  736. }
  737. $entityType = $request->get('entity_type');
  738. if($entityType){
  739. $records = $records->where('entity_type', $entityType);
  740. }
  741. $records = $records->orderBy('created_at', 'DESC')->paginate(5);
  742. $layout = 'layouts.patient';
  743. $isPopup = false;
  744. if($request->get('popup')){
  745. $layout = 'layouts.popup';
  746. $isPopup = true;
  747. }
  748. return view('app.patient.surveys.list', compact('forms', 'records', 'entityTypes', 'filters', 'patient', 'layout', 'isPopup'));
  749. }
  750. public function surveysCreate(Request $request, Client $patient){
  751. $validator = Validator::make($request->all(), [
  752. 'entityType' => 'required|string',
  753. 'entityUid' => 'required|string',
  754. 'internalName' => 'required|string'
  755. ]);
  756. if ($validator->fails()) {
  757. return $this->fail('Invalid data provided!');
  758. }
  759. $internalName = $request->get('internalName');
  760. $entityType = $request->get('entityType');
  761. $entityUid = $request->get('entityUid');
  762. $surveyService = new SurveyService($internalName);
  763. $defaultHtml = $surveyService->defaultHTML;
  764. if(!$defaultHtml) return $this->fail('No default HTML template found for ' . $internalName);
  765. $initializedData = $surveyService->getInitializedData($entityType, $entityUid);
  766. $data = [
  767. 'internalName' => $internalName,
  768. 'title' => $request->get('title'),
  769. 'entityType' => $entityType,
  770. 'entityUid' => $entityUid,
  771. 'surveyHTML' => $defaultHtml,
  772. 'surveyDataJSON' => json_encode($initializedData)
  773. ];
  774. $response = $this->callJavaApi('/survey/create', $data);
  775. if(!$response['success']){
  776. return $this->fail(@$response['message']);
  777. }
  778. return $this->pass();
  779. }
  780. public function getEntityRecords(Request $request, Client $patient)
  781. {
  782. $term = $request->get('term');
  783. $type = $request->get('type');
  784. if(!in_array($type, Survey::ALLOWED_ENTITIES)){
  785. return $this->fail('Invalid entity type');
  786. }
  787. $records = [];
  788. if($type === 'Client'){
  789. $clients = Client::query();
  790. $clients = $clients->where('is_active', true);
  791. $clients = $clients->where(function ($q) use ($term) {
  792. return $q->orWhereRaw('LOWER(name_first::text) ILIKE ?', ['%' . $term . '%'])
  793. ->orWhereRaw('LOWER(name_last::text) ILIKE ?', ['%' . $term . '%'])
  794. ->orWhereRaw('LOWER(email_address::text) ILIKE ?', ['%' . $term . '%'])
  795. ->orWhereRaw('cell_number ILIKE ?', ['%' . $term . '%']);
  796. });
  797. $clients = $clients->orderBy('name_first', 'ASC')->limit(10)->get();
  798. $clientsData = $clients->map(function($client) {
  799. return [
  800. "uid" => $client->uid,
  801. "id" => $client->id,
  802. "text" => $client->displayName(),
  803. ];
  804. });
  805. return json_encode([
  806. "results" => $clientsData
  807. ]);
  808. }
  809. return $this->pass($records);
  810. }
  811. public function patientRequests(Request $request, Client $patient)
  812. {
  813. $patientRequests = PatientRequest::where('client_id', $patient->id)->paginate(30);
  814. $data = [
  815. 'patientRequests' => $patientRequests,
  816. 'patient' => $patient
  817. ];
  818. return view('app.patient.patient-requests', $data);
  819. }
  820. public function patientRequestCreateInvoice(Request $request, Client $client){
  821. $params = $request->all();
  822. $response = $this->callJavaApi('/invoice/create', $params);
  823. if(!$response['success']){
  824. return $this->fail(@$response['message']);
  825. }
  826. $invoiceUid = $response['data'];
  827. $invoice = Invoice::where('uid', $invoiceUid)->first();
  828. $patientRequest = PatientRequest::where('uid', $params['patientRequestUid'])->first();
  829. $patientRequest->invoice_id = $invoice->id;
  830. $patientRequest->save();
  831. return $this->pass();
  832. }
  833. public function manageCCM(Request $request, Client $patient){
  834. return view('app.patient.manage-ccm', compact('patient'));
  835. }
  836. public function manageRPM(Request $request, Client $patient){
  837. return view('app.patient.manage-rpm', compact('patient'));
  838. }
  839. }