PracticeManagementController.php 214 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Models\AppSession;
  4. use App\Models\BillingReport;
  5. use App\Models\CareMonth;
  6. use App\Models\ClaimEDI;
  7. use App\Models\ClientProChange;
  8. use App\Models\Company;
  9. use App\Models\Handout;
  10. use App\Models\IncomingReport;
  11. use App\Models\MBClaim;
  12. use App\Models\Measurement;
  13. use App\Models\Bill;
  14. use App\Models\Claim;
  15. use App\Models\Client;
  16. use App\Models\McpRequest;
  17. use App\Models\McCodeCheck;
  18. use App\Models\Note;
  19. use App\Models\Pack;
  20. use App\Models\Pro;
  21. use App\Models\Product;
  22. use App\Models\ProFavorite;
  23. use App\Models\ProGeneralAvailability;
  24. use App\Models\ProProAccess;
  25. use App\Models\ProRate;
  26. use App\Models\ProSpecificAvailability;
  27. use App\Models\ProSpecificUnavailability;
  28. use App\Models\ProTeam;
  29. use App\Models\ProTextShortcut;
  30. use App\Models\ProTransaction;
  31. use App\Models\Shipment;
  32. use App\Models\SupplyOrder;
  33. use App\Models\Team;
  34. use App\Models\Ticket;
  35. use App\Models\AccountInvite;
  36. use App\Models\ClientMeasurementDaysPerMonth;
  37. use App\Models\ClientBDTDevice;
  38. use App\Models\ClientMemo;
  39. use Carbon\Carbon;
  40. use Illuminate\Pagination\LengthAwarePaginator;
  41. use Illuminate\Support\Facades\DB;
  42. use Illuminate\Support\Facades\Http;
  43. use PDF;
  44. use DateTime;
  45. use DateTimeZone;
  46. use Illuminate\Http\Request;
  47. use App\Models\SegmentTemplate;
  48. use App\Models\VisitTemplate;
  49. use App\Models\VisitTemplateSegmentTemplate;
  50. use App\Models\VisitTemplateAccess;
  51. use App\Models\ClientReviewRequest;
  52. class PracticeManagementController extends Controller
  53. {
  54. public function incomingReports(Request $request, $filter = '')
  55. {
  56. $incomingReports = IncomingReport::where('is_entry_error', '<>', true);
  57. if($filter === 'not-signed') {
  58. $incomingReports = $incomingReports->where('has_hcp_pro_signed', '<>', true);
  59. }
  60. else if($filter === 'signed') {
  61. $incomingReports = $incomingReports->where('has_hcp_pro_signed', true);
  62. }
  63. $incomingReports = $incomingReports->paginate(25);
  64. return view('app.practice-management.incoming-reports', compact('incomingReports', 'filter'));
  65. }
  66. public function rpmMatrix(Request $request)
  67. {
  68. $proID = $this->performer()->pro->id;
  69. $isAdmin = $this->performer()->pro->pro_type == 'ADMIN';
  70. $query = Client::whereNull('shadow_pro_id');
  71. if(!$isAdmin) $query->where('mcp_pro_id', '=', $proID);
  72. $clients = $query->orderByRaw('most_recent_cellular_measurement_at desc nulls last')
  73. ->paginate(50);
  74. return view ('app.practice-management.rpm-matrix', compact('clients'));
  75. }
  76. public function mcCodeChecks(Request $request)
  77. {
  78. $checks = McCodeCheck::orderBy('next_eligible_date_professional', 'asc')->get();
  79. return view ('app.practice-management.mc-code-checks', compact('checks'));
  80. }
  81. public function remoteMonitoringReport(Request $request)
  82. {
  83. $rows = null;
  84. $proID = $this->performer()->pro->id;
  85. $isAdmin = $this->performer()->pro->pro_type == 'ADMIN';
  86. //$rows = $isAdmin ? ClientMeasurementDaysPerMonth::all() : ClientMeasurementDaysPerMonth::where('mcp_pro_id', $proID)->orderBy('year_month', 'asc')->orderBy('num_of_days_with_measurement', 'asc')->get();
  87. $query = CareMonth::whereNotNull('mcp_pro_id')
  88. ->where('number_of_days_with_remote_measurements', '>=', 16)
  89. ->where('days_between_most_recent_mcp_note_date_and_end_of_care_month', '<=', 90);
  90. if(!$isAdmin) $query->where('mcp_pro_id', '=', $proID);
  91. if($request->get('show_billing_not_closed_only')){
  92. $query->where(function($q){
  93. return $q->where('is_bill_closed', false)->orWhereNull('is_bill_closed');
  94. });
  95. }
  96. $rows = $query->orderByRaw(DB::raw('start_date DESC'))->paginate(100) ;
  97. return view ('app.practice-management.remote-monitoring-report', compact('rows', 'isAdmin'));
  98. }
  99. public function dailyTreatmentServices(Request $request) {
  100. $type = $request->input('t');
  101. $fPro = null;
  102. if($type === 'pro') {
  103. $fPro = Pro::where('uid', $request->input('p'))->first();
  104. $rows = DB::select(DB::raw("
  105. SELECT effective_date, hcp_pro_id, p.name_first, p.name_last, count(*), sum(number_of_units) as units
  106. FROM bill JOIN pro p on p.id = bill.hcp_pro_id
  107. WHERE code = 'Treatment Services'
  108. GROUP BY effective_date, hcp_pro_id, p.name_first, p.name_last
  109. ORDER BY effective_date DESC, p.name_first ASC, p.name_last ASC
  110. "));
  111. }
  112. else {
  113. $rows = DB::select(DB::raw("
  114. SELECT effective_date, count(*), sum(number_of_units) as units FROM bill WHERE code = 'Treatment Services' GROUP BY effective_date ORDER BY effective_date DESC
  115. "));
  116. }
  117. return view ('app.practice-management.daily-treatment-services', compact('rows'));
  118. }
  119. public function clientProChanges(Request $request)
  120. {
  121. $filters = $request->all();
  122. $rows = ClientProChange::query();
  123. $associationTypes = DB::table('client_pro_change')->select('responsibility_type')->distinct()->pluck('responsibility_type')->toArray();
  124. $this->filterMultiQuery($request, $rows, 'created_at', 'date_category', 'date_value_1', 'date_value_2');
  125. $this->filterSimpleQuery($request, $rows, 'responsibility_type', 'responsibility_type');
  126. $oldProUid = $request->get('old_pro');
  127. if($oldProUid){
  128. $oldPro = Pro::where('uid', $oldProUid)->first();
  129. $rows = $rows->where('previous_pro_id',$oldPro->id);
  130. }
  131. $newProUid = $request->get('new_pro');
  132. if($newProUid){
  133. $newPro = Pro::where('uid', $newProUid)->first();
  134. $rows = $rows->where('new_pro_id',$newPro->id);
  135. }
  136. $rows = $rows->orderByRaw('created_at::date DESC')->orderBy('client_id', 'desc')->paginate(20);
  137. return view ('app.practice-management.client-pro-changes', compact('rows', 'filters', 'associationTypes'));
  138. }
  139. public function billingReport(Request $request)
  140. {
  141. $filters = $request->all();
  142. $claimStatus = $request->get('status');
  143. // conditions
  144. $conditions = [];
  145. $conditions[] = "(c.client_engagement_status_category != 'DUMMY')";
  146. $no_claims = $request->get('no_claims');
  147. $zero_deductible = $request->get('zero_deductible');
  148. $claim_status = $request->get('claim_status');
  149. $verified = $request->get('verified');
  150. $from = $request->get('from');
  151. $to = $request->get('to');
  152. if($no_claims){
  153. $conditions[] = "(clm.id IS NULL)";
  154. }
  155. if($zero_deductible){
  156. $conditions[] = "(SELECT count(*) FROM client_primary_coverage cpc WHERE
  157. ((cpc.plan_type = 'MEDICARE' AND cpc.auto_medicare_mpb_deductible > 0) OR (cpc.plan_type = 'COMMERCIAL' AND cpc.deductible_amount > 0))
  158. AND c.effective_client_primary_coverage_id = cpc.id) = 0";
  159. }
  160. if($claim_status){
  161. $conditions[] = "(clm.status = '{$claim_status}')";
  162. }
  163. if($verified){
  164. if($verified == 'VERIFIED'){
  165. $conditions[] = "(SELECT count(*) FROM bill b WHERE
  166. b.is_verified IS TRUE AND b.is_cancelled IS FALSE AND b.note_id = n.id) > 0";
  167. }
  168. if($verified == 'UNVERIFIED'){
  169. $conditions[] = "(SELECT count(*) FROM bill b WHERE
  170. b.is_verified IS FALSE AND b.is_cancelled IS FALSE AND b.note_id = n.id) > 0";
  171. }
  172. }
  173. if($from) {
  174. $conditions[] = "(n.effective_dateest::date >= '{$from}')";
  175. }
  176. if($to) {
  177. $conditions[] = "(n.effective_dateest::date <= '{$to}')";
  178. }
  179. $from = "FROM note n
  180. JOIN (SELECT count(*) AS count,
  181. bill.note_id
  182. FROM bill
  183. WHERE NOT bill.is_cancelled
  184. GROUP BY bill.note_id) bill_sum ON n.id = bill_sum.note_id
  185. LEFT JOIN client c ON n.client_id = c.id
  186. LEFT JOIN pro p ON n.hcp_pro_id = p.id
  187. LEFT JOIN claim clm on n.id = clm.note_id
  188. LEFT JOIN client_primary_coverage cpc on c.effective_client_primary_coverage_id = cpc.id";
  189. $defaultPageSize = 25;
  190. $page = $request->input('page') ?: 1;
  191. $perPage = $request->input('per_page') ?: $defaultPageSize;
  192. $offset = ($page - 1) * $perPage;
  193. $countQuery = "
  194. SELECT COUNT(*)
  195. $from
  196. WHERE n.is_cancelled IS NOT TRUE AND " . implode(' AND ', $conditions) . "
  197. ";
  198. $countResult = DB::select($countQuery);
  199. $total = $countResult[0]->count;
  200. $sql = "
  201. SELECT c.id AS client_id,
  202. c.uid AS client_uid,
  203. n.id AS note_id,
  204. n.uid AS note_uid,
  205. p.id AS pro_id,
  206. p.uid AS pro_uid,
  207. (('https://care.leadershiphealth.org/mc/patients/view/'::text || c.uid::text) || '/notes/view/'::text) ||
  208. n.uid::text AS link,
  209. c.name_last AS client_last,
  210. c.name_first AS client_first,
  211. p.name_last AS pro_last,
  212. p.name_first AS pro_first,
  213. n.effective_dateest AS note_date,
  214. n.new_or_fu AS new_or_fu_auto,
  215. n.new_or_fu_or_na,
  216. n.new_or_fu_or_na::text = n.new_or_fu AS new_or_fu_auto_match,
  217. n.method,
  218. n.is_bill_closed AS is_billing_closed,
  219. n.is_claim_closed AS is_claiming_closed,
  220. bill_sum.count AS bill_count,
  221. clm.status AS claim_status,
  222. cpc.plan_type AS plan_type,
  223. cpc.auto_medicare_is_partbprimary AS auto_medicare_is_partbprimary,
  224. cpc.auto_medicare_mpb_deductible AS medicare_deductible,
  225. cpc.deductible_amount AS commercial_deductible,
  226. (SELECT name from payer WHERE payer.id = cpc.commercial_payer_id) AS payer_name,
  227. array_to_string(
  228. ARRAY(SELECT ((((bill.code::text || ' | '::text) || bill.number_of_units::text) || ' units | '::text) ||
  229. round(bill.number_of_units * 60::numeric)) || ' mins'::text
  230. FROM bill
  231. WHERE bill.note_id = n.id), '
  232. '::text) AS bills,
  233. array_to_string(ARRAY(SELECT (note_reason.code || ' | '::text) || note_reason.description
  234. FROM note_reason
  235. WHERE note_reason.note_id = n.id
  236. ORDER BY note_reason.position_index), '
  237. '::text) AS icds,
  238. array_to_string(ARRAY(SELECT ((cl.cpt::text || ' | '::text) || cl.units::text) || ' units'::text
  239. FROM claim_line cl
  240. WHERE (cl.claim_id IN (SELECT claim.id
  241. FROM claim
  242. WHERE claim.note_id = n.id))
  243. ORDER BY cl.position_index), '
  244. '::text) AS claim_lines,
  245. array_to_string(ARRAY(SELECT cl2.status FROM claim cl2 WHERE cl2.note_id = n.id
  246. ORDER BY cl2.created_at DESC), '
  247. '::text) AS claim_statuses
  248. $from
  249. WHERE n.is_cancelled IS NOT TRUE AND " . implode(' AND ', $conditions) . "
  250. ORDER BY n.effective_dateest DESC NULLS LAST, p.id
  251. OFFSET {$offset} LIMIT {$perPage}
  252. ";
  253. $rows = DB::select($sql);
  254. $claimStatuses = DB::select('SELECT distinct status FROM claim ORDER BY status DESC');
  255. $paginator = new LengthAwarePaginator($rows, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  256. $perPage = $request->input('per_page') ?: $defaultPageSize;
  257. $paginator->setPath(route('practice-management.billing-report'));
  258. return view('app.practice-management.billing-report', compact('rows', 'claimStatuses', 'filters', 'paginator'));
  259. }
  260. public function dashboard(Request $request)
  261. {
  262. return view('app.practice-management.dashboard');
  263. }
  264. public function rates(Request $request, $selectedProUid = 'all')
  265. {
  266. $proUid = $selectedProUid ? $selectedProUid : 'all';
  267. $rates = ProRate::where('is_active', true);
  268. if ($proUid !== 'all') {
  269. $selectedPro = Pro::where('uid', $proUid)->first();
  270. $rates = $rates->where('pro_id', $selectedPro->id);
  271. }
  272. $rates = $rates->orderBy('pro_id', 'asc')->get();
  273. $pros = $this->pros;
  274. return view('app.practice-management.rates', compact('rates', 'pros', 'selectedProUid'));
  275. }
  276. public function previousBills(Request $request)
  277. {
  278. return view('app.practice-management.previous-bills');
  279. }
  280. public function financialTransactions(Request $request)
  281. {
  282. $pro = $this->performer()->pro;
  283. $transactions = null;
  284. if($pro->pro_type === 'ADMIN') {
  285. $transactions = ProTransaction::whereNotNull('id');
  286. }
  287. else {
  288. $transactions = ProTransaction::where('pro_id', $pro->id);
  289. }
  290. $filter = $request->input('p');
  291. if ($filter) {
  292. $filterPro = Pro::where('uid', $filter)->first();
  293. if($filterPro) {
  294. $transactions = $transactions->where('pro_id', '=', $filterPro->id);
  295. }
  296. }
  297. $filter = $request->input('t');
  298. if ($filter) {
  299. $transactions = $transactions->where('plus_or_minus', '=', $filter);
  300. }
  301. $filter = $request->input('c');
  302. if ($filter) {
  303. $transactions = $transactions->where('company_id', '=', $filter);
  304. }
  305. $filter = $request->input('bs');
  306. if ($filter) {
  307. $transactions = $transactions->where('created_at', '>=', $filter);
  308. }
  309. $filter = $request->input('be');
  310. if ($filter) {
  311. $transactions = $transactions->where('created_at', '<=', $filter);
  312. }
  313. $transactions = $transactions->orderBy('created_at', 'desc')->paginate();
  314. $companies = Company::where('is_active', true)->orderBy('name')->get();
  315. return view('app.practice-management.financial-transactions', compact('transactions', 'companies'));
  316. }
  317. public function pendingBillsToSign(Request $request)
  318. {
  319. return view('app.practice-management.pending-bills-to-sign');
  320. }
  321. public function HR(Request $request)
  322. {
  323. return view('app.practice-management.hr');
  324. }
  325. public function directDepositSettings(Request $request)
  326. {
  327. return view('app.practice-management.direct-deposit-settings');
  328. }
  329. public function w9(Request $request)
  330. {
  331. return view('app.practice-management.w9');
  332. }
  333. public function contract(Request $request)
  334. {
  335. return view('app.practice-management.contract');
  336. }
  337. public function notes(Request $request, $filter = '')
  338. {
  339. $proID = $this->performer()->pro->id;
  340. $query = Note::where('is_cancelled', FALSE)->where('is_core_note', '<>', true);
  341. if ($this->performer()->pro->pro_type !== 'ADMIN') {
  342. $query = $query->where('hcp_pro_id', $proID);
  343. }
  344. switch ($filter) {
  345. case 'not-yet-signed':
  346. $query = $query->where('is_signed_by_hcp', false);
  347. break;
  348. case 'not-yet-signed-but-ally-signed':
  349. $query = $query->where('is_signed_by_hcp', false)->where('is_signed_by_ally', true);
  350. break;
  351. case 'without-bills':
  352. $query = $query->where('is_signed_by_hcp', true)->where('is_cancelled', false)->whereDoesntHave('bills');
  353. break;
  354. // more cases can be added as needed
  355. default:
  356. break;
  357. }
  358. $notes = $query->orderBy('created_at', 'desc')->paginate(30);
  359. return view('app.practice-management.notes', compact('notes', 'filter'));
  360. }
  361. public function allNotes(Request $request)
  362. {
  363. $filters = $request->all();
  364. $query = Note::query();
  365. $query = $query->where('is_core_note', false);
  366. $this->filterMultiQuery($request, $query, 'created_at', 'created_at_category', 'created_at_value_1', 'created_at_value_2');
  367. $this->filterMultiQuery($request, $query, 'effective_dateest', 'effective_date_category', 'effective_date_value_1', 'effective_date_value_2');
  368. $filterByProsIDs = $request->get('pros');
  369. if($filterByProsIDs && count($filterByProsIDs)){
  370. $query = $query->whereIn('hcp_pro_id', $filterByProsIDs);
  371. }
  372. $filterByAllyProsIDs = $request->get('ally_pros');
  373. if($filterByAllyProsIDs && count($filterByAllyProsIDs)){
  374. $query = $query->whereIn('ally_pro_id', $filterByAllyProsIDs);
  375. }
  376. $filterByPatientsIDs = $request->get('patients');
  377. if($filterByPatientsIDs && count($filterByPatientsIDs)){
  378. $query = $query->whereIn('client_id', $filterByPatientsIDs);
  379. }
  380. $status = $request->get('status');
  381. if($status){
  382. if($status == 'CANCELLED') $query = $query->where('is_cancelled', true);
  383. if($status == 'SIGNED') $query = $query->where('is_signed_by_hcp', true);
  384. if($status == 'NOT_YET_SIGNED') $query = $query->where('is_signed_by_hcp', false);
  385. if($status == 'NOT_YET_SIGNED_BUT_ALLY_SIGNED') $query = $query->where('is_signed_by_hcp', false)->where('is_signed_by_ally', true);
  386. if($status == 'WITH_BILLS') $query = $query->where('is_signed_by_hcp', true)->where('is_cancelled', false)->whereHas('bills');
  387. if($status == 'WITHOUT_BILLS') $query = $query->where('is_signed_by_hcp', true)->where('is_cancelled', false)->whereDoesntHave('bills');
  388. }
  389. $allProsWithNotesIDs = DB::table('note')->pluck('hcp_pro_id')->toArray();
  390. $allProsWithNotes = Pro::whereIn('id', $allProsWithNotesIDs)->get();
  391. $allPatientsWithNotesIDs = DB::table('note')->pluck('client_id')->toArray();
  392. $allPatientsWithNotes = Client::whereIn('id', $allPatientsWithNotesIDs)->get();
  393. $allAllyProsIDs = DB::table('note')->pluck('ally_pro_id')->toArray();
  394. $allAllyPros = Pro::whereIn('id', $allAllyProsIDs)->get();
  395. $notes = $query->orderBy('created_at', 'desc')->paginate(30);
  396. return view('app.practice-management.all-notes', compact('notes', 'filters','allProsWithNotes', 'allPatientsWithNotes', 'allAllyPros'));
  397. }
  398. public function dnaNotesPendingMcpSign(Request $request)
  399. {
  400. $proID = $this->performer()->pro->id;
  401. $notes = Note::where('ally_pro_id', $proID)
  402. ->where('is_signed_by_hcp', false)
  403. ->where('is_cancelled', false)
  404. ->orderBy('created_at', 'desc')
  405. ->get();
  406. return view('app.practice-management.dna-notes-pending-mcp-sign', compact('notes'));
  407. }
  408. public function naBillableSignedNotes(Request $request)
  409. {
  410. $notes = Note
  411. ::where('is_signed_by_hcp', TRUE)
  412. ->where('ally_pro_id', $this->performer()->pro->id)
  413. ->where('is_cancelled', FALSE)
  414. ->whereRaw("
  415. (
  416. SELECT count(bill.id)
  417. FROM bill WHERE
  418. bill.is_cancelled = FALSE AND
  419. bill.generic_pro_id = {$this->performer()->pro->id} AND
  420. bill.note_id = note.id
  421. ) = 0
  422. ");
  423. $notes = $notes->orderBy('created_at', 'desc')->get();
  424. return view('app.practice-management.na-billable-signed-notes', compact('notes'));
  425. }
  426. public function bills(Request $request, $filter = '')
  427. {
  428. $proID = $this->performer()->pro->id;
  429. $isAdmin = $this->performer()->pro->pro_type === 'ADMIN';
  430. $query = Bill::where('is_cancelled', false)->whereRaw("(bill_service_type = 'NOTE' OR bill_service_type = 'GENERIC')");
  431. switch ($filter) {
  432. case 'not-yet-signed':
  433. $query = $query
  434. ->where(function ($q) use ($proID, $isAdmin) {
  435. $q->where(function ($q2) use ($proID, $isAdmin) {
  436. $q2->where('is_signed_by_hcp', false);
  437. if (!$isAdmin) {
  438. $q2->where('hcp_pro_id', $proID);
  439. } else {
  440. $q2->whereNotNull('hcp_pro_id');
  441. }
  442. })->orWhere(function ($q2) use ($proID, $isAdmin) {
  443. $q2->where('is_signed_by_generic_pro', false);
  444. if (!$isAdmin) {
  445. $q2->where('generic_pro_id', $proID);
  446. }
  447. else {
  448. $q2->whereNotNull('generic_pro_id');
  449. }
  450. });
  451. });
  452. break;
  453. case 'previous':
  454. $query = $query
  455. ->where(function ($q) use ($proID, $isAdmin) {
  456. $q->where(function ($q2) use ($proID, $isAdmin) {
  457. $q2->where('is_signed_by_hcp', true);
  458. if (!$isAdmin) {
  459. $q2->where('hcp_pro_id', $proID);
  460. } else {
  461. $q2->whereNotNull('hcp_pro_id');
  462. }
  463. })->orWhere(function ($q2) use ($proID, $isAdmin) {
  464. $q2->where('is_signed_by_generic_pro', true);
  465. if (!$isAdmin) {
  466. $q2->where('generic_pro_id', $proID);
  467. }
  468. else {
  469. $q2->whereNotNull('generic_pro_id');
  470. }
  471. });
  472. });
  473. break;
  474. // more cases can be added as needed
  475. default:
  476. $query = $query
  477. ->where(function ($q) use ($proID, $isAdmin) {
  478. $q->where(function ($q2) use ($proID, $isAdmin) {
  479. if (!$isAdmin) {
  480. $q2->where('hcp_pro_id', $proID);
  481. } else {
  482. $q2->whereNotNull('hcp_pro_id');
  483. }
  484. })->orWhere(function ($q2) use ($proID, $isAdmin) {
  485. if (!$isAdmin) {
  486. $q2->where('generic_pro_id', $proID);
  487. }
  488. else {
  489. $q2->whereNotNull('generic_pro_id');
  490. }
  491. });
  492. });
  493. break;
  494. }
  495. $bills = $query->orderBy('created_at', 'desc')->paginate(50);
  496. return view('app.practice-management.bills', compact('bills', 'filter'));
  497. }
  498. public function rmBillsToSign(Request $request)
  499. {
  500. $performerProID = $this->performer()->pro->id;
  501. $bills = Bill::where('is_cancelled', false)->where('cm_or_rm', 'RM')
  502. ->where(function ($q) use ($performerProID) {
  503. $q
  504. ->where(function ($q2) use ($performerProID) {
  505. $q2->where('hcp_pro_id', $performerProID)->where('is_signed_by_hcp', false);
  506. })
  507. ->orWhere(function ($q2) use ($performerProID) {
  508. $q2->where('rme_pro_id', $performerProID)->where('is_signed_by_rme', false);
  509. })
  510. ->orWhere(function ($q2) use ($performerProID) {
  511. $q2->where('rmm_pro_id', $performerProID)->where('is_signed_by_rmm', false);
  512. })
  513. ->orWhere(function ($q2) use ($performerProID) {
  514. $q2->where('generic_pro_id', $performerProID)->where('is_signed_by_generic_pro', false);
  515. });
  516. })
  517. ->orderBy('effective_date', 'desc')
  518. ->get();
  519. return view('app.practice-management.rm-bills-to-sign', compact('bills'));
  520. }
  521. public function unacknowledgedCancelledBills(Request $request)
  522. {
  523. $bills = Bill::where('hcp_pro_id', $this->performer()->pro->id)
  524. ->where('is_cancelled', true)
  525. ->where('is_cancellation_acknowledged', false)
  526. ->orderBy('created_at', 'desc')
  527. ->get();
  528. return view('app.practice-management.unacknowledged-cancelled-bills', compact('bills'));
  529. }
  530. public function myTickets(Request $request, $filter = 'open')
  531. {
  532. $performer = $this->performer();
  533. $myTickets = Ticket::where(function ($q) use ($performer) {
  534. $q->where('assigned_pro_id', $performer->pro_id)
  535. ->orWhere('manager_pro_id', $performer->pro_id)
  536. ->orWhere('ordering_pro_id', $performer->pro_id)
  537. ->orWhere('initiating_pro_id', $performer->pro_id);
  538. })->where('category', 'other');
  539. if ($filter === 'open') {
  540. $myTickets = $myTickets->where('is_open', true);
  541. } else if ($filter === 'closed') {
  542. $myTickets = $myTickets->where('is_open', false);
  543. }
  544. $myTickets = $myTickets->orderBy('created_at', 'desc')->get();
  545. return view('app.practice-management.my-tickets', compact('myTickets', 'filter'));
  546. }
  547. public function myTextShortcuts(Request $request)
  548. {
  549. $personalShortcuts = DB::table('pro_text_shortcut')
  550. ->leftJoin('pro', 'pro_text_shortcut.pro_id', '=', 'pro.id')
  551. ->select(
  552. 'pro_text_shortcut.uid',
  553. 'pro_text_shortcut.shortcut',
  554. 'pro_text_shortcut.text',
  555. 'pro.name_first',
  556. 'pro.name_last'
  557. )
  558. ->where('pro_text_shortcut.is_removed', false);
  559. if($this->performer()->pro->pro_type !== 'ADMIN') {
  560. $personalShortcuts = $personalShortcuts->where('pro_id', $this->performer()->pro_id);
  561. }
  562. $personalShortcuts = $personalShortcuts
  563. ->orderBy('pro.name_last')
  564. ->orderBy('pro.name_first')
  565. ->orderBy('pro_text_shortcut.shortcut')
  566. ->get();
  567. $globalTextShortcuts = DB::table('pro_text_shortcut')
  568. ->select(
  569. 'pro_text_shortcut.uid',
  570. 'pro_text_shortcut.shortcut',
  571. 'pro_text_shortcut.text'
  572. )
  573. ->whereNull('pro_id')
  574. ->where('pro_text_shortcut.is_removed', false)
  575. ->orderBy('pro_text_shortcut.shortcut')
  576. ->get();
  577. return view('app.practice-management.my-text-shortcuts', compact('personalShortcuts', 'globalTextShortcuts'));
  578. }
  579. public function myFavorites(Request $request, $filter = 'all')
  580. {
  581. $performer = $this->performer();
  582. $myFavorites = ProFavorite::where('pro_id', $performer->pro_id)->where('is_removed', false);
  583. if ($filter !== 'all') {
  584. $myFavorites = $myFavorites->where('category', $filter);
  585. }
  586. $myFavorites = $myFavorites
  587. ->whereIn('category', ['allergy', 'medication', 'problem'])
  588. ->orderBy('category', 'asc')
  589. ->orderBy('position_index', 'asc')
  590. ->get();
  591. return view('app.practice-management.my-favorites', compact('myFavorites', 'filter'));
  592. }
  593. public function patientsWithoutCoverage(Request $request, $filter = 'all')
  594. {
  595. $performer = $this->performer();
  596. $sql = "SELECT cl.uid, cl.name_first, cl.name_last FROM client cl ";
  597. $joinClause = 'LEFT JOIN client_primary_coverage cpc ON cl.effective_client_primary_coverage_id = cpc.id ';
  598. $withoutCondition = "cl.effective_client_primary_coverage_id IS NULL";
  599. $pendingCondition = "
  600. (cl.effective_client_primary_coverage_id IS NOT NULL -- coverage exists, but status is null or unknown
  601. AND (
  602. (cpc.plan_type = 'MEDICARE' AND (cpc.is_partbprimary = 'UNKNOWN' OR cpc.is_partbprimary IS NULL))
  603. OR
  604. (cpc.plan_type != 'MEDICARE' AND
  605. (cpc.manual_determination_category = 'UNKNOWN' OR cpc.manual_determination_category IS NULL))
  606. ))";
  607. switch ($filter) {
  608. case 'without-coverage-information':
  609. $sql .= 'WHERE cl.shadow_pro_id IS NULL AND ';
  610. $sql .= $withoutCondition;
  611. break;
  612. case 'pending-coverage-verification':
  613. $sql .= $joinClause . 'WHERE cl.shadow_pro_id IS NULL AND ';
  614. $sql .= $pendingCondition;
  615. break;
  616. default:
  617. $sql .= $joinClause . 'WHERE cl.shadow_pro_id IS NULL AND ';
  618. $sql .= '(' . $withoutCondition . ' OR ' . $pendingCondition . ')';
  619. break;
  620. }
  621. $sql .= ' ORDER BY cl.name_first ASC';
  622. $pendingCoverage = DB::select(DB::raw($sql));
  623. return view('app.practice-management.patients-without-coverage', compact('pendingCoverage', 'filter'));
  624. }
  625. public function proAvailability(Request $request, $proUid = null)
  626. {
  627. $performer = $this->performer();
  628. $pro = $performer->pro;
  629. if ($proUid) {
  630. $pro = Pro::where('uid', $proUid)->first();
  631. }
  632. if ($request->get('pro_uid')) {
  633. $proUid = $request->get('pro_uid');
  634. $pro = Pro::where('uid', $proUid)->first();
  635. }
  636. $selectedProUid = $pro->uid;
  637. $pros = $this->pros;
  638. $generalAvailabilitiesList = ProGeneralAvailability::where('pro_id', $pro->id)->where('is_cancelled', false)->orderBy('created_at', 'asc')->get();
  639. $generalAvailabilities = [
  640. 'MONDAY' => [],
  641. 'TUESDAY' => [],
  642. 'WEDNESDAY' => [],
  643. 'THURSDAY' => [],
  644. 'FRIDAY' => [],
  645. 'SATURDAY' => [],
  646. 'SUNDAY' => [],
  647. ];
  648. foreach ($generalAvailabilitiesList as $ga) {
  649. if ($ga->day_of_week == 'MONDAY') {
  650. $generalAvailabilities['MONDAY'][] = $ga;
  651. }
  652. if ($ga->day_of_week == 'TUESDAY') {
  653. $generalAvailabilities['TUESDAY'][] = $ga;
  654. }
  655. if ($ga->day_of_week == 'WEDNESDAY') {
  656. $generalAvailabilities['WEDNESDAY'][] = $ga;
  657. }
  658. if ($ga->day_of_week == 'THURSDAY') {
  659. $generalAvailabilities['THURSDAY'][] = $ga;
  660. }
  661. if ($ga->day_of_week == 'FRIDAY') {
  662. $generalAvailabilities['FRIDAY'][] = $ga;
  663. }
  664. if ($ga->day_of_week == 'SATURDAY') {
  665. $generalAvailabilities['SATURDAY'][] = $ga;
  666. }
  667. if ($ga->day_of_week == 'SUNDAY') {
  668. $generalAvailabilities['SUNDAY'][] = $ga;
  669. }
  670. }
  671. $specificAvailabilities = ProSpecificAvailability::where('pro_id', $pro->id)->where('is_cancelled', false)->orderBy('start_time')->get();
  672. $specificUnavailabilities = ProSpecificUnavailability::where('pro_id', $pro->id)->where('is_cancelled', false)->orderBy('start_time', 'asc')->get();
  673. //events for the calendar
  674. $startDate = date('Y-m-d', strtotime("sunday -1 week"));
  675. $endDateTime = new DateTime($startDate);
  676. $endDateTime->modify('+6 day');
  677. $endDate = $endDateTime->format("Y-m-d");
  678. $eventsData = $pro->getAvailabilityEvents($startDate, $endDate);
  679. $events = json_encode($eventsData);
  680. return view(
  681. 'app.practice-management.pro-availability',
  682. compact(
  683. 'pros',
  684. 'generalAvailabilities',
  685. 'specificAvailabilities',
  686. 'specificUnavailabilities',
  687. 'events',
  688. 'selectedProUid'
  689. )
  690. );
  691. }
  692. public function loadAvailability(Request $request, $proUid)
  693. {
  694. $performer = $this->performer();
  695. $pro = $performer->pro;
  696. $startDate = $request->get('start');
  697. $endDate = $request->get('end');
  698. $selectedPro = Pro::where('uid', $proUid)->first();
  699. return $selectedPro->getAvailabilityEvents($startDate, $endDate, $request->input('tz') ? $request->input('tz') : 'EASTERN');
  700. }
  701. public function proAvailabilityFilter(Request $request)
  702. {
  703. $proUid = $request->get('proUid');
  704. return ['success' => true, 'data' => $proUid];
  705. }
  706. // video call page (RHS)
  707. // generic call handle (no uid)
  708. // specific call handle (uid of client)
  709. public function meet(Request $request, $uid = false)
  710. {
  711. $session = AppSession::where('session_key', $request->cookie('sessionKey'))->first();
  712. $client = !empty($uid) ? Client::where('uid', $uid)->first() : null;
  713. if (!empty($client)) {
  714. return view('app.video.call-minimal', compact('session', 'client'));
  715. }
  716. return view('app.video.call-agora-v2', compact('session', 'client'));
  717. }
  718. // check video page
  719. public function checkVideo(Request $request, $uid)
  720. {
  721. $session = AppSession::where('session_key', $request->cookie('sessionKey'))->first();
  722. $client = !empty($uid) ? Client::where('uid', $uid)->first() : null;
  723. $publish = false;
  724. return view('app.video.check-video-minimal', compact('session', 'client'));
  725. }
  726. public function getParticipantInfo(Request $request)
  727. {
  728. $sid = intval($request->get('uid')) - 1000000;
  729. $session = AppSession::where('id', $sid)->first();
  730. $result = [
  731. "type" => '',
  732. "name" => ''
  733. ];
  734. if ($session) {
  735. $result["type"] = $session->session_type;
  736. switch ($session->session_type) {
  737. case 'PRO':
  738. $pro = Pro::where('id', $session->pro_id)->first();
  739. $result["name"] = $pro->displayName();
  740. break;
  741. case 'CLIENT':
  742. $client = Client::where('id', $session->client_id)->first();
  743. $result["name"] = $client->displayName();
  744. break;
  745. }
  746. }
  747. return json_encode($result);
  748. }
  749. // ajax ep used by the video page
  750. // this is needed bcoz meet() is used not
  751. // just for the client passed to the view
  752. public function getOpentokSessionKey(Request $request, $uid)
  753. {
  754. $client = Client::where('uid', $uid)->first();
  755. return json_encode(["data" => $client ? $client->opentok_session_id : '']);
  756. }
  757. // poll to check if there are patients with active mcp requests
  758. public function getPatientsInQueue(Request $request)
  759. {
  760. $myInitiatives = $this->performer->pro->initiatives;
  761. if ($myInitiatives) {
  762. $myInitiatives = strtoupper($myInitiatives);
  763. }
  764. $myInitiativesList = explode('|', $myInitiatives);
  765. $myForeignLanguages = $this->performer->pro->foreign_languages;
  766. if ($myForeignLanguages) {
  767. $myForeignLanguages = strtoupper($myForeignLanguages);
  768. }
  769. $myForeignLanguagesList = explode('|', $myForeignLanguages);
  770. $clients = Client::whereNotNull('active_mcp_request_id')->where(function ($query) use ($myInitiativesList) {
  771. $query->whereNull('initiative')->orWhereIn('initiative', $myInitiativesList);
  772. })
  773. ->where(function ($query) use ($myForeignLanguagesList) {
  774. $query->whereNull('preferred_foreign_language')->orWhereIn('preferred_foreign_language', $myForeignLanguagesList);
  775. })->limit(3)->get();
  776. $results = [];
  777. foreach ($clients as $client) {
  778. $results[] = [
  779. 'clientUid' => $client->uid,
  780. 'name' => $client->displayName(),
  781. 'initials' => substr($client->name_first, 0, 1) . substr($client->name_last, 0, 1)
  782. ];
  783. }
  784. return json_encode($results);
  785. }
  786. public function currentWork(Request $request)
  787. {
  788. return view('app/current-work');
  789. }
  790. public function calendar(Request $request, $proUid = null)
  791. {
  792. $pros = Pro::all();
  793. if ($this->pro && $this->pro->pro_type != 'ADMIN') {
  794. $accessiblePros = ProProAccess::where('owner_pro_id', $this->pro->id);
  795. $accessibleProIds = [];
  796. foreach ($accessiblePros as $accessiblePro) {
  797. $accessibleProIds[] = $accessiblePro->id;
  798. }
  799. $accessibleProIds[] = $this->pro->id;
  800. $pros = Pro::whereIn('id', $accessibleProIds)->get();
  801. }
  802. return view('app.practice-management.calendar', compact('pros'));
  803. }
  804. public function cellularDeviceManager(Request $request, $proUid = null)
  805. {
  806. $proUid = $proUid ? $proUid : $request->get('pro-uid');
  807. $performerPro = $this->performer->pro;
  808. $targetPro = null;
  809. $expectedForHcp = null;
  810. if ($performerPro->pro_type == 'ADMIN') {
  811. $targetPro = Pro::where('uid', $proUid)->first();
  812. } else {
  813. $targetPro = $performerPro;
  814. }
  815. $clients = [];
  816. if ($targetPro) {
  817. $clients = Client::where('mcp_pro_id', $targetPro->id)->orderBy('created_at', 'desc')->paginate(20);
  818. } else {
  819. $clients = Client::orderBy('created_at', 'desc')->paginate(20);
  820. }
  821. return view('app.practice-management.cellular-device-manager', compact('clients', 'targetPro', 'proUid'));
  822. }
  823. public function treatmentServiceUtil(Request $request)
  824. {
  825. $view_treatment_service_utilization_org = DB::select(DB::raw("SELECT * FROM view_treatment_service_utilization_org ORDER BY effective_date DESC"));
  826. $view_treatment_service_utilization = DB::select(DB::raw("SELECT * FROM view_treatment_service_utilization ORDER BY effective_date DESC, total_hrs DESC"));
  827. $view_treatment_service_utilization_by_patient = DB::select(DB::raw("SELECT * FROM view_treatment_service_utilization_by_patient ORDER BY pro_lname ASC, pro_fname ASC, hcp_pro_id ASC, total_hrs DESC"));
  828. return view('app.practice-management.treatment-services-util', compact(
  829. 'view_treatment_service_utilization_org',
  830. 'view_treatment_service_utilization',
  831. 'view_treatment_service_utilization_by_patient'));
  832. }
  833. public function processingBillMatrix(Request $request, $proUid = null)
  834. {
  835. $proUid = $proUid ? $proUid : $request->get('pro-uid');
  836. $performerPro = $this->performer->pro;
  837. $targetPro = null;
  838. if ($performerPro->pro_type == 'ADMIN') {
  839. $targetPro = Pro::where('uid', $proUid)->first();
  840. } else {
  841. $targetPro = $performerPro;
  842. }
  843. $bills = Bill::where('is_cancelled', false);
  844. if(!$request->input('t') || $request->input('t') === 'hcp') {
  845. $bills = $bills
  846. ->where('has_hcp_been_paid', false)
  847. ->where('hcp_expected_payment_amount', '>', 0)
  848. ->where('is_signed_by_hcp', true);
  849. if ($targetPro) {
  850. $bills = $bills->where('hcp_pro_id', $targetPro->id);
  851. }
  852. if($request->input('c')) {
  853. $bills = $bills->whereRaw('(SELECT company_id from company_pro where id = hcp_company_pro_id) = ' . $request->input('c'));
  854. }
  855. }
  856. else if($request->input('t') === 'na') {
  857. $bills = $bills
  858. ->where('has_generic_pro_been_paid', false)
  859. ->where('generic_pro_expected_payment_amount', '>', 0)
  860. ->where('is_signed_by_generic_pro', true);
  861. if ($targetPro) {
  862. $bills = $bills->where('generic_pro_id', $targetPro->id);
  863. }
  864. if($request->input('c')) {
  865. $bills = $bills->whereRaw('(SELECT company_id from company_pro where id = generic_company_pro_id) = ' . $request->input('c'));
  866. }
  867. }
  868. $filter = $request->input('f');
  869. switch ($filter) {
  870. case 'verified':
  871. $bills = $bills->where('is_verified', true);
  872. break;
  873. case 'not-verified':
  874. $bills = $bills->where('is_verified', false);
  875. break;
  876. }
  877. $filter = $request->input('bs');
  878. if ($filter) {
  879. $bills = $bills->where('balance_post_date', '>=', $filter);
  880. }
  881. $filter = $request->input('be');
  882. if ($filter) {
  883. $bills = $bills->where('balance_post_date', '<=', $filter);
  884. }
  885. $filter = $request->input('s');
  886. if ($filter) {
  887. $bills = $bills->where('code', '=', $filter);
  888. }
  889. $bills = $bills->orderBy('effective_date', 'desc')->paginate();
  890. $companies = Company::where('is_active', true)->orderBy('name')->get();
  891. $codes = DB::select(DB::raw("SELECT code, count(*) as count FROM bill WHERE is_cancelled IS FALSE GROUP BY code ORDER BY code"));
  892. $viewData = [
  893. 'bills' => $bills,
  894. 'targetPro' => $targetPro,
  895. 'performerPro' => $performerPro,
  896. 'proUid' => $proUid,
  897. 'companies' => $companies,
  898. 'codes' => $codes
  899. ];
  900. return view('app.practice-management.processing-bill-matrix', $viewData);
  901. }
  902. public function processingBillMatrix2(Request $request, $proUid = null)
  903. {
  904. $proUid = $proUid ? $proUid : $request->get('pro-uid');
  905. $performerPro = $this->performer->pro;
  906. $targetPro = null;
  907. if ($performerPro->pro_type == 'ADMIN') {
  908. $targetPro = Pro::where('uid', $proUid)->first();
  909. } else {
  910. $targetPro = $performerPro;
  911. }
  912. $bills = Bill::where('is_cancelled', false);
  913. if(!$request->input('t') || $request->input('t') === 'hcp') {
  914. $bills = $bills
  915. ->where('hcp_expected_payment_amount', '>', 0)
  916. ->where('is_signed_by_hcp', true);
  917. if ($targetPro) {
  918. $bills = $bills->where('hcp_pro_id', $targetPro->id);
  919. }
  920. if($request->input('c')) {
  921. $bills = $bills->whereRaw('(SELECT company_id from company_pro where id = hcp_company_pro_id) = ' . $request->input('c'));
  922. }
  923. }
  924. else if($request->input('t') === 'na') {
  925. $bills = $bills
  926. ->where('generic_pro_expected_payment_amount', '>', 0)
  927. ->where('is_signed_by_generic_pro', true);
  928. if ($targetPro) {
  929. $bills = $bills->where('generic_pro_id', $targetPro->id);
  930. }
  931. if($request->input('c')) {
  932. $bills = $bills->whereRaw('(SELECT company_id from company_pro where id = generic_company_pro_id) = ' . $request->input('c'));
  933. }
  934. }
  935. $filter = $request->input('f');
  936. switch ($filter) {
  937. case 'verified':
  938. $bills = $bills->where('is_verified', true);
  939. break;
  940. case 'not-verified':
  941. $bills = $bills->where('is_verified', false);
  942. break;
  943. }
  944. $filter = $request->input('bs');
  945. if ($filter) {
  946. $bills = $bills->where('balance_post_date', '>=', $filter);
  947. }
  948. $filter = $request->input('be');
  949. if ($filter) {
  950. $bills = $bills->where('balance_post_date', '<=', $filter);
  951. }
  952. $filter = $request->input('s');
  953. if ($filter) {
  954. $bills = $bills->where('code', '=', $filter);
  955. }
  956. $bills = $bills->orderBy('effective_date', 'desc')->paginate();
  957. $companies = Company::where('is_active', true)->orderBy('name')->get();
  958. $codes = DB::select(DB::raw("SELECT code, count(*) as count FROM bill WHERE is_cancelled IS FALSE GROUP BY code ORDER BY code"));
  959. $viewData = [
  960. 'bills' => $bills,
  961. 'targetPro' => $targetPro,
  962. 'performerPro' => $performerPro,
  963. 'proUid' => $proUid,
  964. 'companies' => $companies,
  965. 'codes' => $codes
  966. ];
  967. return view('app.practice-management.processing-bill-matrix2', $viewData);
  968. }
  969. public function hcpNoteActivity(Request $request)
  970. {
  971. $filters = $request->all();
  972. $from_date = $request->get('from_date');
  973. // if(!$from_date) {
  974. // $from_date = '2010-01-01';
  975. // }
  976. $to_date = $request->get('to_date');
  977. // if(!$to_date){
  978. // $to_date = '2900-12-31';
  979. // }
  980. //TODO sanitize inputs
  981. $proUid = $request->get('pro-uid');
  982. $now = Carbon::now();
  983. $startOfCurrentMonth = $now->startOfMonth('Y-m-d');
  984. $startOfCurrentMonth = $startOfCurrentMonth->toDateString();
  985. $endOfCurrentMonth = $now->endOfMonth()->format('Y-m-d');
  986. $rows = DB::table('pro')
  987. ->selectRaw(" *,
  988. (SELECT id FROM note WHERE note.hcp_pro_id = pro.id AND is_cancelled = false ORDER BY created_at DESC LIMIT 1) as last_note_id,
  989. (SELECT note.created_at FROM note WHERE note.hcp_pro_id = pro.id AND note.is_cancelled = false ORDER BY note.created_at DESC LIMIT 1) as last_note_created_at,
  990. (SELECT COUNT(*) FROM note WHERE note.hcp_pro_id = pro.id AND note.is_cancelled = false AND created_at::DATE >= '${startOfCurrentMonth}'::DATE AND created_at::DATE <= '${endOfCurrentMonth}'::DATE ) AS notes_this_month,
  991. (SELECT COUNT(*) FROM client WHERE client.mcp_pro_id = pro.id AND client.client_engagement_status_category <> 'DUMMY' AND client.client_engagement_status_category <> 'DUPLICATE') as total_client_count,
  992. (SELECT COUNT(*) FROM client WHERE client.mcp_pro_id = pro.id AND client.client_engagement_status_category <> 'DUMMY' AND client.client_engagement_status_category <> 'DUPLICATE' AND client.most_recent_completed_mcp_note_date >= (NOW() - interval '60 days')::DATE) as active_client_count
  993. " . (!!$from_date && !!$to_date ? ",(SELECT COUNT(*) FROM note WHERE note.hcp_pro_id = pro.id AND note.is_cancelled = false AND created_at::DATE >= '${from_date}'::DATE AND created_at::DATE <= '${to_date}'::DATE ) AS notes_this_period" : ""));
  994. $prosIDs = $request->get('pros_ids');
  995. if($prosIDs){
  996. $pros =
  997. $rows = $rows->whereIn('pro.id', $prosIDs);
  998. }
  999. $sortBy = $request->input('sort_by') ?: 'name_first';
  1000. $sortDir = $request->input('sort_dir') ?: 'ASC';
  1001. $rows = $rows->orderByRaw("$sortBy $sortDir NULLS LAST");
  1002. $rows = $rows->paginate(50);
  1003. return view('app.practice-management.hcp-note-activity', compact('rows', 'filters'));
  1004. }
  1005. public function proFinancials(Request $request, $proUid = null)
  1006. {
  1007. $proUid = $proUid ? $proUid : $request->get('pro-uid');
  1008. $performerPro = $this->performer->pro;
  1009. $targetPro = null;
  1010. if ($performerPro->pro_type == 'ADMIN') {
  1011. $targetPro = Pro::where('uid', $proUid)->first();
  1012. } else {
  1013. $targetPro = $performerPro;
  1014. }
  1015. // calculate totals (without pagination)
  1016. $fPros = Pro::whereNotNull('balance')->where('balance', '>', 0)->get();
  1017. $grandTotal = 0;
  1018. $companies = [];
  1019. foreach ($fPros as $row) {
  1020. foreach($row->companyPros as $companyPro) {
  1021. if($companyPro->balance) {
  1022. if(!isset($companies[$companyPro->company->name])) {
  1023. $companies[$companyPro->company->name] = 0;
  1024. }
  1025. $companies[$companyPro->company->name] += $companyPro->balance;
  1026. $grandTotal += $companyPro->balance;
  1027. }
  1028. }
  1029. }
  1030. arsort($companies);
  1031. $fPros = Pro::whereNotNull('balance');
  1032. if($targetPro) {
  1033. $fPros = $fPros->where('uid', $targetPro->uid);
  1034. }
  1035. $fPros = $fPros
  1036. ->where('balance', '>', 0)
  1037. ->orderBy('name_first')
  1038. ->orderBy('name_last')
  1039. ->paginate();
  1040. return view('app.practice-management.pro-financials', compact('fPros', 'targetPro', 'grandTotal', 'companies'));
  1041. }
  1042. public function hcpBillMatrix(Request $request, $proUid = null)
  1043. {
  1044. $proUid = $proUid ? $proUid : $request->get('pro-uid');
  1045. $performerPro = $this->performer->pro;
  1046. $targetPro = null;
  1047. $allPros = [];
  1048. $expectedForHcp = null;
  1049. if ($performerPro->pro_type == 'ADMIN') {
  1050. $allPros = Pro::all();
  1051. $targetPro = Pro::where('uid', $proUid)->first();
  1052. } else {
  1053. $targetPro = $performerPro;
  1054. }
  1055. $rows = [];
  1056. if ($targetPro) {
  1057. $rows = DB::select(DB::raw("SELECT * FROM aemish_bill_report WHERE hcp_pro_id = :targetProID"), ['targetProID' => $targetPro->id]);
  1058. } else {
  1059. $rows = DB::select(DB::raw("SELECT * FROM aemish_bill_report"));
  1060. }
  1061. return view('app.practice-management.hcp-bill-matrix', compact('rows', 'allPros', 'expectedForHcp', 'targetPro', 'proUid'));
  1062. }
  1063. public function billingManager(Request $request, $proUid = null)
  1064. {
  1065. $proUid = $proUid ? $proUid : $request->get('pro-uid');
  1066. $performerPro = $this->performer->pro;
  1067. $targetPro = null;
  1068. $allPros = [];
  1069. $expectedForHcp = null;
  1070. if ($performerPro->pro_type == 'ADMIN') {
  1071. $allPros = Pro::query()->orderBy('name_first', 'asc')->get();
  1072. $targetPro = Pro::where('uid', $proUid)->first();
  1073. } else {
  1074. $targetPro = $performerPro;
  1075. }
  1076. $notes = [];
  1077. if ($targetPro) {
  1078. $expectedForHcp = DB::select(DB::raw("SELECT coalesce(SUM(hcp_expected_payment_amount),0) as expected_pay FROM bill WHERE hcp_pro_id = :targetProID AND is_signed_by_hcp IS TRUE AND is_cancelled = false"), ['targetProID' => $targetPro->id])[0]->expected_pay;
  1079. $notes = Note::where('hcp_pro_id', $targetPro->id);
  1080. } else {
  1081. $notes = Note::where('id', '>', 0);
  1082. }
  1083. if($request->input('date')) {
  1084. $notes = $notes->where('effective_dateest', $request->input('date'));
  1085. }
  1086. $filters = [];
  1087. $filters['bills_created'] = $request->input('bills_created');
  1088. $filters['is_billing_marked_done'] = $request->input('is_billing_marked_done');
  1089. $filters['bills_resolved'] = $request->input('bills_resolved');
  1090. $filters['bills_closed'] = $request->input('bills_closed');
  1091. $filters['claims_created'] = $request->input('claims_created');
  1092. $filters['claims_closed'] = $request->input('claims_closed');
  1093. if ($filters['bills_created']) {
  1094. $notes->where(
  1095. 'bill_total_expected',
  1096. ($filters['bills_created'] === 'yes' ? '>' : '<='),
  1097. 0);
  1098. }
  1099. if ($filters['is_billing_marked_done']) {
  1100. $notes->where(
  1101. 'is_billing_marked_done',
  1102. ($filters['is_billing_marked_done'] === 'yes' ? '=' : '!='),
  1103. true);
  1104. }
  1105. if ($filters['bills_resolved']) {
  1106. $notes->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id) > 0'); // have bills
  1107. if ($filters['bills_resolved'] === 'yes') {
  1108. $notes->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND (is_cancelled = false AND is_verified = false) OR (is_cancelled = TRUE AND is_cancellation_acknowledged = FALSE)) > 0');
  1109. } elseif ($filters['bills_resolved'] === 'no') {
  1110. $notes->whereRaw('(SELECT count(id) FROM bill WHERE note_id = note.id AND ((is_cancelled = true AND is_cancellation_acknowledged = true) OR is_verified = true)) = 0');
  1111. }
  1112. }
  1113. if ($filters['bills_closed']) {
  1114. $notes->where(
  1115. 'is_bill_closed',
  1116. ($filters['bills_closed'] === 'yes' ? '=' : '!='),
  1117. true);
  1118. }
  1119. if ($filters['claims_created']) {
  1120. $notes->where(
  1121. 'claim_total_expected',
  1122. ($filters['claims_created'] === 'yes' ? '>' : '<='),
  1123. 0);
  1124. }
  1125. if ($filters['claims_closed']) {
  1126. $notes->where(
  1127. 'is_claim_closed',
  1128. ($filters['claims_closed'] === 'yes' ? '=' : '!='),
  1129. true);
  1130. }
  1131. $notes = $notes->orderBy('effective_dateest', 'desc')->paginate(20);
  1132. return view('app.practice-management.billing-manager', compact('notes', 'allPros', 'expectedForHcp', 'targetPro', 'proUid', 'filters'));
  1133. }
  1134. public function remoteMonitoring(Request $request) {
  1135. $performer = $this->performer();
  1136. // abort_if($performer->pro->pro_type !== 'ADMIN' && !$performer->pro->can_view_rm_matrix, 403);
  1137. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1138. $careMonthStart = date($ym . '-01');
  1139. $rc = $request->input('rc') ?: 1;
  1140. $rc2 = $request->input('rc2') ?: 2;
  1141. $conditions = [];// $this->rpmConditions($performer, $rc, $rc2);
  1142. $sortBy = $request->input('sort_by') ?: 'name_first';
  1143. $sortDir = $request->input('sort_dir') ?: 'ASC';
  1144. $orderBy = "ORDER BY $sortBy $sortDir NULLS LAST";
  1145. $query = "
  1146. SELECT client.name_first, client.name_last,
  1147. (client.name_first || ' ' || client.name_last) as client_name,
  1148. client.uid as client_uid,
  1149. client.dob,
  1150. care_month.is_client_enrolled_in_rm,
  1151. client.most_recent_completed_mcp_note_date,
  1152. client.most_recent_completed_mcp_note_id,
  1153. mrmnote.effective_dateest::date as most_recent_completed_mcp_note_date_cm,
  1154. mrmnote.id as most_recent_completed_mcp_note_id_cm,
  1155. mrmnote.uid as most_recent_completed_mcp_note_uid_cm,
  1156. client.cell_number,
  1157. client.is_assigned_cellular_bp_device,
  1158. client.is_assigned_cellular_weight_scale_device,
  1159. care_month.uid as care_month_uid,
  1160. care_month.id as care_month_id,
  1161. care_month.start_date,
  1162. care_month.rm_total_time_in_seconds_by_mcp,
  1163. care_month.rm_total_time_in_seconds_by_rmm_pro,
  1164. care_month.number_of_days_with_remote_measurements,
  1165. care_month.has_mcp_interacted_with_client_about_rm,
  1166. care_month.rm_num_measurements_not_stamped_by_mcp,
  1167. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  1168. care_month.rm_num_measurements_not_stamped_by_rmm,
  1169. care_month.rm_num_measurements_not_stamped_by_rme,
  1170. care_month.mcp_pro_id as care_month_mcp_pro_id,
  1171. care_month.rmm_pro_id as care_month_rmm_pro_id,
  1172. client.mcp_pro_id,
  1173. client.default_na_pro_id,
  1174. client.rmm_pro_id,
  1175. client.rme_pro_id,
  1176. client.cell_number,
  1177. care_month.most_recent_cellular_bp_dbp_mm_hg,
  1178. care_month.most_recent_cellular_bp_sbp_mm_hg,
  1179. care_month.most_recent_cellular_bp_measurement_at,
  1180. care_month.most_recent_cellular_weight_value,
  1181. care_month.most_recent_cellular_weight_measurement_at
  1182. FROM care_month join client on care_month.client_id = client.id join note mrnote on client.most_recent_completed_mcp_note_id = mrnote.id
  1183. left join note mrmnote on mrmnote.id = (
  1184. select max(n.id) from note n
  1185. where
  1186. n.client_id = client.id AND
  1187. n.is_cancelled = FALSE AND
  1188. (n.is_signed_by_hcp IS NOT NULL AND n.is_signed_by_hcp = TRUE) AND
  1189. n.effective_dateest::date >= care_month.start_date::date AND
  1190. n.effective_dateest::date < (care_month.start_date::date + INTERVAL '1 month')
  1191. )
  1192. WHERE
  1193. (care_month.mcp_pro_id = {$performer->pro->id} OR care_month.rmm_pro_id = {$performer->pro->id})
  1194. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1195. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1196. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '') . "
  1197. $orderBy
  1198. ";
  1199. $patients = DB::select($query);
  1200. $timestamp = strtotime(date('Y-m-d'));
  1201. $daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
  1202. return view('app.practice-management.remote-monitoring', compact('patients', 'daysRemaining', 'careMonthStart'));
  1203. }
  1204. public function remoteMonitoring_Row(Request $request) {
  1205. $clientUid = $request->input('clientUid');
  1206. $careMonthUid = $request->input('careMonthUid');
  1207. $query = "
  1208. SELECT client.name_first, client.name_last,
  1209. (client.name_first || ' ' || client.name_last) as client_name,
  1210. client.uid as client_uid,
  1211. client.dob,
  1212. care_month.is_client_enrolled_in_rm,
  1213. client.most_recent_completed_mcp_note_date,
  1214. client.most_recent_completed_mcp_note_id,
  1215. mrmnote.effective_dateest::date as most_recent_completed_mcp_note_date_cm,
  1216. mrmnote.id as most_recent_completed_mcp_note_id_cm,
  1217. mrmnote.uid as most_recent_completed_mcp_note_uid_cm,
  1218. client.cell_number,
  1219. client.is_assigned_cellular_bp_device,
  1220. client.is_assigned_cellular_weight_scale_device,
  1221. care_month.uid as care_month_uid,
  1222. care_month.id as care_month_id,
  1223. care_month.start_date,
  1224. care_month.rm_total_time_in_seconds_by_mcp,
  1225. care_month.rm_total_time_in_seconds_by_rmm_pro,
  1226. care_month.number_of_days_with_remote_measurements,
  1227. care_month.has_mcp_interacted_with_client_about_rm,
  1228. care_month.rm_num_measurements_not_stamped_by_mcp,
  1229. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  1230. care_month.rm_num_measurements_not_stamped_by_rmm,
  1231. care_month.rm_num_measurements_not_stamped_by_rme,
  1232. care_month.mcp_pro_id as care_month_mcp_pro_id,
  1233. care_month.rmm_pro_id as care_month_rmm_pro_id,
  1234. client.mcp_pro_id,
  1235. client.default_na_pro_id,
  1236. client.rmm_pro_id,
  1237. client.rme_pro_id,
  1238. client.cell_number,
  1239. care_month.most_recent_cellular_bp_dbp_mm_hg,
  1240. care_month.most_recent_cellular_bp_sbp_mm_hg,
  1241. care_month.most_recent_cellular_bp_measurement_at,
  1242. care_month.most_recent_cellular_weight_value,
  1243. care_month.most_recent_cellular_weight_measurement_at
  1244. FROM care_month join client on care_month.client_id = client.id join note mrnote on client.most_recent_completed_mcp_note_id = mrnote.id
  1245. left join note mrmnote on mrmnote.id = (
  1246. select max(n.id) from note n
  1247. where
  1248. n.client_id = client.id AND
  1249. n.is_cancelled = FALSE AND
  1250. (n.is_signed_by_hcp IS NOT NULL AND n.is_signed_by_hcp = TRUE) AND
  1251. n.effective_dateest::date >= care_month.start_date::date AND
  1252. n.effective_dateest::date < (care_month.start_date::date + INTERVAL '1 month')
  1253. )
  1254. WHERE care_month.uid = '{$careMonthUid}' AND client.uid = '{$clientUid}'
  1255. ";
  1256. $patients = DB::select($query);
  1257. return view('app.practice-management.remote-monitoring-row', ['iPatient' => $patients[0], 'trIndex' => $request->input('trIndex')]);
  1258. }
  1259. private function remoteMonitoring_RowByProType(Request $request, $mode) {
  1260. $clientUid = $request->input('clientUid');
  1261. $careMonthUid = $request->input('careMonthUid');
  1262. $query = "
  1263. SELECT client.name_first, client.name_last,
  1264. (client.name_first || ' ' || client.name_last) as client_name,
  1265. client.uid as client_uid,
  1266. client.dob,
  1267. care_month.is_client_enrolled_in_rm,
  1268. client.most_recent_completed_mcp_note_date,
  1269. client.most_recent_completed_mcp_note_id,
  1270. mrmnote.effective_dateest::date as most_recent_completed_mcp_note_date_cm,
  1271. mrmnote.id as most_recent_completed_mcp_note_id_cm,
  1272. mrmnote.uid as most_recent_completed_mcp_note_uid_cm,
  1273. client.cell_number,
  1274. client.is_assigned_cellular_bp_device,
  1275. client.is_assigned_cellular_weight_scale_device,
  1276. care_month.uid as care_month_uid,
  1277. care_month.id as care_month_id,
  1278. care_month.start_date,
  1279. care_month.rm_total_time_in_seconds_by_mcp,
  1280. care_month.rm_total_time_in_seconds_by_rmm_pro,
  1281. care_month.number_of_days_with_remote_measurements,
  1282. care_month.has_mcp_interacted_with_client_about_rm,
  1283. care_month.rm_num_measurements_not_stamped_by_mcp,
  1284. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  1285. care_month.rm_num_measurements_not_stamped_by_rmm,
  1286. care_month.rm_num_measurements_not_stamped_by_rme,
  1287. care_month.mcp_pro_id as care_month_mcp_pro_id,
  1288. care_month.rmm_pro_id as care_month_rmm_pro_id,
  1289. client.mcp_pro_id,
  1290. client.default_na_pro_id,
  1291. client.rmm_pro_id,
  1292. client.rme_pro_id,
  1293. client.cell_number,
  1294. care_month.most_recent_cellular_bp_dbp_mm_hg,
  1295. care_month.most_recent_cellular_bp_sbp_mm_hg,
  1296. care_month.most_recent_cellular_bp_measurement_at,
  1297. care_month.most_recent_cellular_weight_value,
  1298. care_month.most_recent_cellular_weight_measurement_at
  1299. FROM care_month join client on care_month.client_id = client.id join note mrnote on client.most_recent_completed_mcp_note_id = mrnote.id
  1300. left join note mrmnote on mrmnote.id = (
  1301. select max(n.id) from note n
  1302. where
  1303. n.client_id = client.id AND
  1304. n.is_cancelled = FALSE AND
  1305. (n.is_signed_by_hcp IS NOT NULL AND n.is_signed_by_hcp = TRUE) AND
  1306. n.effective_dateest::date >= care_month.start_date::date AND
  1307. n.effective_dateest::date < (care_month.start_date::date + INTERVAL '1 month')
  1308. )
  1309. WHERE care_month.uid = '{$careMonthUid}' AND client.uid = '{$clientUid}'
  1310. ";
  1311. $patients = DB::select($query);
  1312. return view('app.practice-management.remote-monitoring-row-by-pro-type', ['iPatient' => $patients[0], 'trIndex' => $request->input('trIndex'), 'mode' => $mode]);
  1313. }
  1314. private function remoteMonitoring_RowForAdmin(Request $request) {
  1315. $clientUid = $request->input('clientUid');
  1316. $careMonthUid = $request->input('careMonthUid');
  1317. $query = "
  1318. SELECT client.name_first, client.name_last,
  1319. (client.name_first || ' ' || client.name_last) as client_name,
  1320. client.uid as client_uid,
  1321. client.dob,
  1322. care_month.is_client_enrolled_in_rm,
  1323. client.most_recent_completed_mcp_note_date,
  1324. client.most_recent_completed_mcp_note_id,
  1325. mrmnote.effective_dateest::date as most_recent_completed_mcp_note_date_cm,
  1326. mrmnote.id as most_recent_completed_mcp_note_id_cm,
  1327. mrmnote.uid as most_recent_completed_mcp_note_uid_cm,
  1328. client.cell_number,
  1329. client.is_assigned_cellular_bp_device,
  1330. client.is_assigned_cellular_weight_scale_device,
  1331. care_month.uid as care_month_uid,
  1332. care_month.id as care_month_id,
  1333. care_month.start_date,
  1334. care_month.rm_total_time_in_seconds_by_mcp,
  1335. care_month.rm_total_time_in_seconds_by_rmm_pro,
  1336. care_month.number_of_days_with_remote_measurements,
  1337. care_month.has_mcp_interacted_with_client_about_rm,
  1338. care_month.rm_num_measurements_not_stamped_by_mcp,
  1339. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  1340. care_month.rm_num_measurements_not_stamped_by_rmm,
  1341. care_month.rm_num_measurements_not_stamped_by_rme,
  1342. care_month.mcp_pro_id as care_month_mcp_pro_id,
  1343. care_month.rmm_pro_id as care_month_rmm_pro_id,
  1344. client.mcp_pro_id,
  1345. client.default_na_pro_id,
  1346. client.rmm_pro_id,
  1347. client.rme_pro_id,
  1348. client.cell_number,
  1349. care_month.most_recent_cellular_bp_dbp_mm_hg,
  1350. care_month.most_recent_cellular_bp_sbp_mm_hg,
  1351. care_month.most_recent_cellular_bp_measurement_at,
  1352. care_month.most_recent_cellular_weight_value,
  1353. care_month.most_recent_cellular_weight_measurement_at
  1354. FROM care_month join client on care_month.client_id = client.id join note mrnote on client.most_recent_completed_mcp_note_id = mrnote.id
  1355. left join note mrmnote on mrmnote.id = (
  1356. select max(n.id) from note n
  1357. where
  1358. n.client_id = client.id AND
  1359. n.is_cancelled = FALSE AND
  1360. (n.is_signed_by_hcp IS NOT NULL AND n.is_signed_by_hcp = TRUE) AND
  1361. n.effective_dateest::date >= care_month.start_date::date AND
  1362. n.effective_dateest::date < (care_month.start_date::date + INTERVAL '1 month')
  1363. )
  1364. WHERE care_month.uid = '{$careMonthUid}' AND client.uid = '{$clientUid}'
  1365. ";
  1366. $patients = DB::select($query);
  1367. return view('app.practice-management.remote-monitoring-row-for-admin', ['iPatient' => $patients[0], 'trIndex' => $request->input('trIndex')]);
  1368. }
  1369. private function rpmMatrixByProType(Request $request, $mode) {
  1370. $performer = $this->performer();
  1371. // abort_if($performer->pro->pro_type !== 'ADMIN' && !$performer->pro->can_view_rm_matrix, 403);
  1372. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1373. $careMonthStart = date($ym . '-01');
  1374. $rc = $request->input('rc') ?: 1;
  1375. $rc2 = $request->input('rc2') ?: 2;
  1376. $conditions = [];// $this->rpmConditions($performer, $rc, $rc2);
  1377. $sortBy = $request->input('sort_by') ?: 'name_first';
  1378. $sortDir = $request->input('sort_dir') ?: 'ASC';
  1379. $orderBy = "ORDER BY $sortBy $sortDir NULLS LAST";
  1380. // special case of if-bill-exists
  1381. if($sortBy === 'mcp_rm_generic_bill_id' || $sortBy === 'rmm_rm_generic_bill_id') {
  1382. if($sortDir === 'ASC') {
  1383. $orderBy = "ORDER BY $sortBy $sortDir NULLS FIRST";
  1384. }
  1385. else {
  1386. $orderBy = "ORDER BY $sortBy $sortDir NULLS LAST";
  1387. }
  1388. }
  1389. // default sort
  1390. if(!$request->input('sort_by')) {
  1391. if($mode === 'mcp') {
  1392. $orderBy = "ORDER BY care_month.number_of_days_with_remote_measurements DESC NULLS LAST, care_month.rm_total_time_in_seconds_by_mcp DESC NULLS LAST";
  1393. }
  1394. elseif ($mode === 'rmm') {
  1395. $orderBy = "ORDER BY care_month.number_of_days_with_remote_measurements DESC NULLS LAST, care_month.rm_total_time_in_seconds_by_rmm_pro DESC NULLS LAST";
  1396. }
  1397. else {
  1398. $orderBy = "ORDER BY care_month.number_of_days_with_remote_measurements DESC NULLS LAST";
  1399. }
  1400. }
  1401. else {
  1402. $sortBy = $request->input('sort_by');
  1403. $sortDir = $request->input('sort_dir');
  1404. if($sortBy && $sortDir) {
  1405. if(!in_array($sortBy, ['number_of_days_with_remote_measurements', 'rm_total_time_in_seconds_by_mcp', 'rm_total_time_in_seconds_by_rmm_pro'])) {
  1406. if($mode === 'mcp') {
  1407. $orderBy = "ORDER BY $sortBy $sortDir NULLS LAST, care_month.number_of_days_with_remote_measurements DESC NULLS LAST, care_month.rm_total_time_in_seconds_by_mcp DESC NULLS LAST";
  1408. }
  1409. elseif ($mode === 'rmm') {
  1410. $orderBy = "ORDER BY $sortBy $sortDir NULLS LAST, care_month.number_of_days_with_remote_measurements DESC NULLS LAST, care_month.rm_total_time_in_seconds_by_rmm_pro DESC NULLS LAST";
  1411. }
  1412. else {
  1413. $orderBy = "ORDER BY $sortBy $sortDir NULLS LAST, care_month.number_of_days_with_remote_measurements DESC NULLS LAST";
  1414. }
  1415. }
  1416. else {
  1417. $orderBy = "ORDER BY $sortBy $sortDir NULLS LAST";
  1418. }
  1419. }
  1420. }
  1421. // filters from the UI
  1422. if(trim($request->input('f_name'))) {
  1423. $v = trim($request->input('f_name'));
  1424. $conditions[] = "(client.name_first ILIKE '%{$v}%' OR client.name_last ILIKE '%{$v}%')";
  1425. }
  1426. if(trim($request->input('f_dob_op')) && trim($request->input('f_dob'))) {
  1427. $o = trim($request->input('f_dob_op'));
  1428. $v = trim($request->input('f_dob'));
  1429. $conditions[] = "(client.dob {$o} '{$v}')";
  1430. }
  1431. if(trim($request->input('f_rpm'))) {
  1432. $v = trim($request->input('f_rpm'));
  1433. if($v === 'yes') {
  1434. $conditions[] = "(care_month.is_client_enrolled_in_rm IS TRUE)";
  1435. }
  1436. elseif($v === 'no') {
  1437. $conditions[] = "(care_month.is_client_enrolled_in_rm IS NOT TRUE)";
  1438. }
  1439. }
  1440. if(trim($request->input('f_cell_bp'))) {
  1441. $v = trim($request->input('f_cell_bp'));
  1442. if($v === 'yes') {
  1443. $conditions[] = "(client.is_assigned_cellular_bp_device IS NOT NULL AND client.is_assigned_cellular_bp_device = TRUE)";
  1444. }
  1445. elseif($v === 'no') {
  1446. $conditions[] = "(client.is_assigned_cellular_bp_device IS NULL OR client.is_assigned_cellular_bp_device = FALSE)";
  1447. }
  1448. }
  1449. if(trim($request->input('f_cell_wt'))) {
  1450. $v = trim($request->input('f_cell_wt'));
  1451. if($v === 'yes') {
  1452. $conditions[] = "(client.is_assigned_cellular_weight_scale_device IS NOT NULL AND client.is_assigned_cellular_weight_scale_device = TRUE)";
  1453. }
  1454. elseif($v === 'no') {
  1455. $conditions[] = "(client.is_assigned_cellular_weight_scale_device IS NULL OR client.is_assigned_cellular_weight_scale_device = FALSE)";
  1456. }
  1457. }
  1458. if(trim($request->input('f_comm'))) {
  1459. $v = trim($request->input('f_comm'));
  1460. if($v === 'yes') {
  1461. $conditions[] = "(care_month.has_mcp_interacted_with_client_about_rm IS NOT NULL AND care_month.has_mcp_interacted_with_client_about_rm = TRUE)";
  1462. }
  1463. elseif($v === 'no') {
  1464. $conditions[] = "(care_month.has_mcp_interacted_with_client_about_rm IS NULL OR care_month.has_mcp_interacted_with_client_about_rm = FALSE)";
  1465. }
  1466. }
  1467. if($mode === 'mcp' || $mode === 'rmm') {
  1468. if(trim($request->input('f_billable'))) {
  1469. $v = trim($request->input('f_billable'));
  1470. if($v === 'yes') {
  1471. $conditions[] = "(care_month.{$mode}_rm_generic_bill_id IS NOT NULL)";
  1472. }
  1473. elseif($v === 'no') {
  1474. $conditions[] = "(care_month.{$mode}_rm_generic_bill_id IS NULL)";
  1475. }
  1476. }
  1477. }
  1478. if(trim($request->input('f_md_op')) && trim($request->input('f_md')) !== '') {
  1479. $o = trim($request->input('f_md_op'));
  1480. $v = trim($request->input('f_md'));
  1481. $conditions[] = "(care_month.number_of_days_with_remote_measurements {$o} {$v})";
  1482. }
  1483. if(trim($request->input('f_unst_op')) && trim($request->input('f_unst')) !== '') {
  1484. $o = trim($request->input('f_unst_op'));
  1485. $v = trim($request->input('f_unst'));
  1486. $conditions[] = "(care_month.rm_num_measurements_not_stamped_by_mcp {$o} {$v})";
  1487. }
  1488. if(trim($request->input('f_mins_op')) && trim($request->input('f_mins')) !== '') {
  1489. $o = trim($request->input('f_mins_op'));
  1490. $v = intval(trim($request->input('f_mins'))) * 60;
  1491. $field = 'rm_total_time_in_seconds_by_mcp';
  1492. switch($mode) {
  1493. case 'mcp':
  1494. $field = 'rm_total_time_in_seconds_by_mcp';
  1495. break;
  1496. case 'rmm':
  1497. $field = 'rm_total_time_in_seconds_by_rmm_pro';
  1498. break;
  1499. break;
  1500. }
  1501. $conditions[] = "(care_month.{$field} {$o} {$v})";
  1502. }
  1503. if($request->input('not-enrolled')) {
  1504. $conditions[] = "(care_month.is_client_enrolled_in_rm IS NOT TRUE)";
  1505. }
  1506. else {
  1507. $conditions[] = "(care_month.is_client_enrolled_in_rm IS TRUE)";
  1508. }
  1509. $proTypeCondition = '';
  1510. $genericBillIdColumns = '';
  1511. $genericBillJoinClause = '';
  1512. switch($mode) {
  1513. case 'mcp':
  1514. $proTypeCondition = "care_month.mcp_pro_id = {$performer->pro->id}";
  1515. $genericBillIdColumns = "care_month.mcp_rm_generic_bill_id,
  1516. bill.uid as mcp_rm_generic_bill_uid,
  1517. bill.generic_pro_id as mcp_rm_generic_bill_generic_pro_id,
  1518. bill.generic_pro_expected_payment_amount as mcp_rm_generic_bill_expected_payment_amount,
  1519. bill.is_signed_by_generic_pro as mcp_rm_generic_bill_signed";
  1520. $genericBillJoinClause = 'left join bill on care_month.mcp_rm_generic_bill_id = bill.id';
  1521. break;
  1522. case 'rmm':
  1523. $proTypeCondition = "care_month.rmm_pro_id = {$performer->pro->id}";
  1524. $genericBillIdColumns = "care_month.rmm_rm_generic_bill_id,
  1525. bill.uid as rmm_rm_generic_bill_uid,
  1526. bill.generic_pro_id as rmm_rm_generic_bill_generic_pro_id,
  1527. bill.generic_pro_expected_payment_amount as rmm_rm_generic_bill_expected_payment_amount,
  1528. bill.is_signed_by_generic_pro as rmm_rm_generic_bill_signed";
  1529. $genericBillJoinClause = 'left join bill on care_month.rmm_rm_generic_bill_id = bill.id';
  1530. break;
  1531. case 'rme':
  1532. $proTypeCondition = "care_month.rmm_pro_id = {$performer->pro->id}";
  1533. $genericBillIdColumns = "care_month.rmm_rm_generic_bill_id,
  1534. bill.uid as rmm_rm_generic_bill_uid,
  1535. bill.generic_pro_id as rmm_rm_generic_bill_generic_pro_id,
  1536. bill.generic_pro_expected_payment_amount as rmm_rm_generic_bill_expected_payment_amount,
  1537. bill.is_signed_by_generic_pro as rmm_rm_generic_bill_signed";
  1538. $genericBillJoinClause = 'left join bill on care_month.rmm_rm_generic_bill_id = bill.id';
  1539. break;
  1540. }
  1541. $query = "
  1542. SELECT client.name_first, client.name_last,
  1543. (client.name_first || ' ' || client.name_last) as client_name,
  1544. client.uid as client_uid,
  1545. client.dob,
  1546. care_month.is_client_enrolled_in_rm,
  1547. client.most_recent_completed_mcp_note_date,
  1548. client.most_recent_completed_mcp_note_id,
  1549. mrmnote.effective_dateest::date as most_recent_completed_mcp_note_date_cm,
  1550. mrmnote.id as most_recent_completed_mcp_note_id_cm,
  1551. mrmnote.uid as most_recent_completed_mcp_note_uid_cm,
  1552. client.cell_number,
  1553. client.is_assigned_cellular_bp_device,
  1554. client.is_assigned_cellular_weight_scale_device,
  1555. care_month.uid as care_month_uid,
  1556. care_month.id as care_month_id,
  1557. care_month.start_date,
  1558. care_month.rm_total_time_in_seconds_by_mcp,
  1559. care_month.rm_total_time_in_seconds_by_rmm_pro,
  1560. care_month.number_of_days_with_remote_measurements,
  1561. care_month.has_mcp_interacted_with_client_about_rm,
  1562. care_month.rm_num_measurements_not_stamped_by_mcp,
  1563. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  1564. care_month.rm_num_measurements_not_stamped_by_rmm,
  1565. care_month.rm_num_measurements_not_stamped_by_rme,
  1566. care_month.mcp_pro_id as care_month_mcp_pro_id,
  1567. care_month.rmm_pro_id as care_month_rmm_pro_id,
  1568. client.mcp_pro_id,
  1569. client.default_na_pro_id,
  1570. client.rmm_pro_id,
  1571. client.rme_pro_id,
  1572. client.cell_number,
  1573. care_month.most_recent_cellular_bp_dbp_mm_hg,
  1574. care_month.most_recent_cellular_bp_sbp_mm_hg,
  1575. care_month.most_recent_cellular_bp_measurement_at,
  1576. care_month.most_recent_cellular_weight_value,
  1577. care_month.most_recent_cellular_weight_measurement_at,
  1578. mcp.name_last || ', ' || mcp.name_last AS mcp_name,
  1579. {$genericBillIdColumns}
  1580. FROM care_month join client on care_month.client_id = client.id left join pro AS mcp on care_month.mcp_pro_id = mcp.id join note mrnote on client.most_recent_completed_mcp_note_id = mrnote.id
  1581. {$genericBillJoinClause}
  1582. left join note mrmnote on mrmnote.id = (
  1583. select max(n.id) from note n
  1584. where
  1585. n.client_id = client.id AND
  1586. n.is_cancelled = FALSE AND
  1587. (n.is_signed_by_hcp IS NOT NULL AND n.is_signed_by_hcp = TRUE) AND
  1588. n.effective_dateest::date >= care_month.start_date::date AND
  1589. n.effective_dateest::date < (care_month.start_date::date + INTERVAL '1 month')
  1590. )
  1591. WHERE
  1592. $proTypeCondition
  1593. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1594. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1595. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '') . "
  1596. $orderBy
  1597. ";
  1598. // dd($query);
  1599. $patients = DB::select($query);
  1600. $timestamp = strtotime(date('Y-m-d'));
  1601. $daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
  1602. return view('app.practice-management.rpm-matrix-by-pro-type', compact('patients', 'daysRemaining', 'careMonthStart', 'mode'));
  1603. }
  1604. public function rpmMatrixForAdmin(Request $request) {
  1605. $performer = $this->performer();
  1606. // abort_if($performer->pro->pro_type !== 'ADMIN' && !$performer->pro->can_view_rm_matrix, 403);
  1607. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1608. $careMonthStart = date($ym . '-01');
  1609. $rc = $request->input('rc') ?: 1;
  1610. $rc2 = $request->input('rc2') ?: 2;
  1611. $conditions = [];// $this->rpmConditions($performer, $rc, $rc2);
  1612. $sortBy = $request->input('sort_by') ?: 'name_first';
  1613. $sortDir = $request->input('sort_dir') ?: 'ASC';
  1614. $orderBy = "ORDER BY $sortBy $sortDir NULLS LAST";
  1615. // special case of if-bill-exists
  1616. if($sortBy === 'mcp_rm_generic_bill_id' || $sortBy === 'rmm_rm_generic_bill_id') {
  1617. if($sortDir === 'ASC') {
  1618. $orderBy = "ORDER BY $sortBy $sortDir NULLS FIRST";
  1619. }
  1620. else {
  1621. $orderBy = "ORDER BY $sortBy $sortDir NULLS LAST";
  1622. }
  1623. }
  1624. // default sort
  1625. if(!$request->input('sort_by')) {
  1626. $orderBy = "ORDER BY care_month.number_of_days_with_remote_measurements DESC NULLS LAST, care_month.rm_total_time_in_seconds_by_mcp DESC NULLS LAST, care_month.rm_total_time_in_seconds_by_rmm_pro DESC NULLS LAST";
  1627. }
  1628. else {
  1629. $sortBy = json_decode($request->input('sort_by'));
  1630. $orderByClause = [];
  1631. $includeDefaultKeys = true;
  1632. foreach ($sortBy as $sortCriteria) {
  1633. $orderByClause[] = "{$sortCriteria->key} {$sortCriteria->order} NULLS LAST";
  1634. if(in_array($sortCriteria->key, ['number_of_days_with_remote_measurements', 'rm_total_time_in_seconds_by_mcp', 'rm_total_time_in_seconds_by_rmm_pro'])) {
  1635. $includeDefaultKeys = false;
  1636. }
  1637. }
  1638. if($includeDefaultKeys) {
  1639. $orderByClause[] = "care_month.number_of_days_with_remote_measurements DESC NULLS LAST";
  1640. $orderByClause[] = "care_month.rm_total_time_in_seconds_by_mcp DESC NULLS LAST";
  1641. $orderByClause[] = "care_month.rm_total_time_in_seconds_by_rmm_pro DESC NULLS LAST";
  1642. }
  1643. $orderBy = 'ORDER BY ' . implode(', ', $orderByClause);
  1644. }
  1645. // filters from the UI
  1646. if(trim($request->input('f_ces'))) {
  1647. $v = trim($request->input('f_ces'));
  1648. if($v === 'ACTIVE') {
  1649. $conditions[] = "(client.client_engagement_status_category IS NULL OR client.client_engagement_status_category = '{$v}')";
  1650. }
  1651. else {
  1652. $conditions[] = "(client.client_engagement_status_category = '{$v}')";
  1653. }
  1654. }
  1655. if(trim($request->input('f_name'))) {
  1656. $v = trim($request->input('f_name'));
  1657. $conditions[] = "(client.name_first ILIKE '%{$v}%' OR client.name_last ILIKE '%{$v}%')";
  1658. }
  1659. if(trim($request->input('f_payer_type'))) {
  1660. switch($request->input('f_payer_type')) {
  1661. case 'Medicare':
  1662. $conditions[] = "(cpc.plan_type = 'MEDICARE')";
  1663. break;
  1664. case 'Non Medicare':
  1665. $conditions[] = "(cpc.plan_type != 'MEDICARE')";
  1666. break;
  1667. case 'Medicaid':
  1668. $conditions[] = "(cpc.plan_type = 'MEDICAID')";
  1669. break;
  1670. case 'Commercial':
  1671. $conditions[] = "(cpc.plan_type = 'COMMERCIAL')";
  1672. break;
  1673. }
  1674. }
  1675. if((trim($request->input('f_payer_type')) === 'Non Medicare' || trim($request->input('f_payer_type')) === 'Commercial') && trim($request->input('f_payer'))) {
  1676. $v = trim($request->input('f_payer'));
  1677. $conditions[] = "(payer.name ILIKE '%{$v}%')";
  1678. }
  1679. if(trim($request->input('f_state'))) {
  1680. $v = trim($request->input('f_state'));
  1681. switch($v) {
  1682. case 'NONE':
  1683. $conditions[] = "(client.mailing_address_state IS NULL)";
  1684. break;
  1685. case 'NOT_MD':
  1686. $conditions[] = "(client.mailing_address_state IS NOT NULL AND client.mailing_address_state != 'MD')";
  1687. break;
  1688. default:
  1689. $conditions[] = "(client.mailing_address_state ILIKE '%{$v}%')";
  1690. break;
  1691. }
  1692. }
  1693. if(trim($request->input('f_mcp'))) {
  1694. $v = trim($request->input('f_mcp'));
  1695. $conditions[] = "(mcpPro.uid = '{$v}')";
  1696. }
  1697. if(trim($request->input('f_dob_op')) && trim($request->input('f_dob'))) {
  1698. $o = trim($request->input('f_dob_op'));
  1699. $v = trim($request->input('f_dob'));
  1700. $conditions[] = "(client.dob {$o} '{$v}')";
  1701. }
  1702. if(trim($request->input('f_rpm'))) {
  1703. $v = trim($request->input('f_rpm'));
  1704. if($v === 'yes') {
  1705. $conditions[] = "(care_month.is_client_enrolled_in_rm IS TRUE)";
  1706. }
  1707. elseif($v === 'no') {
  1708. $conditions[] = "(care_month.is_client_enrolled_in_rm IS NOT TRUE)";
  1709. }
  1710. }
  1711. if(trim($request->input('f_cell_bp'))) {
  1712. $v = trim($request->input('f_cell_bp'));
  1713. if($v === 'yes') {
  1714. $conditions[] = "(client.is_assigned_cellular_bp_device IS NOT NULL AND client.is_assigned_cellular_bp_device = TRUE)";
  1715. }
  1716. elseif($v === 'no') {
  1717. $conditions[] = "(client.is_assigned_cellular_bp_device IS NULL OR client.is_assigned_cellular_bp_device = FALSE)";
  1718. }
  1719. }
  1720. if(trim($request->input('f_cell_wt'))) {
  1721. $v = trim($request->input('f_cell_wt'));
  1722. if($v === 'yes') {
  1723. $conditions[] = "(client.is_assigned_cellular_weight_scale_device IS NOT NULL AND client.is_assigned_cellular_weight_scale_device = TRUE)";
  1724. }
  1725. elseif($v === 'no') {
  1726. $conditions[] = "(client.is_assigned_cellular_weight_scale_device IS NULL OR client.is_assigned_cellular_weight_scale_device = FALSE)";
  1727. }
  1728. }
  1729. if(trim($request->input('f_lmb'))) {
  1730. $v = trim($request->input('f_lmb'));
  1731. switch($v) {
  1732. case '1':
  1733. $conditions[] = "(GREATEST(client.most_recent_cellular_bp_measurement_at::DATE, client.most_recent_cellular_weight_measurement_at::DATE)::DATE < (NOW() - INTERVAL '1 DAY')::DATE)";
  1734. break;
  1735. case '2':
  1736. $conditions[] = "(GREATEST(client.most_recent_cellular_bp_measurement_at::DATE, client.most_recent_cellular_weight_measurement_at::DATE)::DATE < (NOW() - INTERVAL '2 DAYS')::DATE)";
  1737. break;
  1738. case '3':
  1739. $conditions[] = "(GREATEST(client.most_recent_cellular_bp_measurement_at::DATE, client.most_recent_cellular_weight_measurement_at::DATE)::DATE < (NOW() - INTERVAL '3 DAYS')::DATE)";
  1740. break;
  1741. case '3+':
  1742. $conditions[] = "(GREATEST(client.most_recent_cellular_bp_measurement_at::DATE, client.most_recent_cellular_weight_measurement_at::DATE)::DATE < (NOW() - INTERVAL '4 DAYS')::DATE)";
  1743. break;
  1744. }
  1745. }
  1746. if(trim($request->input('f_comm'))) {
  1747. $v = trim($request->input('f_comm'));
  1748. if($v === 'yes') {
  1749. $conditions[] = "(care_month.has_mcp_interacted_with_client_about_rm IS NOT NULL AND care_month.has_mcp_interacted_with_client_about_rm = TRUE)";
  1750. }
  1751. elseif($v === 'no') {
  1752. $conditions[] = "(care_month.has_mcp_interacted_with_client_about_rm IS NULL OR care_month.has_mcp_interacted_with_client_about_rm = FALSE)";
  1753. }
  1754. }
  1755. if(trim($request->input('f_mcp_billable'))) {
  1756. $v = trim($request->input('f_mcp_billable'));
  1757. if($v === 'yes') {
  1758. $conditions[] = "(care_month.mcp_rm_generic_bill_id IS NOT NULL)";
  1759. }
  1760. elseif($v === 'no') {
  1761. $conditions[] = "(care_month.mcp_rm_generic_bill_id IS NULL)";
  1762. }
  1763. }
  1764. if(trim($request->input('f_rmm_billable'))) {
  1765. $v = trim($request->input('f_rmm_billable'));
  1766. if($v === 'yes') {
  1767. $conditions[] = "(care_month.rmm_rm_generic_bill_id IS NOT NULL)";
  1768. }
  1769. elseif($v === 'no') {
  1770. $conditions[] = "(care_month.rmm_rm_generic_bill_id IS NULL)";
  1771. }
  1772. }
  1773. if(trim($request->input('f_md_op')) && trim($request->input('f_md')) !== '') {
  1774. $o = trim($request->input('f_md_op'));
  1775. $v = trim($request->input('f_md'));
  1776. $conditions[] = "(care_month.number_of_days_with_remote_measurements {$o} {$v})";
  1777. }
  1778. if(trim($request->input('f_unst_op')) && trim($request->input('f_unst')) !== '') {
  1779. $o = trim($request->input('f_unst_op'));
  1780. $v = trim($request->input('f_unst'));
  1781. $conditions[] = "(care_month.rm_num_measurements_not_stamped_by_mcp {$o} {$v})";
  1782. }
  1783. if(trim($request->input('f_mcp_mins_op')) && trim($request->input('f_mcp_mins')) !== '') {
  1784. $o = trim($request->input('f_mcp_mins_op'));
  1785. $v = intval(trim($request->input('f_mcp_mins'))) * 60;
  1786. $conditions[] = "(care_month.rm_total_time_in_seconds_by_mcp {$o} {$v})";
  1787. }
  1788. if(trim($request->input('f_rmm_mins_op')) && trim($request->input('f_rmm_mins')) !== '') {
  1789. $o = trim($request->input('f_rmm_mins_op'));
  1790. $v = intval(trim($request->input('f_rmm_mins'))) * 60;
  1791. $conditions[] = "(care_month.rm_total_time_in_seconds_by_rmm_pro {$o} {$v})";
  1792. }
  1793. if(trim($request->input('f_dslm_op')) && trim($request->input('f_dslm')) !== '') {
  1794. $o = trim($request->input('f_dslm_op'));
  1795. $v = trim($request->input('f_dslm'));
  1796. $conditions[] = "(DATE_PART('day', NOW() - client.most_recent_cellular_measurement_at) {$o} {$v})";
  1797. }
  1798. if($request->input('not-enrolled')) {
  1799. $conditions[] = "(care_month.is_client_enrolled_in_rm IS NOT TRUE)";
  1800. }
  1801. else {
  1802. $conditions[] = "(care_month.is_client_enrolled_in_rm IS TRUE)";
  1803. }
  1804. if($request->input('f_claim_closed')) {
  1805. if($request->input('f_claim_closed') === 'no') {
  1806. $conditions[] = "(care_month.is_claim_closed IS NULL OR care_month.is_claim_closed IS FALSE)";
  1807. }
  1808. else {
  1809. $conditions[] = "(care_month.is_claim_closed IS TRUE)";
  1810. }
  1811. }
  1812. if($request->input('f_mcp_billable')) {
  1813. if($request->input('f_mcp_billable') === 'no') {
  1814. $conditions[] = "(care_month.is_billable_by_mcp IS NULL OR care_month.is_billable_by_mcp IS FALSE)";
  1815. }
  1816. else {
  1817. $conditions[] = "(care_month.is_billable_by_mcp IS TRUE)";
  1818. }
  1819. }
  1820. if($request->input('f_rmm_billable')) {
  1821. if($request->input('f_rmm_billable') === 'no') {
  1822. $conditions[] = "(care_month.is_billable_by_rmm IS NULL OR care_month.is_billable_by_rmm IS FALSE)";
  1823. }
  1824. else {
  1825. $conditions[] = "(care_month.is_billable_by_rmm IS TRUE)";
  1826. }
  1827. }
  1828. switch($request->input('f_454')) {
  1829. case 'Claimable':
  1830. $conditions[] = "(care_month.is_99454_claimable IS TRUE)";
  1831. break;
  1832. case 'Not Claimable':
  1833. $conditions[] = "(care_month.is_99454_claimable IS NULL OR care_month.is_99454_claimable IS FALSE)";
  1834. break;
  1835. case 'Claimed':
  1836. $conditions[] = "(care_month.is_99454_claimable IS TRUE AND care_month.is_99454_claimed IS TRUE)";
  1837. break;
  1838. case 'Not Claimed':
  1839. $conditions[] = "(care_month.is_99454_claimable IS TRUE AND (care_month.is_99454_claimed IS NULL OR care_month.is_99454_claimed IS FALSE))";
  1840. break;
  1841. case 'Waived':
  1842. $conditions[] = "(care_month.is_99454_claimable IS TRUE AND care_month.is_99454_claiming_waived IS TRUE)";
  1843. break;
  1844. }
  1845. switch($request->input('f_454')) {
  1846. case 'Claimable':
  1847. $conditions[] = "(care_month.is_99454_claimable IS TRUE)";
  1848. break;
  1849. case 'Not Claimable':
  1850. $conditions[] = "(care_month.is_99454_claimable IS NULL OR care_month.is_99454_claimable IS FALSE)";
  1851. break;
  1852. case 'Claimed':
  1853. $conditions[] = "(care_month.is_99454_claimable IS TRUE AND care_month.is_99454_claimed IS TRUE)";
  1854. break;
  1855. case 'Not Claimed':
  1856. $conditions[] = "(care_month.is_99454_claimable IS TRUE AND (care_month.is_99454_claimed IS NULL OR care_month.is_99454_claimed IS FALSE))";
  1857. break;
  1858. case 'Waived':
  1859. $conditions[] = "(care_month.is_99454_claimable IS TRUE AND care_month.is_99454_claiming_waived IS TRUE)";
  1860. break;
  1861. }
  1862. switch($request->input('f_457')) {
  1863. case 'Claimable':
  1864. $conditions[] = "(care_month.is_99457_claimable IS TRUE)";
  1865. break;
  1866. case 'Not Claimable':
  1867. $conditions[] = "(care_month.is_99457_claimable IS NULL OR care_month.is_99457_claimable IS FALSE)";
  1868. break;
  1869. case 'Claimed':
  1870. $conditions[] = "(care_month.is_99457_claimable IS TRUE AND care_month.is_99457_claimed IS TRUE)";
  1871. break;
  1872. case 'Not Claimed':
  1873. $conditions[] = "(care_month.is_99457_claimable IS TRUE AND (care_month.is_99457_claimed IS NULL OR care_month.is_99457_claimed IS FALSE))";
  1874. break;
  1875. case 'Waived':
  1876. $conditions[] = "(care_month.is_99457_claimable IS TRUE AND care_month.is_99457_claiming_waived IS TRUE)";
  1877. break;
  1878. }
  1879. switch($request->input('f_458')) {
  1880. case 'Claimable':
  1881. $conditions[] = "(care_month.is_99458_claimable IS TRUE)";
  1882. break;
  1883. case 'Not Claimable':
  1884. $conditions[] = "(care_month.is_99458_claimable IS NULL OR care_month.is_99458_claimable IS FALSE)";
  1885. break;
  1886. case 'Claimed':
  1887. $conditions[] = "(care_month.is_99458_claimable IS TRUE AND care_month.is_99458_claimed IS TRUE)";
  1888. break;
  1889. case 'Not Claimed':
  1890. $conditions[] = "(care_month.is_99458_claimable IS TRUE AND (care_month.is_99458_claimed IS NULL OR care_month.is_99458_claimed IS FALSE))";
  1891. break;
  1892. case 'Waived':
  1893. $conditions[] = "(care_month.is_99458_claimable IS TRUE AND care_month.is_99458_claiming_waived IS TRUE)";
  1894. break;
  1895. }
  1896. if($request->input('f_visit_90_days')) {
  1897. /*if($request->input('f_visit_90_days') === 'yes') {
  1898. $conditions[] = "(care_month.is_claim_closed IS " . ($request->input('f_claim_closed') === 'yes' ? 'TRUE' : 'FALSE') . ")";
  1899. }
  1900. else {
  1901. $conditions[] = "(care_month.is_claim_closed IS " . ($request->input('f_claim_closed') === 'yes' ? 'TRUE' : 'FALSE') . ")";
  1902. }*/
  1903. }
  1904. $genericBillIdColumns = "care_month.mcp_rm_generic_bill_id,
  1905. mcpBill.uid as mcp_rm_generic_bill_uid,
  1906. mcpBill.generic_pro_id as mcp_rm_generic_bill_generic_pro_id,
  1907. mcpBill.generic_pro_expected_payment_amount as mcp_rm_generic_bill_expected_payment_amount,
  1908. mcpBill.is_signed_by_generic_pro as mcp_rm_generic_bill_signed,
  1909. care_month.rmm_rm_generic_bill_id,
  1910. rmmBill.uid as rmm_rm_generic_bill_uid,
  1911. rmmBill.generic_pro_id as rmm_rm_generic_bill_generic_pro_id,
  1912. rmmBill.generic_pro_expected_payment_amount as rmm_rm_generic_bill_expected_payment_amount,
  1913. rmmBill.is_signed_by_generic_pro as rmm_rm_generic_bill_signed";
  1914. $genericBillJoinClause = "left join bill mcpBill on care_month.mcp_rm_generic_bill_id = mcpBill.id
  1915. left join bill rmmBill on care_month.rmm_rm_generic_bill_id = rmmBill.id";
  1916. $defaultPageSize = 25;
  1917. $page = $request->input('page') ?: 1;
  1918. $perPage = $request->input('per_page') ?: $defaultPageSize;
  1919. $offset = ($page - 1) * $perPage;
  1920. $countQuery = "
  1921. SELECT COUNT(*)
  1922. FROM care_month join client on care_month.client_id = client.id
  1923. join note mrnote on client.most_recent_completed_mcp_note_id = mrnote.id
  1924. left join pro mcpPro on care_month.mcp_pro_id = mcpPro.id
  1925. left join pro rmmPro on care_month.rmm_pro_id = rmmPro.id
  1926. left join client_primary_coverage cpc on client.effective_client_primary_coverage_id = cpc.id
  1927. left join payer on cpc.commercial_payer_id = payer.id
  1928. {$genericBillJoinClause}
  1929. WHERE
  1930. EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1931. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1932. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '') . "
  1933. ";
  1934. $countResult = DB::select($countQuery);
  1935. $total = $countResult[0]->count;
  1936. $query = "
  1937. SELECT client.name_first, client.name_last,
  1938. (client.name_first || ' ' || client.name_last) as client_name,
  1939. client.uid as client_uid,
  1940. client.dob,
  1941. client.age_in_years,
  1942. care_month.is_client_enrolled_in_rm,
  1943. client.most_recent_completed_mcp_note_date,
  1944. client.most_recent_completed_mcp_note_id,
  1945. client.cell_number,
  1946. client.is_assigned_cellular_bp_device,
  1947. client.is_assigned_cellular_weight_scale_device,
  1948. nv.raw_date as next_visit_date,
  1949. DATE_PART('day', NOW() - client.most_recent_cellular_measurement_at) as dslm,
  1950. care_month.uid as care_month_uid,
  1951. care_month.id as care_month_id,
  1952. care_month.is_claim_closed,
  1953. care_month.start_date,
  1954. care_month.rm_total_time_in_seconds,
  1955. care_month.rm_total_time_in_seconds_by_mcp,
  1956. care_month.rm_total_time_in_seconds_by_rmm_pro,
  1957. care_month.number_of_days_with_remote_measurements,
  1958. care_month.has_mcp_interacted_with_client_about_rm,
  1959. care_month.has_anyone_interacted_with_client_about_rm,
  1960. care_month.rm_num_measurements_not_stamped_by_mcp,
  1961. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  1962. care_month.rm_num_measurements_not_stamped_by_rmm,
  1963. care_month.rm_num_measurements_not_stamped_by_rme,
  1964. care_month.is_99454_claimable,
  1965. care_month.is_99454_claimed,
  1966. care_month.is_99454_claiming_waived,
  1967. care_month.is_99457_claimable,
  1968. care_month.is_99457_claimed,
  1969. care_month.is_99457_claiming_waived,
  1970. care_month.is_99458_claimable,
  1971. care_month.is_99458_claimed,
  1972. care_month.is_99458_claiming_waived,
  1973. care_month.is_billable_by_mcp,
  1974. care_month.is_billable_by_rmm,
  1975. care_month.why_99454_not_claimable_reason,
  1976. care_month.why_99457_not_claimable_reason,
  1977. care_month.why_99458_not_claimable_reason,
  1978. care_month.why_claiming_99454_waived,
  1979. care_month.why_claiming_99457_waived,
  1980. care_month.why_claiming_99458_waived,
  1981. care_month.mcp_pro_id as care_month_mcp_pro_id,
  1982. care_month.rmm_pro_id as care_month_rmm_pro_id,
  1983. client.mcp_pro_id,
  1984. client.default_na_pro_id,
  1985. client.rmm_pro_id,
  1986. client.rme_pro_id,
  1987. client.cell_number,
  1988. care_month.most_recent_cellular_bp_dbp_mm_hg,
  1989. care_month.most_recent_cellular_bp_sbp_mm_hg,
  1990. care_month.most_recent_cellular_bp_measurement_at,
  1991. care_month.most_recent_cellular_weight_value,
  1992. care_month.most_recent_cellular_weight_measurement_at,
  1993. mcpPro.mcp_rpm_payment_strategy,
  1994. mcpPro.mcp_rpm_payment_amount,
  1995. (mcpPro.name_first || ' ' || mcpPro.name_last) as mcp_name,
  1996. rmmPro.rmm_payment_strategy,
  1997. rmmPro.rmm_payment_amount,
  1998. client.mailing_address_state,
  1999. care_month.most_recent_cellular_weight_measurement_at,
  2000. care_month.days_between_most_recent_mcp_note_date_and_end_of_care_month,
  2001. cpc.plan_type,
  2002. cpc.auto_medicare_is_partbprimary,
  2003. (CASE
  2004. WHEN cpc.plan_type LIKE 'COMMERCIAL' THEN payer.name
  2005. ELSE cpc.plan_type
  2006. END) as payer_name,
  2007. (SELECT COUNT(*) FROM claim_line where claim_line.cpt = '99454' AND claim_line.claim_id IN (SELECT claim.id FROM claim WHERE claim.care_month_id = care_month.id AND claim.status != 'CANCELLED')) as claim_454,
  2008. (SELECT COUNT(*) FROM claim_line where claim_line.cpt = '99457' AND claim_line.claim_id IN (SELECT claim.id FROM claim WHERE claim.care_month_id = care_month.id AND claim.status != 'CANCELLED')) as claim_457,
  2009. (SELECT COUNT(*) FROM claim_line where claim_line.cpt = '99458' AND claim_line.claim_id IN (SELECT claim.id FROM claim WHERE claim.care_month_id = care_month.id AND claim.status != 'CANCELLED')) as claim_458,
  2010. {$genericBillIdColumns}
  2011. FROM care_month join client on care_month.client_id = client.id
  2012. left join note mrnote on client.most_recent_completed_mcp_note_id = mrnote.id
  2013. left join pro mcpPro on care_month.mcp_pro_id = mcpPro.id
  2014. left join pro rmmPro on care_month.rmm_pro_id = rmmPro.id
  2015. left join client_primary_coverage cpc on client.effective_client_primary_coverage_id = cpc.id
  2016. left join payer on cpc.commercial_payer_id = payer.id
  2017. left join appointment nv on nv.id = mrnote.follow_up_appointment_id
  2018. {$genericBillJoinClause}
  2019. WHERE
  2020. EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  2021. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  2022. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '') . "
  2023. {$orderBy} OFFSET {$offset} LIMIT {$perPage}
  2024. ";
  2025. // dd($query);
  2026. $patients = DB::select($query);
  2027. $timestamp = strtotime(date('Y-m-d'));
  2028. $daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
  2029. $paginator = new LengthAwarePaginator($patients, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  2030. $perPage = $request->input('per_page') ?: $defaultPageSize;
  2031. $paginator->setPath(route('practice-management.rpm-matrix-admin'));
  2032. return view('app.practice-management.rpm-matrix-for-admin', compact('patients', 'daysRemaining', 'careMonthStart', 'paginator', 'perPage'));
  2033. }
  2034. public function claimsReport(Request $request) {
  2035. $performer = $this->performer();
  2036. $conditions = ["(claim.status = 'SUBMITTED')"];
  2037. // default sort
  2038. if(!$request->input('sort_by')) {
  2039. $orderBy = "cline.created_at DESC NULLS LAST";
  2040. }
  2041. else {
  2042. $sortBy = json_decode($request->input('sort_by'));
  2043. $orderByClause = [];
  2044. foreach ($sortBy as $sortCriteria) {
  2045. $orderByClause[] = "{$sortCriteria->key} {$sortCriteria->order} NULLS LAST";
  2046. }
  2047. $orderBy = implode(', ', $orderByClause);
  2048. }
  2049. // filters from the UI
  2050. if(trim($request->input('f_start'))) {
  2051. $v = trim($request->input('f_start'));
  2052. $conditions[] = "(cline.date_of_service >= '{$v}')";
  2053. }
  2054. if(trim($request->input('f_end'))) {
  2055. $v = trim($request->input('f_end'));
  2056. $conditions[] = "(cline.date_of_service <= '{$v}')";
  2057. }
  2058. $defaultPageSize = 25;
  2059. $page = $request->input('page') ?: 1;
  2060. $perPage = $request->input('per_page') ?: $defaultPageSize;
  2061. $offset = ($page - 1) * $perPage;
  2062. $countQuery = "
  2063. SELECT COUNT(*)
  2064. FROM claim_line cline
  2065. join claim on cline.claim_id = claim.id
  2066. join client on claim.client_id = client.id
  2067. left join pro on claim.pro_id = pro.id
  2068. left join client_primary_coverage cpc on client.effective_client_primary_coverage_id = cpc.id
  2069. left join payer on cpc.commercial_payer_id = payer.id
  2070. WHERE
  2071. " . implode(' AND ', $conditions) . "
  2072. ";
  2073. $countResult = DB::select($countQuery);
  2074. $total = $countResult[0]->count;
  2075. $query = "
  2076. SELECT (client.name_first || ' ' || client.name_last) as client_name,
  2077. client.uid as client_uid,
  2078. client.dob,
  2079. client.age_in_years,
  2080. client.is_enrolled_in_rm,
  2081. client.mailing_address_state,
  2082. (pro.name_first || ' ' || pro.name_last) as pro_name,
  2083. (CASE
  2084. WHEN cpc.plan_type LIKE 'COMMERCIAL' THEN payer.name
  2085. ELSE cpc.plan_type
  2086. END) as payer_name,
  2087. cline.date_of_service,
  2088. cline.cpt
  2089. FROM claim_line cline
  2090. join claim on cline.claim_id = claim.id
  2091. join client on claim.client_id = client.id
  2092. left join pro on claim.pro_id = pro.id
  2093. left join client_primary_coverage cpc on client.effective_client_primary_coverage_id = cpc.id
  2094. left join payer on cpc.commercial_payer_id = payer.id
  2095. WHERE
  2096. " . implode(' AND ', $conditions) . "
  2097. ORDER BY {$orderBy} OFFSET {$offset} LIMIT {$perPage}
  2098. ";
  2099. // dd($query);
  2100. $rows = DB::select($query);
  2101. $paginator = new LengthAwarePaginator($rows, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  2102. $perPage = $request->input('per_page') ?: $defaultPageSize;
  2103. $paginator->setPath(route('practice-management.claims-report'));
  2104. return view('app.practice-management.claims-report', compact('rows', 'paginator', 'perPage'));
  2105. }
  2106. public function problemsReport(Request $request) {
  2107. $performer = $this->performer();
  2108. $conditions = [];
  2109. // default sort
  2110. if(!$request->input('sort_by')) {
  2111. $orderBy = "p.created_at DESC NULLS LAST";
  2112. }
  2113. else {
  2114. $sortBy = json_decode($request->input('sort_by'));
  2115. $orderByClause = [];
  2116. foreach ($sortBy as $sortCriteria) {
  2117. $orderByClause[] = "{$sortCriteria->key} {$sortCriteria->order} NULLS LAST";
  2118. }
  2119. $orderBy = implode(', ', $orderByClause);
  2120. }
  2121. // filters from the UI
  2122. if(trim($request->input('f_client'))) {
  2123. $v = trim($request->input('f_client'));
  2124. $v = Client::where('uid', $v)->first();
  2125. if($v) {
  2126. $conditions[] = "(c.id = {$v->id})";
  2127. }
  2128. }
  2129. if(trim($request->input('f_mcp'))) {
  2130. $v = trim($request->input('f_mcp'));
  2131. $v = Pro::where('uid', $v)->first();
  2132. if($v) {
  2133. $conditions[] = "(c.mcp_pro_id = {$v->id})";
  2134. }
  2135. }
  2136. if(trim($request->input('f_problem'))) {
  2137. $v = strtolower(trim($request->input('f_problem')));
  2138. if($v) {
  2139. $conditions[] = "(((p.data)::json->>'name')::text ILIKE '%{$v}%')";
  2140. }
  2141. }
  2142. if(trim($request->input('f_icd'))) {
  2143. $v = strtolower(trim($request->input('f_icd')));
  2144. if($v) {
  2145. $conditions[] = "(((p.data)::json->>'icd')::text ILIKE '{$v}%')";
  2146. }
  2147. }
  2148. if(trim($request->input('f_lr_date_op')) && trim($request->input('f_lr_date')) !== '') {
  2149. $o = trim($request->input('f_lr_date_op'));
  2150. $v = trim($request->input('f_lr_date'));
  2151. $conditions[] = "(p.last_child_review_effective_date {$o} '{$v}')";
  2152. }
  2153. if(trim($request->input('f_lr_by'))) {
  2154. $v = trim($request->input('f_lr_by'));
  2155. if($v) {
  2156. $conditions[] = "(p.last_child_review_creator_pro_uid = '{$v}')";
  2157. }
  2158. }
  2159. if(trim($request->input('f_lp_date_op')) && trim($request->input('f_lp_date')) !== '') {
  2160. $o = trim($request->input('f_lp_date_op'));
  2161. $v = trim($request->input('f_lp_date'));
  2162. $conditions[] = "(p.last_child_plan_effective_date {$o} '{$v}')";
  2163. }
  2164. if(trim($request->input('f_lp_by'))) {
  2165. $v = trim($request->input('f_lp_by'));
  2166. if($v) {
  2167. $conditions[] = "(p.last_child_plan_creator_pro_uid = '{$v}')";
  2168. }
  2169. }
  2170. $defaultPageSize = 25;
  2171. $page = $request->input('page') ?: 1;
  2172. $perPage = $request->input('per_page') ?: $defaultPageSize;
  2173. $offset = ($page - 1) * $perPage;
  2174. $countQuery = "
  2175. SELECT COUNT(*)
  2176. FROM point p
  2177. join client c on p.client_id = c.id
  2178. join pro mcp on c.mcp_pro_id = mcp.id
  2179. left join client_primary_coverage cpc on c.effective_client_primary_coverage_id = cpc.id
  2180. left join payer on cpc.commercial_payer_id = payer.id
  2181. WHERE p.category = 'PROBLEM'
  2182. AND p.is_removed_due_to_entry_error IS NOT TRUE " .
  2183. (count($conditions) ? ' AND ' . implode(' AND ', $conditions) : '');
  2184. $countResult = DB::select($countQuery);
  2185. $total = $countResult[0]->count;
  2186. $query = "
  2187. SELECT p.uid as point_uid,
  2188. (c.name_first || ' ' || c.name_last) as client_name,
  2189. c.uid as client_uid,
  2190. c.dob,
  2191. c.age_in_years,
  2192. c.is_enrolled_in_rm,
  2193. c.mailing_address_state,
  2194. (mcp.name_first || ' ' || mcp.name_last) as mcp_name,
  2195. (CASE
  2196. WHEN cpc.plan_type LIKE 'COMMERCIAL' THEN payer.name
  2197. ELSE cpc.plan_type
  2198. END) as payer_name,
  2199. row_to_json(p.*) as point,
  2200. ((p.data)::json->>'name')::text as problem,
  2201. ((p.data)::json->>'icd')::text as icd,
  2202. p.last_child_review_effective_date as last_review_date,
  2203. (p.last_child_review_creator_pro_first_name || ' ' || p.last_child_review_creator_pro_last_name) as last_review_by,
  2204. ((last_review.data)::json->>'value')::text as last_review_content,
  2205. p.last_child_plan_effective_date as last_plan_date,
  2206. (p.last_child_plan_creator_pro_first_name || ' ' || p.last_child_plan_creator_pro_last_name) as last_plan_by,
  2207. ((last_plan.data)::json->>'value')::text as last_plan_content
  2208. FROM point p
  2209. join client c on p.client_id = c.id
  2210. join pro mcp on c.mcp_pro_id = mcp.id
  2211. left join client_primary_coverage cpc on c.effective_client_primary_coverage_id = cpc.id
  2212. left join payer on cpc.commercial_payer_id = payer.id
  2213. left join point last_review on p.last_child_review_point_id = last_review.id
  2214. left join point last_plan on p.last_child_plan_point_id = last_plan.id
  2215. WHERE p.category = 'PROBLEM'
  2216. AND p.is_removed_due_to_entry_error IS NOT TRUE " .
  2217. (count($conditions) ? ' AND ' . implode(' AND ', $conditions) : '') . "
  2218. ORDER BY {$orderBy} OFFSET {$offset} LIMIT {$perPage}";
  2219. // dd($query);
  2220. $rows = DB::select($query);
  2221. $paginator = new LengthAwarePaginator($rows, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  2222. $perPage = $request->input('per_page') ?: $defaultPageSize;
  2223. $paginator->setPath(route('practice-management.problems-report'));
  2224. return view('app.practice-management.problems-report', compact('rows', 'paginator', 'perPage'));
  2225. }
  2226. public function remoteMonitoringMCP(Request $request) {
  2227. return $this->rpmMatrixByProType($request, 'mcp');
  2228. }
  2229. public function remoteMonitoringRMM(Request $request) {
  2230. return $this->rpmMatrixByProType($request, 'rmm');
  2231. }
  2232. public function remoteMonitoringRME(Request $request) {
  2233. return $this->rpmMatrixByProType($request, 'rme');
  2234. }
  2235. public function remoteMonitoring_RowMCP(Request $request) {
  2236. return $this->remoteMonitoring_RowByProType($request, 'mcp');
  2237. }
  2238. public function remoteMonitoring_RowRMM(Request $request) {
  2239. return $this->remoteMonitoring_RowByProType($request, 'rmm');
  2240. }
  2241. public function remoteMonitoring_RowRME(Request $request) {
  2242. return $this->remoteMonitoring_RowByProType($request, 'rme');
  2243. }
  2244. public function remoteMonitoring_RowADMIN(Request $request) {
  2245. return $this->remoteMonitoring_RowForAdmin($request);
  2246. }
  2247. public function rpm_work_matrix(Request $request) {
  2248. // get the patient having most recent unstamped measurement
  2249. $performer = $this->performer();
  2250. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  2251. $careMonthStart = date($ym . '-01');
  2252. $patient = null;
  2253. $careMonth = null;
  2254. if($request->input('patientUid') && $request->input('careMonthUid')) {
  2255. $patient = Client::where('uid', $request->input('patientUid'))->first();
  2256. $careMonth = CareMonth::where('uid', $request->input('careMonthUid'))->first();
  2257. }
  2258. if(!$patient && !$careMonth) {
  2259. $query = "
  2260. SELECT client.name_first, client.name_last,
  2261. (client.name_first || ' ' || client.name_last) as client_name,
  2262. client.uid as client_uid,
  2263. client.dob,
  2264. care_month.is_client_enrolled_in_rm,
  2265. client.most_recent_completed_mcp_note_date,
  2266. care_month.uid as care_month_uid,
  2267. care_month.id as care_month_id,
  2268. care_month.start_date,
  2269. care_month.rm_total_time_in_seconds_by_mcp,
  2270. care_month.number_of_days_with_remote_measurements,
  2271. care_month.rm_num_measurements_not_stamped_by_mcp,
  2272. care_month.rm_num_measurements_not_stamped_by_rmm,
  2273. client.mcp_pro_id,
  2274. client.default_na_pro_id,
  2275. client.rmm_pro_id,
  2276. client.rme_pro_id,
  2277. client.cell_number,
  2278. client.most_recent_cellular_bp_dbp_mm_hg,
  2279. client.most_recent_cellular_bp_sbp_mm_hg,
  2280. client.most_recent_cellular_bp_measurement_at,
  2281. client.most_recent_cellular_weight_value,
  2282. client.most_recent_cellular_weight_measurement_at,
  2283. GREATEST(client.most_recent_cellular_bp_measurement_at, client.most_recent_cellular_weight_measurement_at) as latest_measurement_at
  2284. FROM care_month join client on care_month.client_id = client.id
  2285. WHERE
  2286. (
  2287. (care_month.mcp_pro_id = {$performer->pro->id} AND care_month.rm_num_measurements_not_stamped_by_mcp > 0) OR
  2288. (care_month.rmm_pro_id = {$performer->pro->id} AND care_month.rm_num_measurements_not_stamped_by_rmm > 0)
  2289. )
  2290. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  2291. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  2292. ORDER BY latest_measurement_at DESC
  2293. LIMIT 1
  2294. ";
  2295. $patients = DB::select($query);
  2296. if (count($patients)) {
  2297. $patient = Client::where('uid', $patients[0]->client_uid)->first();
  2298. $careMonth = CareMonth::where('uid', $patients[0]->care_month_uid)->first();
  2299. }
  2300. }
  2301. return view('app.practice-management.rpm_work_matrix', compact('patient', 'careMonth'));
  2302. }
  2303. public function remoteMonitoringCount(Request $request) {
  2304. $performer = $this->performer();
  2305. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  2306. $careMonthStart = date($ym . '-01');
  2307. $rc = $request->input('rc') ?: 1;
  2308. $rc2 = $request->input('rc2') ?: 2;
  2309. $conditions = $this->rpmConditions($performer, $rc, $rc2);
  2310. $count = DB::select(
  2311. DB::raw(
  2312. "
  2313. SELECT count(*)
  2314. FROM care_month join client on care_month.client_id = client.id
  2315. WHERE
  2316. client.mcp_pro_id = {$performer->pro->id}
  2317. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  2318. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  2319. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '')
  2320. )
  2321. );
  2322. return $count[0]->count;
  2323. }
  2324. public function remoteMonitoringAdmin(Request $request) {
  2325. $performer = $this->performer();
  2326. // abort_if($performer->pro->pro_type !== 'ADMIN' && !$performer->pro->can_view_rm_matrix, 403);
  2327. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  2328. $careMonthStart = date($ym . '-01');
  2329. $rc = $request->input('rc') ?: 1;
  2330. $rc2 = $request->input('rc2') ?: 2;
  2331. $conditions = [];// $this->rpmConditions($performer, $rc, $rc2);
  2332. $sortBy = $request->input('sort_by') ?: 'name_first';
  2333. $sortDir = $request->input('sort_dir') ?: 'ASC';
  2334. $orderBy = "ORDER BY $sortBy $sortDir NULLS LAST";
  2335. $query = "
  2336. SELECT client.name_first, client.name_last,
  2337. (client.name_first || ' ' || client.name_last) as client_name,
  2338. (mcp_pro.name_first || ' ' || mcp_pro.name_last) as mcp_pro_name,
  2339. (rmm_pro.name_first || ' ' || rmm_pro.name_last) as rmm_pro_name,
  2340. client.uid as client_uid,
  2341. client.chart_number,
  2342. client.dob,
  2343. care_month.is_client_enrolled_in_rm,
  2344. client.most_recent_completed_mcp_note_date,
  2345. client.most_recent_completed_mcp_note_id,
  2346. mrmnote.effective_dateest::date as most_recent_completed_mcp_note_date_cm,
  2347. mrmnote.id as most_recent_completed_mcp_note_id_cm,
  2348. mrmnote.uid as most_recent_completed_mcp_note_uid_cm,
  2349. client.cell_number,
  2350. client.is_assigned_cellular_bp_device,
  2351. client.is_assigned_cellular_weight_scale_device,
  2352. care_month.uid as care_month_uid,
  2353. care_month.id as care_month_id,
  2354. care_month.start_date,
  2355. care_month.rm_total_time_in_seconds_by_mcp,
  2356. care_month.rm_total_time_in_seconds_by_rmm_pro,
  2357. care_month.number_of_days_with_remote_measurements,
  2358. care_month.has_anyone_interacted_with_client_about_rm,
  2359. care_month.has_mcp_interacted_with_client_about_rm,
  2360. care_month.rm_num_measurements_not_stamped_by_mcp,
  2361. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  2362. care_month.rm_num_measurements_not_stamped_by_rmm,
  2363. care_month.rm_num_measurements_not_stamped_by_rme,
  2364. care_month.mcp_pro_id as care_month_mcp_pro_id,
  2365. care_month.rmm_pro_id as care_month_rmm_pro_id,
  2366. client.mcp_pro_id,
  2367. client.default_na_pro_id,
  2368. client.rmm_pro_id,
  2369. client.rme_pro_id,
  2370. client.cell_number,
  2371. care_month.most_recent_cellular_bp_dbp_mm_hg,
  2372. care_month.most_recent_cellular_bp_sbp_mm_hg,
  2373. care_month.most_recent_cellular_bp_measurement_at,
  2374. care_month.most_recent_cellular_weight_value,
  2375. care_month.most_recent_cellular_weight_measurement_at
  2376. FROM care_month join client on care_month.client_id = client.id join note mrnote on client.most_recent_completed_mcp_note_id = mrnote.id
  2377. left join note mrmnote on mrmnote.id = (
  2378. select max(n.id) from note n
  2379. where
  2380. n.client_id = client.id AND
  2381. n.is_cancelled = FALSE AND
  2382. (n.is_signed_by_hcp IS NOT NULL AND n.is_signed_by_hcp = TRUE) AND
  2383. n.effective_dateest::date >= care_month.start_date::date AND
  2384. n.effective_dateest::date < (care_month.start_date::date + INTERVAL '1 month')
  2385. )
  2386. left join pro mcp_pro on care_month.mcp_pro_id = mcp_pro.id
  2387. left join pro rmm_pro on care_month.rmm_pro_id = rmm_pro.id
  2388. WHERE
  2389. EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  2390. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  2391. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '') . "
  2392. $orderBy
  2393. ";
  2394. $patients = DB::select($query);
  2395. $timestamp = strtotime(date('Y-m-d'));
  2396. $daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
  2397. return view('app.practice-management.remote-monitoring-admin', compact('patients', 'daysRemaining', 'careMonthStart'));
  2398. }
  2399. public function remoteMonitoringAdminCount(Request $request) {
  2400. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  2401. $careMonthStart = date($ym . '-01');
  2402. $rc = $request->input('rc') ?: 1;
  2403. $rc2 = $request->input('rc2') ?: 2;
  2404. $conditions = $this->rpmConditionsAdmin($this->performer(), $rc, $rc2);
  2405. $count = DB::select(
  2406. DB::raw(
  2407. "
  2408. SELECT count(*)
  2409. FROM care_month join client on care_month.client_id = client.id
  2410. WHERE
  2411. client.shadow_pro_id is null AND care_month.is_client_enrolled_in_rm IS TRUE
  2412. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  2413. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  2414. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '')
  2415. )
  2416. );
  2417. return $count[0]->count;
  2418. }
  2419. private function rpmConditions($performer, $rc, $rc2) {
  2420. $conditions = [];
  2421. $c_isMCP = "client.mcp_pro_id = {$performer->pro->id}";
  2422. $c_enrolledInRPM = "care_month.is_client_enrolled_in_rm IS TRUE";
  2423. $c_hasDevice = "(SELECT COUNT(client_bdt_device.id) FROM client_bdt_device JOIN bdt_device bd on client_bdt_device.device_id = bd.id WHERE client_bdt_device.client_id = client.id) > 0";
  2424. $c_lastVisitBefore90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) > 90";
  2425. $c_lastVisitWithin90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) <= 90";
  2426. $c_notSpokenToThisMonth = "(care_month.has_anyone_interacted_with_client_about_rm_outside_note IS NULL OR care_month.has_anyone_interacted_with_client_about_rm_outside_note = FALSE)";
  2427. $c_spokenToThisMonth = "care_month.has_anyone_interacted_with_client_about_rm_outside_note = TRUE";
  2428. $c_hasUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp > 0";
  2429. $c_hasNoUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp = 0";
  2430. $c_lt16MeasurementDays = "care_month.number_of_days_with_remote_measurements < 16";
  2431. $c_gte16MeasurementDays = "care_month.number_of_days_with_remote_measurements >= 16";
  2432. $c_subscribedToSMS = "client.send_sms_on_bdt_measurement = TRUE";
  2433. $c_deviceUsed = "(client.most_recent_cellular_bp_measurement_at IS NOT NULL OR most_recent_cellular_weight_measurement_at IS NOT NULL)";
  2434. $c_lt20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp < 1200";
  2435. $c_gte20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp >= 1200";
  2436. switch ($rc) {
  2437. case 1:
  2438. $conditions = [$c_isMCP];
  2439. break;
  2440. case 2:
  2441. $conditions = [$c_isMCP, $c_enrolledInRPM];
  2442. break;
  2443. case 3:
  2444. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice];
  2445. break;
  2446. case 4:
  2447. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, ($rc2 == 1 ? $c_lastVisitBefore90Days : $c_lastVisitWithin90Days)];
  2448. break;
  2449. case 5:
  2450. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, ($rc2 == 1 ? $c_notSpokenToThisMonth : $c_spokenToThisMonth)];
  2451. break;
  2452. case 6:
  2453. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_hasUnstamped : $c_hasNoUnstamped)];
  2454. break;
  2455. case 7:
  2456. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_lt16MeasurementDays : $c_gte16MeasurementDays)];
  2457. break;
  2458. case 10:
  2459. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, $c_gte16MeasurementDays, ($rc2 == 1 ? $c_lt20BillingMinutes : $c_gte20BillingMinutes)];
  2460. break;
  2461. case 8:
  2462. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_subscribedToSMS];
  2463. break;
  2464. case 9:
  2465. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_deviceUsed];
  2466. break;
  2467. }
  2468. return $conditions;
  2469. }
  2470. private function rpmConditionsAdmin($performer, $rc, $rc2) {
  2471. $conditions = [];
  2472. $c_enrolledInRPM = "care_month.is_client_enrolled_in_rm IS TRUE";
  2473. $c_hasDevice = "(SELECT COUNT(client_bdt_device.id) FROM client_bdt_device JOIN bdt_device bd on client_bdt_device.device_id = bd.id WHERE client_bdt_device.client_id = client.id) > 0";
  2474. $c_lastVisitBefore90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) > 90";
  2475. $c_lastVisitWithin90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) <= 90";
  2476. $c_notSpokenToThisMonth = "(care_month.has_anyone_interacted_with_client_about_rm_outside_note IS NULL OR care_month.has_anyone_interacted_with_client_about_rm_outside_note = FALSE)";
  2477. $c_spokenToThisMonth = "care_month.has_anyone_interacted_with_client_about_rm_outside_note = TRUE";
  2478. $c_hasUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp > 0";
  2479. $c_hasNoUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp = 0";
  2480. $c_lt16MeasurementDays = "care_month.number_of_days_with_remote_measurements < 16";
  2481. $c_gte16MeasurementDays = "care_month.number_of_days_with_remote_measurements >= 16";
  2482. $c_subscribedToSMS = "client.send_sms_on_bdt_measurement = TRUE";
  2483. $c_deviceUsed = "(client.most_recent_cellular_bp_measurement_at IS NOT NULL OR client.most_recent_cellular_weight_measurement_at IS NOT NULL)";
  2484. $c_lt20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp < 1200";
  2485. $c_gte20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp >= 1200";
  2486. switch ($rc) {
  2487. case 2:
  2488. $conditions = [$c_enrolledInRPM];
  2489. break;
  2490. case 3:
  2491. $conditions = [$c_enrolledInRPM, $c_hasDevice];
  2492. break;
  2493. case 4:
  2494. $conditions = [$c_enrolledInRPM, $c_hasDevice, ($rc2 == 1 ? $c_lastVisitBefore90Days : $c_lastVisitWithin90Days)];
  2495. break;
  2496. case 5:
  2497. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, ($rc2 == 1 ? $c_notSpokenToThisMonth : $c_spokenToThisMonth)];
  2498. break;
  2499. case 6:
  2500. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_hasUnstamped : $c_hasNoUnstamped)];
  2501. break;
  2502. case 7:
  2503. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_lt16MeasurementDays : $c_gte16MeasurementDays)];
  2504. break;
  2505. case 10:
  2506. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, $c_gte16MeasurementDays, ($rc2 == 1 ? $c_lt20BillingMinutes : $c_gte20BillingMinutes)];
  2507. break;
  2508. case 8:
  2509. $conditions = [$c_enrolledInRPM, $c_subscribedToSMS];
  2510. break;
  2511. case 9:
  2512. $conditions = [$c_enrolledInRPM, $c_deviceUsed];
  2513. break;
  2514. }
  2515. return $conditions;
  2516. }
  2517. public function remoteMonitoringMeasurements(Request $request, CareMonth $careMonth) {
  2518. $performer = $this->performer();
  2519. $measurements = DB::select(
  2520. DB::raw(
  2521. "
  2522. SELECT measurement.label,
  2523. measurement.ts,
  2524. measurement.effective_date,
  2525. measurement.sbp_mm_hg,
  2526. measurement.dbp_mm_hg,
  2527. measurement.value_pulse,
  2528. measurement.value_irregular,
  2529. measurement.numeric_value,
  2530. measurement.value,
  2531. measurement.uid,
  2532. client.name_first,
  2533. client.name_last,
  2534. client.mcp_pro_id,
  2535. client.default_na_pro_id,
  2536. client.rmm_pro_id,
  2537. client.rme_pro_id
  2538. FROM measurement RIGHT JOIN client on measurement.client_id = client.id
  2539. WHERE
  2540. client.id = {$careMonth->client_id}
  2541. AND measurement.label IS NOT NULL
  2542. AND measurement.label NOT IN ('SBP', 'DBP')
  2543. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  2544. AND measurement.is_removed IS FALSE
  2545. AND measurement.client_bdt_measurement_id IS NOT NULL
  2546. AND measurement.care_month_id = {$careMonth->id}
  2547. AND (
  2548. (client.mcp_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_mcp IS FALSE)
  2549. OR (client.rmm_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_rmm IS FALSE)
  2550. OR (client.rme_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_rme IS FALSE)
  2551. OR (client.default_na_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_non_hcp IS FALSE)
  2552. )
  2553. ORDER BY ts DESC
  2554. "
  2555. )
  2556. );
  2557. return view('app.practice-management.remote-monitoring-measurements', compact('careMonth', 'measurements'));
  2558. }
  2559. public function billMatrix(Request $request)
  2560. {
  2561. $bClients = [];
  2562. $bHCPPros = [];
  2563. $bNAPros = [];
  2564. $filters = [];
  2565. $filters['client'] = $request->input('client');
  2566. $filters['service'] = $request->input('service');
  2567. $filters['hcp'] = $request->input('hcp');
  2568. $filters['hcp_paid'] = $request->input('hcp_paid');
  2569. $filters['expected_op'] = $request->input('expected_op');
  2570. $filters['expected_value'] = $request->input('expected_value');
  2571. $filters['paid_op'] = $request->input('paid_op');
  2572. $filters['paid_value'] = $request->input('paid_value');
  2573. $filters['bal_post_date_op'] = $request->input('bal_post_date_op');
  2574. $filters['bal_post_date_value'] = $request->input('bal_post_date_value');
  2575. $filters['hcp_sign'] = $request->input('hcp_sign');
  2576. $filters['verified'] = $request->input('verified');
  2577. $filters['cancelled'] = $request->input('cancelled');
  2578. $bills = Bill::orderBy('effective_date')->paginate();
  2579. return view('app.practice-management.bill-matrix', compact('bills', 'bClients', 'bHCPPros', 'filters'));
  2580. }
  2581. public function medicarePartBClaims(Request $request)
  2582. {
  2583. $medicarePartBOnly = $request->get("medicare_part_b");
  2584. $allClaims = Claim::where('was_submitted', false)->orWhere('was_submitted', null)->orderBy('created_at', 'desc')->get();
  2585. //Only medicare claims
  2586. $claims = [];
  2587. foreach ($allClaims as $claim) {
  2588. if ($claim->client != null && $claim->client->getPrimaryCoverageStatus() == 'YES' && !$claim->edi) {
  2589. $claims[] = $claim;
  2590. }
  2591. }
  2592. $claimEDIs = ClaimEDI::all();
  2593. return view('app.practice-management.medicare-partb-claims', compact('claims', 'claimEDIs'));
  2594. }
  2595. // Generate PDF
  2596. public function downloadClaims()
  2597. {
  2598. $claims = Claim::where('was_submitted', false)->orWhere('was_submitted', null)->orderBy('created_at', 'desc')->limit(100)->get();
  2599. view()->share('claims', $claims);
  2600. $pdf = PDF::loadView('app.practice-management.claims-pdf', $claims);
  2601. return $pdf->download('pdf_file.pdf');
  2602. }
  2603. public function tickets(Request $request, $proUid = null)
  2604. {
  2605. $tickets = Ticket::orderBy('created_at', 'desc')->paginate();
  2606. return view('app.practice-management.tickets', compact('tickets'));
  2607. }
  2608. public function supplyOrders(Request $request)
  2609. {
  2610. // counts
  2611. $counts = $this->getSupplyOrderCounts();
  2612. // so clients
  2613. $soClientIDs = DB::table('supply_order')->select('client_id')->distinct()->get()->toArray();
  2614. $soClientIDs = array_map(function ($_x) {
  2615. return $_x->client_id;
  2616. }, $soClientIDs);
  2617. $soClients = Client::whereIn('id', $soClientIDs)->get();
  2618. // so products
  2619. $soProductIDs = DB::table('supply_order')->select('product_id')->distinct()->get()->toArray();
  2620. $soProductIDs = array_map(function ($_x) {
  2621. return $_x->product_id;
  2622. }, $soProductIDs);
  2623. $soProducts = Product::whereIn('id', $soProductIDs)->get();
  2624. $filters = [];
  2625. $filters['client'] = $request->input('client');
  2626. $filters['product'] = $request->input('product');
  2627. $filters['reason'] = $request->input('reason');
  2628. $filters['cu_memo'] = $request->input('cu_memo');
  2629. $filters['pro_sign'] = $request->input('pro_sign');
  2630. $filters['client_sign'] = $request->input('client_sign');
  2631. $filters['shipment'] = $request->input('shipment');
  2632. $filters['lot_number'] = $request->input('lot_number');
  2633. $filters['imei'] = $request->input('imei');
  2634. $filters['cancelled'] = $request->input('cancelled');
  2635. $supplyOrders = SupplyOrder::where('id', '>', 0);
  2636. // apply filters
  2637. if ($filters['client']) $supplyOrders->where('client_id', $filters['client']);
  2638. if ($filters['product']) $supplyOrders->where('product_id', $filters['product']);
  2639. if ($filters['reason']) $supplyOrders->where('reason', 'ILIKE', '%' . $filters['reason'] . '%');
  2640. if ($filters['cu_memo']) $supplyOrders->where('cu_memo', 'ILIKE', '%' . $filters['cu_memo'] . '%');
  2641. if ($filters['pro_sign']) $supplyOrders->where('is_signed_by_pro', ($filters['pro_sign'] === 'signed'));
  2642. if ($filters['client_sign']) {
  2643. if ($filters['client_sign'] === 'signed')
  2644. $supplyOrders->where('is_signed_by_client', true);
  2645. elseif ($filters['client_sign'] === 'waived')
  2646. $supplyOrders->where('is_client_signature_waived', true);
  2647. else
  2648. $supplyOrders->where('is_client_signature_waived', false)->where('is_signed_by_client', false);
  2649. }
  2650. if ($filters['shipment']) {
  2651. if ($filters['shipment'] === 'not_cleared_for_shipment')
  2652. $supplyOrders->whereNull('shipment_id')->where('is_cleared_for_shipment', false);
  2653. elseif ($filters['shipment'] === 'cleared_for_shipment')
  2654. $supplyOrders->whereNull('shipment_id')->where('is_cleared_for_shipment', true);
  2655. else
  2656. $supplyOrders
  2657. ->whereNotNull('shipment_id')
  2658. ->whereRaw('(SELECT status FROM shipment WHERE id = shipment_id LIMIT 1) = ?', [$filters['shipment']]);
  2659. }
  2660. if ($filters['lot_number']) $supplyOrders->where('lot_number', 'ILIKE', '%' . $filters['lot_number'] . '%');
  2661. if ($filters['imei']) $supplyOrders->where('imei', 'ILIKE', '%' . $filters['imei'] . '%');
  2662. if ($filters['cancelled']) $supplyOrders->where('is_cancelled', ($filters['cancelled'] === 'cancelled'));
  2663. $supplyOrders = $supplyOrders->orderBy('created_at', 'desc')->paginate();
  2664. return view('app.practice-management.supply-orders',
  2665. compact('supplyOrders', 'filters',
  2666. 'soClients', 'soProducts', 'counts'
  2667. )
  2668. );
  2669. }
  2670. public function shipments(Request $request, $filter = null)
  2671. {
  2672. // counts
  2673. $counts = $this->getShipmentCounts();
  2674. // so clients
  2675. $shClientIDs = DB::table('shipment')->select('client_id')->distinct()->get()->toArray();
  2676. $shClientIDs = array_map(function ($_x) {
  2677. return $_x->client_id;
  2678. }, $shClientIDs);
  2679. $shClients = Client::whereIn('id', $shClientIDs)->get();
  2680. $shipments = Shipment::where('id', '>', 0);
  2681. $filters = [];
  2682. $filters['client'] = $request->input('client');
  2683. $filters['courier'] = $request->input('courier');
  2684. $filters['tracking_num'] = $request->input('tracking_num');
  2685. $filters['label'] = $request->input('label');
  2686. $filters['status'] = $request->input('status');
  2687. $filters['cancelled'] = $request->input('cancelled');
  2688. if ($filters['client']) $shipments->where('client_id', $filters['client']);
  2689. if ($filters['courier']) $shipments->where('courier', 'ILIKE', '%' . $filters['courier'] . '%');
  2690. if ($filters['tracking_num']) $shipments->where('tracking_number', 'ILIKE', '%' . $filters['tracking_num'] . '%');
  2691. if ($filters['label']) {
  2692. if ($filters['label'] === 'yes')
  2693. $shipments->whereNotNull('label_system_file_id');
  2694. else
  2695. $shipments->whereNull('label_system_file_id');
  2696. }
  2697. if ($filters['status']) $shipments->where('status', $filters['status']);
  2698. if ($filters['cancelled']) $shipments->where('is_cancelled', ($filters['cancelled'] === 'cancelled'));
  2699. $shipments = $shipments->orderBy('created_at', 'desc')->paginate();
  2700. return view('app.practice-management.shipments', compact('shipments', 'filters', 'shClients', 'counts'));
  2701. }
  2702. public function cellularMeasurements(Request $request)
  2703. {
  2704. $measurements = Measurement::orderBy('ts', 'desc')->whereNotNull('ts')->paginate();
  2705. return view('app.practice-management.cellular-measurements', compact('measurements'));
  2706. }
  2707. // v2 supply-orders & shipments management (wh)
  2708. public function supplyOrdersReadyToShip(Request $request)
  2709. {
  2710. $counts = $this->getSupplyOrderCounts();
  2711. $supplyOrders = SupplyOrder
  2712. ::where('is_cleared_for_shipment', true)
  2713. ->where('is_cancelled', false)
  2714. ->whereNull('shipment_id')
  2715. ->join('client', 'client.id', '=', 'supply_order.client_id')
  2716. ->orderBy('client.name_last', 'ASC')
  2717. ->orderBy('client.name_first', 'ASC')
  2718. ->orderBy('supply_order.client_id', 'ASC')
  2719. ->orderBy('supply_order.mailing_address_full', 'ASC')
  2720. ->orderBy('supply_order.created_at', 'ASC')
  2721. ->select('supply_order.*')
  2722. ->paginate();
  2723. return view('app.practice-management.supply-orders-ready-to-ship', compact('supplyOrders', 'counts'));
  2724. }
  2725. public function supplyOrdersShipmentUnderway(Request $request)
  2726. {
  2727. $counts = $this->getSupplyOrderCounts();
  2728. $supplyOrders = SupplyOrder
  2729. ::where('is_cancelled', false)
  2730. ->whereNotNull('shipment_id')
  2731. ->orderBy('client_id', 'ASC')
  2732. ->orderBy('mailing_address_full', 'ASC')
  2733. ->orderBy('created_at', 'ASC')
  2734. ->paginate();
  2735. return view('app.practice-management.supply-orders-shipment-underway', compact('supplyOrders', 'counts'));
  2736. }
  2737. public function supplyOrdersHanging(Request $request)
  2738. {
  2739. $counts = $this->getSupplyOrderCounts();
  2740. $supplyOrders = SupplyOrder
  2741. ::select('supply_order.*')
  2742. ->leftJoin('shipment', function($join) {
  2743. $join->on('supply_order.shipment_id', '=', 'shipment.id');
  2744. })
  2745. ->where('shipment.status', 'CANCELLED')
  2746. ->where('supply_order.is_cancelled', false)
  2747. ->orderBy('supply_order.client_id', 'ASC')
  2748. ->orderBy('supply_order.mailing_address_full', 'ASC')
  2749. ->orderBy('supply_order.created_at', 'ASC')
  2750. ->paginate();
  2751. return view('app.practice-management.supply-orders-hanging', compact('supplyOrders', 'counts'));
  2752. }
  2753. public function supplyOrdersCancelledButUnacknowledged(Request $request)
  2754. {
  2755. $supplyOrders = SupplyOrder::where('signed_by_pro_id', $this->performer()->pro->id)
  2756. ->where('is_cancelled', true)
  2757. ->where('is_cancellation_acknowledged', false)
  2758. ->orderBy('created_at', 'desc')
  2759. ->paginate();
  2760. return view('app.practice-management.supply-orders-cancelled-but-unacknowledged', compact('supplyOrders'));
  2761. }
  2762. public function supplyOrdersUnsigned(Request $request)
  2763. {
  2764. $supplyOrders = SupplyOrder
  2765. ::where('is_cancelled', false)
  2766. ->where('is_signed_by_pro', false)
  2767. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$this->performer()->pro->id])
  2768. ->orderBy('created_at', 'desc')
  2769. ->paginate();
  2770. return view('app.practice-management.supply-orders-unsigned', compact('supplyOrders'));
  2771. }
  2772. private function getSupplyOrderCounts()
  2773. {
  2774. return [
  2775. "supplyOrders" => SupplyOrder::count(),
  2776. "supplyOrdersReadyToShip" => SupplyOrder
  2777. ::where('is_cleared_for_shipment', true)
  2778. ->where('is_cancelled', false)
  2779. ->whereNull('shipment_id')->count(),
  2780. "supplyOrdersShipmentUnderway" => SupplyOrder
  2781. ::where('is_cancelled', false)
  2782. ->whereNotNull('shipment_id')->count(),
  2783. "supplyOrdersHanging" => SupplyOrder
  2784. ::leftJoin('shipment', function($join) {
  2785. $join->on('supply_order.shipment_id', '=', 'shipment.id');
  2786. })
  2787. ->where('shipment.status', 'CANCELLED')
  2788. ->where('supply_order.is_cancelled', false)
  2789. ->count(),
  2790. ];
  2791. }
  2792. public function shipmentsReadyToPrint(Request $request)
  2793. {
  2794. $counts = $this->getShipmentCounts();
  2795. $shipments = Shipment
  2796. ::where('is_cancelled', false)
  2797. ->where('status', 'CREATED')
  2798. ->orderBy('created_at', 'ASC')
  2799. ->paginate();
  2800. return view('app.practice-management.shipments-ready-to-print', compact('shipments', 'counts'));
  2801. }
  2802. public function shipmentsShipmentUnderway(Request $request)
  2803. {
  2804. $counts = $this->getShipmentCounts();
  2805. $shipments = Shipment
  2806. ::where('is_cancelled', false)
  2807. ->where('status', 'PRINTED')
  2808. ->orderBy('created_at', 'ASC')
  2809. ->paginate();
  2810. return view('app.practice-management.shipments-waiting-for-picker', compact('shipments', 'counts'));
  2811. }
  2812. private function getShipmentCounts()
  2813. {
  2814. return [
  2815. "shipments" => Shipment::count(),
  2816. "shipmentsReadyToPrint" => Shipment
  2817. ::where('is_cancelled', false)
  2818. ->where('status', 'CREATED')
  2819. ->count(),
  2820. "shipmentsWaitingForPicker" => Shipment
  2821. ::where('is_cancelled', false)
  2822. ->where('status', 'PRINTED')
  2823. ->count()
  2824. ];
  2825. }
  2826. public function shipment(Request $request, Shipment $shipment)
  2827. {
  2828. return view('app.practice-management.shipment', compact('shipment'));
  2829. }
  2830. public function shipmentsMultiPrint(Request $request, $ids)
  2831. {
  2832. $ids = array_map(function ($_x) {
  2833. return intval($_x);
  2834. }, explode("|", $ids));
  2835. $shipments = Shipment::whereIn('id', $ids)->get();
  2836. return view('app.practice-management.shipments-multi-print', compact('shipments'));
  2837. }
  2838. public function patientClaimSummary(Request $request, $proUid = null)
  2839. {
  2840. $notesTotal = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE"))[0]->count;
  2841. $notesTotalWithBillingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE AND is_bill_closed IS TRUE"))[0]->count;
  2842. $notesTotalWithClaimingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE AND is_claim_closed IS TRUE"))[0]->count;
  2843. $notes3rdPartyTotal = DB::select(DB::raw("SELECT COUNT(*) FROM note n LEFT JOIN client c ON n.client_id = c.id WHERE n.is_cancelled IS NOT TRUE AND c.is_part_b_primary <> 'YES'"))[0]->count;
  2844. $notes3rdPartyTotalWithBillingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note n LEFT JOIN client c ON n.client_id = c.id WHERE n.is_cancelled IS NOT TRUE AND n.is_bill_closed IS TRUE AND c.is_part_b_primary <> 'YES'"))[0]->count;
  2845. $notes3rdPartyTotalWithClaimingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note n LEFT JOIN client c ON n.client_id = c.id WHERE n.is_cancelled IS NOT TRUE AND n.is_claim_closed IS TRUE AND c.is_part_b_primary <> 'YES'"))[0]->count;
  2846. $patientsTotal = DB::select(DB::raw("SELECT COUNT(*) FROM client WHERE is_active IS TRUE AND 0 NOT IN (SELECT c FROM (SELECT COUNT(*) c FROM note WHERE is_cancelled IS NOT TRUE AND note.client_id = client.id) x)"))[0]->count;
  2847. $patientsTotalWithBillingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM client WHERE is_active IS TRUE AND 0 NOT IN (SELECT c FROM (SELECT COUNT(*) c FROM note WHERE is_cancelled IS NOT TRUE AND note.client_id = client.id) y) AND 0 IN (SELECT c FROM (SELECT COUNT(*) c FROM note WHERE is_cancelled IS NOT TRUE AND is_bill_closed IS NOT TRUE AND note.client_id = client.id) x)"))[0]->count;
  2848. $patientsTotalWithClaimingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM client WHERE is_active IS TRUE AND 0 NOT IN (SELECT c FROM (SELECT COUNT(*) c FROM note WHERE is_cancelled IS NOT TRUE AND note.client_id = client.id) y) AND 0 IN (SELECT c FROM (SELECT COUNT(*) c FROM note WHERE is_cancelled IS NOT TRUE AND is_claim_closed IS NOT TRUE AND note.client_id = client.id) x)"))[0]->count;
  2849. $performerPro = $this->performer->pro;
  2850. $allPros = [];
  2851. if ($performerPro->pro_type == 'ADMIN') {
  2852. $allPros = Pro::all();
  2853. } else {
  2854. $allPros = [$performerPro];
  2855. }
  2856. //Patient | MCP | # Notes Total | # Notes without Billing Closed | # Notes without Claiming Closed
  2857. $patientsQuery = Client::where('is_dummy', '=', false)
  2858. ->whereNull('shadow_pro_id')
  2859. ->select('id', 'uid', 'name_first', 'name_last', 'mcp_pro_id', 'is_part_b_primary', 'medicare_advantage_plan',
  2860. DB::raw("(SELECT name_first||' '||name_last FROM pro where pro.id = client.mcp_pro_id) as mcp"),
  2861. DB::raw("(SELECT uid FROM pro where pro.id = mcp_pro_id) as mcp_pro_uid"),
  2862. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id) as notes_total"),
  2863. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id AND is_bill_closed IS NOT true) as notes_without_billing_closed"),
  2864. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id AND is_claim_closed IS NOT true) as notes_without_claiming_closed")
  2865. )->orderBy('is_part_b_primary', 'asc')->orderBy('notes_without_claiming_closed', 'desc');
  2866. if ($proUid) {
  2867. $mcpPro = Pro::where('uid', $proUid)->first();
  2868. if ($mcpPro) {
  2869. $patientsQuery->where('client.mcp_pro_id', '=', $mcpPro->id);
  2870. }
  2871. }
  2872. $patientsQuery->whereRaw('(SELECT COUNT(*) FROM note where note.client_id = client.id) > 0');
  2873. $patientsQuery->orderBy('notes_total', 'DESC');
  2874. $patients = $patientsQuery->paginate(50);
  2875. $data = [
  2876. 'patients' => $patients,
  2877. 'proUid' => $proUid,
  2878. 'allPros' => $allPros,
  2879. 'notesTotal' => $notesTotal,
  2880. 'notesTotalWithBillingClosed' => $notesTotalWithBillingClosed,
  2881. 'notesTotalWithClaimingClosed' => $notesTotalWithClaimingClosed,
  2882. 'notes3rdPartyTotal' => $notes3rdPartyTotal,
  2883. 'notes3rdPartyTotalWithBillingClosed' => $notes3rdPartyTotalWithBillingClosed,
  2884. 'notes3rdPartyTotalWithClaimingClosed' => $notes3rdPartyTotalWithClaimingClosed,
  2885. 'patientsTotal' => $patientsTotal,
  2886. 'patientsTotalWithBillingClosed' => $patientsTotalWithBillingClosed,
  2887. 'patientsTotalWithClaimingClosed' => $patientsTotalWithClaimingClosed
  2888. ];
  2889. return view('app.practice-management.patient-claim-summary', $data);
  2890. }
  2891. public function claims(Request $request){
  2892. $status = $request->get('status');
  2893. $claims = [];
  2894. if(!$status){
  2895. $claims = Claim::orderBy('created_at', 'DESC')->paginate();
  2896. }else{
  2897. $claims = Claim::where('status', $status)->orderBy('created_at', 'DESC')->paginate();
  2898. }
  2899. return view('app.practice-management.claims', compact('claims', 'status'));
  2900. }
  2901. public function processClaims(Request $request) {
  2902. $status = '';
  2903. $q = $request->input('q') ? $request->input('q') : '';
  2904. $from = $request->input('from') ? $request->input('from') : '1900-01-01';
  2905. $to = $request->input('to') ? $request->input('to') : '2100-01-01';
  2906. $params = [
  2907. 'q' => '%' . $q . '%',
  2908. 'from' => $from,
  2909. 'to' => $to
  2910. ];
  2911. $hcpPro = $request->input('hcp') ? Pro::where('uid', $request->input('hcp'))->first() : null;
  2912. if($hcpPro) {
  2913. $params['hcp'] = $hcpPro->id;
  2914. }
  2915. $claims = DB::select(DB::raw("
  2916. SELECT claim.uid AS uid,
  2917. DATE(claim.created_at) AS created,
  2918. claim.status,
  2919. client.uid AS client_uid,
  2920. client.cell_number AS client_phone,
  2921. client.phone_home AS client_phone_home,
  2922. (client.name_last || ' ' || client.name_first) AS client ,
  2923. client.chart_number AS client_chart_number,
  2924. cp.id AS claim_pro_id,
  2925. (cp.name_last || ' ' || cp.name_first) AS claim_pro,
  2926. sp.id AS status_pro_id,
  2927. (sp.name_last || ' ' || sp.name_first) AS status_pro,
  2928. note.uid AS note_uid,
  2929. note.method,
  2930. note.new_or_fu_or_na,
  2931. care_month.uid AS care_month_uid,
  2932. care_month.start_date as care_month_start__date,
  2933. -- claim.status_updated_at,
  2934. (DATE(claim.status_updated_at) || ' ' ||
  2935. LPAD(EXTRACT(hour FROM claim.status_updated_at)::text, 2, '0') || ':' ||
  2936. LPAD(EXTRACT(minute FROM claim.status_updated_at)::text, 2, '0')) AS status_updated_at,
  2937. (SELECT string_agg(claim_line.cpt, ', ') FROM claim_line where claim_id = claim.id) AS cpts,
  2938. (SELECT COUNT(claim_line_icd.id) FROM claim_line_icd WHERE claim_line_id IN (SELECT id FROM claim_line WHERE claim_id = claim.id)) AS icds,
  2939. ROUND(claim.expected_total, 3) as expected_total
  2940. FROM claim
  2941. join client on claim.client_id = client.id
  2942. join pro cp on claim.pro_id = cp.id
  2943. left join note on claim.note_id = note.id
  2944. left join care_month on claim.care_month_id = care_month.id
  2945. left join app_session on claim.status_updated_by_session_id = app_session.id
  2946. left join pro sp on app_session.pro_id = sp.id
  2947. --WHERE claim.status IS NULL OR claim.status = 'NEW'
  2948. WHERE (claim.status is NULL OR claim.status NOT IN ('CANCELLED', 'ABANDONED'" . ($request->input('show-submitted') ? "" : ", 'SUBMITTED'") . "))
  2949. -- AND claim.current_version_id IS NOT NULL
  2950. AND (client.name_first ILIKE :q OR
  2951. client.name_last ILIKE :q OR
  2952. client.chart_number ILIKE :q OR
  2953. client.mcn ILIKE :q)
  2954. AND (claim.created_at >= :from AND claim.created_at <= :to)
  2955. " . ($hcpPro ? "AND claim.pro_id = :hcp" : '') . "
  2956. AND claim.id IN (SELECT mb_claim.claim_id FROM mb_claim)
  2957. ORDER BY claim.created_at DESC
  2958. --OFFSET 0 LIMIT 15
  2959. "), $params);
  2960. if($request->input('json')) {
  2961. return json_encode($claims);
  2962. }
  2963. return view('app.practice-management.process-claims', compact('claims', 'status'));
  2964. }
  2965. public function rmLaunchAndClean(Request $request) {
  2966. $keyNumbers = [];
  2967. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_40'] = CareMonth::where('is_bill_closed', false)
  2968. ->whereNotNull('company_pro_id')
  2969. ->whereNotNull('company_pro_payer_id')
  2970. ->whereNotNull('company_location_id')
  2971. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2972. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  2973. ->where('rm_total_time_in_seconds', '>=', 4200) // at 4200 (70 minutes, it becomes eligible for plus40)
  2974. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2975. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2976. ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS TRUE OR has_mcp_rm_interacted_by_note IS TRUE )')
  2977. ->count();
  2978. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_40_ifHadInteraction'] = CareMonth::where('is_bill_closed', false)
  2979. ->whereNotNull('company_pro_id')
  2980. ->whereNotNull('company_pro_payer_id')
  2981. ->whereNotNull('company_location_id')
  2982. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2983. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  2984. ->where('rm_total_time_in_seconds', '>=', 4200) // at 4200 (70 minutes, it becomes eligible for plus40)
  2985. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2986. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2987. ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS NOT TRUE AND has_mcp_rm_interacted_by_note IS NOT TRUE AND is_rm_interaction_waived IS NOT TRUE )')
  2988. ->count();
  2989. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_20'] = CareMonth::where('is_bill_closed', false)
  2990. ->whereNotNull('company_pro_id')
  2991. ->whereNotNull('company_pro_payer_id')
  2992. ->whereNotNull('company_location_id')
  2993. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2994. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  2995. ->where('rm_total_time_in_seconds', '<', 4200)
  2996. ->where('rm_total_time_in_seconds', '>=', 3000) // at 3000 (50 minutes, it becomes eligible for plus20)
  2997. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2998. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2999. ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS TRUE OR has_mcp_rm_interacted_by_note IS TRUE)')
  3000. ->count();
  3001. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_20_ifHadInteraction'] = CareMonth::where('is_bill_closed', false)
  3002. ->whereNotNull('company_pro_id')
  3003. ->whereNotNull('company_pro_payer_id')
  3004. ->whereNotNull('company_location_id')
  3005. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  3006. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  3007. ->where('rm_total_time_in_seconds', '<', 4200)
  3008. ->where('rm_total_time_in_seconds', '>=', 3000) // at 3000 (50 minutes, it becomes eligible for plus20)
  3009. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  3010. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  3011. ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS NOT TRUE AND has_mcp_rm_interacted_by_note IS NOT TRUE AND is_rm_interaction_waived IS NOT TRUE )')
  3012. ->count();
  3013. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP'] = CareMonth::where('is_bill_closed', false)
  3014. ->whereNotNull('company_pro_id')
  3015. ->whereNotNull('company_pro_payer_id')
  3016. ->whereNotNull('company_location_id')
  3017. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  3018. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  3019. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  3020. ->whereRaw('(rm_total_time_in_seconds < 3000 OR (rm_total_time_in_seconds >= 3000 AND is_rm_interaction_waived IS TRUE))')
  3021. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  3022. ->count();
  3023. $keyNumbers['careMonthsEligibleForBillGeneration_RMB'] = CareMonth::where('is_bill_closed', false)
  3024. ->whereNotNull('company_pro_id')
  3025. ->whereNotNull('company_pro_payer_id')
  3026. ->whereNotNull('company_location_id')
  3027. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  3028. ->whereRaw('is_rm_time_waived IS TRUE')
  3029. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  3030. ->count();
  3031. $keyNumbers['careMonthsWith16OrMoreMeasurementDays'] = CareMonth::where('is_bill_closed', false)
  3032. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  3033. ->count();
  3034. $careMonthsWith16PlusMeasurements = CareMonth::where('is_bill_closed', false)
  3035. ->where('number_of_days_with_remote_measurements', '>=', 16 )->get();
  3036. return view('app.practice-management.rm-launch-and-clean', compact('keyNumbers', 'careMonthsWith16PlusMeasurements'));
  3037. }
  3038. public function processNotes(Request $request) {
  3039. $mode = $request->input('mode') ? $request->input('mode') : '1';
  3040. if(($mode < 1 || $mode > 5) && $mode != 8) $mode = 1;
  3041. DB::enableQueryLog(); // Enable query log
  3042. $test = Note::where('is_cancelled', false)
  3043. ->where('is_signed_by_hcp', true)
  3044. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  3045. ->whereNull('current_note_pickup_for_processing_id')
  3046. ->where('is_billing_marked_done', true)
  3047. ->where('is_bill_closed', true)
  3048. ->where('is_claim_closed', true)
  3049. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  3050. ->count();
  3051. // var_dump($test);
  3052. // dd(DB::getQueryLog()); // Show results of log
  3053. // exit;
  3054. $counts = [
  3055. "picked" => Note::where('is_cancelled', false)
  3056. ->whereNotNull('current_note_pickup_for_processing_id')
  3057. ->count(),
  3058. "bad" => Note::where('is_cancelled', false)
  3059. ->whereRaw("((detail_json)::json->>'isBad' = 'true')")
  3060. ->count(),
  3061. // not yet signed
  3062. "mode-1" => Note::where('is_cancelled', false)
  3063. ->where('is_signed_by_hcp', false)
  3064. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3065. // ->whereNull('current_note_pickup_for_processing_id')
  3066. ->count(),
  3067. // billing not marked done
  3068. "mode-2" => Note::where('is_cancelled', false)
  3069. ->where('is_signed_by_hcp', true)
  3070. //->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3071. // ->whereNull('current_note_pickup_for_processing_id')
  3072. ->where('is_billing_marked_done', false)
  3073. ->count(),
  3074. // billing not closed
  3075. "mode-3" => Note::where('is_cancelled', false)
  3076. ->where('is_signed_by_hcp', true)
  3077. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3078. // ->whereNull('current_note_pickup_for_processing_id')
  3079. ->where('is_billing_marked_done', true)
  3080. ->where('is_bill_closed', false)
  3081. ->count(),
  3082. // claiming not closed
  3083. "mode-4" => Note::where('is_cancelled', false)
  3084. ->where('is_signed_by_hcp', true)
  3085. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3086. // ->whereNull('current_note_pickup_for_processing_id')
  3087. ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true' OR ((detail_json)::json->>'isGood')::text IS NULL)")
  3088. ->where('is_billing_marked_done', true)
  3089. ->where('is_bill_closed', true)
  3090. ->where('is_claim_closed', false)
  3091. ->count(),
  3092. // has unsubmitted claims
  3093. "mode-5" => Note::where('is_cancelled', false)
  3094. /*->where('is_signed_by_hcp', true)
  3095. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3096. ->whereNull('current_note_pickup_for_processing_id')
  3097. ->where('is_billing_marked_done', true)
  3098. ->where('is_bill_closed', true)
  3099. ->where('is_claim_closed', true)
  3100. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0")
  3101. */
  3102. ->where('is_signed_by_hcp', true)
  3103. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3104. // ->whereNull('current_note_pickup_for_processing_id')
  3105. ->where('is_billing_marked_done', true)
  3106. ->where('is_bill_closed', true)
  3107. // ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true')")
  3108. ->where('is_claim_closed', true)
  3109. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0)")
  3110. ->count(),
  3111. // has unsubmitted claims MARKED GOOD!
  3112. "mode-8" => Note::where('is_cancelled', false)
  3113. ->where('is_signed_by_hcp', true)
  3114. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  3115. ->whereNull('current_note_pickup_for_processing_id')
  3116. ->where('is_billing_marked_done', true)
  3117. ->where('is_bill_closed', true)
  3118. ->where('is_claim_closed', false)
  3119. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  3120. ->count(),
  3121. // all good
  3122. "mode-6" => Note::where('is_cancelled', false)
  3123. ->where('is_signed_by_hcp', true)
  3124. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3125. // ->whereNull('current_note_pickup_for_processing_id')
  3126. ->where('is_billing_marked_done', true)
  3127. ->where('is_bill_closed', true)
  3128. ->where('is_claim_closed', true)
  3129. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id) > 0)")
  3130. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  3131. ->count(),
  3132. "mode-7" => Note::where('is_cancelled', false)
  3133. ->whereRaw("(detail_json)::json->>'isBad' = 'true'")
  3134. ->count(),
  3135. ];
  3136. return view('app.practice-management.process-notes', compact('mode', 'counts'));
  3137. }
  3138. public function notesProcessingCenter(Request $request) {
  3139. $notes = Note::where('is_cancelled', false);
  3140. // filters
  3141. $proUid = $request->input('proUid');
  3142. if($proUid) {
  3143. $fPro = Pro::where('uid', $proUid)->first();
  3144. if($fPro) {
  3145. $notes = $notes->where('hcp_pro_id', $fPro->id);
  3146. }
  3147. }
  3148. $proSigned = $request->input('proSigned');
  3149. switch($proSigned) {
  3150. case 'yes': $notes = $notes->where('is_signed_by_hcp', true); break;
  3151. case 'no': $notes = $notes->where('is_signed_by_hcp', '!=', true); break;
  3152. }
  3153. $billingMarkedDone = $request->input('billingMarkedDone');
  3154. switch($billingMarkedDone) {
  3155. case 'yes': $notes = $notes->where('is_billing_marked_done', true); break;
  3156. case 'no': $notes = $notes->where('is_billing_marked_done', '!=', true); break;
  3157. }
  3158. $billingClosed = $request->input('billingClosed');
  3159. switch($billingClosed) {
  3160. case 'yes': $notes = $notes->where('is_bill_closed', true); break;
  3161. case 'no': $notes = $notes->where('is_bill_closed', '!=', true); break;
  3162. }
  3163. $claimingClosed = $request->input('claimingClosed');
  3164. switch($claimingClosed) {
  3165. case 'yes': $notes = $notes->where('is_claim_closed', true); break;
  3166. case 'no': $notes = $notes->where('is_claim_closed', '!=', true); break;
  3167. }
  3168. $allClaimsSubmitted = $request->input('allClaimsSubmitted');
  3169. if($allClaimsSubmitted) {
  3170. // TODO
  3171. }
  3172. $goodBad = $request->input('goodBad');
  3173. switch($goodBad) {
  3174. case 'good': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' = 'false'"); break;
  3175. case 'bad': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' = 'true'"); break;
  3176. case 'unclassified': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' is null"); break;
  3177. }
  3178. $startDate = $request->input('startDate');
  3179. if($startDate) {
  3180. $notes = $notes->where('effective_dateest', '>=', $startDate);
  3181. }
  3182. $endDate = $request->input('endDate');
  3183. if($endDate) {
  3184. $notes = $notes->where('effective_dateest', '<=', $endDate);
  3185. }
  3186. $mcPartB = $request->input('mcPartB');
  3187. if($mcPartB) {
  3188. // TODO
  3189. }
  3190. $notes = $notes->orderBy('effective_dateest')->paginate(10);
  3191. return view('app.practice-management.notes-processing-center', compact('notes'));
  3192. }
  3193. public function getNextNote(Request $request, $mode)
  3194. {
  3195. $note = null;
  3196. switch (+$mode) {
  3197. case 1:
  3198. $note = Note::where('is_cancelled', false)
  3199. ->where('is_signed_by_hcp', false)
  3200. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3201. ->whereNull('current_note_pickup_for_processing_id')
  3202. ->orderBy('effective_dateest', 'DESC')
  3203. ->first();
  3204. break;
  3205. case 2:
  3206. $note = Note::where('is_cancelled', false)
  3207. ->where('is_signed_by_hcp', true)
  3208. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3209. ->whereNull('current_note_pickup_for_processing_id')
  3210. ->where('is_billing_marked_done', false)
  3211. ->orderBy('effective_dateest', 'DESC')
  3212. ->first();
  3213. break;
  3214. case 3:
  3215. $note = Note::where('is_cancelled', false)
  3216. ->where('is_signed_by_hcp', true)
  3217. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3218. ->whereNull('current_note_pickup_for_processing_id')
  3219. ->where('is_billing_marked_done', true)
  3220. ->where('is_bill_closed', false)
  3221. ->orderBy('effective_dateest', 'DESC')
  3222. ->first();
  3223. break;
  3224. case 4: // claiming not closed
  3225. DB::enableQueryLog(); // Enable query log
  3226. $note = Note::where('is_cancelled', false)
  3227. ->where('is_signed_by_hcp', true)
  3228. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3229. ->whereNull('current_note_pickup_for_processing_id')
  3230. ->where('is_billing_marked_done', true)
  3231. ->where('is_bill_closed', true)
  3232. ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true' OR ((detail_json)::json->>'isGood')::text IS NULL)")
  3233. ->where('is_claim_closed', false)
  3234. ->orderBy('effective_dateest', 'DESC')
  3235. ->first();
  3236. // DB::enableQueryLog(); // Enable query log
  3237. // Your Eloquent query executed by using get()
  3238. // dd(DB::getQueryLog()); // Show results of log
  3239. break;
  3240. case 5:
  3241. $note = Note::where('is_cancelled', false)
  3242. ->where('is_signed_by_hcp', true)
  3243. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3244. ->whereNull('current_note_pickup_for_processing_id')
  3245. ->where('is_billing_marked_done', true)
  3246. ->where('is_bill_closed', true)
  3247. ->where('is_claim_closed', true)
  3248. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0")
  3249. ->orderBy('effective_dateest', 'DESC')
  3250. ->first();
  3251. break;
  3252. case 8:
  3253. $note = Note::where('is_cancelled', false)
  3254. ->where('is_signed_by_hcp', true)
  3255. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  3256. ->whereNull('current_note_pickup_for_processing_id')
  3257. ->where('is_billing_marked_done', true)
  3258. ->where('is_bill_closed', true)
  3259. ->where('is_claim_closed', false)
  3260. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  3261. ->orderBy('effective_dateest', 'DESC')
  3262. ->first();
  3263. break;
  3264. }
  3265. if($note) {
  3266. $note->client_uid = $note->client->uid;
  3267. }
  3268. return json_encode($note);
  3269. }
  3270. public function pickedNotes(Request $request) {
  3271. $counts = [
  3272. "unpicked" => Note::where('is_cancelled', false)
  3273. ->whereNull('current_note_pickup_for_processing_id')
  3274. ->count(),
  3275. ];
  3276. $notes = Note::where('is_cancelled', false)
  3277. ->whereNotNull('current_note_pickup_for_processing_id')
  3278. ->orderBy('effective_dateest', 'ASC')
  3279. ->paginate();
  3280. return view('app.practice-management.picked-notes', compact('counts', 'notes'));
  3281. }
  3282. public function badNotes(Request $request) {
  3283. $counts = [
  3284. "unpicked" => Note::where('is_cancelled', false)
  3285. ->whereNull('current_note_pickup_for_processing_id')
  3286. ->count(),
  3287. ];
  3288. $notes = Note::where('is_cancelled', false)
  3289. ->whereRaw("(detail_json)::json->>'isBad' = 'true'")
  3290. ->orderBy('effective_dateest', 'ASC')
  3291. ->paginate();
  3292. return view('app.practice-management.bad-notes', compact('counts', 'notes'));
  3293. }
  3294. public function doneNotes(Request $request) {
  3295. $counts = [
  3296. "unpicked" => Note::where('is_cancelled', false)
  3297. ->whereNull('current_note_pickup_for_processing_id')
  3298. ->count(),
  3299. ];
  3300. $notes = Note::where('is_cancelled', false)
  3301. ->where('is_signed_by_hcp', true)
  3302. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3303. ->whereNull('current_note_pickup_for_processing_id')
  3304. ->where('is_billing_marked_done', true)
  3305. ->where('is_bill_closed', true)
  3306. ->where('is_claim_closed', true)
  3307. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id) > 0")
  3308. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0")
  3309. ->orderBy('effective_dateest', 'ASC')
  3310. ->paginate();
  3311. return view('app.practice-management.done-notes', compact('counts', 'notes'));
  3312. }
  3313. public function currentMbClaim(Request $request, $claimUid) {
  3314. $claim = Claim::where('uid', $claimUid)->first();
  3315. return json_encode(MBClaim::where('claim_version_id', $claim->currentVersion->id)->where('status', '!=', 'CANCELLED')->first());
  3316. }
  3317. public function currentClaimLines(Request $request, $claimUid) {
  3318. $claim = Claim::where('uid', $claimUid)->first();
  3319. if($request->input('json')) {
  3320. foreach ($claim->lines as $line) {
  3321. $line->expected_total = round($line->expected_total, 3);
  3322. $x = $line->claimLineIcds;
  3323. }
  3324. return json_encode($claim->lines);
  3325. }
  3326. return view('app.practice-management._claim-lines', compact('claim'));
  3327. }
  3328. public function packsMultiPrint(Request $request) {
  3329. $packs = Pack
  3330. ::select('pack.*')
  3331. ->leftJoin('shipment', function($join) {
  3332. $join->on('pack.shipment_id', '=', 'shipment.id');
  3333. })
  3334. ->whereNotIn('shipment.status', ['CANCELLED', 'DISPATCHED'])
  3335. ->where(function ($query) {
  3336. $query->where('pack.status', '<>', 'DELETED')->orWhereNull('pack.status'); // weird, but just the <> isn't working!
  3337. })
  3338. ->whereNotNull('pack.label_system_file_id')
  3339. ->orderBy('pack.created_at', 'ASC')
  3340. ->get();
  3341. return view('app.practice-management.packs-multi-print', compact('packs'));
  3342. }
  3343. public function packsMultiPDF(Request $request, $ids) {
  3344. $ids = array_map(function ($_x) {
  3345. return intval($_x);
  3346. }, explode("|", $ids));
  3347. $packs = Pack::whereIn('id', $ids)->get();
  3348. }
  3349. public function handouts(Request $request) {
  3350. $handouts = Handout::orderBy('display_name')->get();
  3351. return view('app.practice-management.handouts', compact('handouts'));
  3352. }
  3353. private function callJava($request, $endPoint, $data)
  3354. {
  3355. $url = config('stag.backendUrl') . $endPoint;
  3356. $response = Http::asForm()
  3357. ->withHeaders([
  3358. 'sessionKey' => $request->cookie('sessionKey')
  3359. ])
  3360. ->post($url, $data)
  3361. ->body();
  3362. dd($response);
  3363. return $response;
  3364. }
  3365. public function genericBills(Request $request)
  3366. {
  3367. return view('app.practice-management.generic-bills');
  3368. }
  3369. public function billsUnderProcessing(Request $request)
  3370. {
  3371. $bills = Bill::where('is_cancelled', false)
  3372. ->where(function ($query) { // mcp of any client program and program OB pending
  3373. $query
  3374. ->where(function ($_query) {
  3375. $_query->where('hcp_pro_id', $this->pro->id)
  3376. ->where('hcp_expected_payment_amount', '>', 0)
  3377. ->where('has_hcp_been_paid', false)
  3378. ->where('is_signed_by_hcp', true);
  3379. })
  3380. ->orWhere(function ($_query) {
  3381. $_query->where('cm_pro_id', $this->pro->id)
  3382. ->where('cm_expected_payment_amount', '>', 0)
  3383. ->where('has_cm_been_paid', false)
  3384. ->where('is_signed_by_cm', true);
  3385. })
  3386. ->orWhere(function ($_query) {
  3387. $_query->where('rme_pro_id', $this->pro->id)
  3388. ->where('rme_expected_payment_amount', '>', 0)
  3389. ->where('has_rme_been_paid', false)
  3390. ->where('is_signed_by_rme', true);
  3391. })
  3392. ->orWhere(function ($_query) {
  3393. $_query->where('rmm_pro_id', $this->pro->id)
  3394. ->where('rmm_expected_payment_amount', '>', 0)
  3395. ->where('has_rmm_been_paid', false)
  3396. ->where('is_signed_by_rmm', true);
  3397. })
  3398. ->orWhere(function ($_query) {
  3399. $_query->where('generic_pro_id', $this->pro->id)
  3400. ->where('generic_pro_expected_payment_amount', '>', 0)
  3401. ->where('has_generic_pro_been_paid', false)
  3402. ->where('is_signed_by_generic_pro', true);
  3403. });
  3404. })
  3405. ->orderBy('created_at', 'DESC')
  3406. ->paginate();
  3407. return view('app.practice-management.bills-under-processing', compact('bills'));
  3408. }
  3409. public function careMonthReport(Request $request) {
  3410. $m = $request->input('m');
  3411. $y = $request->input('y');
  3412. if(!$m || !$y) {
  3413. $date = date('Y-m-01');
  3414. }
  3415. else {
  3416. $date = date('Y-m-d', strtotime("$m/1/$y"));
  3417. }
  3418. $pro = $this->pro;
  3419. $records = DB::select("
  3420. SELECT cm.id as care_month_id,
  3421. cm.uid as care_month_uid,
  3422. c.id as client_id,
  3423. c.uid as client_uid,
  3424. cm.number_of_days_with_remote_measurements,
  3425. cm.rm_total_time_in_seconds_by_mcp,
  3426. cm.rm_total_time_in_seconds_by_rme_pro,
  3427. cm.rm_total_time_in_seconds_by_rmm_pro,
  3428. cm.mcp_pro_id,
  3429. cm.rme_pro_id,
  3430. cm.rmm_pro_id,
  3431. (c.name_first || ' ' || c.name_last) as client_name
  3432. FROM care_month cm
  3433. JOIN client c on cm.client_id = c.id
  3434. WHERE cm.start_date = :startDate
  3435. AND (cm.mcp_pro_id = :proID OR
  3436. cm.rme_pro_id = :proID OR
  3437. cm.rmm_pro_id = :proID)
  3438. ORDER BY c.name_last, c.name_first
  3439. ",
  3440. ['startDate' => $date, 'proID' => $pro->id]
  3441. );
  3442. return view('app.practice-management.care-month-report', compact('records', 'date'));
  3443. }
  3444. public function myTeams(Request $request) {
  3445. $pro = $this->pro;
  3446. // get all teams where the authed-pro is the assistant pro
  3447. $teams = ProTeam::where('assistant_pro_id', $pro->id)
  3448. ->where('is_active', true)
  3449. ->orderBy('slug')
  3450. ->get();
  3451. return view('app.practice-management.my-teams', compact('teams'));
  3452. }
  3453. public function patientsAccountsInvites(Request $request){
  3454. $filters = $request->all();
  3455. $accountInvites = AccountInvite::select('account_invite.*')
  3456. ->join('client', 'client.id', '=', 'account_invite.for_client_id');
  3457. if($this->performer->pro->pro_type !== 'ADMIN'){
  3458. $accountInvites = $accountInvites->where('client.mcp_pro_id', $this->performer->pro->id);
  3459. }
  3460. $this->filterMultiQuery($request, $accountInvites, 'account_invite.created_at', 'date_category', 'date_value_1', 'date_value_2');
  3461. $this->filterSimpleQuery($request, $accountInvites, 'account_invite.status', 'status');
  3462. $accountInvites = $accountInvites->orderBy('created_at', 'DESC')->paginate(20);
  3463. return view('app.practice-management.patients-accounts-invites', compact('accountInvites','filters'));
  3464. }
  3465. public function clientsBdtDevices(Request $request){
  3466. $filters = $request->all();
  3467. $devices = ClientBDTDevice::select(
  3468. 'client_bdt_device.*',
  3469. DB::raw('(SELECT COUNT(*) FROM bdt_measurement WHERE bdt_measurement.bdt_device_id = client_bdt_device.device_id AND is_cellular_zero IS FALSE) as num_of_measurements'))
  3470. // DB::raw('(SELECT ts_date_time FROM bdt_measurement WHERE bdt_measurement.bdt_device_id = client_bdt_device.device_id AND is_cellular_zero IS FALSE ORDER BY ts_date_time DESC LIMIT 1) as most_recent_none_zero_measurement_at'))
  3471. ->join('client', 'client.id', '=', 'client_bdt_device.client_id');
  3472. if($this->performer->pro->pro_type !== 'ADMIN'){
  3473. $devices = $devices->where('client.mcp_pro_id', $this->performer->pro->id);
  3474. }
  3475. $this->filterMultiQuery($request, $devices, 'client_bdt_device.most_recent_measurement_at', 'date_category', 'date_value_1', 'date_value_2');
  3476. // $dateKeyName = $request->get('date_category');
  3477. // $date1 = $request->get('date_value_1');
  3478. // $date2 = $request->get('date_value_2');
  3479. // $dateColumnName = "(SELECT (MAX(ts_date_time))::DATE FROM bdt_measurement WHERE bdt_measurement.bdt_device_id = client_bdt_device.device_id AND is_cellular_zero IS FALSE)";
  3480. // switch($dateKeyName) {
  3481. // case 'EXACTLY':
  3482. // if($date1) {
  3483. // $devices->whereRaw($dateColumnName." = '$date1'::DATE");
  3484. // }
  3485. // break;
  3486. // case 'LESS_THAN':
  3487. // if($date1) {
  3488. // $devices->whereRaw($dateColumnName. "< '$date1'::DATE" );
  3489. // }
  3490. // break;
  3491. // case 'GREATER_THAN':
  3492. // if($date1) {
  3493. // $devices->whereRaw($dateColumnName. "> '$date1'::DATE");
  3494. // }
  3495. // break;
  3496. // case 'BETWEEN':
  3497. // if($date1 && $date2) {
  3498. // $devices
  3499. // ->whereRaw($dateColumnName. ">= '$date1'::DATE")
  3500. // ->whereRaw($dateColumnName. "<= '$date2'::DATE");
  3501. // }
  3502. // break;
  3503. // case 'NOT_BETWEEN':
  3504. // if($date2 && $date1) {
  3505. // $devices
  3506. // ->where(function ($q) use ($request, $dateColumnName, $date1, $date2) {
  3507. // $q->whereRaw($dateColumnName. "< '$date1'::DATE")
  3508. // ->orWhereRaw($dateColumnName. "> '$date2'::DATE");
  3509. // });
  3510. // }
  3511. // break;
  3512. // }
  3513. $keyName = $request->get('measurement_count_category');
  3514. $value1 = $request->get('measurement_count_value_1');
  3515. $value2 = $request->get('measurement_count_value_2');
  3516. $columnName = "(SELECT COUNT(*) FROM bdt_measurement WHERE bdt_measurement.bdt_device_id = client_bdt_device.device_id AND is_cellular_zero IS FALSE)";
  3517. switch($keyName) {
  3518. case 'EXACTLY':
  3519. if($value1) {
  3520. $devices->whereRaw($columnName.'='.$value1);
  3521. }
  3522. break;
  3523. case 'LESS_THAN':
  3524. if($value1) {
  3525. $devices->whereRaw($columnName. '<' .$value1);
  3526. }
  3527. break;
  3528. case 'GREATER_THAN':
  3529. if($value1) {
  3530. $devices->whereRaw($columnName. '>'. $value1);
  3531. }
  3532. break;
  3533. case 'BETWEEN':
  3534. if($value1 && $value2) {
  3535. $devices
  3536. ->whereRaw($columnName. '>=' . $value1)
  3537. ->whereRaw($columnName. '<=' . $value1);
  3538. }
  3539. break;
  3540. case 'NOT_BETWEEN':
  3541. if($value1 && $value2) {
  3542. $devices
  3543. ->where(function ($q) use ($request, $columnName, $value1, $value2) {
  3544. $q->whereRaw($columnName. '<'. $value1)
  3545. ->orWhereRaw($columnName. '>'.$value2);
  3546. });
  3547. }
  3548. break;
  3549. }
  3550. $status = $request->get('status');
  3551. if($status){
  3552. if($status === 'ACTIVE') $devices = $devices->where('client_bdt_device.is_active', true);
  3553. if($status === 'DEACTIVATED') $devices = $devices->where('client_bdt_device.is_active', false);
  3554. }
  3555. $devices = $devices->orderBy('num_of_measurements', 'DESC')->paginate(20);
  3556. return view('app.practice-management.clients_bdt_devices', compact('devices','filters'));
  3557. }
  3558. public function memos(Request $request){
  3559. $filters = $request->all();
  3560. $memos = ClientMemo::select('client_memo.*')
  3561. ->join('client', 'client.id', '=', 'client_memo.client_id');
  3562. if($this->performer->pro->pro_type !== 'ADMIN'){
  3563. $memos = $memos->where('client.mcp_pro_id', $this->performer->pro->id);
  3564. }
  3565. $this->filterMultiQuery($request, $memos, 'client_memo.created_at', 'date_category', 'date_value_1', 'date_value_2');
  3566. $this->filterSimpleQuery($request, $memos, 'category', 'category');
  3567. $memos = $memos->orderBy('created_at', 'DESC')->paginate(20);
  3568. return view('app.practice-management.memos', compact('memos', 'filters'));
  3569. }
  3570. public function segmentTemplates(Request $request){
  3571. $segmentTemplates = SegmentTemplate::query();
  3572. $segmentTemplates = $segmentTemplates->orderBy('created_at', 'DESC');
  3573. $responseType = $request->get('response_type');
  3574. if($responseType && $responseType == 'json'){
  3575. $segmentTemplates = $segmentTemplates->where('is_active', true)->get();
  3576. return $this->pass($segmentTemplates);
  3577. }
  3578. $segmentTemplates = $segmentTemplates->paginate(30);
  3579. return view('app.practice-management.segment-templates.index', compact('segmentTemplates'));
  3580. }
  3581. public function visitTemplates(Request $request){
  3582. $visitTemplates = VisitTemplate::query();
  3583. $visitTemplates = $visitTemplates->orderBy('created_at', 'DESC');
  3584. $responseType = $request->get('response_type');
  3585. if($responseType && $responseType == 'json'){
  3586. $visitTemplates = $visitTemplates->where('is_active', true)->get();
  3587. return $this->pass($visitTemplates);
  3588. }
  3589. $visitTemplates = $visitTemplates->paginate(30);
  3590. return view('app.practice-management.visit-templates.index', compact('visitTemplates'));
  3591. }
  3592. public function visitTemplate(Request $request, VisitTemplate $visitTemplate){
  3593. $visitTemplateSegmentTemplates = VisitTemplateSegmentTemplate::query();
  3594. $visitTemplateSegmentTemplates = $visitTemplateSegmentTemplates->where('visit_template_id', $visitTemplate->id);
  3595. $visitTemplateSegmentTemplates = $visitTemplateSegmentTemplates->orderBy('position_index', 'ASC');
  3596. $visitTemplateSegmentTemplates = $visitTemplateSegmentTemplates->paginate(50);
  3597. return view('app.practice-management.visit-templates.visit-template-segment-templates.index', compact('visitTemplate','visitTemplateSegmentTemplates'));
  3598. }
  3599. public function visitTemplateAccess(Request $request, VisitTemplate $visitTemplate){
  3600. $visitTemplateAccesses = VisitTemplateAccess::where('visit_template_id', $visitTemplate->id)->paginate(50);
  3601. return view('app.practice-management.visit-templates.visit-template-accesses.index', compact('visitTemplate','visitTemplateAccesses'));
  3602. }
  3603. public function clientCcmRmStatus(Request $request){
  3604. $filters = $request->all();
  3605. $patients = Client::whereNull('shadow_pro_id');
  3606. $pro = $this->performer()->pro;
  3607. if($pro->pro_type !== 'ADMIN') {
  3608. if($pro->is_hcp){
  3609. $patients = $patients->where('mcp_pro_id', $this->performer()->pro->id);
  3610. }
  3611. if($pro->is_considered_for_dna){
  3612. $patients = $patients->where('default_na_pro_id', $this->performer()->pro->id);
  3613. }
  3614. }
  3615. // filters
  3616. /*
  3617. array:18 [▼
  3618. "age_category" => "LESS_THAN"
  3619. "age_value_1" => "34"
  3620. "age_value_2" => null
  3621. "sex" => "M"
  3622. "bmi_category" => "BETWEEN"
  3623. "bmi_value_1" => "20"
  3624. "bmi_value_2" => "25"
  3625. "last_visit_category" => "LESS_THAN"
  3626. "last_visit_value_1" => "2021-10-14"
  3627. "last_visit_value_2" => null
  3628. "next_appointment_category" => "LESS_THAN"
  3629. "next_appointment_value_1" => "2021-10-15"
  3630. "status" => "ACTIVE"
  3631. "last_weighed_in_category" => "EXACTLY"
  3632. "last_weighed_in_value_1" => "2021-10-07"
  3633. "last_bp_category" => "BETWEEN"
  3634. "last_bp_value_1" => "2021-10-01"
  3635. "last_bp_value_2" => "2021-10-31"
  3636. ]
  3637. */
  3638. $this->filterMultiQuery($request, $patients, 'age_in_years', 'age_category', 'age_value_1', 'age_value_2', false);
  3639. $this->filterSimpleQuery($request, $patients, 'sex', 'sex');
  3640. $this->filterMultiQuery($request, $patients, 'usual_bmi', 'bmi_category', 'bmi_value_1', 'bmi_value_2');
  3641. $this->filterMultiQuery($request, $patients, 'most_recent_weight_at', 'last_weighed_in_category', 'last_weighed_in_value_1', 'last_weighed_in_value_2');
  3642. $this->filterMultiQuery($request, $patients, 'most_recent_bp_at', 'last_bp_category', 'last_bp_value_1', 'last_bp_value_2');
  3643. switch($request->input('status')) {
  3644. case 'ACTIVE':
  3645. $patients->where('is_active', true)->where('has_mcp_done_onboarding_visit', true);
  3646. break;
  3647. case 'AWAITING_VISIT':
  3648. $patients->where('is_active', true)->where('has_mcp_done_onboarding_visit', false);
  3649. break;
  3650. case 'INACTIVE':
  3651. $patients->where('is_active', '<>', true);
  3652. break;
  3653. }
  3654. if($request->input('is_eligible_for_cm')){
  3655. $patients->where('is_eligible_for_cm', '=', $request->input('is_eligible_for_cm'));
  3656. }
  3657. if($request->input('is_enrolled_in_cm')){
  3658. $patients->where('is_enrolled_in_cm', '=', $request->input('is_enrolled_in_cm'));
  3659. }
  3660. if($request->input('has_cm_setup_been_performed')){
  3661. $patients->where('has_cm_setup_been_performed', '=', $request->input('has_cm_setup_been_performed')=='YES'? true : false);
  3662. }
  3663. if($request->input('is_eligible_for_rm')){
  3664. $patients->where('is_eligible_for_rm', '=', $request->input('is_eligible_for_rm'));
  3665. }
  3666. if($request->input('is_enrolled_in_rm')){ /*-- correct --*/
  3667. $patients->where('is_enrolled_in_rm', '=', $request->input('is_enrolled_in_rm')); /*-- correct --*/
  3668. }
  3669. if($request->input('has_rm_setup_been_performed')){
  3670. $patients->where('has_rm_setup_been_performed', '=', $request->input('has_rm_setup_been_performed') =='YES'? true : false);
  3671. }
  3672. $patients = $patients->orderBy('created_at', 'DESC')->paginate(20);
  3673. return view('app.admin.client-ccm-rm-status', compact('patients', 'filters'));
  3674. }
  3675. public function rmActionReport(Request $request){
  3676. $filters = $request->all();
  3677. $careMonthStartDate = $request->get('care_month_start_date');
  3678. $careMonthYear = $request->get('care_month_year');
  3679. if(!$careMonthStartDate){
  3680. $careMonthStartDate = '2022-01-01';
  3681. }
  3682. if($careMonthYear){
  3683. $careMonthStartDate = $careMonthYear . "-01";
  3684. }
  3685. $lastDateOfMonth = new DateTime(date("Y-m-t", strtotime(get_current_date())));
  3686. $today = new DateTime(get_current_date());
  3687. $diff = $lastDateOfMonth->diff($today);
  3688. $daysBetweenNowAndEndmonth = $diff->days;
  3689. $minRequiredMeasurements = 16 - $daysBetweenNowAndEndmonth -1;
  3690. $numOfMeasurements = $request->get('num_of_measurements'); //16_or_more, 12_or_more
  3691. $hasRecentVisit = $request->get('has_recent_visit'); //yes no
  3692. $hasBeenSpokenToThisMonth = $request->get('has_been_spoken_to'); //yes no
  3693. // default sort
  3694. if(!$request->input('sort_by')) {
  3695. $orderBy = "cm.start_date ASC NULLS LAST, cm.client_id ASC NULLS LAST";
  3696. }
  3697. else {
  3698. $sortBy = json_decode($request->input('sort_by'));
  3699. $orderByClause = [];
  3700. $includeDefaultKeys = true;
  3701. foreach ($sortBy as $sortCriteria) {
  3702. $orderByClause[] = "{$sortCriteria->key} {$sortCriteria->order} NULLS LAST";
  3703. }
  3704. $orderBy = implode(', ', $orderByClause);
  3705. }
  3706. $conditions = [];
  3707. // start date
  3708. $conditions[] = "(cm.start_date >= '$careMonthStartDate')";
  3709. if($request->input('rm_eligible')) {
  3710. $conditions[] = "(c.is_eligible_for_rm = '" . $request->input('rm_eligible') . "')";
  3711. }
  3712. if($request->input('rm_enrolled')) {
  3713. if($request->input('rm_enrolled') === 'YES') {
  3714. $conditions[] = "(cm.is_client_enrolled_in_rm IS TRUE)";
  3715. }
  3716. else {
  3717. $conditions[] = "(cm.is_client_enrolled_in_rm IS NOT TRUE)";
  3718. }
  3719. }
  3720. if($request->input('rm_setup')) {
  3721. $conditions[] = "(c.has_rm_setup_been_performed IS " . ($request->input('rm_setup') === 'YES' ? 'TRUE' : 'FALSE') . ")";
  3722. }
  3723. // measurement days
  3724. if($numOfMeasurements){
  3725. if($numOfMeasurements == '16_or_more') {
  3726. $conditions[] = "(cm.number_of_days_with_remote_measurements >= 16)";
  3727. }
  3728. elseif($numOfMeasurements == 'min_or_more') {
  3729. $conditions[] = "(cm.number_of_days_with_remote_measurements >= $minRequiredMeasurements AND cm.number_of_days_with_remote_measurements < 16)";
  3730. }
  3731. elseif($numOfMeasurements == 'less_than_min') {
  3732. $conditions[] = "(cm.number_of_days_with_remote_measurements < $minRequiredMeasurements)";
  3733. }
  3734. }
  3735. // days since last visit
  3736. if($hasRecentVisit){
  3737. if($hasRecentVisit == 'YES'){
  3738. $conditions[] = "(c.most_recent_completed_mcp_note_date >= ((NOW() - interval '90 days')::DATE))";
  3739. }else{
  3740. $conditions[] = "(c.most_recent_completed_mcp_note_date::DATE < ((NOW() - interval '90 days')::DATE))";
  3741. }
  3742. }
  3743. // communicated
  3744. if($hasBeenSpokenToThisMonth){
  3745. if($hasBeenSpokenToThisMonth == 'YES') {
  3746. $conditions[] = "(cm.has_anyone_interacted_with_client_about_rm_outside_note IS TRUE)";
  3747. }
  3748. else {
  3749. $conditions[] = "(cm.has_anyone_interacted_with_client_about_rm_outside_note IS NOT TRUE)";
  3750. }
  3751. }
  3752. // claiming closed
  3753. $claimingClosed = $request->get('claiming_closed');
  3754. if($claimingClosed){
  3755. if($claimingClosed === 'YES') {
  3756. $conditions[] = "(cm.is_claim_closed IS TRUE)";
  3757. }
  3758. elseif($claimingClosed === 'NO') {
  3759. $conditions[] = "(cm.is_claim_closed IS TRUE)";
  3760. }
  3761. }
  3762. // mcp
  3763. if($request->input('mcp_uid')) {
  3764. $mcp = Pro::where('uid', $request->input('mcp_uid'))->first();
  3765. if($mcp) {
  3766. $conditions[] = "(cm.mcp_pro_id = $mcp->id)";
  3767. }
  3768. }
  3769. // client status
  3770. if($request->input('status')) {
  3771. $v = trim($request->input('status'));
  3772. if($v === 'ACTIVE') {
  3773. $conditions[] = "(c.client_engagement_status_category IS NULL OR c.client_engagement_status_category = '{$v}')";
  3774. }
  3775. else {
  3776. $conditions[] = "(c.client_engagement_status_category = '{$v}')";
  3777. }
  3778. }
  3779. else {
  3780. $conditions[] = "(c.client_engagement_status_category IS NULL OR c.client_engagement_status_category = 'ACTIVE')";
  3781. }
  3782. $columns = "
  3783. cm.id as care_month_id,
  3784. cm.uid as care_month_uid,
  3785. cm.start_date,
  3786. c.uid as client_uid,
  3787. c.is_eligible_for_rm,
  3788. cm.is_client_enrolled_in_rm,
  3789. c.has_rm_setup_been_performed,
  3790. (c.name_first || ' ' || c.name_last) as client_name,
  3791. (mcp.name_first || ' ' || mcp.name_last) as mcp_name,
  3792. (rmm.name_first || ' ' || rmm.name_last) as rmm_name,
  3793. cm.number_of_days_with_remote_measurements,
  3794. DATE_PART('day', NOW() - c.most_recent_cellular_measurement_at) as dslm,
  3795. c.most_recent_completed_mcp_note_date as mr_note_date,
  3796. cm.days_between_most_recent_mcp_note_date_and_end_of_care_month,
  3797. mrnote.uid as mr_note_uid,
  3798. cm.rm_total_time_in_seconds,
  3799. cm.rm_total_time_in_seconds_by_mcp,
  3800. cm.rm_total_time_in_seconds_by_rmm_pro,
  3801. cm.has_admin_interacted_with_client_about_rm,
  3802. cm.has_mcp_interacted_with_client_about_rm,
  3803. cm.claim_suggestion_json,
  3804. cm.is_claim_closed,
  3805. (CASE
  3806. WHEN cm.mcp_rm_generic_bill_id IS NOT NULL AND mcp_rm_bill.is_cancelled IS NOT TRUE THEN TRUE
  3807. ELSE FALSE
  3808. END) as mcp_payable,
  3809. (CASE
  3810. WHEN cm.rmm_rm_generic_bill_id IS NOT NULL AND rmm_rm_bill.is_cancelled IS NOT TRUE THEN TRUE
  3811. ELSE FALSE
  3812. END) as rmm_payable,
  3813. mcp_rm_bill.uid as mcp_rm_bill_uid,
  3814. rmm_rm_bill.uid as rmm_rm_bill_uid,
  3815. mcp_rm_bill.code as mcp_rm_bill_code,
  3816. rmm_rm_bill.code as rmm_rm_bill_code,
  3817. cl.status as claim_status,
  3818. cl.uid as claim_uid,
  3819. array_to_string(
  3820. ARRAY(SELECT claim_line.cpt FROM claim_line WHERE claim_line.claim_id = cl.id),
  3821. ', '::text
  3822. ) AS cpts
  3823. ";
  3824. $from = "
  3825. care_month cm
  3826. join client c on cm.client_id = c.id
  3827. left join pro mcp on c.mcp_pro_id = mcp.id
  3828. left join pro rmm on c.rmm_pro_id = rmm.id
  3829. left join bill mcp_rm_bill on cm.mcp_rm_generic_bill_id = mcp_rm_bill.id
  3830. left join bill rmm_rm_bill on cm.rmm_rm_generic_bill_id = rmm_rm_bill.id
  3831. left join note mrnote on c.most_recent_completed_mcp_note_id = mrnote.id
  3832. left join claim cl on cl.care_month_id = cm.id AND cl.is_cancelled IS NOT TRUE
  3833. ";
  3834. $page = $request->input('page') ?: 1;
  3835. $perPage = $request->input('per_page') ?: 15;
  3836. $offset = ($page - 1) * $perPage;
  3837. $countSql = "
  3838. SELECT
  3839. COUNT(*)
  3840. FROM
  3841. $from
  3842. where " . implode(" AND ", $conditions) . "
  3843. AND cl.is_cancelled IS NOT TRUE
  3844. ";
  3845. $countResult = DB::select($countSql);
  3846. $total = $countResult[0]->count;
  3847. $sql = "
  3848. SELECT
  3849. $columns
  3850. FROM
  3851. $from
  3852. WHERE " . implode(" AND ", $conditions) . "
  3853. ORDER BY $orderBy
  3854. OFFSET {$offset} LIMIT {$perPage}
  3855. ";
  3856. $rows = DB::select($sql);
  3857. $paginator = new LengthAwarePaginator($rows, $total, $request->input('per_page') ?: 15, $request->input('page') ?: 1);
  3858. $perPage = $request->input('per_page') ?: 15;
  3859. $paginator->setPath(route('practice-management.rmActionReport'));
  3860. return view('app.practice-management.rm-action-report', compact('rows', 'filters', 'minRequiredMeasurements', 'paginator'));
  3861. }
  3862. public function myFlyers(Request $request){
  3863. $pro = $this->performer->pro;
  3864. $slug = $pro->slug ?? $pro->uid;
  3865. $url = config('app.stagfe6_url') . '/flyers/json-list?slug=' . $slug;
  3866. $arrContextOptions=array(
  3867. "ssl"=>array(
  3868. "verify_peer"=>false,
  3869. "verify_peer_name"=>false,
  3870. ),
  3871. );
  3872. $response = @file_get_contents($url, false, stream_context_create($arrContextOptions));
  3873. $response = @json_decode($response);
  3874. $flyerTemplates = [];
  3875. if(isset($response->data)){
  3876. $flyerTemplates = $response->data;
  3877. }
  3878. return view('app.my-flyers', compact('pro','flyerTemplates'));
  3879. }
  3880. public function notesPendingPhysicianSupervisorStamping(Request $request){
  3881. $hideTitle = $request->get('hideTitle');
  3882. $pro = $this->performer->pro;
  3883. //All companyProIds that I am supervisor
  3884. $flaggedNotes = Note::where('is_stamped_by_supervising_physician', false)->where('is_flagged_for_supervising_physician_review', true)->whereHas('hcpCompanyPro', function($qry) use($pro){
  3885. return $qry->whereHas('supervisingPhysicianCompanyPro', function($qr) use($pro){
  3886. return $qr->where('pro_id', $pro->id);
  3887. });
  3888. })->get();
  3889. return view('app.notes-pending-physician-supervisor-stamping', compact('flaggedNotes', 'hideTitle'));
  3890. }
  3891. public function clientsWithoutDefaultCompanyProPayer(Request $request){
  3892. $rows = \App\Models\Client::whereNull('shadow_pro_id')
  3893. ->where('is_active', true)
  3894. ->where(function ($q) {
  3895. $q->whereNull('client_engagement_status_category')
  3896. ->orWhere('client_engagement_status_category', 'ACTIVE');
  3897. })
  3898. ->whereRaw('(default_mcp_company_pro_payer_id IS NULL OR default_mcp_company_location_id IS NULL)')
  3899. ->orderBy('created_at', 'DESC')
  3900. ->paginate(25);
  3901. return view('app.clients-without-default-company-pro-payer', compact('rows'));
  3902. }
  3903. public function notesWithoutHcpCompanyProPayer(Request $request){
  3904. $rows = \App\Models\Note::where('is_cancelled', false)
  3905. ->where('is_core_note', false)
  3906. ->where('is_signed_by_hcp', true)
  3907. ->whereNull('hcp_company_pro_payer_id')
  3908. ->orderBy('created_at', 'DESC')
  3909. ->paginate(25);
  3910. return view('app.notes-without-hcp-company-pro-payer', compact('rows'));
  3911. }
  3912. public function noteHcpBillsWithoutCompanyPro(Request $request){
  3913. $rows = \App\Models\Bill::where('bill_service_type', 'NOTE')
  3914. ->where('is_cancelled', false)
  3915. ->whereNotNull('hcp_pro_id')
  3916. ->whereNull('hcp_company_pro_id')
  3917. ->where('has_hcp_been_paid', false)
  3918. ->orderBy('created_at', 'DESC')
  3919. ->paginate(25);
  3920. return view('app.note-hcp-bills-without-company-pro', compact('rows'));
  3921. }
  3922. public function rpmMcpBillsWithoutCompanyPro(Request $request){
  3923. $rows = \App\Models\Bill::where('bill_service_type', 'GENERIC')
  3924. ->where('is_cancelled', false)
  3925. ->whereNotNull('generic_pro_id')
  3926. ->whereNull('generic_company_pro_id')
  3927. ->where('has_generic_pro_been_paid', false)
  3928. ->where('code', 'RM MCP')
  3929. ->orderBy('created_at', 'DESC')
  3930. ->paginate(25);
  3931. return view('app.rpm-mcp-bills-without-company-pro', compact('rows'));
  3932. }
  3933. public function rpmRmmBillsWithoutCompanyPro(Request $request){
  3934. $rows = \App\Models\Bill::where('bill_service_type', 'GENERIC')
  3935. ->where('is_cancelled', false)
  3936. ->whereNotNull('generic_pro_id')
  3937. ->whereNull('generic_company_pro_id')
  3938. ->where('has_generic_pro_been_paid', false)
  3939. ->where('code', 'RM RMM')
  3940. ->orderBy('created_at', 'DESC')
  3941. ->paginate(25);
  3942. return view('app.rpm-rmm-bills-without-company-pro', compact('rows'));
  3943. }
  3944. public function notesResolutionCenter(Request $request) {
  3945. $columns = "(c.name_first || ' ' || c.name_last) as client_name,
  3946. (hcp.name_first || ' ' || hcp.name_last) as hcp_name,
  3947. (na.name_first || ' ' || na.name_last) as na_name,
  3948. c.chart_number,
  3949. c.uid as client_uid,
  3950. n.effective_dateest,
  3951. n.uid,
  3952. n.detail_json,
  3953. n.is_claim_closed,
  3954. n.visit_number,
  3955. ROUND(b.number_of_units * 60) as minutes,
  3956. n.note_reason_icd1 AS icd1,
  3957. n.note_reason_icd1description AS icd1description,
  3958. n.note_reason_icd2 AS icd2,
  3959. n.note_reason_icd2description AS icd2description,
  3960. n.note_reason_icd3 AS icd3,
  3961. n.note_reason_icd3description AS icd3description,
  3962. n.note_reason_icd4 AS icd4,
  3963. n.note_reason_icd4description AS icd4description,
  3964. n.note_reason_memo AS icd_memo,
  3965. n.visit_number
  3966. ";
  3967. $from = "FROM note AS n
  3968. LEFT JOIN pro AS hcp ON n.hcp_pro_id = hcp.id
  3969. LEFT JOIN pro AS na ON n.ally_pro_id = na.id
  3970. JOIN client AS c ON n.client_id = c.id
  3971. JOIN bill AS b ON (b.note_id = n.id AND b.is_cancelled IS NOT TRUE AND b.code ILIKE '%treatment%')
  3972. ";
  3973. $where = "WHERE
  3974. -- n.visit_number IN (1,2) AND
  3975. n.is_signed_by_hcp IS TRUE AND
  3976. -- n.is_claim_closed IS NOT TRUE AND
  3977. n.is_cancelled IS NOT TRUE AND
  3978. n.created_at::DATE >= '2022-01-01'::DATE AND
  3979. c.client_engagement_status_category <> 'DUMMY' AND
  3980. c.name_first NOT ILIKE '%test%' AND
  3981. c.name_last NOT ILIKE '%test%' AND
  3982. n.id IN (SELECT note_id FROM bill WHERE code ILIKE '%treatment%' AND bill.is_cancelled IS NOT TRUE AND note_id IS NOT NULL) AND
  3983. -- n.id NOT IN (SELECT note_id FROM claim WHERE note_id IS NOT NULL) AND
  3984. c.is_part_b_primary = 'YES' AND
  3985. c.latest_eligible_refresh_at::DATE >= '2022-01-01' AND
  3986. c.mpb_remaining = 0 AND
  3987. c.created_at::DATE >= '2022-01-01'::DATE
  3988. ";
  3989. $filters = [];
  3990. if($request->input('f')) {
  3991. $filters[] = "(n.detail_json IS NOT NULL AND ((n.detail_json)::json->'farah_decision')::text = '\"" . $request->input('f') . "\"')";
  3992. }
  3993. if($request->input('s')) {
  3994. $filters[] = "(n.detail_json IS NOT NULL AND ((n.detail_json)::json->'shawn_decision')::text = '\"" . $request->input('s') . "\"')";
  3995. }
  3996. if(count($filters)) {
  3997. $filters = 'AND ' . implode(' AND ', $filters);
  3998. }
  3999. else {
  4000. $filters = '';
  4001. }
  4002. // $filters = '';
  4003. $orderBy = "ORDER BY c.id ASC, n.visit_number ASC";
  4004. $countQuery = "SELECT count(*) {$from} {$where} {$filters}";
  4005. // dd($countQuery);
  4006. $countResult = DB::select($countQuery);
  4007. $total = $countResult[0]->count;
  4008. $defaultPageSize = 25;
  4009. $page = $request->input('page') ?: 1;
  4010. $perPage = $request->input('per_page') ?: $defaultPageSize;
  4011. $offset = ($page - 1) * $perPage;
  4012. $dataQuery = "SELECT {$columns} {$from} {$where} {$filters} {$orderBy} OFFSET {$offset} LIMIT {$perPage}";
  4013. $rows = DB::select($dataQuery);
  4014. $paginator = new LengthAwarePaginator($rows, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  4015. $paginator->setPath(route('practice-management.notes-resolution-center'));
  4016. return view('app.practice-management.notes-resolution-center', compact('rows', 'paginator'));
  4017. }
  4018. public function notesResolutionCenterV2(Request $request) {
  4019. $columns = "(c.name_first || ' ' || c.name_last) as client_name,
  4020. (hcp.name_first || ' ' || hcp.name_last) as hcp_name,
  4021. (na.name_first || ' ' || na.name_last) as na_name,
  4022. c.chart_number,
  4023. c.uid as client_uid,
  4024. n.effective_dateest,
  4025. n.uid,
  4026. n.detail_json,
  4027. n.is_claim_closed,
  4028. n.visit_number,
  4029. ROUND(b.number_of_units * 60) as minutes,
  4030. n.note_reason_icd1 AS icd1,
  4031. n.note_reason_icd1description AS icd1description,
  4032. n.note_reason_icd2 AS icd2,
  4033. n.note_reason_icd2description AS icd2description,
  4034. n.note_reason_icd3 AS icd3,
  4035. n.note_reason_icd3description AS icd3description,
  4036. n.note_reason_icd4 AS icd4,
  4037. n.note_reason_icd4description AS icd4description,
  4038. n.note_reason_memo AS icd_memo
  4039. ";
  4040. $from = "FROM note AS n
  4041. LEFT JOIN pro AS hcp ON n.hcp_pro_id = hcp.id
  4042. LEFT JOIN pro AS na ON n.ally_pro_id = na.id
  4043. JOIN client AS c ON n.client_id = c.id
  4044. JOIN bill AS b ON (b.note_id = n.id AND b.is_cancelled IS NOT TRUE AND b.code ILIKE '%treatment%')
  4045. ";
  4046. $where = "WHERE
  4047. -- n.visit_number = 2 AND
  4048. n.is_signed_by_hcp IS TRUE AND
  4049. -- n.effective_dateest < '2022-03-01' AND
  4050. n.is_claim_closed IS NOT TRUE AND
  4051. n.is_cancelled IS NOT TRUE AND
  4052. c.client_engagement_status_category <> 'DUMMY' AND
  4053. c.name_first NOT ILIKE '%test%' AND
  4054. c.name_last NOT ILIKE '%test%' AND
  4055. n.id IN (SELECT note_id FROM bill WHERE code ILIKE '%treatment%' AND bill.is_cancelled IS NOT TRUE AND note_id IS NOT NULL)
  4056. -- AND
  4057. -- n.id NOT IN (SELECT note_id FROM claim WHERE note_id IS NOT NULL) AND
  4058. ";
  4059. $filters = [];
  4060. if(trim($request->input('f_pb_primary'))) {
  4061. $v = trim($request->input('f_pb_primary'));
  4062. if($v === 'yes') {
  4063. $filters[] = "(c.is_part_b_primary = 'YES')";
  4064. }
  4065. else if($v === 'no') {
  4066. $filters[] = "(c.is_part_b_primary != 'YES')";
  4067. }
  4068. }
  4069. if(trim($request->input('f_deductible_zero'))) {
  4070. $v = trim($request->input('f_deductible_zero'));
  4071. if($v === 'yes') {
  4072. $filters[] = "(c.mpb_remaining = 0)";
  4073. }
  4074. else if($v === 'no') {
  4075. $filters[] = "(c.mpb_remaining > 0)";
  4076. }
  4077. }
  4078. if(trim($request->input('f_note_hcp'))) {
  4079. $v = trim($request->input('f_note_hcp'));
  4080. $filters[] = "(n.hcp_pro_id IN (SELECT id FROM pro WHERE uid = '{$v}'))";
  4081. }
  4082. if(trim($request->input('f_2022_patient'))) {
  4083. $v = trim($request->input('f_2022_patient'));
  4084. if($v === 'yes') {
  4085. $filters[] = "(c.created_at::DATE >= '2022-01-01'::DATE)";
  4086. }
  4087. else if($v === 'no') {
  4088. $filters[] = "(c.created_at::DATE < '2022-01-01'::DATE)";
  4089. }
  4090. }
  4091. if(count($filters)) {
  4092. $filters = 'AND ' . implode(' AND ', $filters);
  4093. }
  4094. else {
  4095. $filters = '';
  4096. }
  4097. // $filters = '';
  4098. $orderBy = "ORDER BY
  4099. -- c.id ASC,
  4100. n.id ASC, n.effective_dateest ASC";
  4101. $countQuery = "SELECT count(*) {$from} {$where} {$filters}";
  4102. // dd($countQuery);
  4103. $countResult = DB::select($countQuery);
  4104. $total = $countResult[0]->count;
  4105. $defaultPageSize = 50;
  4106. $page = $request->input('page') ?: 1;
  4107. $perPage = $request->input('per_page') ?: $defaultPageSize;
  4108. $offset = ($page - 1) * $perPage;
  4109. $dataQuery = "SELECT {$columns} {$from} {$where} {$filters} {$orderBy} OFFSET {$offset} LIMIT {$perPage}";
  4110. $rows = DB::select($dataQuery);
  4111. $paginator = new LengthAwarePaginator($rows, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  4112. $paginator->setPath(route('practice-management.notes-resolution-center-v2'));
  4113. return view('app.practice-management.notes-resolution-center-v2', compact('rows', 'paginator'));
  4114. }
  4115. public function coverages(Request $request) {
  4116. $columns = "(c.name_first || ' ' || c.name_last) as client_name,
  4117. c.id,
  4118. c.uid,
  4119. c.created_at,
  4120. c.sex,
  4121. c.dob,
  4122. c.age_in_years,
  4123. row_to_json(lcpc.*) as latest_client_primary_coverage,
  4124. row_to_json(lacpc.*) as latest_auto_client_primary_coverage,
  4125. row_to_json(lmcpc.*) as latest_manual_client_primary_coverage,
  4126. row_to_json(lmcpc_payer.*) as latest_manual_client_primary_coverage_payer
  4127. ";
  4128. $from = "FROM client AS c
  4129. LEFT JOIN client_primary_coverage lcpc on c.effective_client_primary_coverage_id = lcpc.id
  4130. LEFT JOIN client_primary_coverage lacpc on c.latest_auto_refresh_client_primary_coverage_id = lacpc.id
  4131. LEFT JOIN client_primary_coverage lmcpc on c.latest_manual_client_primary_coverage_id = lmcpc.id
  4132. LEFT JOIN payer lmcpc_payer on lmcpc.commercial_payer_id = lmcpc_payer.id
  4133. ";
  4134. $where = "WHERE
  4135. c.client_engagement_status_category <> 'DUMMY' AND
  4136. c.name_first NOT ILIKE '%test%' AND
  4137. c.name_last NOT ILIKE '%test%' AND
  4138. c.created_at::DATE >= '2022-01-01'::DATE
  4139. -- lmcpc.id IS NOT NULL ANd lmcpc.plan_type != 'MEDICARE'
  4140. ";
  4141. $filters = [];
  4142. if(trim($request->input('f_name'))) {
  4143. $v = trim($request->input('f_name'));
  4144. $filters[] = "(c.name_first ILIKE '%{$v}%' OR c.name_last ILIKE '%{$v}%')";
  4145. }
  4146. if(trim($request->input('f_covered'))) {
  4147. $v = trim($request->input('f_covered'));
  4148. if($v !== 'any') {
  4149. switch($v) {
  4150. case 'covered':
  4151. $filters[] = "(
  4152. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.manual_determination_category = 'COVERED') OR
  4153. ((lmcpc.id IS NULL OR lmcpc.is_cancelled IS TRUE) AND lacpc.id IS NOT NULL AND lacpc.is_cancelled IS NOT TRUE AND lacpc.auto_medicare_is_partbprimary = 'YES')
  4154. )";
  4155. break;
  4156. case 'not-covered':
  4157. $filters[] = "(
  4158. (lmcpc.id IS NULL OR (lmcpc.is_cancelled IS TRUE OR lmcpc.manual_determination_category = 'NOT_COVERED')) AND
  4159. (lacpc.id IS NULL OR (lacpc.is_cancelled IS TRUE OR lacpc.auto_medicare_is_partbprimary = 'NO')) AND
  4160. (lmcpc.id IS NOT NULL OR lacpc.id IS NOT NULL)
  4161. )";
  4162. break;
  4163. case 'unknown':
  4164. $filters[] = "(
  4165. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.manual_determination_category = 'UNKNOWN') OR
  4166. ((lmcpc.id IS NULL OR lmcpc.is_cancelled IS TRUE) AND lacpc.id IS NOT NULL AND lacpc.is_cancelled IS NOT TRUE AND lacpc.auto_medicare_is_partbprimary = 'UNKNOWN')
  4167. )";
  4168. break;
  4169. }
  4170. }
  4171. }
  4172. if(trim($request->input('f_covered'))) {
  4173. $v = trim($request->input('f_covered'));
  4174. if($v !== 'any') {
  4175. switch($v) {
  4176. case 'covered':
  4177. $filters[] = "(
  4178. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.manual_determination_category = 'COVERED') OR
  4179. ((lmcpc.id IS NULL OR lmcpc.is_cancelled IS TRUE) AND lacpc.id IS NOT NULL AND lacpc.is_cancelled IS NOT TRUE AND lacpc.auto_medicare_is_partbprimary = 'YES')
  4180. )";
  4181. break;
  4182. case 'not-covered':
  4183. $filters[] = "(
  4184. (lmcpc.id IS NULL OR (lmcpc.is_cancelled IS TRUE OR lmcpc.manual_determination_category = 'NOT_COVERED')) AND
  4185. (lacpc.id IS NULL OR (lacpc.is_cancelled IS TRUE OR lacpc.auto_medicare_is_partbprimary = 'NO')) AND
  4186. (lmcpc.id IS NOT NULL OR lacpc.id IS NOT NULL)
  4187. )";
  4188. break;
  4189. case 'unknown':
  4190. $filters[] = "(
  4191. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.manual_determination_category = 'UNKNOWN') OR
  4192. ((lmcpc.id IS NULL OR lmcpc.is_cancelled IS TRUE) AND lacpc.id IS NOT NULL AND lacpc.is_cancelled IS NOT TRUE AND lacpc.auto_medicare_is_partbprimary = 'UNKNOWN')
  4193. )";
  4194. break;
  4195. }
  4196. }
  4197. }
  4198. if(trim($request->input('f_plan_type'))) {
  4199. $v = strtoupper(trim($request->input('f_plan_type')));
  4200. if($v !== 'ANY') {
  4201. $filters[] = "(
  4202. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.plan_type = '{$v}') OR
  4203. ((lmcpc.id IS NULL OR lmcpc.is_cancelled IS TRUE) AND lacpc.id IS NOT NULL AND lacpc.is_cancelled IS NOT TRUE AND lacpc.plan_type = '{$v}')
  4204. )";
  4205. }
  4206. }
  4207. if(trim($request->input('f_pb_primary'))) {
  4208. $v = trim($request->input('f_pb_primary'));
  4209. if($v !== 'any') {
  4210. switch($v) {
  4211. case 'primary':
  4212. $filters[] = "(
  4213. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.is_partbprimary = 'YES') OR
  4214. ((lmcpc.id IS NULL OR lmcpc.is_cancelled IS TRUE) AND lacpc.id IS NOT NULL AND lacpc.is_cancelled IS NOT TRUE AND lacpc.auto_medicare_is_partbprimary = 'YES')
  4215. )";
  4216. break;
  4217. case 'not-primary':
  4218. $filters[] = "(
  4219. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.is_partbprimary = 'NO') OR
  4220. ((lmcpc.id IS NULL OR lmcpc.is_cancelled IS TRUE) AND lacpc.id IS NOT NULL AND lacpc.is_cancelled IS NOT TRUE AND lacpc.auto_medicare_is_partbprimary = 'NO')
  4221. )";
  4222. break;
  4223. case 'unknown':
  4224. $filters[] = "(
  4225. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.is_partbprimary = 'UNKNOWN') OR
  4226. ((lmcpc.id IS NULL OR lmcpc.is_cancelled IS TRUE) AND lacpc.id IS NOT NULL AND lacpc.is_cancelled IS NOT TRUE AND lacpc.auto_medicare_is_partbprimary = 'UNKNOWN')
  4227. )";
  4228. break;
  4229. }
  4230. }
  4231. }
  4232. if(trim($request->input('f_pb_active'))) {
  4233. $v = trim($request->input('f_pb_active'));
  4234. // TODO
  4235. }
  4236. if(trim($request->input('f_pc_active'))) {
  4237. $v = trim($request->input('f_pc_active'));
  4238. // TODO
  4239. }
  4240. if(trim($request->input('f_comm_payer'))) {
  4241. $v = trim($request->input('f_comm_payer'));
  4242. $filters[] = "(lmcpc_payer.name ILIKE '%{$v}%')";
  4243. }
  4244. if(trim($request->input('f_comm_member_id'))) {
  4245. $v = trim($request->input('f_comm_member_id'));
  4246. if($v !== 'any') {
  4247. $filters[] = "(
  4248. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.commercial_member_identifier ILIKE '%{$v}%') OR
  4249. ((lmcpc.id IS NULL OR lmcpc.is_cancelled IS TRUE) AND lacpc.id IS NOT NULL AND lacpc.is_cancelled IS NOT TRUE AND lacpc.commercial_member_identifier ILIKE '%{$v}%')
  4250. )";
  4251. }
  4252. }
  4253. if(trim($request->input('f_comm_group_num'))) {
  4254. $v = trim($request->input('f_comm_group_num'));
  4255. if($v !== 'any') {
  4256. $filters[] = "(
  4257. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.commercial_group_number ILIKE '%{$v}%') OR
  4258. ((lmcpc.id IS NULL OR lmcpc.is_cancelled IS TRUE) AND lacpc.id IS NOT NULL AND lacpc.is_cancelled IS NOT TRUE AND lacpc.commercial_group_number ILIKE '%{$v}%')
  4259. )";
  4260. }
  4261. }
  4262. if(count($filters)) {
  4263. $filters = 'AND ' . implode(' AND ', $filters);
  4264. }
  4265. else {
  4266. $filters = '';
  4267. }
  4268. // $filters = '';
  4269. $orderBy = "ORDER BY client_name ASC";
  4270. $countQuery = "SELECT count(*) {$from} {$where} {$filters}";
  4271. // dd($countQuery);
  4272. $countResult = DB::select($countQuery);
  4273. $total = $countResult[0]->count;
  4274. $defaultPageSize = 10;
  4275. $page = $request->input('page') ?: 1;
  4276. $perPage = $request->input('per_page') ?: $defaultPageSize;
  4277. $offset = ($page - 1) * $perPage;
  4278. $dataQuery = "SELECT {$columns} {$from} {$where} {$filters} {$orderBy} OFFSET {$offset} LIMIT {$perPage}";
  4279. $rows = DB::select($dataQuery);
  4280. $paginator = new LengthAwarePaginator($rows, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  4281. $paginator->setPath(route('practice-management.coverages'));
  4282. // dd($rows);
  4283. return view('app.practice-management.coverages', compact('rows', 'paginator'));
  4284. }
  4285. public function clientReviewRequests(Request $request){
  4286. $pro = $this->performer->pro;
  4287. $reviewRequests = ClientReviewRequest::where('status', '!=', 'DONE');
  4288. if($pro->pro_type !== 'ADMIN'){
  4289. $reviewRequests = $reviewRequests->where('pro_id', $pro->id);
  4290. }
  4291. $reviewRequests = $reviewRequests->orderBy('created_at', 'DESC')->paginate(50);
  4292. return view('app.ps.review-requests.list', compact('reviewRequests'));
  4293. }
  4294. }