AdminController.php 44 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Models\AccountingItem;
  4. use App\Models\AppSetting;
  5. use App\Models\Claim;
  6. use App\Models\Lead;
  7. use App\Models\Appointment;
  8. use App\Models\BDTDevice;
  9. use App\Models\CareMonth;
  10. use App\Models\Client;
  11. use App\Models\ClientBDTDevice;
  12. use App\Models\ClientInfoLine;
  13. use App\Models\Erx;
  14. use App\Models\Facility;
  15. use App\Models\Handout;
  16. use App\Models\IncomingReport;
  17. use App\Models\InternalMessage;
  18. use App\Models\MBClaim;
  19. use App\Models\MBPayer;
  20. use App\Models\Note;
  21. use App\Models\NoteTemplate;
  22. use App\Models\Pro;
  23. use App\Models\Product;
  24. use App\Models\ProProAccess;
  25. use App\Models\SectionTemplate;
  26. use App\Models\Shipment;
  27. use App\Models\SupplyOrder;
  28. use App\Models\Ticket;
  29. use Illuminate\Http\Request;
  30. use Illuminate\Support\Facades\DB;
  31. use Illuminate\Support\Facades\File;
  32. use App\Models\Bill;
  33. use App\Models\ClientSMS;
  34. use App\Models\Point;
  35. use Illuminate\Support\Facades\Http;
  36. use Illuminate\Support\Str;
  37. use PDF;
  38. use Illuminate\Support\Facades\Schema;
  39. use App\Models\AdminPatient;
  40. use App\Models\SupplyOrderView;
  41. use Illuminate\Pagination\LengthAwarePaginator;
  42. class AdminController extends Controller
  43. {
  44. public function patients(Request $request)
  45. {
  46. // DB::enableQueryLog();
  47. $filters = $request->all();
  48. $patients = AdminPatient::whereNull('shadow_pro_id');
  49. if ($request->input('name')) {
  50. $name = trim($request->input('name'));
  51. if ($name) {
  52. $patients = $patients->where(function ($q) use ($name) {
  53. $q->where('display_name', 'ILIKE', '%' . $name . '%');
  54. });
  55. }
  56. }
  57. if ($request->input('mcp')) {
  58. if($request->input('mcp') == 'NO_MCP'){
  59. $patients = $patients->whereNull('mcp_pro_id');
  60. }else{
  61. $mcp = Pro::where('uid', trim($request->input('mcp')))->first();
  62. if ($mcp) {
  63. $patients = $patients->where('mcp_pro_id', $mcp->id);
  64. }
  65. }
  66. }
  67. if ($request->input('na')) {
  68. if($request->input('na') == 'NO_NA'){
  69. $patients = $patients->whereNull('default_na_pro_id');
  70. }else{
  71. $na = Pro::where('uid', trim($request->input('na')))->first();
  72. if ($na) {
  73. $patients = $patients->where('default_na_pro_id', $na->id);
  74. }
  75. }
  76. }
  77. if ($request->input('ob')) {
  78. if ($request->input('ob') == 'yes') {
  79. $patients = $patients->where('has_mcp_done_onboarding_visit', 'YES');
  80. } else {
  81. $patients = $patients->where('has_mcp_done_onboarding_visit', '!=', 'YES');
  82. }
  83. }
  84. if ($request->input('next_appointment_category')) {
  85. if($request->input('next_appointment_category') == 'NONE'){
  86. $patients = $patients->whereNull('next_mcp_appointment_id');
  87. }else{
  88. $self = $this;
  89. $patients = $patients->whereHas('nextMcpAppointment', function($pQry) use ($request, $self){
  90. return $self->filterMultiQuery($request, $pQry, 'raw_date', 'next_appointment_category', 'next_appointment_value_1', 'next_appointment_value_2');
  91. });
  92. }
  93. }
  94. if ($request->input('chart_number')) {
  95. $patients = $patients->where('chart_number', 'ILIKE' , '%'.$request->input('chart_number').'%');
  96. }
  97. if ($request->input('home_address_state')) {
  98. if($request->input('home_address_state') == 'NONE'){
  99. $patients = $patients->whereRaw("mailing_address_state IS NULL OR TRIM(BOTH FROM mailing_address_state = ''");
  100. }else if($request->input('home_address_state') == 'NOT_MD'){
  101. $patients = $patients->whereRaw("(TRIM(BOTH FROM mailing_address_state) NOT ILIKE 'MD' AND TRIM(BOTH FROM mailing_address_state) NOT ILIKE 'MARYLAND')");
  102. }else{
  103. $patients = $patients->whereRaw("TRIM(BOTH FROM mailing_address_state) = '" . $request->input('home_address_state') . "'");
  104. }
  105. }
  106. $this->filterMultiQuery($request, $patients, 'age_in_years', 'age_category', 'age_value_1', 'age_value_2', false);
  107. $this->filterSimpleQuery($request, $patients, 'sex', 'sex');
  108. $this->filterMultiQuery($request, $patients, 'usual_bmi_max', 'bmi_category', 'bmi_value_1', 'bmi_value_2', false);
  109. $this->filterMultiQuery($request, $patients, 'most_recent_weight_at', 'last_weighed_in_category', 'last_weighed_in_value_1', 'last_weighed_in_value_2');
  110. $this->filterMultiQuery($request, $patients, 'most_recent_bp_at', 'last_bp_category', 'last_bp_value_1', 'last_bp_value_2');
  111. $this->filterMultiQuery($request, $patients, 'created_at', 'created_at', 'created_at_value_1', 'created_at_value_2');
  112. $this->filterMultiQuery($request, $patients, 'most_recent_completed_mcp_note_date', 'last_visit_category', 'last_visit_value_1', 'last_visit_value_2');
  113. $fVal = $request->input('has_email');
  114. if($fVal) {
  115. if($fVal === 'YES') {
  116. $patients = $patients->whereRaw("(email_address IS NOT NULL AND TRIM(email_address) != '')");
  117. }
  118. else {
  119. $patients = $patients->whereRaw("(email_address IS NULL OR TRIM(email_address) = '')");
  120. }
  121. }
  122. $fVal = $request->input('has_account');
  123. if($fVal) {
  124. if($fVal === 'YES') {
  125. $patients = $patients->whereRaw("((SELECT COUNT(ac.id) FROM account_client ac WHERE ac.client_id = admin_patient_list.id) > 0)");
  126. }
  127. else {
  128. $patients = $patients->whereRaw("((SELECT COUNT(ac.id) FROM account_client ac WHERE ac.client_id = admin_patient_list.id) = 0)");
  129. }
  130. }
  131. $fVal = $request->input('has_default_mcp_company_pro');
  132. if($fVal) {
  133. if($fVal === 'YES') {
  134. $patients = $patients->whereRaw("(default_mcp_company_pro_id IS NOT NULL)");
  135. }
  136. else {
  137. $patients = $patients->whereRaw("(default_mcp_company_pro_id IS NULL)");
  138. }
  139. }
  140. $fVal = $request->input('has_default_mcp_company_pro_payer');
  141. if($fVal) {
  142. if($fVal === 'YES') {
  143. $patients = $patients->whereRaw("(default_mcp_company_pro_payer_id IS NOT NULL)");
  144. }
  145. else {
  146. $patients = $patients->whereRaw("(default_mcp_company_pro_payer_id IS NULL)");
  147. }
  148. }
  149. $fVal = $request->input('has_default_mcp_company_location');
  150. if($fVal) {
  151. if($fVal === 'YES') {
  152. $patients = $patients->whereRaw("(default_mcp_company_location_id IS NOT NULL)");
  153. }
  154. else {
  155. $patients = $patients->whereRaw("(default_mcp_company_location_id IS NULL)");
  156. }
  157. }
  158. $fVal = $request->input('has_bp_device');
  159. if($fVal) {
  160. if($fVal === 'YES') {
  161. $patients = $patients->whereRaw("((SELECT count(sh.id) " .
  162. "FROM shipment sh LEFT JOIN supply_order so ON so.shipment_id = sh.id " .
  163. "WHERE so.product_id = 1 AND sh.status IN ('DELIVERED', 'DISPATCHED') AND so.client_id = admin_patient_list.id) > 0)");
  164. }
  165. else {
  166. $patients = $patients->whereRaw("((SELECT count(sh.id) " .
  167. "FROM shipment sh LEFT JOIN supply_order so ON so.shipment_id = sh.id " .
  168. "WHERE so.product_id = 1 AND sh.status IN ('DELIVERED', 'DISPATCHED') AND so.client_id = admin_patient_list.id) = 0)");
  169. }
  170. }
  171. $fVal = $request->input('has_weight_scale');
  172. if($fVal) {
  173. if($fVal === 'YES') {
  174. $patients = $patients->whereRaw("((SELECT count(sh.id) " .
  175. "FROM shipment sh LEFT JOIN supply_order so ON so.shipment_id = sh.id " .
  176. "WHERE so.product_id = 2 AND sh.status IN ('DELIVERED', 'DISPATCHED') AND so.client_id = admin_patient_list.id) > 0)");
  177. }
  178. else {
  179. $patients = $patients->whereRaw("((SELECT count(sh.id) " .
  180. "FROM shipment sh LEFT JOIN supply_order so ON so.shipment_id = sh.id " .
  181. "WHERE so.product_id = 2 AND sh.status IN ('DELIVERED', 'DISPATCHED') AND so.client_id = admin_patient_list.id) = 0)");
  182. }
  183. }
  184. $fVal = $request->input('has_pulse_ox');
  185. if($fVal) {
  186. if($fVal === 'YES') {
  187. $patients = $patients->whereRaw("((SELECT count(sh.id) " .
  188. "FROM shipment sh LEFT JOIN supply_order so ON so.shipment_id = sh.id " .
  189. "WHERE so.product_id = 3 AND sh.status IN ('DELIVERED', 'DISPATCHED') AND so.client_id = admin_patient_list.id) > 0)");
  190. }
  191. else {
  192. $patients = $patients->whereRaw("((SELECT count(sh.id) " .
  193. "FROM shipment sh LEFT JOIN supply_order so ON so.shipment_id = sh.id " .
  194. "WHERE so.product_id = 3 AND sh.status IN ('DELIVERED', 'DISPATCHED') AND so.client_id = admin_patient_list.id) = 0)");
  195. }
  196. }
  197. $fVal = $request->input('has_temp_fun');
  198. if($fVal) {
  199. if($fVal === 'YES') {
  200. $patients = $patients->whereRaw("((SELECT count(sh.id) " .
  201. "FROM shipment sh LEFT JOIN supply_order so ON so.shipment_id = sh.id " .
  202. "WHERE so.product_id = 4 AND sh.status IN ('DELIVERED', 'DISPATCHED') AND so.client_id = admin_patient_list.id) > 0)");
  203. }
  204. else {
  205. $patients = $patients->whereRaw("((SELECT count(sh.id) " .
  206. "FROM shipment sh LEFT JOIN supply_order so ON so.shipment_id = sh.id " .
  207. "WHERE so.product_id = 4 AND sh.status IN ('DELIVERED', 'DISPATCHED') AND so.client_id = admin_patient_list.id) = 0)");
  208. }
  209. }
  210. $fVal = $request->input('imei');
  211. if($fVal) {
  212. $patients = $patients->whereRaw("((SELECT count(cbd.id) FROM client_bdt_device cbd
  213. WHERE cbd.client_id = admin_patient_list.id AND cbd.device_id IN (SELECT bd.id FROM bdt_device bd WHERE bd.imei LIKE '%$fVal%' AND bd.is_active IS TRUE)) > 0)");
  214. }
  215. if($request->input('number_of_measurements')){
  216. $keyName = $request->input('number_of_measurements');
  217. $measurementCountQuery = '(SELECT COUNT(*) FROM measurement WHERE measurement.client_id = admin_patient_list.id AND is_active IS TRUE AND is_cellular IS TRUE AND is_cellular_zero IS NOT TRUE)';
  218. switch($keyName) {
  219. case 'EXACTLY':
  220. if($request->input('number_of_measurements_value_1')) {
  221. $patients->whereRaw($measurementCountQuery . '='.$request->input('number_of_measurements_value_1'));
  222. }
  223. break;
  224. case 'LESS_THAN':
  225. if($request->input('number_of_measurements_value_1')) {
  226. $patients->whereRaw($measurementCountQuery . '<='.$request->input('number_of_measurements_value_1'));
  227. }
  228. break;
  229. case 'GREATER_THAN':
  230. if($request->input('number_of_measurements_value_1')) {
  231. $patients->whereRaw($measurementCountQuery . '>='.$request->input('number_of_measurements_value_1'));
  232. }
  233. break;
  234. case 'BETWEEN':
  235. if($request->input('number_of_measurements_value_1') && $request->input('number_of_measurements_value_2')) {
  236. $patients->whereRaw($measurementCountQuery.'>='.$request->input('number_of_measurements_value_1') .' AND '. $measurementCountQuery . '<='.$request->input('number_of_measurements_value_2'));
  237. }
  238. break;
  239. case 'NOT_BETWEEN':
  240. if($request->input('number_of_measurements_value_1') && $request->input('number_of_measurements_value_2')) {
  241. $patients->where(function ($q) use ($request, $measurementCountQuery) {
  242. $q->whereRaw($measurementCountQuery . '<'.$request->input('number_of_measurements_value_1') .' OR '. $measurementCountQuery . '>'.$request->input('number_of_measurements_value_2'));
  243. });
  244. }
  245. break;
  246. }
  247. }
  248. $status = $request->input('status');
  249. if($status){
  250. if($status === 'ACTIVE'){
  251. $patients->where('is_active', true)->where(function($q) use ($status){
  252. return $q->where('client_engagement_status_category', $status)
  253. ->orWhereNull('client_engagement_status_category');
  254. });
  255. }elseif($status === 'NONE'){
  256. $patients->whereNull('client_engagement_status_category');
  257. }else {
  258. $patients->where('client_engagement_status_category', $status);
  259. }
  260. }
  261. $initiative = $request->input('initiative');
  262. if($initiative){
  263. $wildCardedInitiative = '%'.$initiative.'%';
  264. $patients->where('initiative', 'ilike', $wildCardedInitiative);
  265. }
  266. $include_test_records = $request->input('include_test_records');
  267. if(!$include_test_records && $status != 'DUMMY'){
  268. $patients = $patients->where(function ($q) {
  269. $q->whereNull('client_engagement_status_category')
  270. ->orWhere('client_engagement_status_category', '<>', 'DUMMY');
  271. });
  272. }
  273. $zero_deductible = $request->input('zero_deductible');
  274. if($zero_deductible){
  275. $patients = $patients->where(function ($q) {
  276. $q->where('mpb_remaining', 0);
  277. });
  278. }
  279. $insurance = $request->get('insurance');
  280. if($insurance){
  281. if(strpos($insurance, '_new_|') === 0){
  282. $trimmed = trim(str_replace('_new_|', '', $insurance));
  283. $condSql = "EXISTS(SELECT 1 FROM insurance_card WHERE client_id = admin_patient_list.id AND is_active = TRUE AND (carrier_category ILIKE '%{$trimmed}%' OR carrier_name ILIKE '%{$trimmed}%'))";
  284. $patients = $patients->whereRaw($condSql);
  285. }
  286. else {
  287. if($insurance === 'MEDICARE'){
  288. $patients = $patients->whereHas('effectiveClientPrimaryCoverage', function($cpcQuery) {
  289. return $cpcQuery->where('is_partbprimary', '=', 'YES');
  290. });
  291. }else{
  292. $patients = $patients->whereHas('effectiveClientPrimaryCoverage', function($cpcQuery) use ($insurance) {
  293. return $cpcQuery->where('commercial_payer_id', '=', $insurance);
  294. });
  295. }
  296. }
  297. }
  298. $companyID = $request->get('company');
  299. if($companyID){
  300. if($companyID == 'NONE'){
  301. $patients = $patients->doesntHave('companyClients');
  302. }else{
  303. $patients = $patients->whereHas('companyClients', function($qry)use($companyID){
  304. if($companyID != 'ANY'){
  305. return $qry->where('company_id', $companyID);
  306. }
  307. });
  308. }
  309. }
  310. // search by tag
  311. if ($request->input('tags')) {
  312. $tags = trim($request->input('tags'));
  313. if ($tags) {
  314. try {
  315. $condSql = "((SELECT COUNT(ct.id) FROM client_tag ct WHERE ct.client_id = admin_patient_list.id AND UPPER(ct.tag) LIKE '%" . strtoupper($tags) . "%') > 0)";
  316. $patients = $patients->whereRaw($condSql);
  317. }
  318. catch (\Exception $e) {
  319. dd($e->getMessage());
  320. }
  321. }
  322. }
  323. $sortBy = $request->input('sort_by') ?: 'name_first';
  324. $sortDir = $request->input('sort_dir') ?: 'ASC';
  325. $sortBySQL = "$sortBy $sortDir NULLS LAST";
  326. if($sortBy !== 'client_engagement_status_category' && $request->input('status')) {
  327. $sortBySQL = "client_engagement_status_category DESC NULLS LAST";
  328. }
  329. if(@$filters['mapView'] == 1){
  330. $patients = $patients->orderByRaw($sortBySQL)->paginate(100);
  331. }else{
  332. $patients = $patients->orderByRaw($sortBySQL)->paginate(25);
  333. }
  334. $oldInsurances = DB::select('SELECT DISTINCT commercial_payer_name, commercial_payer_id FROM client_primary_coverage WHERE commercial_payer_name IS NOT NULL ORDER BY commercial_payer_name ASC');
  335. $newInsurances = DB::select("select distinct COALESCE(ic.carrier_name, ic.carrier_category) as payer_name from insurance_card ic");
  336. // $qLog = DB::getQueryLog();
  337. // dd($qLog);
  338. return view('app.admin.patients', compact('patients', 'filters', 'oldInsurances', 'newInsurances'));
  339. }
  340. public function partBPatients(Request $request){
  341. $filters = $request->all();
  342. $patients = Client::whereNull('shadow_pro_id');
  343. if ($request->input('name')) {
  344. $name = trim($request->input('name'));
  345. if ($name) {
  346. $patients = $patients->where(function ($q) use ($name) {
  347. $q->where('name_first', 'ILIKE', '%' . $name . '%')
  348. ->orWhere('name_last', 'ILIKE', '%' . $name . '%');
  349. });
  350. }
  351. }
  352. if ($request->input('mcp')) {
  353. if($request->input('mcp') == 'NO_MCP'){
  354. $patients = $patients->whereNull('mcp_pro_id');
  355. }else{
  356. $mcp = Pro::where('uid', trim($request->input('mcp')))->first();
  357. if ($mcp) {
  358. $patients = $patients->where('mcp_pro_id', $mcp->id);
  359. }
  360. }
  361. }
  362. if ($request->input('na')) {
  363. if($request->input('na') == 'NO_NA'){
  364. $patients = $patients->whereNull('default_na_pro_id');
  365. }else{
  366. $na = Pro::where('uid', trim($request->input('na')))->first();
  367. if ($na) {
  368. $patients = $patients->where('default_na_pro_id', $na->id);
  369. }
  370. }
  371. }
  372. if ($request->input('next_appointment_category')) {
  373. if($request->input('next_appointment_category') == 'NONE'){
  374. $patients = $patients->whereNull('next_mcp_appointment_id');
  375. }
  376. }
  377. if ($request->input('chart_number')) {
  378. $patients = $patients->where('chart_number', 'ILIKE' , '%'.$request->input('chart_number').'%');
  379. }
  380. if ($request->input('home_address_state')) {
  381. if($request->input('home_address_state') == 'NONE'){
  382. $patients = $patients->whereNull('mailing_address_state');
  383. }else if($request->input('home_address_state') == 'NOT_MD'){
  384. $patients = $patients->where('mailing_address_state', '<>' , 'MD');
  385. }else{
  386. $patients = $patients->where('mailing_address_state', '=' , $request->input('home_address_state'));
  387. }
  388. }
  389. $this->filterMultiQuery($request, $patients, 'age_in_years', 'age_category', 'age_value_1', 'age_value_2', false);
  390. $this->filterSimpleQuery($request, $patients, 'sex', 'sex');
  391. $this->filterMultiQuery($request, $patients, 'usual_bmi_max', 'bmi_category', 'bmi_value_1', 'bmi_value_2', false);
  392. $this->filterMultiQuery($request, $patients, 'most_recent_weight_at', 'last_weighed_in_category', 'last_weighed_in_value_1', 'last_weighed_in_value_2');
  393. $this->filterMultiQuery($request, $patients, 'most_recent_bp_at', 'last_bp_category', 'last_bp_value_1', 'last_bp_value_2');
  394. if($request->input('deductible')){
  395. $keyName = $request->input('deductible');
  396. switch($keyName) {
  397. case 'EXACTLY':
  398. $patients = $patients->whereHas('effectiveClientPrimaryCoverage', function($q) use ($request){
  399. return $q->where('auto_medicare_mpb_deductible', '=', $request->input('deductible_value_1'));
  400. });
  401. break;
  402. case 'LESS_THAN':
  403. if($request->input('deductible_value_1')) {
  404. $patients = $patients->whereHas('effectiveClientPrimaryCoverage', function($q) use ($request){
  405. return $q->where('auto_medicare_mpb_deductible', '<=', $request->input('deductible_value_1'));
  406. });
  407. }
  408. break;
  409. case 'GREATER_THAN':
  410. if($request->input('deductible_value_1')) {
  411. $patients = $patients->whereHas('effectiveClientPrimaryCoverage', function($q) use ($request){
  412. return $q->where('auto_medicare_mpb_deductible', '>=', $request->input('deductible_value_1'));
  413. });
  414. }
  415. break;
  416. case 'BETWEEN':
  417. $patients = $patients->whereHas('effectiveClientPrimaryCoverage', function($q) use ($request){
  418. return $q->where('auto_medicare_mpb_deductible', '>=', $request->input('deductible_value_1'))
  419. ->where('auto_medicare_mpb_deductible', '<=', $request->input('deductible_value_2'));
  420. });
  421. break;
  422. case 'NOT_BETWEEN':
  423. if($request->input('deductible_value_1') && $request->input('deductible_value_2')) {
  424. $patients = $patients->whereHas('effectiveClientPrimaryCoverage', function($q) use ($request){
  425. return $q->where(function($qq) use ($request){
  426. return $qq->where('auto_medicare_mpb_deductible', '<', $request->input('deductible_value_1'))
  427. ->orWhere('auto_medicare_mpb_deductible', '>', $request->input('deductible_value_2'));
  428. });
  429. });
  430. }
  431. break;
  432. }
  433. }
  434. switch($request->input('status')) {
  435. case 'ACTIVE':
  436. $patients->where('is_active', true)->where('has_mcp_done_onboarding_visit', true);
  437. break;
  438. case 'AWAITING_VISIT':
  439. $patients->where('is_active', true)->where('has_mcp_done_onboarding_visit', false);
  440. break;
  441. case 'INACTIVE':
  442. $patients->where('is_active', '<>', true);
  443. break;
  444. }
  445. $initiative = $request->input('initiative');
  446. if($initiative){
  447. $wildCardedInitiative = '%'.$initiative.'%';
  448. $patients->where('initiative', 'ilike', $wildCardedInitiative);
  449. }
  450. $include_test_records = $request->input('include_test_records');
  451. if(!$include_test_records){
  452. $patients = $patients->where(function ($q) {
  453. return $q->whereNull('client_engagement_status_category')
  454. ->orWhere('client_engagement_status_category', '<>', 'DUMMY');
  455. });
  456. }
  457. $with_claim_not_closed = $request->input('with_claim_not_closed');
  458. if($with_claim_not_closed){
  459. $patients = $patients->whereHas('notes', function ($q) {
  460. return $q->where('is_claim_closed', false)
  461. ->where('is_signed_by_hcp', true)
  462. ->where('is_cancelled', false);
  463. });
  464. }
  465. $patients = $patients->whereHas('effectiveClientPrimaryCoverage', function($cpcQuery){
  466. return $cpcQuery->where('is_partbprimary', '=', 'YES');
  467. });
  468. $patients = $patients->orderBy('created_at', 'DESC')->paginate(25);
  469. return view('app.admin.part_b_patients', compact('patients', 'filters'));
  470. }
  471. public function leads(Request $request){
  472. $leads = Lead::whereNotNull('created_at');
  473. $leads = $leads->orderBy('created_at', 'DESC')->paginate(25);
  474. return view('app.admin.leads', compact('leads'));
  475. }
  476. public function notes(Request $request)
  477. {
  478. $notes = Note::paginate(5);
  479. // SELECT * FROM note WHERE client_id IN (SELECT id FROM client WHERE mcp_pro_id = :me.id);
  480. return view('app.mcp.notes', compact('notes'));
  481. }
  482. public function notes_pending_summary_suggestion(Request $request){
  483. $pro = $this->performer->pro;
  484. $data = [
  485. 'records' => $pro->get_notes_pending_summary_suggestion_as_admin()
  486. ];
  487. return view('app.admin.notes_pending_summary_suggestion', $data);
  488. }
  489. public function notes_rejected_summary_suggestion(Request $request){
  490. $pro = $this->performer->pro;
  491. $data = [
  492. 'records' => $pro->get_notes_rejected_summary_suggestion_as_admin()
  493. ];
  494. return view('app.admin.notes_rejected_summary_suggestion', $data);
  495. }
  496. public function appointments(Request $request)
  497. {
  498. $appointments = Appointment::paginate(5);
  499. return view('app.mcp.appointments', compact('appointments'));
  500. }
  501. public function bills(Request $request)
  502. {
  503. $bills = Bill::paginate(5);
  504. return view('app.mcp.bills', compact('bills'));
  505. }
  506. public function erx_and_orders(Request $request)
  507. {
  508. $erxAndOrders = Erx::paginate(5);
  509. return view('app.mcp.erx_and_orders', compact('erxAndOrders'));
  510. }
  511. public function reports(Request $request)
  512. {
  513. $data = [];
  514. return view('app.mcp.reports', $data);
  515. }
  516. public function supply_orders(Request $request)
  517. {
  518. $supplyOrders = SupplyOrderView::paginate(5);
  519. return view('app.mcp.supply_orders', compact('supplyOrders'));
  520. }
  521. public function getCreateNewPatientScriptTemplate(Request $request){
  522. $template = $request->get('template');
  523. if(!$template) return $this->fail('No script template');
  524. $path = resource_path() . '/views/app/patient/create-patient/scripts/' . $template . '.blade.php';
  525. if(!File::exists($path)) return $this->fail('Invalid script template');
  526. $templateContent = file_get_contents($path);
  527. return $this->pass($templateContent);
  528. }
  529. public function bdtDevices(Request $request)
  530. {
  531. $filters = $request->all();
  532. $bdtDevices = BDTDevice::query();
  533. $imei = $request->input('imei');
  534. if($imei){
  535. $bdtDevices = $bdtDevices->where('imei', '=', $imei);
  536. }
  537. $client = $request->input('client');
  538. if($client){
  539. $client = '%'.$client.'%';
  540. $bdtDevices = $bdtDevices->whereHas('clientBDTDevice', function($cbdtdQuery) use ($client) {
  541. return $cbdtdQuery->whereHas('client', function($clientQuery) use ($client){
  542. return $clientQuery->where(function($q) use ($client){
  543. return $q->where('name_first', 'ilike', $client)
  544. ->orWhere('name_last', 'ilike', $client)
  545. ->orWhere('cell_number', 'ilike', $client)
  546. ->orWhereRaw("name_first||' '||name_last ILIKE "."'".$client."'");
  547. });
  548. });
  549. });
  550. }
  551. $is_issued = $request->input('is_issued');
  552. if($is_issued){
  553. if($is_issued == 'YES'){
  554. $bdtDevices = $bdtDevices->whereHas('clientBDTDevice');
  555. }
  556. if($is_issued == 'NO'){
  557. $bdtDevices = $bdtDevices->whereDoesntHave('clientBDTDevice');
  558. }
  559. }
  560. $is_issued = $request->input('is_issued');
  561. if($is_issued){
  562. if($is_issued == 'YES'){
  563. $bdtDevices = $bdtDevices->whereHas('clientBDTDevice');
  564. }
  565. if($is_issued == 'NO'){
  566. $bdtDevices = $bdtDevices->whereDoesntHave('clientBDTDevice');
  567. }
  568. }
  569. $mcp = $request->input('mcp');
  570. if($mcp){
  571. $bdtDevices = $bdtDevices->whereHas('clientBDTDevice', function($cbdtdQuery) use ($mcp) {
  572. return $cbdtdQuery->whereHas('client', function($clientQuery) use ($mcp){
  573. $mcpPro = Pro::where('uid', $mcp)->first();
  574. return $clientQuery->where('mcp_pro_id', $mcpPro->id);
  575. });
  576. });
  577. }
  578. $bdtDevices = $bdtDevices->paginate(20);
  579. return view('app.admin.bdt_devices', compact('bdtDevices', 'filters'));
  580. }
  581. public function patientsMissingDefasultSettings(Request $request){
  582. $filters = $request->all();
  583. $patients = Client::whereNull('shadow_pro_id');
  584. $patients = $patients->where(function($qry){
  585. return $qry->orWhereNull('mcp_pro_id')->orWhereNull('default_mcp_company_pro_id')->orWhereNull('default_mcp_company_pro_payer_id')->orWhereNull('default_mcp_company_location_id');
  586. });
  587. if ($request->input('name')) {
  588. $name = trim($request->input('name'));
  589. if ($name) {
  590. $patients = $patients->where(function ($q) use ($name) {
  591. $q->where('name_first', 'ILIKE', '%' . $name . '%')
  592. ->orWhere('name_last', 'ILIKE', '%' . $name . '%');
  593. });
  594. }
  595. }
  596. if ($request->input('mcp')) {
  597. if($request->input('mcp') == 'NO_MCP'){
  598. $patients = $patients->whereNull('mcp_pro_id');
  599. }else{
  600. $mcp = Pro::where('uid', trim($request->input('mcp')))->first();
  601. if ($mcp) {
  602. $patients = $patients->where('mcp_pro_id', $mcp->id);
  603. }
  604. }
  605. }
  606. if ($request->input('chart_number')) {
  607. $patients = $patients->where('chart_number', 'ILIKE' , '%'.$request->input('chart_number').'%');
  608. }
  609. $status = $request->input('status');
  610. if($status){
  611. if($status == 'ACTIVE'){
  612. $patients->where('is_active', true)->where(function($q) use ($status){
  613. return $q->where('client_engagement_status_category', $status)
  614. ->orWhereNull('client_engagement_status_category');
  615. });
  616. }else {
  617. $patients->where('client_engagement_status_category', $status);
  618. }
  619. }
  620. $insurance = $request->get('insurance');
  621. if($insurance){
  622. if($insurance === 'MEDICARE'){
  623. $patients = $patients->whereHas('effectiveClientPrimaryCoverage', function($cpcQuery){
  624. return $cpcQuery->where('is_partbprimary', '=', 'YES');
  625. });
  626. }elseif($insurance === 'MEDICARE_PENDING'){
  627. $patients = $patients->whereHas('effectiveClientPrimaryCoverage', function($cpcQuery){
  628. return $cpcQuery->where('plan_type', 'MEDICARE')->where('is_covered', '!=', 'YES');
  629. });
  630. }elseif($insurance === 'NOT_COVERED'){
  631. $patients = $patients->whereHas('effectiveClientPrimaryCoverage', function($cpcQuery){
  632. return $cpcQuery->where('is_covered', '!=', 'YES');
  633. });
  634. }elseif($insurance === 'PENDING'){
  635. $patients = $patients->whereHas('effectiveClientPrimaryCoverage', function($cpcQuery){
  636. return $cpcQuery->where('is_covered', '=', 'UNKNOWN');
  637. });
  638. }
  639. else{
  640. $patients = $patients->whereDoesntHave('effectiveClientPrimaryCoverage', function($cpcQuery){
  641. return $cpcQuery->where('is_partbprimary', '=', 'YES');
  642. });
  643. }
  644. }
  645. $missing_default_settings = $request->get('missing_default_settings');
  646. if($missing_default_settings){
  647. if($missing_default_settings === 'NO_MCP') $patients = $patients->whereNull('mcp_pro_id');
  648. if($missing_default_settings === 'NO_MCP_COMPANY_PRO') $patients = $patients->whereNull('default_mcp_company_pro_id');
  649. if($missing_default_settings === 'NO_MCP_COMPANY_PRO_PAYER') $patients = $patients->whereNull('default_mcp_company_pro_payer_id');
  650. if($missing_default_settings === 'NO_MCP_COMPANY_LOCATION') $patients = $patients->whereNull('default_mcp_company_location_id');
  651. }
  652. $care_plan = $request->get('care_plan');
  653. if($care_plan){
  654. if($care_plan === 'UNSIGNED_CARE_PLANS'){
  655. $patients = $patients->whereHas('notes', function($noteQuery){
  656. return $noteQuery->where('cm_setup_manager_signature_status', '!=', 'SIGNED');
  657. });
  658. }
  659. if($care_plan === 'UNCLEARED_CARE_PLANS'){
  660. $patients = $patients->where('has_care_plan_flag', true)->where('is_flag_cleared', false);
  661. }
  662. }
  663. $patients = $patients->orderBy('created_at', 'DESC')->paginate(50);
  664. return view('app.admin.patients_missing_default_settings', compact('patients', 'filters'));
  665. }
  666. public function points(Request $request)
  667. {
  668. $filters = $request->all();
  669. $points = Point::query();
  670. $points = $points->where('is_removed', '!=', true)
  671. ->where('category', '!=', 'REVIEW')
  672. ->where('category', '!=', 'PLAN');
  673. $intentions = DB::select("SELECT intention, COUNT(intention) as count FROM point WHERE intention is not null and is_removed is not true and category != 'REVIEW' and category != 'PLAN' GROUP BY intention ORDER BY intention ASC");
  674. $categories = [];
  675. $names = [];
  676. if ($request->input('mcp')) {
  677. $mcp = Pro::where('uid', trim($request->input('mcp')))->first();
  678. if ($mcp) {
  679. // $points = $points->where('created_by_pro_id', $mcp->id);
  680. }
  681. }
  682. $implodedIntentions = null;
  683. if ($request->input('intentions')) {
  684. $points = $points->whereIn('intention', $request->input('intentions'));
  685. $implodedIntentions = join("','", $request->input('intentions'));
  686. $categories = DB::select("SELECT category, COUNT(id) as count FROM point WHERE intention in ('" . $implodedIntentions . "') and is_removed is not true and category != 'REVIEW' and category != 'PLAN' GROUP BY category ORDER BY category ASC");
  687. }
  688. if ($request->input('categories')) {
  689. $points = $points->whereIn('category', $request->input('categories'));
  690. $implodedCategories = join("','", $request->input('categories'));
  691. $names = DB::select("select (data::json)->>'name' as name, count(id) as count from point where category in ('".$implodedCategories."') and is_removed is not true and intention in ('".$implodedIntentions."') and category != 'REVIEW' and category != 'PLAN' group by 1 order by 1 asc");
  692. }
  693. if ($request->input('names')){
  694. $implodedNames = join("','", $request->input('names'));
  695. $points = $points->whereRaw("(data::json)->>'name' in ('".$implodedNames."')");
  696. }
  697. $points = $points->paginate(30);
  698. $_point = new Point;
  699. $tableName = $_point->getTable();
  700. $columns = Schema::getColumnListing($tableName);
  701. return view('app.admin.points.index', compact('points', 'filters', 'columns', 'intentions', 'categories', 'names'));
  702. }
  703. public function pointDetails(Request $request, $uid){
  704. $point = Point::where('uid', $uid)->first();
  705. $tableName = $point->getTable();
  706. $columns = Schema::getColumnListing($tableName);
  707. return view('app.admin.points.record-details', compact('point', 'columns'));
  708. }
  709. public function messages(Request $request)
  710. {
  711. $messages = InternalMessage::orderBy('created_at', 'desc')->paginate(50);
  712. return view('app.admin.messages', compact('messages'));
  713. }
  714. public function patientsNotesPointsFilter(Request $request){
  715. $filters = $request->all();
  716. $searchArrayStrings = null;
  717. $searchString = $request->get('string');
  718. if($searchString){
  719. $searchStrings = explode(',', $searchString);
  720. $searchArray = [];
  721. foreach($searchStrings as $string){
  722. $s = "'" . '%'.strtolower(trim($string)).'%'. "'";
  723. array_push($searchArray, $s);
  724. }
  725. $searchArrayStrings = implode(',', $searchArray);
  726. }
  727. //Query distinct clients who have points that contain specific substrings in the point.data
  728. $qry = "
  729. SELECT
  730. DISTINCT ON (p.client_id)
  731. p.client_id,
  732. p.id,
  733. p.uid,
  734. c.uid as client_uid,
  735. c.chart_number,
  736. c.cell_number,
  737. c.phone_home,
  738. c.phone_mobile,
  739. c.phone_work,
  740. c.email_address,
  741. c.dob,
  742. (c.name_first ||' '||c.name_last) as patient_name,
  743. (mcp.name_first ||' '||mcp.name_last) as mcp_name,
  744. c.most_recent_completed_mcp_note_date as last_visit_date,
  745. (cover.plan_type) as cover
  746. FROM
  747. point p
  748. LEFT JOIN client c on c.id = p.client_id
  749. LEFT JOIN pro mcp on mcp.id = c.mcp_pro_id
  750. LEFT JOIN client_primary_coverage cover on cover.client_id = c.id
  751. ";
  752. if($searchArrayStrings){
  753. $qry = $qry . " WHERE lower(p.data) ILIKE any (array[".$searchArrayStrings."])";
  754. }
  755. $qry = $qry . " ORDER BY p.client_id DESC, p.created_at DESC";
  756. $records = null;
  757. if($searchArrayStrings){
  758. $records = DB::select($qry);
  759. $page = $request->get('page', 1);
  760. $size = 20;
  761. $collect = collect($records);
  762. $records = new LengthAwarePaginator(
  763. $collect->forPage($page, $size),
  764. $collect->count(),
  765. $size,
  766. $page
  767. );
  768. $records->setPath(route('admin.patients-notes-points-filter'));
  769. }
  770. return view('app.admin.patients-notes-points-filter', compact('records', 'filters'));
  771. }
  772. public function manageAccountingItemsForBill(Request $request, Bill $bill) {
  773. return view('app.admin.accounting-items-for-bill', ['bill' => $bill]);
  774. }
  775. public function putClaimProperty(Request $request)
  776. {
  777. $claim = Claim::where('uid', $request->get('uid'))->first();
  778. if($claim){
  779. $json = $claim->detail_json;
  780. if($json) {
  781. $parsed = json_decode($json, true);
  782. if(!$parsed) $parsed = [];
  783. }
  784. else $parsed = [];
  785. $parsed[$request->get('name')] = $request->get('value');
  786. $json = json_encode($parsed);
  787. DB::select("UPDATE claim SET detail_json = '$json' WHERE uid = '$claim->uid'");
  788. return json_encode([
  789. "success" => true,
  790. "data" => $claim->uid
  791. ]);
  792. }
  793. return json_encode([
  794. "success" => false,
  795. "error" => "Claim does not exist."
  796. ]);
  797. }
  798. public function putAppSetting(Request $request)
  799. {
  800. $key = $request->get('key');
  801. $value = $request->get('value');
  802. $setting = AppSetting::where('key', $key)->first();
  803. if($setting){
  804. DB::select("UPDATE app_setting SET value = :value WHERE key = :key", [
  805. 'value' => $value,
  806. 'key' => $key
  807. ]);
  808. }
  809. else {
  810. $uuid = Str::uuid();
  811. DB::select("INSERT INTO app_setting
  812. (id, uid, created_at, last_updated_at, created_by_pro_id, created_by_session_id, type, detail_json, key, value, data_type)
  813. VALUES
  814. (nextval('app_setting_id_seq'), :uuid, NOW(), NOW(),
  815. NULL, NULL, 'AppSetting', NULL,
  816. :key, :value, NULL)", [
  817. 'uuid' => $uuid,
  818. 'value' => $value,
  819. 'key' => $key
  820. ]);
  821. }
  822. return json_encode([
  823. "success" => true,
  824. "data" => null
  825. ]);
  826. }
  827. public function accountingItems(Request $request) {
  828. if($request->input('_ql')) DB::enableQueryLog();
  829. $columns = [
  830. 'ai.id',
  831. 'ai.uid',
  832. 'ai.entity_type',
  833. 'ai.entity_id',
  834. 'ai.entity_uid',
  835. 'ai.pro_id',
  836. 'ai.client_id',
  837. 'ai.note_id',
  838. 'ai.care_month_id',
  839. 'ai.bill_id',
  840. 'ai.supply_order_id',
  841. 'ai.positive_or_negative',
  842. 'ai.memo',
  843. 'ai.expected_value',
  844. 'ai.received_value',
  845. 'ai.created_at',
  846. 'ai.last_updated_at',
  847. 'ai.is_open',
  848. 'ai.is_active',
  849. 'cl.uid as client_uid',
  850. 'cl.name_first as client_name_first',
  851. 'cl.name_last as client_name_last',
  852. 'p.uid as pro_uid',
  853. 'p.name_first as pro_name_first',
  854. 'p.name_last as pro_name_last',
  855. 'n.uid as note_uid',
  856. 'cm.uid as care_month_uid',
  857. 'o.uid as supply_order_uid',
  858. 'b.uid as bill_uid',
  859. ];
  860. $tables = [
  861. 'accounting_item ai',
  862. 'LEFT JOIN client cl ON cl.id = ai.client_id',
  863. 'LEFT JOIN pro p ON p.id = ai.pro_id',
  864. 'LEFT JOIN note n ON n.id = ai.note_id',
  865. 'LEFT JOIN supply_order o ON o.id = ai.supply_order_id',
  866. 'LEFT JOIN care_month cm ON cm.id = ai.care_month_id',
  867. 'LEFT JOIN bill b ON b.id = ai.bill_id',
  868. ];
  869. $conditions = ["ai.id > 0"];
  870. $params = [];
  871. if($request->input('type') == 'revenue')
  872. $conditions[] = 'ai.positive_or_negative = 0';
  873. elseif($request->input('type') == 'cost')
  874. $conditions[] = 'ai.positive_or_negative = 1';
  875. if($request->input('context')) {
  876. $conditions[] = 'ai.entity_type = :context';
  877. $params['context'] = $request->input('context');
  878. }
  879. if($request->input('open') == 'open')
  880. $conditions[] = 'ai.is_open IS TRUE';
  881. elseif($request->input('open') == 'closed')
  882. $conditions[] = 'ai.is_open IS FALSE';
  883. if($request->input('active') == 'active')
  884. $conditions[] = 'ai.is_active IS TRUE';
  885. elseif($request->input('active') == 'inactive')
  886. $conditions[] = 'ai.is_active IS FALSE';
  887. // execute
  888. $columns = implode(",\n", $columns);
  889. $tables = implode("\n", $tables);
  890. $conditions = implode(" AND\n", $conditions);
  891. $pagination = "";
  892. if($request->input('paginate')) {
  893. $page = $request->get('page', 1);
  894. $size = $request->get('size', 25);
  895. $pagination = "OFFSET ".(($page - 1) * $size) . " LIMIT $size";
  896. }
  897. $countSql = "SELECT count(ai.id) as count FROM $tables WHERE $conditions";
  898. $countResult = DB::select($countSql, $params);
  899. $dataSql = "SELECT
  900. $columns
  901. FROM
  902. $tables
  903. WHERE
  904. $conditions
  905. ORDER BY
  906. ai.created_at DESC
  907. $pagination";
  908. $dataResult = DB::select($dataSql, $params);
  909. $revenueTotalSql = "SELECT
  910. SUM(COALESCE(ai.expected_value, 0)) as total_expected_value, SUM(COALESCE(ai.received_value, 0)) as total_received_value
  911. FROM
  912. $tables
  913. WHERE
  914. $conditions AND ai.positive_or_negative = 0";
  915. $revenueTotalResult = DB::select($revenueTotalSql, $params);
  916. $costTotalSql = "SELECT
  917. SUM(COALESCE(ai.expected_value, 0)) as total_expected_value, SUM(COALESCE(ai.received_value, 0)) as total_received_value
  918. FROM
  919. $tables
  920. WHERE
  921. $conditions AND ai.positive_or_negative = 1";
  922. $costTotalResult = DB::select($costTotalSql, $params);
  923. $expectedTotal = $revenueTotalResult[0]->total_expected_value - $costTotalResult[0]->total_expected_value;
  924. $receivedTotal = $revenueTotalResult[0]->total_received_value - $costTotalResult[0]->total_received_value;
  925. $paginator = null;
  926. if($request->input('paginate')) {
  927. $paginator = new LengthAwarePaginator($dataResult, $countResult[0]->count, $size, $page);
  928. $paginator->setPath(route('accounting-items'));
  929. }
  930. $html = view('app.admin.accounting-items', [
  931. 'total' => $countResult[0]->count,
  932. 'records' => $dataResult,
  933. 'paginator' => $paginator,
  934. 'expected_total' => $expectedTotal,
  935. 'received_total' => $receivedTotal,
  936. ]);
  937. if($request->input('_ql')) printQueryLog(DB::getQueryLog());
  938. return $html;
  939. }
  940. }