PatientController.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961
  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. $careMonths = CareMonth::where('client_id', $patient->id)->orderBy('start_date', 'desc')->get();
  354. $notes = Note::where('is_cancelled', false)->get();
  355. return view('app.patient.care-months', compact('patient', 'careMonths', 'notes'));
  356. }
  357. public function presence(Request $request, Client $patient )
  358. {
  359. return json_encode([
  360. "online" => $patient->is_online
  361. ]);
  362. }
  363. public function embedSection(Request $request, Client $patient, $section, $selectable) {
  364. return view('app.patient.partials.' . $section, compact('patient', 'selectable'));
  365. }
  366. public function calendar(Request $request, Client $patient, Appointment $currentAppointment) {
  367. $pros = [];
  368. if($this->pro && $this->pro->pro_type != 'ADMIN') {
  369. $accessiblePros = ProProAccess::where('owner_pro_id', $this->pro->id)->get();
  370. $accessibleProIds = [];
  371. foreach($accessiblePros as $accessiblePro){
  372. $accessibleProIds[] = $accessiblePro->accessible_pro_id;
  373. }
  374. $accessibleProIds[] = $this->pro->id;
  375. // for dna, add pros accessible via pro teams
  376. if($this->performer->pro->isDefaultNA()) {
  377. $teams = $this->performer->pro->teamsWhereAssistant;
  378. foreach ($teams as $team) {
  379. if(!in_array($team->mcp_pro_id, $accessibleProIds)) {
  380. $accessibleProIds[] = $team->mcp_pro_id;
  381. }
  382. }
  383. }
  384. $pros = Pro::whereIn('id', $accessibleProIds)->get();
  385. }
  386. $dateLastWeek = date_sub(date_create(), date_interval_create_from_date_string("14 days"));
  387. $dateLastWeek = date_format($dateLastWeek, "Y-m-d");
  388. $appointments = Appointment::where('client_id', $patient->id)
  389. ->orderBy('raw_date', 'desc')->orderBy('raw_start_time', 'desc')
  390. ->where('raw_date', '>=', $dateLastWeek)
  391. ->get();
  392. $appointmentProIDs = $appointments->map(function($_item) {
  393. return $_item->pro_id;
  394. });
  395. $appointmentPros = Pro::whereIn('id', $appointmentProIDs)->get();
  396. return view('app.patient.appointment-calendar',
  397. compact('pros', 'patient', 'currentAppointment', 'appointments', 'appointmentPros'));
  398. }
  399. public function flowsheets(Request $request, Client $patient, $filter = '') {
  400. $pros = $this->pros;
  401. return view('app.patient.flowsheets', compact('patient', 'pros', 'filter'));
  402. }
  403. public function vitalsSettings(Request $request, Client $patient) {
  404. return view('app.patient.vitals-settings', compact('patient'));
  405. }
  406. public function vitalsGraph(Request $request, Client $patient, $filter = '') {
  407. $pros = $this->pros;
  408. return view('app.patient.vitals-graph', compact('patient', 'pros', 'filter'));
  409. }
  410. public function sleepStudy(Request $request, Client $patient) {
  411. return view('app.patient.sleep-study', compact('patient'));
  412. }
  413. public function sleepStudyStep(Request $request, Client $patient) {
  414. return view('app.patient.sleep-study.' . $request->input('step'), compact('patient'));
  415. }
  416. public function tickets(Request $request, Client $patient, $type = '', String $currentTicket = '') {
  417. $pros = $this->pros;
  418. $allPros = Pro::all();
  419. $qlTicket = $currentTicket;
  420. if(!!$currentTicket) {
  421. $qlTicket = Ticket::where('uid', $currentTicket)->first();
  422. if($qlTicket) {
  423. $currentTicket = $qlTicket;
  424. }
  425. }
  426. return view('app.patient.tickets', compact('patient', 'pros', 'allPros', 'type', 'currentTicket'));
  427. }
  428. protected function getDefaultFacility(){
  429. $defaultFacility = Facility::where('name', 'Ultra Care Pharmacy')->where('address_city', 'Baltimore')->first();
  430. return $defaultFacility;
  431. }
  432. public function prescriptions(Request $request, Client $patient, String $type = '', String $currentErx = '') {
  433. $this->updateDefaultPatientPharmacy($patient);
  434. if(!!$currentErx) {
  435. $currentErx = Erx::where('uid', $currentErx)->first();
  436. }
  437. $note = $patient->coreNote;
  438. $defaultFacility = $this->getDefaultFacility();
  439. $patient->refresh();
  440. return view('app.patient.prescriptions.index', compact('patient', 'type', 'currentErx', 'note', 'defaultFacility'));
  441. }
  442. protected function updateDefaultPatientPharmacy(Client $patient){
  443. $prescriptions = $patient->prescriptions;
  444. if(!count($prescriptions)) return;
  445. $defaultFacility = $this->getDefaultFacility();
  446. if(!$defaultFacility) return;
  447. foreach($prescriptions as $prescription){
  448. if($prescription->logistics_detail_json) continue;
  449. $this->setPrescriptionDefaultPharmacy($prescription, $defaultFacility);
  450. }
  451. }
  452. private function setPrescriptionDefaultPharmacy(Erx $prescription, Facility $facility){
  453. $data = [
  454. 'uid' => $prescription->uid,
  455. 'logisticsDetailJson' => json_encode([
  456. 'facilityName' => $facility->name,
  457. 'facilityCity' => $facility->address_city,
  458. 'facilityState' => $facility->address_state,
  459. 'facilityAddressMemo' => '',
  460. 'facilityPhone' => $facility->phone,
  461. 'facilityFax' => $facility->fax,
  462. 'facilityZip' => $facility->address_zip,
  463. ])
  464. ];
  465. $response = $this->callJavaApi('/erx/updateLogisticsDetail', $data);
  466. }
  467. public function prescriptionsPopup(Request $request, Client $patient, String $type = '', String $currentErx = '') {
  468. if(!!$currentErx) {
  469. $currentErx = Erx::where('uid', $currentErx)->first();
  470. }
  471. $note = null;
  472. if($request->input('noteUid')) {
  473. $note = Note::where('uid', $request->input('noteUid'))->first();
  474. }
  475. return view('app.patient.prescriptions-popup.list-popup', compact('patient', 'type', 'currentErx', 'note'));
  476. }
  477. public function prescriptionsList(Request $request, Client $patient, String $type = '', String $currentErx = '') {
  478. if(!!$currentErx) {
  479. $currentErx = Erx::where('uid', $currentErx)->first();
  480. }
  481. $note = null;
  482. if($request->input('noteUid')) {
  483. $note = Note::where('uid', $request->input('noteUid'))->first();
  484. }
  485. return view('app.patient.prescriptions.list', compact('patient', 'type', 'currentErx', 'note'));
  486. }
  487. public function downloadPrescriptionAsPdf(Request $request, Erx $prescription){
  488. if($request->input('html')) {
  489. return view('app.patient.prescriptions.pdf.pdf-preview', compact('prescription'));
  490. }
  491. else {
  492. $pdf = PDF::loadView('app.patient.prescriptions.pdf.pdf-preview', compact('prescription'));
  493. return $pdf->download($prescription->created_at .'_' . 'erx.pdf');
  494. }
  495. }
  496. public function transmitPrescription(Request $request, Erx $prescription){
  497. // re-generate pdf with cover sheet as first page and save it to FS
  498. $filePath = config('app.temp_dir') . "/{$prescription->uid}.pdf";
  499. $pdf = PDF::loadView('app.patient.prescriptions.pdf.pdf-preview-with-cover-sheet', compact('prescription'));
  500. $pdf->save($filePath);
  501. // send it along with the rest of the params to /api/erx/transmit [multi-part POST]
  502. $url = config('stag.backendUrl') . '/erx/transmit';
  503. $params = [
  504. "uid" => $request->input('uid'),
  505. "toWho" => $request->input('toWho'),
  506. "toEmail" => $request->input('toEmail'),
  507. "toFaxNumber" => $request->input('toFaxNumber'),
  508. "toFaxNumberAttentionLine" => $request->input('toFaxNumberAttentionLine'),
  509. "toFaxNumberCoverSheetMemo" => $request->input('toFaxNumberCoverSheetMemo'),
  510. ];
  511. if($request->input('copyToPatient')) {
  512. $params["copyToPatientFaxNumber"] = $request->input('copyToPatientFaxNumber');
  513. $params["copyToPatientEmail"] = $request->input('copyToPatientEmail');
  514. }
  515. $pdf = fopen($filePath, 'r');
  516. $response = Http
  517. ::attach('pdfSystemFile', $filePath, "{$prescription->uid}.pdf")
  518. ->withHeaders(['sessionKey' => $request->cookie('sessionKey')])
  519. ->post($url, $params)
  520. ->json();
  521. return $response;
  522. }
  523. public function supplyOrders(Request $request, Client $patient, SupplyOrder $supplyOrder = null)
  524. {
  525. $products = Product::where('is_active', true)->orderBy('created_at', 'desc')->get();
  526. return view('app.patient.supply-orders', compact('patient', 'supplyOrder', 'products'));
  527. }
  528. public function shipments(Request $request, Client $patient, Shipment $shipment = null)
  529. {
  530. return view('app.patient.shipments', compact('patient', 'shipment'));
  531. }
  532. public function appointments(Request $request, Client $patient, $forPro = 'all', $status = 'all') {
  533. $pros = $this->pros;
  534. $appointments = $patient->appointmentsForProByStatus($forPro, strtoupper($status));
  535. $appointmentProIDs = $appointments->map(function($_item) {
  536. return $_item->pro_id;
  537. });
  538. $appointmentPros = Pro::whereIn('id', $appointmentProIDs)->get();
  539. return view('app.patient.appointments',
  540. compact('patient', 'pros', 'appointments', 'appointmentPros', 'forPro', 'status'));
  541. }
  542. public function mcpRequests(Request $request, Client $patient) {
  543. return view('app.patient.mcp-requests', compact('patient'));
  544. }
  545. public function eligibleRefreshes(Request $request, Client $patient) {
  546. return view('app.patient.eligible-refreshes', compact('patient'));
  547. }
  548. public function insuranceCoverage(Request $request, Client $patient) {
  549. $mbPayers = MBPayer::all();
  550. return view('app.patient.insurance-coverage', compact('patient', 'mbPayers'));
  551. }
  552. public function clientPrimaryCoverages(Request $request, Client $patient) {
  553. $mbPayers = MBPayer::all();
  554. return view('app.patient.client-primary-coverages', compact('patient', 'mbPayers'));
  555. }
  556. public function primaryCoverage(Request $request, Client $patient) {
  557. $mbPayers = MBPayer::all();
  558. return view('app.patient.primary-coverage', compact('patient', 'mbPayers'));
  559. }
  560. public function primaryCoverageForm(Request $request, Client $patient) {
  561. $mbPayers = MBPayer::all();
  562. return view('app.patient.primary-coverage-form', compact('patient', 'mbPayers'));
  563. }
  564. public function primaryCoverageManualDeterminationModal(Request $request, Client $patient) {
  565. $coverageUid = $request->get('coverageUid');
  566. $coverage = ClientPrimaryCoverage::where('uid', $coverageUid)->first();
  567. if($patient->latestClientPrimaryCoverage->plan_type === 'MEDICARE'){
  568. return view('app.patient.primary-coverage-manual-determination-medicare-modal', compact('patient', 'coverage'));
  569. }
  570. if($patient->latestClientPrimaryCoverage->plan_type === 'MEDICAID'){
  571. return view('app.patient.primary-coverage-manual-determination-medicaid-modal', compact('patient', 'coverage'));
  572. }
  573. if($patient->latestClientPrimaryCoverage->plan_type === 'COMMERCIAL'){
  574. return view('app.patient.primary-coverage-manual-determination-commercial-modal', compact('patient', 'coverage'));
  575. }
  576. return "Plan Type is missing!";
  577. }
  578. public function mbClaim(Request $request, MBClaim $mbClaim) {
  579. return view('app.patient.mb-claim-single', compact('mbClaim'));
  580. }
  581. public function accounts(Request $request, Client $patient) {
  582. return view('app.patient.accounts', compact('patient'));
  583. }
  584. public function companies(Request $request, Client $patient) {
  585. $companies = Company::where('is_active', true)->get();
  586. $companyClientStatusMap = [];
  587. $companyClientStatusMap['NEW'] = 'New';
  588. $companyClientStatusMap['ELIGIBILITY_VERIFIED'] = 'Eligibility Verified';
  589. $companyClientStatusMap['ELIGIBILITY_PENDING'] = 'Eligibility Pending';
  590. $companyClientStatusMap['NOT_ELIGIBLE'] = 'Not Eligible';
  591. $companyClientStatusMap['INITIAL_CONSULT'] = 'Initial Consult';
  592. $companyClientStatusMap['HST_DELIVERED'] = 'HST Delivered';
  593. $companyClientStatusMap['STUDY_PENDING'] = 'Study Pending';
  594. $companyClientStatusMap['STUDY_COMPLETED'] = 'Study Completed';
  595. $companyClientStatusMap['STUDY_INTERPRETED'] = 'Study Interpreted';
  596. $companyClientStatusMap['POST_HST_VISIT'] = 'Post HST Visit';
  597. $companyClientStatusMap['CPAP_RX'] = 'CPAP Rx';
  598. $companyClientStatusMap['ORAL_APPLIANCE_RX'] = 'Oral Appliance Rx';
  599. $companyClientStatusMap['NOT_INTERESTED'] = 'Not Interested';
  600. $companyClientStatusMap['IN_LAB_STUDY'] = 'In Lab Study';
  601. $companyClientStatusMap['UNRESPONSIVE'] = 'Unresponsive';
  602. return view('app.patient.companies', compact('patient', 'companies', 'companyClientStatusMap'));
  603. }
  604. public function rtm(Request $request, Client $patient) {
  605. return view('app.patient.rtm', compact('patient'));
  606. }
  607. public function careMonthMatrix(Request $request, CareMonth $careMonth) {
  608. return view('app.patient.care-month.matrix', [
  609. 'patient' => $careMonth->patient,
  610. 'careMonth' => $careMonth,
  611. ]);
  612. }
  613. public function clientProAccess(Request $request, Client $patient) {
  614. $rows = ClientProAccess::where('client_id', $patient->id)->get();
  615. return view('app.patient.client-pro-access', compact('patient', 'rows'));
  616. }
  617. public function clientDocuments(Request $request, Client $patient){
  618. $templates = get_doc_templates();
  619. $companyProIDs = DB::select('SELECT company_pro_id FROM company_pro_document WHERE related_client_id = ?', [$patient->id]);
  620. $companyProIDInts = [];
  621. foreach($companyProIDs as $cpId){
  622. $companyProIDInts[] = $cpId->company_pro_id;
  623. }
  624. $companyPros = CompanyPro::whereIn('id', $companyProIDInts)->get();
  625. return view('app.patient.client-documents', compact('templates', 'companyPros', 'patient'));
  626. }
  627. public function clientDocumentsRequests(Request $request, Client $patient){
  628. $templates = $this->getTemplates();
  629. $companyClients = CompanyClient::where('client_id', $patient->id)->get();
  630. $companyClientsIds = CompanyClient::where('client_id', $patient->id)->pluck('id')->toArray();
  631. $documents = CompanyProDocument::whereIn('company_client_id', $companyClientsIds)->orderBy('created_at', 'DESC')->paginate(50);
  632. return view('app.patient.client-documents-requests', compact('templates', 'patient', 'companyClients', 'documents'));
  633. }
  634. private function getTemplates(){
  635. return get_doc_templates();
  636. }
  637. public function insuranceCards(Request $request, Client $patient){
  638. $insuranceCards = InsuranceCard::where('client_id', $patient->id)->orderBy('created_at', 'DESC')->get();
  639. return view('app.patient.insurance-cards', compact('patient', 'insuranceCards'));
  640. }
  641. public function insuranceCard(Request $request, Client $patient, InsuranceCard $card){
  642. return view('app.patient.insurance-card', compact('patient', 'card'));
  643. }
  644. public function insuranceCardPutInfo(Request $request, Client $patient, InsuranceCard $card){
  645. //Use java, but currently java is not updating card info columns
  646. $data = $request->except(['uid']);
  647. foreach($data as $key=>$value){
  648. if($key === 'frontImageUrl') $card->front_image_url = $value;
  649. if($key === 'backImageUrl') $card->back_image_url = $value;
  650. }
  651. $card->save();
  652. return $this->pass($card->uid);
  653. }
  654. public function insuranceCoverageHistory(Request $request, Client $patient){
  655. $insuranceCoverageHistory = ClientPrimaryCoverage::where('client_id', $patient->id)->orderBy('created_at', 'DESC')->get();
  656. return view('app.patient.insurance-coverage-history', compact('patient', 'insuranceCoverageHistory'));
  657. }
  658. public function protocolBuilder(Request $request, Client $patient) {
  659. return view('app.patient.rtm.protocol-builder', compact('patient'));
  660. }
  661. public function checkIfCptCodeIsSubmitted(Request $request){
  662. $clientUid = $request->get('clientUid');
  663. $cptCode = $request->get('code');
  664. if(!$clientUid || !$cptCode) return $this->fail('Error');
  665. $client = Client::where('uid', $clientUid)->first();
  666. $notes = $client->notes;
  667. $isCptSubmitted = false;
  668. foreach($notes as $note){
  669. $noteClaims = $note->claims;
  670. foreach($noteClaims as $noteClaim){
  671. foreach($noteClaim->lines as $claimLine){
  672. if($claimLine->cpt == $cptCode){
  673. if($noteClaim->status == 'SUBMITTED'){
  674. $isCptSubmitted = true;
  675. }
  676. }
  677. }
  678. }
  679. }
  680. if($isCptSubmitted) return $this->pass('SUBMITTED');
  681. return $this->pass('NOT_SUBMITTED');
  682. }
  683. public function surveys(Request $request, Client $patient)
  684. {
  685. $filters = $request->all();
  686. $entityTypes = Survey::ALLOWED_ENTITIES;
  687. $surveyFormsPath = resource_path(Survey::FORM_PATH);
  688. $filesInFolder = File::allFiles($surveyFormsPath);
  689. $forms = [];
  690. foreach ($filesInFolder as $path) {
  691. $file = pathinfo($path);
  692. $fileName = $file['filename'];
  693. $internalName = explode('.', $fileName)[0];
  694. $forms[] = $internalName;
  695. }
  696. $records = Survey::where('entity_uid', $patient->uid);
  697. $searchString = $request->get('string');
  698. if($searchString){
  699. $searchString = strtolower($searchString);
  700. $records = $records->where(function ($q) use ($searchString) {
  701. return $q->orWhereRaw('LOWER(title::text) ILIKE ?', ['%' . $searchString . '%'])
  702. ->orWhereRaw('LOWER(internal_name::text) ILIKE ?', ['%' . $searchString . '%'])
  703. ->orWhereRaw('survey_data ILIKE ?', ['%' . $searchString . '%']);
  704. });
  705. }
  706. $entityType = $request->get('entity_type');
  707. if($entityType){
  708. $records = $records->where('entity_type', $entityType);
  709. }
  710. $records = $records->orderBy('created_at', 'DESC')->paginate(5);
  711. $layout = 'layouts.patient';
  712. $isPopup = false;
  713. if($request->get('popup')){
  714. $layout = 'layouts.popup';
  715. $isPopup = true;
  716. }
  717. return view('app.patient.surveys.list', compact('forms', 'records', 'entityTypes', 'filters', 'patient', 'layout', 'isPopup'));
  718. }
  719. public function surveysCreate(Request $request, Client $patient){
  720. $validator = Validator::make($request->all(), [
  721. 'entityType' => 'required|string',
  722. 'entityUid' => 'required|string',
  723. 'internalName' => 'required|string'
  724. ]);
  725. if ($validator->fails()) {
  726. return $this->fail('Invalid data provided!');
  727. }
  728. $internalName = $request->get('internalName');
  729. $entityType = $request->get('entityType');
  730. $entityUid = $request->get('entityUid');
  731. $surveyService = new SurveyService($internalName);
  732. $defaultHtml = $surveyService->defaultHTML;
  733. if(!$defaultHtml) return $this->fail('No default HTML template found for ' . $internalName);
  734. $initializedData = $surveyService->getInitializedData($entityType, $entityUid);
  735. $data = [
  736. 'internalName' => $internalName,
  737. 'title' => $request->get('title'),
  738. 'entityType' => $entityType,
  739. 'entityUid' => $entityUid,
  740. 'surveyHTML' => $defaultHtml,
  741. 'surveyDataJSON' => json_encode($initializedData)
  742. ];
  743. $response = $this->callJavaApi('/survey/create', $data);
  744. if(!$response['success']){
  745. return $this->fail(@$response['message']);
  746. }
  747. return $this->pass();
  748. }
  749. public function getEntityRecords(Request $request, Client $patient)
  750. {
  751. $term = $request->get('term');
  752. $type = $request->get('type');
  753. if(!in_array($type, Survey::ALLOWED_ENTITIES)){
  754. return $this->fail('Invalid entity type');
  755. }
  756. $records = [];
  757. if($type === 'Client'){
  758. $clients = Client::query();
  759. $clients = $clients->where('is_active', true);
  760. $clients = $clients->where(function ($q) use ($term) {
  761. return $q->orWhereRaw('LOWER(name_first::text) ILIKE ?', ['%' . $term . '%'])
  762. ->orWhereRaw('LOWER(name_last::text) ILIKE ?', ['%' . $term . '%'])
  763. ->orWhereRaw('LOWER(email_address::text) ILIKE ?', ['%' . $term . '%'])
  764. ->orWhereRaw('cell_number ILIKE ?', ['%' . $term . '%']);
  765. });
  766. $clients = $clients->orderBy('name_first', 'ASC')->limit(10)->get();
  767. $clientsData = $clients->map(function($client) {
  768. return [
  769. "uid" => $client->uid,
  770. "id" => $client->id,
  771. "text" => $client->displayName(),
  772. ];
  773. });
  774. return json_encode([
  775. "results" => $clientsData
  776. ]);
  777. }
  778. return $this->pass($records);
  779. }
  780. public function patientRequests(Request $request, Client $patient)
  781. {
  782. $patientRequests = PatientRequest::where('client_id', $patient->id)->paginate(30);
  783. $data = [
  784. 'patientRequests' => $patientRequests,
  785. 'patient' => $patient
  786. ];
  787. return view('app.patient.patient-requests', $data);
  788. }
  789. public function patientRequestCreateInvoice(Request $request, Client $client){
  790. $params = $request->all();
  791. $response = $this->callJavaApi('/invoice/create', $params);
  792. if(!$response['success']){
  793. return $this->fail(@$response['message']);
  794. }
  795. $invoiceUid = $response['data'];
  796. $invoice = Invoice::where('uid', $invoiceUid)->first();
  797. $patientRequest = PatientRequest::where('uid', $params['patientRequestUid'])->first();
  798. $patientRequest->invoice_id = $invoice->id;
  799. $patientRequest->save();
  800. return $this->pass();
  801. }
  802. }