PatientController.php 35 KB

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