AdminController.php 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138
  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('y')) {
  872. $conditions[] = 'EXTRACT(YEAR from ai.created_at) = :y';
  873. $params['y'] = intval($request->input('y'));
  874. }
  875. if($request->input('y') && $request->input('m')) {
  876. $conditions[] = 'EXTRACT(MONTH from ai.created_at) = :m';
  877. $params['m'] = intval($request->input('m'));
  878. }
  879. if($request->input('type') == 'revenue')
  880. $conditions[] = 'ai.positive_or_negative = 0';
  881. elseif($request->input('type') == 'cost')
  882. $conditions[] = 'ai.positive_or_negative = 1';
  883. if($request->input('context')) {
  884. $conditions[] = 'ai.entity_type = :context';
  885. $params['context'] = $request->input('context');
  886. }
  887. if($request->input('open') == 'open')
  888. $conditions[] = 'ai.is_open IS TRUE';
  889. elseif($request->input('open') == 'closed')
  890. $conditions[] = 'ai.is_open IS FALSE';
  891. if($request->input('active') == 'active')
  892. $conditions[] = 'ai.is_active IS TRUE';
  893. elseif($request->input('active') == 'inactive')
  894. $conditions[] = 'ai.is_active IS FALSE';
  895. if($request->input('pro')) {
  896. $conditions[] = 'p.uid = :proUid';
  897. $params['proUid'] = $request->input('pro');
  898. }
  899. if($request->input('client')) {
  900. $conditions[] = 'cl.uid = :clientUid';
  901. $params['clientUid'] = $request->input('client');
  902. }
  903. // execute
  904. $columns = implode(",\n", $columns);
  905. $tables = implode("\n", $tables);
  906. $conditions = implode(" AND\n", $conditions);
  907. $pagination = "";
  908. if($request->input('paginate')) {
  909. $page = $request->get('page', 1);
  910. $size = $request->get('size', 25);
  911. $pagination = "OFFSET ".(($page - 1) * $size) . " LIMIT $size";
  912. }
  913. $countSql = "SELECT count(ai.id) as count FROM $tables WHERE $conditions";
  914. $countResult = DB::select($countSql, $params);
  915. $dataSql = "SELECT
  916. $columns
  917. FROM
  918. $tables
  919. WHERE
  920. $conditions
  921. ORDER BY
  922. ai.created_at DESC
  923. $pagination";
  924. $dataResult = DB::select($dataSql, $params);
  925. $revenueTotalSql = "SELECT
  926. SUM(COALESCE(ai.expected_value, 0)) as total_expected_value, SUM(COALESCE(ai.received_value, 0)) as total_received_value
  927. FROM
  928. $tables
  929. WHERE
  930. $conditions AND ai.positive_or_negative = 0";
  931. $revenueTotalResult = DB::select($revenueTotalSql, $params);
  932. $costTotalSql = "SELECT
  933. SUM(COALESCE(ai.expected_value, 0)) as total_expected_value, SUM(COALESCE(ai.received_value, 0)) as total_received_value
  934. FROM
  935. $tables
  936. WHERE
  937. $conditions AND ai.positive_or_negative = 1";
  938. $costTotalResult = DB::select($costTotalSql, $params);
  939. $expectedTotal = $revenueTotalResult[0]->total_expected_value - $costTotalResult[0]->total_expected_value;
  940. $receivedTotal = $revenueTotalResult[0]->total_received_value - $costTotalResult[0]->total_received_value;
  941. $paginator = null;
  942. if($request->input('paginate')) {
  943. $paginator = new LengthAwarePaginator($dataResult, $countResult[0]->count, $size, $page);
  944. $paginator->setPath(route('accounting-items'));
  945. }
  946. // all clients
  947. $allClientsSQL = "SELECT DISTINCT(ai.client_id), cl.uid as client_uid, cl.name_first, cl.name_last
  948. FROM
  949. $tables
  950. WHERE
  951. $conditions";
  952. $allClientsResult = DB::select($allClientsSQL, $params);
  953. // all pros
  954. $allProsSQL = "SELECT DISTINCT(ai.pro_id), p.uid as pro_uid, p.name_first, p.name_last
  955. FROM
  956. $tables
  957. WHERE
  958. $conditions";
  959. $allProsResult = DB::select($allProsSQL, $params);
  960. $html = view('app.admin.accounting-items', [
  961. 'total' => $countResult[0]->count,
  962. 'records' => $dataResult,
  963. 'paginator' => $paginator,
  964. 'expected_total' => $expectedTotal,
  965. 'received_total' => $receivedTotal,
  966. 'all_clients' => $allClientsResult,
  967. 'all_pros' => $allProsResult,
  968. ]);
  969. if($request->input('_ql')) printQueryLog(DB::getQueryLog());
  970. return $html;
  971. }
  972. }