AdminController.php 44 KB

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