PracticeManagementController.php 215 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899
  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 = []; // ["(care_month.start_date >= '2022-01-01')"];
  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.start_date DESC, 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('m'))) {
  1647. $v = trim($request->input('m'));
  1648. $conditions[] = "(EXTRACT(MONTH from care_month.start_date) = $v)";
  1649. }
  1650. if(trim($request->input('y'))) {
  1651. $v = trim($request->input('y'));
  1652. $conditions[] = "(EXTRACT(YEAR from care_month.start_date) = $v)";
  1653. }
  1654. if(trim($request->input('f_ces'))) {
  1655. $v = trim($request->input('f_ces'));
  1656. if($v === 'ACTIVE') {
  1657. $conditions[] = "(client.client_engagement_status_category IS NULL OR client.client_engagement_status_category = '{$v}')";
  1658. }
  1659. else {
  1660. $conditions[] = "(client.client_engagement_status_category = '{$v}')";
  1661. }
  1662. }
  1663. if(trim($request->input('f_name'))) {
  1664. $v = trim($request->input('f_name'));
  1665. $conditions[] = "(client.name_first ILIKE '%{$v}%' OR client.name_last ILIKE '%{$v}%')";
  1666. }
  1667. if(trim($request->input('f_payer_type'))) {
  1668. switch($request->input('f_payer_type')) {
  1669. case 'Medicare':
  1670. $conditions[] = "(cpc.plan_type = 'MEDICARE')";
  1671. break;
  1672. case 'Non Medicare':
  1673. $conditions[] = "(cpc.plan_type != 'MEDICARE')";
  1674. break;
  1675. case 'Medicaid':
  1676. $conditions[] = "(cpc.plan_type = 'MEDICAID')";
  1677. break;
  1678. case 'Commercial':
  1679. $conditions[] = "(cpc.plan_type = 'COMMERCIAL')";
  1680. break;
  1681. }
  1682. }
  1683. if((trim($request->input('f_payer_type')) === 'Non Medicare' || trim($request->input('f_payer_type')) === 'Commercial') && trim($request->input('f_payer'))) {
  1684. $v = trim($request->input('f_payer'));
  1685. $conditions[] = "(payer.name ILIKE '%{$v}%')";
  1686. }
  1687. if(trim($request->input('f_state'))) {
  1688. $v = trim($request->input('f_state'));
  1689. switch($v) {
  1690. case 'NONE':
  1691. $conditions[] = "(client.mailing_address_state IS NULL)";
  1692. break;
  1693. case 'NOT_MD':
  1694. $conditions[] = "(client.mailing_address_state IS NOT NULL AND client.mailing_address_state != 'MD')";
  1695. break;
  1696. default:
  1697. $conditions[] = "(client.mailing_address_state ILIKE '%{$v}%')";
  1698. break;
  1699. }
  1700. }
  1701. if(trim($request->input('f_mcp'))) {
  1702. $v = trim($request->input('f_mcp'));
  1703. $conditions[] = "(mcpPro.uid = '{$v}')";
  1704. }
  1705. if(trim($request->input('f_dob_op')) && trim($request->input('f_dob'))) {
  1706. $o = trim($request->input('f_dob_op'));
  1707. $v = trim($request->input('f_dob'));
  1708. $conditions[] = "(client.dob {$o} '{$v}')";
  1709. }
  1710. if(trim($request->input('f_rpm'))) {
  1711. $v = trim($request->input('f_rpm'));
  1712. if($v === 'yes') {
  1713. $conditions[] = "(care_month.is_client_enrolled_in_rm IS TRUE)";
  1714. }
  1715. elseif($v === 'no') {
  1716. $conditions[] = "(care_month.is_client_enrolled_in_rm IS NOT TRUE)";
  1717. }
  1718. }
  1719. if(trim($request->input('f_cell_bp'))) {
  1720. $v = trim($request->input('f_cell_bp'));
  1721. if($v === 'yes') {
  1722. $conditions[] = "(client.is_assigned_cellular_bp_device IS NOT NULL AND client.is_assigned_cellular_bp_device = TRUE)";
  1723. }
  1724. elseif($v === 'no') {
  1725. $conditions[] = "(client.is_assigned_cellular_bp_device IS NULL OR client.is_assigned_cellular_bp_device = FALSE)";
  1726. }
  1727. }
  1728. if(trim($request->input('f_cell_wt'))) {
  1729. $v = trim($request->input('f_cell_wt'));
  1730. if($v === 'yes') {
  1731. $conditions[] = "(client.is_assigned_cellular_weight_scale_device IS NOT NULL AND client.is_assigned_cellular_weight_scale_device = TRUE)";
  1732. }
  1733. elseif($v === 'no') {
  1734. $conditions[] = "(client.is_assigned_cellular_weight_scale_device IS NULL OR client.is_assigned_cellular_weight_scale_device = FALSE)";
  1735. }
  1736. }
  1737. if(trim($request->input('f_lmb'))) {
  1738. $v = trim($request->input('f_lmb'));
  1739. switch($v) {
  1740. case '1':
  1741. $conditions[] = "(GREATEST(client.most_recent_cellular_bp_measurement_at::DATE, client.most_recent_cellular_weight_measurement_at::DATE)::DATE < (NOW() - INTERVAL '1 DAY')::DATE)";
  1742. break;
  1743. case '2':
  1744. $conditions[] = "(GREATEST(client.most_recent_cellular_bp_measurement_at::DATE, client.most_recent_cellular_weight_measurement_at::DATE)::DATE < (NOW() - INTERVAL '2 DAYS')::DATE)";
  1745. break;
  1746. case '3':
  1747. $conditions[] = "(GREATEST(client.most_recent_cellular_bp_measurement_at::DATE, client.most_recent_cellular_weight_measurement_at::DATE)::DATE < (NOW() - INTERVAL '3 DAYS')::DATE)";
  1748. break;
  1749. case '3+':
  1750. $conditions[] = "(GREATEST(client.most_recent_cellular_bp_measurement_at::DATE, client.most_recent_cellular_weight_measurement_at::DATE)::DATE < (NOW() - INTERVAL '4 DAYS')::DATE)";
  1751. break;
  1752. }
  1753. }
  1754. if(trim($request->input('f_comm'))) {
  1755. $v = trim($request->input('f_comm'));
  1756. if($v === 'yes') {
  1757. $conditions[] = "(care_month.has_mcp_interacted_with_client_about_rm IS NOT NULL AND care_month.has_mcp_interacted_with_client_about_rm = TRUE)";
  1758. }
  1759. elseif($v === 'no') {
  1760. $conditions[] = "(care_month.has_mcp_interacted_with_client_about_rm IS NULL OR care_month.has_mcp_interacted_with_client_about_rm = FALSE)";
  1761. }
  1762. }
  1763. if(trim($request->input('f_mcp_billable'))) {
  1764. $v = trim($request->input('f_mcp_billable'));
  1765. if($v === 'yes') {
  1766. $conditions[] = "(care_month.mcp_rm_generic_bill_id IS NOT NULL)";
  1767. }
  1768. elseif($v === 'no') {
  1769. $conditions[] = "(care_month.mcp_rm_generic_bill_id IS NULL)";
  1770. }
  1771. }
  1772. if(trim($request->input('f_rmm_billable'))) {
  1773. $v = trim($request->input('f_rmm_billable'));
  1774. if($v === 'yes') {
  1775. $conditions[] = "(care_month.rmm_rm_generic_bill_id IS NOT NULL)";
  1776. }
  1777. elseif($v === 'no') {
  1778. $conditions[] = "(care_month.rmm_rm_generic_bill_id IS NULL)";
  1779. }
  1780. }
  1781. if(trim($request->input('f_md_op')) && trim($request->input('f_md')) !== '') {
  1782. $o = trim($request->input('f_md_op'));
  1783. $v = trim($request->input('f_md'));
  1784. $conditions[] = "(care_month.number_of_days_with_remote_measurements {$o} {$v})";
  1785. }
  1786. if(trim($request->input('f_unst_op')) && trim($request->input('f_unst')) !== '') {
  1787. $o = trim($request->input('f_unst_op'));
  1788. $v = trim($request->input('f_unst'));
  1789. $conditions[] = "(care_month.rm_num_measurements_not_stamped_by_mcp {$o} {$v})";
  1790. }
  1791. if(trim($request->input('f_mcp_mins_op')) && trim($request->input('f_mcp_mins')) !== '') {
  1792. $o = trim($request->input('f_mcp_mins_op'));
  1793. $v = intval(trim($request->input('f_mcp_mins'))) * 60;
  1794. $conditions[] = "(care_month.rm_total_time_in_seconds_by_mcp {$o} {$v})";
  1795. }
  1796. if(trim($request->input('f_rmm_mins_op')) && trim($request->input('f_rmm_mins')) !== '') {
  1797. $o = trim($request->input('f_rmm_mins_op'));
  1798. $v = intval(trim($request->input('f_rmm_mins'))) * 60;
  1799. $conditions[] = "(care_month.rm_total_time_in_seconds_by_rmm_pro {$o} {$v})";
  1800. }
  1801. if(trim($request->input('f_dslm_op')) && trim($request->input('f_dslm')) !== '') {
  1802. $o = trim($request->input('f_dslm_op'));
  1803. $v = trim($request->input('f_dslm'));
  1804. $conditions[] = "(DATE_PART('day', NOW() - client.most_recent_cellular_measurement_at) {$o} {$v})";
  1805. }
  1806. if(trim($request->input('f_dslv_op')) && trim($request->input('f_dslv')) !== '') {
  1807. $o = trim($request->input('f_dslv_op'));
  1808. $v = trim($request->input('f_dslv'));
  1809. $conditions[] = "(care_month.days_between_most_recent_mcp_note_date_and_end_of_care_month {$o} {$v})";
  1810. }
  1811. if($request->input('not-enrolled')) {
  1812. $conditions[] = "(care_month.is_client_enrolled_in_rm IS NOT TRUE)";
  1813. }
  1814. else {
  1815. $conditions[] = "(care_month.is_client_enrolled_in_rm IS TRUE)";
  1816. }
  1817. if($request->input('f_claim_closed')) {
  1818. if($request->input('f_claim_closed') === 'no') {
  1819. $conditions[] = "(care_month.is_claim_closed IS NULL OR care_month.is_claim_closed IS FALSE)";
  1820. }
  1821. else {
  1822. $conditions[] = "(care_month.is_claim_closed IS TRUE)";
  1823. }
  1824. }
  1825. if($request->input('f_mcp_billable')) {
  1826. if($request->input('f_mcp_billable') === 'no') {
  1827. $conditions[] = "(care_month.is_billable_by_mcp IS NULL OR care_month.is_billable_by_mcp IS FALSE)";
  1828. }
  1829. else {
  1830. $conditions[] = "(care_month.is_billable_by_mcp IS TRUE)";
  1831. }
  1832. }
  1833. if($request->input('f_rmm_billable')) {
  1834. if($request->input('f_rmm_billable') === 'no') {
  1835. $conditions[] = "(care_month.is_billable_by_rmm IS NULL OR care_month.is_billable_by_rmm IS FALSE)";
  1836. }
  1837. else {
  1838. $conditions[] = "(care_month.is_billable_by_rmm IS TRUE)";
  1839. }
  1840. }
  1841. switch($request->input('f_454')) {
  1842. case 'Claimable':
  1843. $conditions[] = "(care_month.is_99454_claimable IS TRUE)";
  1844. break;
  1845. case 'Not Claimable':
  1846. $conditions[] = "(care_month.is_99454_claimable IS NULL OR care_month.is_99454_claimable IS FALSE)";
  1847. break;
  1848. case 'Claimed':
  1849. $conditions[] = "(care_month.is_99454_claimable IS TRUE AND care_month.is_99454_claimed IS TRUE)";
  1850. break;
  1851. case 'Not Claimed':
  1852. $conditions[] = "(care_month.is_99454_claimable IS TRUE AND (care_month.is_99454_claimed IS NULL OR care_month.is_99454_claimed IS FALSE))";
  1853. break;
  1854. case 'Waived':
  1855. $conditions[] = "(care_month.is_99454_claimable IS TRUE AND care_month.is_99454_claiming_waived IS TRUE)";
  1856. break;
  1857. }
  1858. switch($request->input('f_454')) {
  1859. case 'Claimable':
  1860. $conditions[] = "(care_month.is_99454_claimable IS TRUE)";
  1861. break;
  1862. case 'Not Claimable':
  1863. $conditions[] = "(care_month.is_99454_claimable IS NULL OR care_month.is_99454_claimable IS FALSE)";
  1864. break;
  1865. case 'Claimed':
  1866. $conditions[] = "(care_month.is_99454_claimable IS TRUE AND care_month.is_99454_claimed IS TRUE)";
  1867. break;
  1868. case 'Not Claimed':
  1869. $conditions[] = "(care_month.is_99454_claimable IS TRUE AND (care_month.is_99454_claimed IS NULL OR care_month.is_99454_claimed IS FALSE))";
  1870. break;
  1871. case 'Waived':
  1872. $conditions[] = "(care_month.is_99454_claimable IS TRUE AND care_month.is_99454_claiming_waived IS TRUE)";
  1873. break;
  1874. }
  1875. switch($request->input('f_457')) {
  1876. case 'Claimable':
  1877. $conditions[] = "(care_month.is_99457_claimable IS TRUE)";
  1878. break;
  1879. case 'Not Claimable':
  1880. $conditions[] = "(care_month.is_99457_claimable IS NULL OR care_month.is_99457_claimable IS FALSE)";
  1881. break;
  1882. case 'Claimed':
  1883. $conditions[] = "(care_month.is_99457_claimable IS TRUE AND care_month.is_99457_claimed IS TRUE)";
  1884. break;
  1885. case 'Not Claimed':
  1886. $conditions[] = "(care_month.is_99457_claimable IS TRUE AND (care_month.is_99457_claimed IS NULL OR care_month.is_99457_claimed IS FALSE))";
  1887. break;
  1888. case 'Waived':
  1889. $conditions[] = "(care_month.is_99457_claimable IS TRUE AND care_month.is_99457_claiming_waived IS TRUE)";
  1890. break;
  1891. }
  1892. switch($request->input('f_458')) {
  1893. case 'Claimable':
  1894. $conditions[] = "(care_month.is_99458_claimable IS TRUE)";
  1895. break;
  1896. case 'Not Claimable':
  1897. $conditions[] = "(care_month.is_99458_claimable IS NULL OR care_month.is_99458_claimable IS FALSE)";
  1898. break;
  1899. case 'Claimed':
  1900. $conditions[] = "(care_month.is_99458_claimable IS TRUE AND care_month.is_99458_claimed IS TRUE)";
  1901. break;
  1902. case 'Not Claimed':
  1903. $conditions[] = "(care_month.is_99458_claimable IS TRUE AND (care_month.is_99458_claimed IS NULL OR care_month.is_99458_claimed IS FALSE))";
  1904. break;
  1905. case 'Waived':
  1906. $conditions[] = "(care_month.is_99458_claimable IS TRUE AND care_month.is_99458_claiming_waived IS TRUE)";
  1907. break;
  1908. }
  1909. if($request->input('f_visit_90_days')) {
  1910. /*if($request->input('f_visit_90_days') === 'yes') {
  1911. $conditions[] = "(care_month.is_claim_closed IS " . ($request->input('f_claim_closed') === 'yes' ? 'TRUE' : 'FALSE') . ")";
  1912. }
  1913. else {
  1914. $conditions[] = "(care_month.is_claim_closed IS " . ($request->input('f_claim_closed') === 'yes' ? 'TRUE' : 'FALSE') . ")";
  1915. }*/
  1916. }
  1917. $genericBillIdColumns = "care_month.mcp_rm_generic_bill_id,
  1918. mcpBill.uid as mcp_rm_generic_bill_uid,
  1919. mcpBill.generic_pro_id as mcp_rm_generic_bill_generic_pro_id,
  1920. mcpBill.generic_pro_expected_payment_amount as mcp_rm_generic_bill_expected_payment_amount,
  1921. mcpBill.is_signed_by_generic_pro as mcp_rm_generic_bill_signed,
  1922. care_month.rmm_rm_generic_bill_id,
  1923. rmmBill.uid as rmm_rm_generic_bill_uid,
  1924. rmmBill.generic_pro_id as rmm_rm_generic_bill_generic_pro_id,
  1925. rmmBill.generic_pro_expected_payment_amount as rmm_rm_generic_bill_expected_payment_amount,
  1926. rmmBill.is_signed_by_generic_pro as rmm_rm_generic_bill_signed";
  1927. $genericBillJoinClause = "left join bill mcpBill on care_month.mcp_rm_generic_bill_id = mcpBill.id
  1928. left join bill rmmBill on care_month.rmm_rm_generic_bill_id = rmmBill.id";
  1929. $defaultPageSize = 25;
  1930. $page = $request->input('page') ?: 1;
  1931. $perPage = $request->input('per_page') ?: $defaultPageSize;
  1932. $offset = ($page - 1) * $perPage;
  1933. $countQuery = "
  1934. SELECT COUNT(*)
  1935. FROM care_month join client on care_month.client_id = client.id
  1936. join note mrnote on client.most_recent_completed_mcp_note_id = mrnote.id
  1937. left join pro mcpPro on care_month.mcp_pro_id = mcpPro.id
  1938. left join pro rmmPro on care_month.rmm_pro_id = rmmPro.id
  1939. left join client_primary_coverage cpc on client.effective_client_primary_coverage_id = cpc.id
  1940. left join payer on cpc.commercial_payer_id = payer.id
  1941. {$genericBillJoinClause}
  1942. WHERE
  1943. " . (count($conditions) > 0 ? implode(" AND ", $conditions) : '') . "
  1944. ";
  1945. $countResult = DB::select($countQuery);
  1946. $total = $countResult[0]->count;
  1947. $query = "
  1948. SELECT client.name_first, client.name_last,
  1949. (client.name_first || ' ' || client.name_last) as client_name,
  1950. client.uid as client_uid,
  1951. client.dob,
  1952. client.age_in_years,
  1953. care_month.is_client_enrolled_in_rm,
  1954. client.most_recent_completed_mcp_note_date,
  1955. client.most_recent_completed_mcp_note_id,
  1956. client.cell_number,
  1957. client.is_assigned_cellular_bp_device,
  1958. client.is_assigned_cellular_weight_scale_device,
  1959. nv.raw_date as next_visit_date,
  1960. DATE_PART('day', NOW() - client.most_recent_cellular_measurement_at) as dslm,
  1961. care_month.uid as care_month_uid,
  1962. care_month.id as care_month_id,
  1963. care_month.is_claim_closed,
  1964. care_month.start_date,
  1965. care_month.rm_total_time_in_seconds,
  1966. care_month.rm_total_time_in_seconds_by_mcp,
  1967. care_month.rm_total_time_in_seconds_by_rmm_pro,
  1968. care_month.number_of_days_with_remote_measurements,
  1969. care_month.has_mcp_interacted_with_client_about_rm,
  1970. care_month.has_anyone_interacted_with_client_about_rm,
  1971. care_month.rm_num_measurements_not_stamped_by_mcp,
  1972. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  1973. care_month.rm_num_measurements_not_stamped_by_rmm,
  1974. care_month.rm_num_measurements_not_stamped_by_rme,
  1975. care_month.is_99454_claimable,
  1976. care_month.is_99454_claimed,
  1977. care_month.is_99454_claiming_waived,
  1978. care_month.is_99457_claimable,
  1979. care_month.is_99457_claimed,
  1980. care_month.is_99457_claiming_waived,
  1981. care_month.is_99458_claimable,
  1982. care_month.is_99458_claimed,
  1983. care_month.is_99458_claiming_waived,
  1984. care_month.is_billable_by_mcp,
  1985. care_month.is_billable_by_rmm,
  1986. care_month.why_99454_not_claimable_reason,
  1987. care_month.why_99457_not_claimable_reason,
  1988. care_month.why_99458_not_claimable_reason,
  1989. care_month.why_claiming_99454_waived,
  1990. care_month.why_claiming_99457_waived,
  1991. care_month.why_claiming_99458_waived,
  1992. care_month.mcp_pro_id as care_month_mcp_pro_id,
  1993. care_month.rmm_pro_id as care_month_rmm_pro_id,
  1994. client.mcp_pro_id,
  1995. client.default_na_pro_id,
  1996. client.rmm_pro_id,
  1997. client.rme_pro_id,
  1998. client.cell_number,
  1999. care_month.most_recent_cellular_bp_dbp_mm_hg,
  2000. care_month.most_recent_cellular_bp_sbp_mm_hg,
  2001. care_month.most_recent_cellular_bp_measurement_at,
  2002. care_month.most_recent_cellular_weight_value,
  2003. care_month.most_recent_cellular_weight_measurement_at,
  2004. mcpPro.mcp_rpm_payment_strategy,
  2005. mcpPro.mcp_rpm_payment_amount,
  2006. (mcpPro.name_first || ' ' || mcpPro.name_last) as mcp_name,
  2007. rmmPro.rmm_payment_strategy,
  2008. rmmPro.rmm_payment_amount,
  2009. client.mailing_address_state,
  2010. care_month.most_recent_cellular_weight_measurement_at,
  2011. care_month.days_between_most_recent_mcp_note_date_and_end_of_care_month,
  2012. cpc.plan_type,
  2013. cpc.auto_medicare_is_partbprimary,
  2014. (CASE
  2015. WHEN cpc.plan_type LIKE 'COMMERCIAL' THEN payer.name
  2016. ELSE cpc.plan_type
  2017. END) as payer_name,
  2018. (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,
  2019. (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,
  2020. (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,
  2021. {$genericBillIdColumns}
  2022. FROM care_month join client on care_month.client_id = client.id
  2023. left join note mrnote on client.most_recent_completed_mcp_note_id = mrnote.id
  2024. left join pro mcpPro on care_month.mcp_pro_id = mcpPro.id
  2025. left join pro rmmPro on care_month.rmm_pro_id = rmmPro.id
  2026. left join client_primary_coverage cpc on client.effective_client_primary_coverage_id = cpc.id
  2027. left join payer on cpc.commercial_payer_id = payer.id
  2028. left join appointment nv on nv.id = mrnote.follow_up_appointment_id
  2029. {$genericBillJoinClause}
  2030. WHERE
  2031. " . (count($conditions) > 0 ? implode(" AND ", $conditions) : '') . "
  2032. {$orderBy} OFFSET {$offset} LIMIT {$perPage}
  2033. ";
  2034. // dd($query);
  2035. $patients = DB::select($query);
  2036. $timestamp = strtotime(date('Y-m-d'));
  2037. $daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
  2038. $paginator = new LengthAwarePaginator($patients, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  2039. $perPage = $request->input('per_page') ?: $defaultPageSize;
  2040. $paginator->setPath(route('practice-management.rpm-matrix-admin'));
  2041. return view('app.practice-management.rpm-matrix-for-admin', compact('patients', 'daysRemaining', 'careMonthStart', 'paginator', 'perPage'));
  2042. }
  2043. public function claimsReport(Request $request) {
  2044. $performer = $this->performer();
  2045. $conditions = ["(claim.status = 'SUBMITTED')"];
  2046. // default sort
  2047. if(!$request->input('sort_by')) {
  2048. $orderBy = "cline.created_at DESC NULLS LAST";
  2049. }
  2050. else {
  2051. $sortBy = json_decode($request->input('sort_by'));
  2052. $orderByClause = [];
  2053. foreach ($sortBy as $sortCriteria) {
  2054. $orderByClause[] = "{$sortCriteria->key} {$sortCriteria->order} NULLS LAST";
  2055. }
  2056. $orderBy = implode(', ', $orderByClause);
  2057. }
  2058. // filters from the UI
  2059. if(trim($request->input('f_start'))) {
  2060. $v = trim($request->input('f_start'));
  2061. $conditions[] = "(cline.date_of_service >= '{$v}')";
  2062. }
  2063. if(trim($request->input('f_end'))) {
  2064. $v = trim($request->input('f_end'));
  2065. $conditions[] = "(cline.date_of_service <= '{$v}')";
  2066. }
  2067. $defaultPageSize = 25;
  2068. $page = $request->input('page') ?: 1;
  2069. $perPage = $request->input('per_page') ?: $defaultPageSize;
  2070. $offset = ($page - 1) * $perPage;
  2071. $countQuery = "
  2072. SELECT COUNT(*)
  2073. FROM claim_line cline
  2074. join claim on cline.claim_id = claim.id
  2075. join client on claim.client_id = client.id
  2076. left join pro on claim.pro_id = pro.id
  2077. left join client_primary_coverage cpc on client.effective_client_primary_coverage_id = cpc.id
  2078. left join payer on cpc.commercial_payer_id = payer.id
  2079. WHERE
  2080. " . implode(' AND ', $conditions) . "
  2081. ";
  2082. $countResult = DB::select($countQuery);
  2083. $total = $countResult[0]->count;
  2084. $query = "
  2085. SELECT (client.name_first || ' ' || client.name_last) as client_name,
  2086. client.uid as client_uid,
  2087. client.dob,
  2088. client.age_in_years,
  2089. client.is_enrolled_in_rm,
  2090. client.mailing_address_state,
  2091. (pro.name_first || ' ' || pro.name_last) as pro_name,
  2092. (CASE
  2093. WHEN cpc.plan_type LIKE 'COMMERCIAL' THEN payer.name
  2094. ELSE cpc.plan_type
  2095. END) as payer_name,
  2096. cline.date_of_service,
  2097. cline.cpt
  2098. FROM claim_line cline
  2099. join claim on cline.claim_id = claim.id
  2100. join client on claim.client_id = client.id
  2101. left join pro on claim.pro_id = pro.id
  2102. left join client_primary_coverage cpc on client.effective_client_primary_coverage_id = cpc.id
  2103. left join payer on cpc.commercial_payer_id = payer.id
  2104. WHERE
  2105. " . implode(' AND ', $conditions) . "
  2106. ORDER BY {$orderBy} OFFSET {$offset} LIMIT {$perPage}
  2107. ";
  2108. // dd($query);
  2109. $rows = DB::select($query);
  2110. $paginator = new LengthAwarePaginator($rows, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  2111. $perPage = $request->input('per_page') ?: $defaultPageSize;
  2112. $paginator->setPath(route('practice-management.claims-report'));
  2113. return view('app.practice-management.claims-report', compact('rows', 'paginator', 'perPage'));
  2114. }
  2115. public function problemsReport(Request $request) {
  2116. $performer = $this->performer();
  2117. $conditions = [];
  2118. // default sort
  2119. if(!$request->input('sort_by')) {
  2120. $orderBy = "p.created_at DESC NULLS LAST";
  2121. }
  2122. else {
  2123. $sortBy = json_decode($request->input('sort_by'));
  2124. $orderByClause = [];
  2125. foreach ($sortBy as $sortCriteria) {
  2126. $orderByClause[] = "{$sortCriteria->key} {$sortCriteria->order} NULLS LAST";
  2127. }
  2128. $orderBy = implode(', ', $orderByClause);
  2129. }
  2130. // filters from the UI
  2131. if(trim($request->input('f_client'))) {
  2132. $v = trim($request->input('f_client'));
  2133. $v = Client::where('uid', $v)->first();
  2134. if($v) {
  2135. $conditions[] = "(c.id = {$v->id})";
  2136. }
  2137. }
  2138. if(trim($request->input('f_mcp'))) {
  2139. $v = trim($request->input('f_mcp'));
  2140. $v = Pro::where('uid', $v)->first();
  2141. if($v) {
  2142. $conditions[] = "(c.mcp_pro_id = {$v->id})";
  2143. }
  2144. }
  2145. if(trim($request->input('f_problem'))) {
  2146. $v = strtolower(trim($request->input('f_problem')));
  2147. if($v) {
  2148. $conditions[] = "(((p.data)::json->>'name')::text ILIKE '%{$v}%')";
  2149. }
  2150. }
  2151. if(trim($request->input('f_icd'))) {
  2152. $v = strtolower(trim($request->input('f_icd')));
  2153. if($v) {
  2154. $conditions[] = "(((p.data)::json->>'icd')::text ILIKE '{$v}%')";
  2155. }
  2156. }
  2157. if(trim($request->input('f_lr_date_op')) && trim($request->input('f_lr_date')) !== '') {
  2158. $o = trim($request->input('f_lr_date_op'));
  2159. $v = trim($request->input('f_lr_date'));
  2160. $conditions[] = "(p.last_child_review_effective_date {$o} '{$v}')";
  2161. }
  2162. if(trim($request->input('f_lr_by'))) {
  2163. $v = trim($request->input('f_lr_by'));
  2164. if($v) {
  2165. $conditions[] = "(p.last_child_review_creator_pro_uid = '{$v}')";
  2166. }
  2167. }
  2168. if(trim($request->input('f_lp_date_op')) && trim($request->input('f_lp_date')) !== '') {
  2169. $o = trim($request->input('f_lp_date_op'));
  2170. $v = trim($request->input('f_lp_date'));
  2171. $conditions[] = "(p.last_child_plan_effective_date {$o} '{$v}')";
  2172. }
  2173. if(trim($request->input('f_lp_by'))) {
  2174. $v = trim($request->input('f_lp_by'));
  2175. if($v) {
  2176. $conditions[] = "(p.last_child_plan_creator_pro_uid = '{$v}')";
  2177. }
  2178. }
  2179. $defaultPageSize = 25;
  2180. $page = $request->input('page') ?: 1;
  2181. $perPage = $request->input('per_page') ?: $defaultPageSize;
  2182. $offset = ($page - 1) * $perPage;
  2183. $countQuery = "
  2184. SELECT COUNT(*)
  2185. FROM point p
  2186. join client c on p.client_id = c.id
  2187. join pro mcp on c.mcp_pro_id = mcp.id
  2188. left join client_primary_coverage cpc on c.effective_client_primary_coverage_id = cpc.id
  2189. left join payer on cpc.commercial_payer_id = payer.id
  2190. WHERE p.category = 'PROBLEM'
  2191. AND p.is_removed_due_to_entry_error IS NOT TRUE " .
  2192. (count($conditions) ? ' AND ' . implode(' AND ', $conditions) : '');
  2193. $countResult = DB::select($countQuery);
  2194. $total = $countResult[0]->count;
  2195. $query = "
  2196. SELECT p.uid as point_uid,
  2197. (c.name_first || ' ' || c.name_last) as client_name,
  2198. c.uid as client_uid,
  2199. c.dob,
  2200. c.age_in_years,
  2201. c.is_enrolled_in_rm,
  2202. c.mailing_address_state,
  2203. (mcp.name_first || ' ' || mcp.name_last) as mcp_name,
  2204. (CASE
  2205. WHEN cpc.plan_type LIKE 'COMMERCIAL' THEN payer.name
  2206. ELSE cpc.plan_type
  2207. END) as payer_name,
  2208. row_to_json(p.*) as point,
  2209. ((p.data)::json->>'name')::text as problem,
  2210. ((p.data)::json->>'icd')::text as icd,
  2211. p.last_child_review_effective_date as last_review_date,
  2212. (p.last_child_review_creator_pro_first_name || ' ' || p.last_child_review_creator_pro_last_name) as last_review_by,
  2213. ((last_review.data)::json->>'value')::text as last_review_content,
  2214. p.last_child_plan_effective_date as last_plan_date,
  2215. (p.last_child_plan_creator_pro_first_name || ' ' || p.last_child_plan_creator_pro_last_name) as last_plan_by,
  2216. ((last_plan.data)::json->>'value')::text as last_plan_content
  2217. FROM point p
  2218. join client c on p.client_id = c.id
  2219. join pro mcp on c.mcp_pro_id = mcp.id
  2220. left join client_primary_coverage cpc on c.effective_client_primary_coverage_id = cpc.id
  2221. left join payer on cpc.commercial_payer_id = payer.id
  2222. left join point last_review on p.last_child_review_point_id = last_review.id
  2223. left join point last_plan on p.last_child_plan_point_id = last_plan.id
  2224. WHERE p.category = 'PROBLEM'
  2225. AND p.is_removed_due_to_entry_error IS NOT TRUE " .
  2226. (count($conditions) ? ' AND ' . implode(' AND ', $conditions) : '') . "
  2227. ORDER BY {$orderBy} OFFSET {$offset} LIMIT {$perPage}";
  2228. // dd($query);
  2229. $rows = DB::select($query);
  2230. $paginator = new LengthAwarePaginator($rows, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  2231. $perPage = $request->input('per_page') ?: $defaultPageSize;
  2232. $paginator->setPath(route('practice-management.problems-report'));
  2233. return view('app.practice-management.problems-report', compact('rows', 'paginator', 'perPage'));
  2234. }
  2235. public function remoteMonitoringMCP(Request $request) {
  2236. return $this->rpmMatrixByProType($request, 'mcp');
  2237. }
  2238. public function remoteMonitoringRMM(Request $request) {
  2239. return $this->rpmMatrixByProType($request, 'rmm');
  2240. }
  2241. public function remoteMonitoringRME(Request $request) {
  2242. return $this->rpmMatrixByProType($request, 'rme');
  2243. }
  2244. public function remoteMonitoring_RowMCP(Request $request) {
  2245. return $this->remoteMonitoring_RowByProType($request, 'mcp');
  2246. }
  2247. public function remoteMonitoring_RowRMM(Request $request) {
  2248. return $this->remoteMonitoring_RowByProType($request, 'rmm');
  2249. }
  2250. public function remoteMonitoring_RowRME(Request $request) {
  2251. return $this->remoteMonitoring_RowByProType($request, 'rme');
  2252. }
  2253. public function remoteMonitoring_RowADMIN(Request $request) {
  2254. return $this->remoteMonitoring_RowForAdmin($request);
  2255. }
  2256. public function rpm_work_matrix(Request $request) {
  2257. // get the patient having most recent unstamped measurement
  2258. $performer = $this->performer();
  2259. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  2260. $careMonthStart = date($ym . '-01');
  2261. $patient = null;
  2262. $careMonth = null;
  2263. if($request->input('patientUid') && $request->input('careMonthUid')) {
  2264. $patient = Client::where('uid', $request->input('patientUid'))->first();
  2265. $careMonth = CareMonth::where('uid', $request->input('careMonthUid'))->first();
  2266. }
  2267. if(!$patient && !$careMonth) {
  2268. $query = "
  2269. SELECT client.name_first, client.name_last,
  2270. (client.name_first || ' ' || client.name_last) as client_name,
  2271. client.uid as client_uid,
  2272. client.dob,
  2273. care_month.is_client_enrolled_in_rm,
  2274. client.most_recent_completed_mcp_note_date,
  2275. care_month.uid as care_month_uid,
  2276. care_month.id as care_month_id,
  2277. care_month.start_date,
  2278. care_month.rm_total_time_in_seconds_by_mcp,
  2279. care_month.number_of_days_with_remote_measurements,
  2280. care_month.rm_num_measurements_not_stamped_by_mcp,
  2281. care_month.rm_num_measurements_not_stamped_by_rmm,
  2282. client.mcp_pro_id,
  2283. client.default_na_pro_id,
  2284. client.rmm_pro_id,
  2285. client.rme_pro_id,
  2286. client.cell_number,
  2287. client.most_recent_cellular_bp_dbp_mm_hg,
  2288. client.most_recent_cellular_bp_sbp_mm_hg,
  2289. client.most_recent_cellular_bp_measurement_at,
  2290. client.most_recent_cellular_weight_value,
  2291. client.most_recent_cellular_weight_measurement_at,
  2292. GREATEST(client.most_recent_cellular_bp_measurement_at, client.most_recent_cellular_weight_measurement_at) as latest_measurement_at
  2293. FROM care_month join client on care_month.client_id = client.id
  2294. WHERE
  2295. (
  2296. (care_month.mcp_pro_id = {$performer->pro->id} AND care_month.rm_num_measurements_not_stamped_by_mcp > 0) OR
  2297. (care_month.rmm_pro_id = {$performer->pro->id} AND care_month.rm_num_measurements_not_stamped_by_rmm > 0)
  2298. )
  2299. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  2300. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  2301. ORDER BY latest_measurement_at DESC
  2302. LIMIT 1
  2303. ";
  2304. $patients = DB::select($query);
  2305. if (count($patients)) {
  2306. $patient = Client::where('uid', $patients[0]->client_uid)->first();
  2307. $careMonth = CareMonth::where('uid', $patients[0]->care_month_uid)->first();
  2308. }
  2309. }
  2310. return view('app.practice-management.rpm_work_matrix', compact('patient', 'careMonth'));
  2311. }
  2312. public function remoteMonitoringCount(Request $request) {
  2313. $performer = $this->performer();
  2314. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  2315. $careMonthStart = date($ym . '-01');
  2316. $rc = $request->input('rc') ?: 1;
  2317. $rc2 = $request->input('rc2') ?: 2;
  2318. $conditions = $this->rpmConditions($performer, $rc, $rc2);
  2319. $count = DB::select(
  2320. DB::raw(
  2321. "
  2322. SELECT count(*)
  2323. FROM care_month join client on care_month.client_id = client.id
  2324. WHERE
  2325. client.mcp_pro_id = {$performer->pro->id}
  2326. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  2327. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  2328. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '')
  2329. )
  2330. );
  2331. return $count[0]->count;
  2332. }
  2333. public function remoteMonitoringAdmin(Request $request) {
  2334. $performer = $this->performer();
  2335. // abort_if($performer->pro->pro_type !== 'ADMIN' && !$performer->pro->can_view_rm_matrix, 403);
  2336. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  2337. $careMonthStart = date($ym . '-01');
  2338. $rc = $request->input('rc') ?: 1;
  2339. $rc2 = $request->input('rc2') ?: 2;
  2340. $conditions = [];// $this->rpmConditions($performer, $rc, $rc2);
  2341. $sortBy = $request->input('sort_by') ?: 'name_first';
  2342. $sortDir = $request->input('sort_dir') ?: 'ASC';
  2343. $orderBy = "ORDER BY $sortBy $sortDir NULLS LAST";
  2344. $query = "
  2345. SELECT client.name_first, client.name_last,
  2346. (client.name_first || ' ' || client.name_last) as client_name,
  2347. (mcp_pro.name_first || ' ' || mcp_pro.name_last) as mcp_pro_name,
  2348. (rmm_pro.name_first || ' ' || rmm_pro.name_last) as rmm_pro_name,
  2349. client.uid as client_uid,
  2350. client.chart_number,
  2351. client.dob,
  2352. care_month.is_client_enrolled_in_rm,
  2353. client.most_recent_completed_mcp_note_date,
  2354. client.most_recent_completed_mcp_note_id,
  2355. mrmnote.effective_dateest::date as most_recent_completed_mcp_note_date_cm,
  2356. mrmnote.id as most_recent_completed_mcp_note_id_cm,
  2357. mrmnote.uid as most_recent_completed_mcp_note_uid_cm,
  2358. client.cell_number,
  2359. client.is_assigned_cellular_bp_device,
  2360. client.is_assigned_cellular_weight_scale_device,
  2361. care_month.uid as care_month_uid,
  2362. care_month.id as care_month_id,
  2363. care_month.start_date,
  2364. care_month.rm_total_time_in_seconds_by_mcp,
  2365. care_month.rm_total_time_in_seconds_by_rmm_pro,
  2366. care_month.number_of_days_with_remote_measurements,
  2367. care_month.has_anyone_interacted_with_client_about_rm,
  2368. care_month.has_mcp_interacted_with_client_about_rm,
  2369. care_month.rm_num_measurements_not_stamped_by_mcp,
  2370. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  2371. care_month.rm_num_measurements_not_stamped_by_rmm,
  2372. care_month.rm_num_measurements_not_stamped_by_rme,
  2373. care_month.mcp_pro_id as care_month_mcp_pro_id,
  2374. care_month.rmm_pro_id as care_month_rmm_pro_id,
  2375. client.mcp_pro_id,
  2376. client.default_na_pro_id,
  2377. client.rmm_pro_id,
  2378. client.rme_pro_id,
  2379. client.cell_number,
  2380. care_month.most_recent_cellular_bp_dbp_mm_hg,
  2381. care_month.most_recent_cellular_bp_sbp_mm_hg,
  2382. care_month.most_recent_cellular_bp_measurement_at,
  2383. care_month.most_recent_cellular_weight_value,
  2384. care_month.most_recent_cellular_weight_measurement_at
  2385. 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
  2386. left join note mrmnote on mrmnote.id = (
  2387. select max(n.id) from note n
  2388. where
  2389. n.client_id = client.id AND
  2390. n.is_cancelled = FALSE AND
  2391. (n.is_signed_by_hcp IS NOT NULL AND n.is_signed_by_hcp = TRUE) AND
  2392. n.effective_dateest::date >= care_month.start_date::date AND
  2393. n.effective_dateest::date < (care_month.start_date::date + INTERVAL '1 month')
  2394. )
  2395. left join pro mcp_pro on care_month.mcp_pro_id = mcp_pro.id
  2396. left join pro rmm_pro on care_month.rmm_pro_id = rmm_pro.id
  2397. WHERE
  2398. EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  2399. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  2400. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '') . "
  2401. $orderBy
  2402. ";
  2403. $patients = DB::select($query);
  2404. $timestamp = strtotime(date('Y-m-d'));
  2405. $daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
  2406. return view('app.practice-management.remote-monitoring-admin', compact('patients', 'daysRemaining', 'careMonthStart'));
  2407. }
  2408. public function remoteMonitoringAdminCount(Request $request) {
  2409. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  2410. $careMonthStart = date($ym . '-01');
  2411. $rc = $request->input('rc') ?: 1;
  2412. $rc2 = $request->input('rc2') ?: 2;
  2413. $conditions = $this->rpmConditionsAdmin($this->performer(), $rc, $rc2);
  2414. $count = DB::select(
  2415. DB::raw(
  2416. "
  2417. SELECT count(*)
  2418. FROM care_month join client on care_month.client_id = client.id
  2419. WHERE
  2420. client.shadow_pro_id is null AND care_month.is_client_enrolled_in_rm IS TRUE
  2421. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  2422. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  2423. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '')
  2424. )
  2425. );
  2426. return $count[0]->count;
  2427. }
  2428. private function rpmConditions($performer, $rc, $rc2) {
  2429. $conditions = [];
  2430. $c_isMCP = "client.mcp_pro_id = {$performer->pro->id}";
  2431. $c_enrolledInRPM = "care_month.is_client_enrolled_in_rm IS TRUE";
  2432. $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";
  2433. $c_lastVisitBefore90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) > 90";
  2434. $c_lastVisitWithin90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) <= 90";
  2435. $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)";
  2436. $c_spokenToThisMonth = "care_month.has_anyone_interacted_with_client_about_rm_outside_note = TRUE";
  2437. $c_hasUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp > 0";
  2438. $c_hasNoUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp = 0";
  2439. $c_lt16MeasurementDays = "care_month.number_of_days_with_remote_measurements < 16";
  2440. $c_gte16MeasurementDays = "care_month.number_of_days_with_remote_measurements >= 16";
  2441. $c_subscribedToSMS = "client.send_sms_on_bdt_measurement = TRUE";
  2442. $c_deviceUsed = "(client.most_recent_cellular_bp_measurement_at IS NOT NULL OR most_recent_cellular_weight_measurement_at IS NOT NULL)";
  2443. $c_lt20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp < 1200";
  2444. $c_gte20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp >= 1200";
  2445. switch ($rc) {
  2446. case 1:
  2447. $conditions = [$c_isMCP];
  2448. break;
  2449. case 2:
  2450. $conditions = [$c_isMCP, $c_enrolledInRPM];
  2451. break;
  2452. case 3:
  2453. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice];
  2454. break;
  2455. case 4:
  2456. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, ($rc2 == 1 ? $c_lastVisitBefore90Days : $c_lastVisitWithin90Days)];
  2457. break;
  2458. case 5:
  2459. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, ($rc2 == 1 ? $c_notSpokenToThisMonth : $c_spokenToThisMonth)];
  2460. break;
  2461. case 6:
  2462. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_hasUnstamped : $c_hasNoUnstamped)];
  2463. break;
  2464. case 7:
  2465. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_lt16MeasurementDays : $c_gte16MeasurementDays)];
  2466. break;
  2467. case 10:
  2468. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, $c_gte16MeasurementDays, ($rc2 == 1 ? $c_lt20BillingMinutes : $c_gte20BillingMinutes)];
  2469. break;
  2470. case 8:
  2471. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_subscribedToSMS];
  2472. break;
  2473. case 9:
  2474. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_deviceUsed];
  2475. break;
  2476. }
  2477. return $conditions;
  2478. }
  2479. private function rpmConditionsAdmin($performer, $rc, $rc2) {
  2480. $conditions = [];
  2481. $c_enrolledInRPM = "care_month.is_client_enrolled_in_rm IS TRUE";
  2482. $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";
  2483. $c_lastVisitBefore90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) > 90";
  2484. $c_lastVisitWithin90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) <= 90";
  2485. $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)";
  2486. $c_spokenToThisMonth = "care_month.has_anyone_interacted_with_client_about_rm_outside_note = TRUE";
  2487. $c_hasUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp > 0";
  2488. $c_hasNoUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp = 0";
  2489. $c_lt16MeasurementDays = "care_month.number_of_days_with_remote_measurements < 16";
  2490. $c_gte16MeasurementDays = "care_month.number_of_days_with_remote_measurements >= 16";
  2491. $c_subscribedToSMS = "client.send_sms_on_bdt_measurement = TRUE";
  2492. $c_deviceUsed = "(client.most_recent_cellular_bp_measurement_at IS NOT NULL OR client.most_recent_cellular_weight_measurement_at IS NOT NULL)";
  2493. $c_lt20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp < 1200";
  2494. $c_gte20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp >= 1200";
  2495. switch ($rc) {
  2496. case 2:
  2497. $conditions = [$c_enrolledInRPM];
  2498. break;
  2499. case 3:
  2500. $conditions = [$c_enrolledInRPM, $c_hasDevice];
  2501. break;
  2502. case 4:
  2503. $conditions = [$c_enrolledInRPM, $c_hasDevice, ($rc2 == 1 ? $c_lastVisitBefore90Days : $c_lastVisitWithin90Days)];
  2504. break;
  2505. case 5:
  2506. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, ($rc2 == 1 ? $c_notSpokenToThisMonth : $c_spokenToThisMonth)];
  2507. break;
  2508. case 6:
  2509. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_hasUnstamped : $c_hasNoUnstamped)];
  2510. break;
  2511. case 7:
  2512. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_lt16MeasurementDays : $c_gte16MeasurementDays)];
  2513. break;
  2514. case 10:
  2515. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, $c_gte16MeasurementDays, ($rc2 == 1 ? $c_lt20BillingMinutes : $c_gte20BillingMinutes)];
  2516. break;
  2517. case 8:
  2518. $conditions = [$c_enrolledInRPM, $c_subscribedToSMS];
  2519. break;
  2520. case 9:
  2521. $conditions = [$c_enrolledInRPM, $c_deviceUsed];
  2522. break;
  2523. }
  2524. return $conditions;
  2525. }
  2526. public function remoteMonitoringMeasurements(Request $request, CareMonth $careMonth) {
  2527. $performer = $this->performer();
  2528. $measurements = DB::select(
  2529. DB::raw(
  2530. "
  2531. SELECT measurement.label,
  2532. measurement.ts,
  2533. measurement.effective_date,
  2534. measurement.sbp_mm_hg,
  2535. measurement.dbp_mm_hg,
  2536. measurement.value_pulse,
  2537. measurement.value_irregular,
  2538. measurement.numeric_value,
  2539. measurement.value,
  2540. measurement.uid,
  2541. client.name_first,
  2542. client.name_last,
  2543. client.mcp_pro_id,
  2544. client.default_na_pro_id,
  2545. client.rmm_pro_id,
  2546. client.rme_pro_id
  2547. FROM measurement RIGHT JOIN client on measurement.client_id = client.id
  2548. WHERE
  2549. client.id = {$careMonth->client_id}
  2550. AND measurement.label IS NOT NULL
  2551. AND measurement.label NOT IN ('SBP', 'DBP')
  2552. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  2553. AND measurement.is_removed IS FALSE
  2554. AND measurement.client_bdt_measurement_id IS NOT NULL
  2555. AND measurement.care_month_id = {$careMonth->id}
  2556. AND (
  2557. (client.mcp_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_mcp IS FALSE)
  2558. OR (client.rmm_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_rmm IS FALSE)
  2559. OR (client.rme_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_rme IS FALSE)
  2560. OR (client.default_na_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_non_hcp IS FALSE)
  2561. )
  2562. ORDER BY ts DESC
  2563. "
  2564. )
  2565. );
  2566. return view('app.practice-management.remote-monitoring-measurements', compact('careMonth', 'measurements'));
  2567. }
  2568. public function billMatrix(Request $request)
  2569. {
  2570. $bClients = [];
  2571. $bHCPPros = [];
  2572. $bNAPros = [];
  2573. $filters = [];
  2574. $filters['client'] = $request->input('client');
  2575. $filters['service'] = $request->input('service');
  2576. $filters['hcp'] = $request->input('hcp');
  2577. $filters['hcp_paid'] = $request->input('hcp_paid');
  2578. $filters['expected_op'] = $request->input('expected_op');
  2579. $filters['expected_value'] = $request->input('expected_value');
  2580. $filters['paid_op'] = $request->input('paid_op');
  2581. $filters['paid_value'] = $request->input('paid_value');
  2582. $filters['bal_post_date_op'] = $request->input('bal_post_date_op');
  2583. $filters['bal_post_date_value'] = $request->input('bal_post_date_value');
  2584. $filters['hcp_sign'] = $request->input('hcp_sign');
  2585. $filters['verified'] = $request->input('verified');
  2586. $filters['cancelled'] = $request->input('cancelled');
  2587. $bills = Bill::orderBy('effective_date')->paginate();
  2588. return view('app.practice-management.bill-matrix', compact('bills', 'bClients', 'bHCPPros', 'filters'));
  2589. }
  2590. public function medicarePartBClaims(Request $request)
  2591. {
  2592. $medicarePartBOnly = $request->get("medicare_part_b");
  2593. $allClaims = Claim::where('was_submitted', false)->orWhere('was_submitted', null)->orderBy('created_at', 'desc')->get();
  2594. //Only medicare claims
  2595. $claims = [];
  2596. foreach ($allClaims as $claim) {
  2597. if ($claim->client != null && $claim->client->getPrimaryCoverageStatus() == 'YES' && !$claim->edi) {
  2598. $claims[] = $claim;
  2599. }
  2600. }
  2601. $claimEDIs = ClaimEDI::all();
  2602. return view('app.practice-management.medicare-partb-claims', compact('claims', 'claimEDIs'));
  2603. }
  2604. // Generate PDF
  2605. public function downloadClaims()
  2606. {
  2607. $claims = Claim::where('was_submitted', false)->orWhere('was_submitted', null)->orderBy('created_at', 'desc')->limit(100)->get();
  2608. view()->share('claims', $claims);
  2609. $pdf = PDF::loadView('app.practice-management.claims-pdf', $claims);
  2610. return $pdf->download('pdf_file.pdf');
  2611. }
  2612. public function tickets(Request $request, $proUid = null)
  2613. {
  2614. $tickets = Ticket::orderBy('created_at', 'desc')->paginate();
  2615. return view('app.practice-management.tickets', compact('tickets'));
  2616. }
  2617. public function supplyOrders(Request $request)
  2618. {
  2619. // counts
  2620. $counts = $this->getSupplyOrderCounts();
  2621. // so clients
  2622. $soClientIDs = DB::table('supply_order')->select('client_id')->distinct()->get()->toArray();
  2623. $soClientIDs = array_map(function ($_x) {
  2624. return $_x->client_id;
  2625. }, $soClientIDs);
  2626. $soClients = Client::whereIn('id', $soClientIDs)->get();
  2627. // so products
  2628. $soProductIDs = DB::table('supply_order')->select('product_id')->distinct()->get()->toArray();
  2629. $soProductIDs = array_map(function ($_x) {
  2630. return $_x->product_id;
  2631. }, $soProductIDs);
  2632. $soProducts = Product::whereIn('id', $soProductIDs)->get();
  2633. $filters = [];
  2634. $filters['client'] = $request->input('client');
  2635. $filters['product'] = $request->input('product');
  2636. $filters['reason'] = $request->input('reason');
  2637. $filters['cu_memo'] = $request->input('cu_memo');
  2638. $filters['pro_sign'] = $request->input('pro_sign');
  2639. $filters['client_sign'] = $request->input('client_sign');
  2640. $filters['shipment'] = $request->input('shipment');
  2641. $filters['lot_number'] = $request->input('lot_number');
  2642. $filters['imei'] = $request->input('imei');
  2643. $filters['cancelled'] = $request->input('cancelled');
  2644. $supplyOrders = SupplyOrder::where('id', '>', 0);
  2645. // apply filters
  2646. if ($filters['client']) $supplyOrders->where('client_id', $filters['client']);
  2647. if ($filters['product']) $supplyOrders->where('product_id', $filters['product']);
  2648. if ($filters['reason']) $supplyOrders->where('reason', 'ILIKE', '%' . $filters['reason'] . '%');
  2649. if ($filters['cu_memo']) $supplyOrders->where('cu_memo', 'ILIKE', '%' . $filters['cu_memo'] . '%');
  2650. if ($filters['pro_sign']) $supplyOrders->where('is_signed_by_pro', ($filters['pro_sign'] === 'signed'));
  2651. if ($filters['client_sign']) {
  2652. if ($filters['client_sign'] === 'signed')
  2653. $supplyOrders->where('is_signed_by_client', true);
  2654. elseif ($filters['client_sign'] === 'waived')
  2655. $supplyOrders->where('is_client_signature_waived', true);
  2656. else
  2657. $supplyOrders->where('is_client_signature_waived', false)->where('is_signed_by_client', false);
  2658. }
  2659. if ($filters['shipment']) {
  2660. if ($filters['shipment'] === 'not_cleared_for_shipment')
  2661. $supplyOrders->whereNull('shipment_id')->where('is_cleared_for_shipment', false);
  2662. elseif ($filters['shipment'] === 'cleared_for_shipment')
  2663. $supplyOrders->whereNull('shipment_id')->where('is_cleared_for_shipment', true);
  2664. else
  2665. $supplyOrders
  2666. ->whereNotNull('shipment_id')
  2667. ->whereRaw('(SELECT status FROM shipment WHERE id = shipment_id LIMIT 1) = ?', [$filters['shipment']]);
  2668. }
  2669. if ($filters['lot_number']) $supplyOrders->where('lot_number', 'ILIKE', '%' . $filters['lot_number'] . '%');
  2670. if ($filters['imei']) $supplyOrders->where('imei', 'ILIKE', '%' . $filters['imei'] . '%');
  2671. if ($filters['cancelled']) $supplyOrders->where('is_cancelled', ($filters['cancelled'] === 'cancelled'));
  2672. $supplyOrders = $supplyOrders->orderBy('created_at', 'desc')->paginate();
  2673. return view('app.practice-management.supply-orders',
  2674. compact('supplyOrders', 'filters',
  2675. 'soClients', 'soProducts', 'counts'
  2676. )
  2677. );
  2678. }
  2679. public function shipments(Request $request, $filter = null)
  2680. {
  2681. // counts
  2682. $counts = $this->getShipmentCounts();
  2683. // so clients
  2684. $shClientIDs = DB::table('shipment')->select('client_id')->distinct()->get()->toArray();
  2685. $shClientIDs = array_map(function ($_x) {
  2686. return $_x->client_id;
  2687. }, $shClientIDs);
  2688. $shClients = Client::whereIn('id', $shClientIDs)->get();
  2689. $shipments = Shipment::where('id', '>', 0);
  2690. $filters = [];
  2691. $filters['client'] = $request->input('client');
  2692. $filters['courier'] = $request->input('courier');
  2693. $filters['tracking_num'] = $request->input('tracking_num');
  2694. $filters['label'] = $request->input('label');
  2695. $filters['status'] = $request->input('status');
  2696. $filters['cancelled'] = $request->input('cancelled');
  2697. if ($filters['client']) $shipments->where('client_id', $filters['client']);
  2698. if ($filters['courier']) $shipments->where('courier', 'ILIKE', '%' . $filters['courier'] . '%');
  2699. if ($filters['tracking_num']) $shipments->where('tracking_number', 'ILIKE', '%' . $filters['tracking_num'] . '%');
  2700. if ($filters['label']) {
  2701. if ($filters['label'] === 'yes')
  2702. $shipments->whereNotNull('label_system_file_id');
  2703. else
  2704. $shipments->whereNull('label_system_file_id');
  2705. }
  2706. if ($filters['status']) $shipments->where('status', $filters['status']);
  2707. if ($filters['cancelled']) $shipments->where('is_cancelled', ($filters['cancelled'] === 'cancelled'));
  2708. $shipments = $shipments->orderBy('created_at', 'desc')->paginate();
  2709. return view('app.practice-management.shipments', compact('shipments', 'filters', 'shClients', 'counts'));
  2710. }
  2711. public function cellularMeasurements(Request $request)
  2712. {
  2713. $measurements = Measurement::orderBy('ts', 'desc')->whereNotNull('ts')->paginate();
  2714. return view('app.practice-management.cellular-measurements', compact('measurements'));
  2715. }
  2716. // v2 supply-orders & shipments management (wh)
  2717. public function supplyOrdersReadyToShip(Request $request)
  2718. {
  2719. $counts = $this->getSupplyOrderCounts();
  2720. $supplyOrders = SupplyOrder
  2721. ::where('is_cleared_for_shipment', true)
  2722. ->where('is_cancelled', false)
  2723. ->whereNull('shipment_id')
  2724. ->join('client', 'client.id', '=', 'supply_order.client_id')
  2725. ->orderBy('client.name_last', 'ASC')
  2726. ->orderBy('client.name_first', 'ASC')
  2727. ->orderBy('supply_order.client_id', 'ASC')
  2728. ->orderBy('supply_order.mailing_address_full', 'ASC')
  2729. ->orderBy('supply_order.created_at', 'ASC')
  2730. ->select('supply_order.*')
  2731. ->paginate();
  2732. return view('app.practice-management.supply-orders-ready-to-ship', compact('supplyOrders', 'counts'));
  2733. }
  2734. public function supplyOrdersShipmentUnderway(Request $request)
  2735. {
  2736. $counts = $this->getSupplyOrderCounts();
  2737. $supplyOrders = SupplyOrder
  2738. ::where('is_cancelled', false)
  2739. ->whereNotNull('shipment_id')
  2740. ->orderBy('client_id', 'ASC')
  2741. ->orderBy('mailing_address_full', 'ASC')
  2742. ->orderBy('created_at', 'ASC')
  2743. ->paginate();
  2744. return view('app.practice-management.supply-orders-shipment-underway', compact('supplyOrders', 'counts'));
  2745. }
  2746. public function supplyOrdersHanging(Request $request)
  2747. {
  2748. $counts = $this->getSupplyOrderCounts();
  2749. $supplyOrders = SupplyOrder
  2750. ::select('supply_order.*')
  2751. ->leftJoin('shipment', function($join) {
  2752. $join->on('supply_order.shipment_id', '=', 'shipment.id');
  2753. })
  2754. ->where('shipment.status', 'CANCELLED')
  2755. ->where('supply_order.is_cancelled', false)
  2756. ->orderBy('supply_order.client_id', 'ASC')
  2757. ->orderBy('supply_order.mailing_address_full', 'ASC')
  2758. ->orderBy('supply_order.created_at', 'ASC')
  2759. ->paginate();
  2760. return view('app.practice-management.supply-orders-hanging', compact('supplyOrders', 'counts'));
  2761. }
  2762. public function supplyOrdersCancelledButUnacknowledged(Request $request)
  2763. {
  2764. $supplyOrders = SupplyOrder::where('signed_by_pro_id', $this->performer()->pro->id)
  2765. ->where('is_cancelled', true)
  2766. ->where('is_cancellation_acknowledged', false)
  2767. ->orderBy('created_at', 'desc')
  2768. ->paginate();
  2769. return view('app.practice-management.supply-orders-cancelled-but-unacknowledged', compact('supplyOrders'));
  2770. }
  2771. public function supplyOrdersUnsigned(Request $request)
  2772. {
  2773. $supplyOrders = SupplyOrder
  2774. ::where('is_cancelled', false)
  2775. ->where('is_signed_by_pro', false)
  2776. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$this->performer()->pro->id])
  2777. ->orderBy('created_at', 'desc')
  2778. ->paginate();
  2779. return view('app.practice-management.supply-orders-unsigned', compact('supplyOrders'));
  2780. }
  2781. private function getSupplyOrderCounts()
  2782. {
  2783. return [
  2784. "supplyOrders" => SupplyOrder::count(),
  2785. "supplyOrdersReadyToShip" => SupplyOrder
  2786. ::where('is_cleared_for_shipment', true)
  2787. ->where('is_cancelled', false)
  2788. ->whereNull('shipment_id')->count(),
  2789. "supplyOrdersShipmentUnderway" => SupplyOrder
  2790. ::where('is_cancelled', false)
  2791. ->whereNotNull('shipment_id')->count(),
  2792. "supplyOrdersHanging" => SupplyOrder
  2793. ::leftJoin('shipment', function($join) {
  2794. $join->on('supply_order.shipment_id', '=', 'shipment.id');
  2795. })
  2796. ->where('shipment.status', 'CANCELLED')
  2797. ->where('supply_order.is_cancelled', false)
  2798. ->count(),
  2799. ];
  2800. }
  2801. public function shipmentsReadyToPrint(Request $request)
  2802. {
  2803. $counts = $this->getShipmentCounts();
  2804. $shipments = Shipment
  2805. ::where('is_cancelled', false)
  2806. ->where('status', 'CREATED')
  2807. ->orderBy('created_at', 'ASC')
  2808. ->paginate();
  2809. return view('app.practice-management.shipments-ready-to-print', compact('shipments', 'counts'));
  2810. }
  2811. public function shipmentsShipmentUnderway(Request $request)
  2812. {
  2813. $counts = $this->getShipmentCounts();
  2814. $shipments = Shipment
  2815. ::where('is_cancelled', false)
  2816. ->where('status', 'PRINTED')
  2817. ->orderBy('created_at', 'ASC')
  2818. ->paginate();
  2819. return view('app.practice-management.shipments-waiting-for-picker', compact('shipments', 'counts'));
  2820. }
  2821. private function getShipmentCounts()
  2822. {
  2823. return [
  2824. "shipments" => Shipment::count(),
  2825. "shipmentsReadyToPrint" => Shipment
  2826. ::where('is_cancelled', false)
  2827. ->where('status', 'CREATED')
  2828. ->count(),
  2829. "shipmentsWaitingForPicker" => Shipment
  2830. ::where('is_cancelled', false)
  2831. ->where('status', 'PRINTED')
  2832. ->count()
  2833. ];
  2834. }
  2835. public function shipment(Request $request, Shipment $shipment)
  2836. {
  2837. return view('app.practice-management.shipment', compact('shipment'));
  2838. }
  2839. public function shipmentsMultiPrint(Request $request, $ids)
  2840. {
  2841. $ids = array_map(function ($_x) {
  2842. return intval($_x);
  2843. }, explode("|", $ids));
  2844. $shipments = Shipment::whereIn('id', $ids)->get();
  2845. return view('app.practice-management.shipments-multi-print', compact('shipments'));
  2846. }
  2847. public function patientClaimSummary(Request $request, $proUid = null)
  2848. {
  2849. $notesTotal = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE"))[0]->count;
  2850. $notesTotalWithBillingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE AND is_bill_closed IS TRUE"))[0]->count;
  2851. $notesTotalWithClaimingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE AND is_claim_closed IS TRUE"))[0]->count;
  2852. $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;
  2853. $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;
  2854. $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;
  2855. $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;
  2856. $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;
  2857. $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;
  2858. $performerPro = $this->performer->pro;
  2859. $allPros = [];
  2860. if ($performerPro->pro_type == 'ADMIN') {
  2861. $allPros = Pro::all();
  2862. } else {
  2863. $allPros = [$performerPro];
  2864. }
  2865. //Patient | MCP | # Notes Total | # Notes without Billing Closed | # Notes without Claiming Closed
  2866. $patientsQuery = Client::where('is_dummy', '=', false)
  2867. ->whereNull('shadow_pro_id')
  2868. ->select('id', 'uid', 'name_first', 'name_last', 'mcp_pro_id', 'is_part_b_primary', 'medicare_advantage_plan',
  2869. DB::raw("(SELECT name_first||' '||name_last FROM pro where pro.id = client.mcp_pro_id) as mcp"),
  2870. DB::raw("(SELECT uid FROM pro where pro.id = mcp_pro_id) as mcp_pro_uid"),
  2871. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id) as notes_total"),
  2872. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id AND is_bill_closed IS NOT true) as notes_without_billing_closed"),
  2873. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id AND is_claim_closed IS NOT true) as notes_without_claiming_closed")
  2874. )->orderBy('is_part_b_primary', 'asc')->orderBy('notes_without_claiming_closed', 'desc');
  2875. if ($proUid) {
  2876. $mcpPro = Pro::where('uid', $proUid)->first();
  2877. if ($mcpPro) {
  2878. $patientsQuery->where('client.mcp_pro_id', '=', $mcpPro->id);
  2879. }
  2880. }
  2881. $patientsQuery->whereRaw('(SELECT COUNT(*) FROM note where note.client_id = client.id) > 0');
  2882. $patientsQuery->orderBy('notes_total', 'DESC');
  2883. $patients = $patientsQuery->paginate(50);
  2884. $data = [
  2885. 'patients' => $patients,
  2886. 'proUid' => $proUid,
  2887. 'allPros' => $allPros,
  2888. 'notesTotal' => $notesTotal,
  2889. 'notesTotalWithBillingClosed' => $notesTotalWithBillingClosed,
  2890. 'notesTotalWithClaimingClosed' => $notesTotalWithClaimingClosed,
  2891. 'notes3rdPartyTotal' => $notes3rdPartyTotal,
  2892. 'notes3rdPartyTotalWithBillingClosed' => $notes3rdPartyTotalWithBillingClosed,
  2893. 'notes3rdPartyTotalWithClaimingClosed' => $notes3rdPartyTotalWithClaimingClosed,
  2894. 'patientsTotal' => $patientsTotal,
  2895. 'patientsTotalWithBillingClosed' => $patientsTotalWithBillingClosed,
  2896. 'patientsTotalWithClaimingClosed' => $patientsTotalWithClaimingClosed
  2897. ];
  2898. return view('app.practice-management.patient-claim-summary', $data);
  2899. }
  2900. public function claims(Request $request){
  2901. $status = $request->get('status');
  2902. $claims = [];
  2903. if(!$status){
  2904. $claims = Claim::orderBy('created_at', 'DESC')->paginate();
  2905. }else{
  2906. $claims = Claim::where('status', $status)->orderBy('created_at', 'DESC')->paginate();
  2907. }
  2908. return view('app.practice-management.claims', compact('claims', 'status'));
  2909. }
  2910. public function processClaims(Request $request) {
  2911. $status = '';
  2912. $q = $request->input('q') ? $request->input('q') : '';
  2913. $from = $request->input('from') ? $request->input('from') : '1900-01-01';
  2914. $to = $request->input('to') ? $request->input('to') : '2100-01-01';
  2915. $params = [
  2916. 'q' => '%' . $q . '%',
  2917. 'from' => $from,
  2918. 'to' => $to
  2919. ];
  2920. $hcpPro = $request->input('hcp') ? Pro::where('uid', $request->input('hcp'))->first() : null;
  2921. if($hcpPro) {
  2922. $params['hcp'] = $hcpPro->id;
  2923. }
  2924. $claims = DB::select(DB::raw("
  2925. SELECT claim.uid AS uid,
  2926. DATE(claim.created_at) AS created,
  2927. claim.status,
  2928. client.uid AS client_uid,
  2929. client.cell_number AS client_phone,
  2930. client.phone_home AS client_phone_home,
  2931. (client.name_last || ' ' || client.name_first) AS client ,
  2932. client.chart_number AS client_chart_number,
  2933. cp.id AS claim_pro_id,
  2934. (cp.name_last || ' ' || cp.name_first) AS claim_pro,
  2935. sp.id AS status_pro_id,
  2936. (sp.name_last || ' ' || sp.name_first) AS status_pro,
  2937. note.uid AS note_uid,
  2938. note.method,
  2939. note.new_or_fu_or_na,
  2940. care_month.uid AS care_month_uid,
  2941. care_month.start_date as care_month_start__date,
  2942. -- claim.status_updated_at,
  2943. (DATE(claim.status_updated_at) || ' ' ||
  2944. LPAD(EXTRACT(hour FROM claim.status_updated_at)::text, 2, '0') || ':' ||
  2945. LPAD(EXTRACT(minute FROM claim.status_updated_at)::text, 2, '0')) AS status_updated_at,
  2946. (SELECT string_agg(claim_line.cpt, ', ') FROM claim_line where claim_id = claim.id) AS cpts,
  2947. (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,
  2948. ROUND(claim.expected_total, 3) as expected_total
  2949. FROM claim
  2950. join client on claim.client_id = client.id
  2951. join pro cp on claim.pro_id = cp.id
  2952. left join note on claim.note_id = note.id
  2953. left join care_month on claim.care_month_id = care_month.id
  2954. left join app_session on claim.status_updated_by_session_id = app_session.id
  2955. left join pro sp on app_session.pro_id = sp.id
  2956. --WHERE claim.status IS NULL OR claim.status = 'NEW'
  2957. WHERE (claim.status is NULL OR claim.status NOT IN ('CANCELLED', 'ABANDONED'" . ($request->input('show-submitted') ? "" : ", 'SUBMITTED'") . "))
  2958. -- AND claim.current_version_id IS NOT NULL
  2959. AND (client.name_first ILIKE :q OR
  2960. client.name_last ILIKE :q OR
  2961. client.chart_number ILIKE :q OR
  2962. client.mcn ILIKE :q)
  2963. AND (claim.created_at >= :from AND claim.created_at <= :to)
  2964. " . ($hcpPro ? "AND claim.pro_id = :hcp" : '') . "
  2965. AND claim.id IN (SELECT mb_claim.claim_id FROM mb_claim)
  2966. ORDER BY claim.created_at DESC
  2967. --OFFSET 0 LIMIT 15
  2968. "), $params);
  2969. if($request->input('json')) {
  2970. return json_encode($claims);
  2971. }
  2972. return view('app.practice-management.process-claims', compact('claims', 'status'));
  2973. }
  2974. public function rmLaunchAndClean(Request $request) {
  2975. $keyNumbers = [];
  2976. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_40'] = CareMonth::where('is_bill_closed', false)
  2977. ->whereNotNull('company_pro_id')
  2978. ->whereNotNull('company_pro_payer_id')
  2979. ->whereNotNull('company_location_id')
  2980. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2981. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  2982. ->where('rm_total_time_in_seconds', '>=', 4200) // at 4200 (70 minutes, it becomes eligible for plus40)
  2983. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2984. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2985. ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS TRUE OR has_mcp_rm_interacted_by_note IS TRUE )')
  2986. ->count();
  2987. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_40_ifHadInteraction'] = CareMonth::where('is_bill_closed', false)
  2988. ->whereNotNull('company_pro_id')
  2989. ->whereNotNull('company_pro_payer_id')
  2990. ->whereNotNull('company_location_id')
  2991. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2992. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  2993. ->where('rm_total_time_in_seconds', '>=', 4200) // at 4200 (70 minutes, it becomes eligible for plus40)
  2994. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2995. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2996. ->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 )')
  2997. ->count();
  2998. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_20'] = CareMonth::where('is_bill_closed', false)
  2999. ->whereNotNull('company_pro_id')
  3000. ->whereNotNull('company_pro_payer_id')
  3001. ->whereNotNull('company_location_id')
  3002. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  3003. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  3004. ->where('rm_total_time_in_seconds', '<', 4200)
  3005. ->where('rm_total_time_in_seconds', '>=', 3000) // at 3000 (50 minutes, it becomes eligible for plus20)
  3006. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  3007. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  3008. ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS TRUE OR has_mcp_rm_interacted_by_note IS TRUE)')
  3009. ->count();
  3010. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_20_ifHadInteraction'] = CareMonth::where('is_bill_closed', false)
  3011. ->whereNotNull('company_pro_id')
  3012. ->whereNotNull('company_pro_payer_id')
  3013. ->whereNotNull('company_location_id')
  3014. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  3015. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  3016. ->where('rm_total_time_in_seconds', '<', 4200)
  3017. ->where('rm_total_time_in_seconds', '>=', 3000) // at 3000 (50 minutes, it becomes eligible for plus20)
  3018. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  3019. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  3020. ->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 )')
  3021. ->count();
  3022. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP'] = CareMonth::where('is_bill_closed', false)
  3023. ->whereNotNull('company_pro_id')
  3024. ->whereNotNull('company_pro_payer_id')
  3025. ->whereNotNull('company_location_id')
  3026. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  3027. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  3028. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  3029. ->whereRaw('(rm_total_time_in_seconds < 3000 OR (rm_total_time_in_seconds >= 3000 AND is_rm_interaction_waived IS TRUE))')
  3030. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  3031. ->count();
  3032. $keyNumbers['careMonthsEligibleForBillGeneration_RMB'] = CareMonth::where('is_bill_closed', false)
  3033. ->whereNotNull('company_pro_id')
  3034. ->whereNotNull('company_pro_payer_id')
  3035. ->whereNotNull('company_location_id')
  3036. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  3037. ->whereRaw('is_rm_time_waived IS TRUE')
  3038. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  3039. ->count();
  3040. $keyNumbers['careMonthsWith16OrMoreMeasurementDays'] = CareMonth::where('is_bill_closed', false)
  3041. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  3042. ->count();
  3043. $careMonthsWith16PlusMeasurements = CareMonth::where('is_bill_closed', false)
  3044. ->where('number_of_days_with_remote_measurements', '>=', 16 )->get();
  3045. return view('app.practice-management.rm-launch-and-clean', compact('keyNumbers', 'careMonthsWith16PlusMeasurements'));
  3046. }
  3047. public function processNotes(Request $request) {
  3048. $mode = $request->input('mode') ? $request->input('mode') : '1';
  3049. if(($mode < 1 || $mode > 5) && $mode != 8) $mode = 1;
  3050. DB::enableQueryLog(); // Enable query log
  3051. $test = Note::where('is_cancelled', false)
  3052. ->where('is_signed_by_hcp', true)
  3053. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  3054. ->whereNull('current_note_pickup_for_processing_id')
  3055. ->where('is_billing_marked_done', true)
  3056. ->where('is_bill_closed', true)
  3057. ->where('is_claim_closed', true)
  3058. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  3059. ->count();
  3060. // var_dump($test);
  3061. // dd(DB::getQueryLog()); // Show results of log
  3062. // exit;
  3063. $counts = [
  3064. "picked" => Note::where('is_cancelled', false)
  3065. ->whereNotNull('current_note_pickup_for_processing_id')
  3066. ->count(),
  3067. "bad" => Note::where('is_cancelled', false)
  3068. ->whereRaw("((detail_json)::json->>'isBad' = 'true')")
  3069. ->count(),
  3070. // not yet signed
  3071. "mode-1" => Note::where('is_cancelled', false)
  3072. ->where('is_signed_by_hcp', false)
  3073. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3074. // ->whereNull('current_note_pickup_for_processing_id')
  3075. ->count(),
  3076. // billing not marked done
  3077. "mode-2" => Note::where('is_cancelled', false)
  3078. ->where('is_signed_by_hcp', true)
  3079. //->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3080. // ->whereNull('current_note_pickup_for_processing_id')
  3081. ->where('is_billing_marked_done', false)
  3082. ->count(),
  3083. // billing not closed
  3084. "mode-3" => Note::where('is_cancelled', false)
  3085. ->where('is_signed_by_hcp', true)
  3086. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3087. // ->whereNull('current_note_pickup_for_processing_id')
  3088. ->where('is_billing_marked_done', true)
  3089. ->where('is_bill_closed', false)
  3090. ->count(),
  3091. // claiming not closed
  3092. "mode-4" => Note::where('is_cancelled', false)
  3093. ->where('is_signed_by_hcp', true)
  3094. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3095. // ->whereNull('current_note_pickup_for_processing_id')
  3096. ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true' OR ((detail_json)::json->>'isGood')::text IS NULL)")
  3097. ->where('is_billing_marked_done', true)
  3098. ->where('is_bill_closed', true)
  3099. ->where('is_claim_closed', false)
  3100. ->count(),
  3101. // has unsubmitted claims
  3102. "mode-5" => Note::where('is_cancelled', false)
  3103. /*->where('is_signed_by_hcp', true)
  3104. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3105. ->whereNull('current_note_pickup_for_processing_id')
  3106. ->where('is_billing_marked_done', true)
  3107. ->where('is_bill_closed', 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. */
  3111. ->where('is_signed_by_hcp', true)
  3112. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3113. // ->whereNull('current_note_pickup_for_processing_id')
  3114. ->where('is_billing_marked_done', true)
  3115. ->where('is_bill_closed', true)
  3116. // ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true')")
  3117. ->where('is_claim_closed', true)
  3118. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0)")
  3119. ->count(),
  3120. // has unsubmitted claims MARKED GOOD!
  3121. "mode-8" => Note::where('is_cancelled', false)
  3122. ->where('is_signed_by_hcp', true)
  3123. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  3124. ->whereNull('current_note_pickup_for_processing_id')
  3125. ->where('is_billing_marked_done', true)
  3126. ->where('is_bill_closed', true)
  3127. ->where('is_claim_closed', false)
  3128. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  3129. ->count(),
  3130. // all good
  3131. "mode-6" => Note::where('is_cancelled', false)
  3132. ->where('is_signed_by_hcp', true)
  3133. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3134. // ->whereNull('current_note_pickup_for_processing_id')
  3135. ->where('is_billing_marked_done', true)
  3136. ->where('is_bill_closed', true)
  3137. ->where('is_claim_closed', true)
  3138. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id) > 0)")
  3139. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  3140. ->count(),
  3141. "mode-7" => Note::where('is_cancelled', false)
  3142. ->whereRaw("(detail_json)::json->>'isBad' = 'true'")
  3143. ->count(),
  3144. ];
  3145. return view('app.practice-management.process-notes', compact('mode', 'counts'));
  3146. }
  3147. public function notesProcessingCenter(Request $request) {
  3148. $notes = Note::where('is_cancelled', false);
  3149. // filters
  3150. $proUid = $request->input('proUid');
  3151. if($proUid) {
  3152. $fPro = Pro::where('uid', $proUid)->first();
  3153. if($fPro) {
  3154. $notes = $notes->where('hcp_pro_id', $fPro->id);
  3155. }
  3156. }
  3157. $proSigned = $request->input('proSigned');
  3158. switch($proSigned) {
  3159. case 'yes': $notes = $notes->where('is_signed_by_hcp', true); break;
  3160. case 'no': $notes = $notes->where('is_signed_by_hcp', '!=', true); break;
  3161. }
  3162. $billingMarkedDone = $request->input('billingMarkedDone');
  3163. switch($billingMarkedDone) {
  3164. case 'yes': $notes = $notes->where('is_billing_marked_done', true); break;
  3165. case 'no': $notes = $notes->where('is_billing_marked_done', '!=', true); break;
  3166. }
  3167. $billingClosed = $request->input('billingClosed');
  3168. switch($billingClosed) {
  3169. case 'yes': $notes = $notes->where('is_bill_closed', true); break;
  3170. case 'no': $notes = $notes->where('is_bill_closed', '!=', true); break;
  3171. }
  3172. $claimingClosed = $request->input('claimingClosed');
  3173. switch($claimingClosed) {
  3174. case 'yes': $notes = $notes->where('is_claim_closed', true); break;
  3175. case 'no': $notes = $notes->where('is_claim_closed', '!=', true); break;
  3176. }
  3177. $allClaimsSubmitted = $request->input('allClaimsSubmitted');
  3178. if($allClaimsSubmitted) {
  3179. // TODO
  3180. }
  3181. $goodBad = $request->input('goodBad');
  3182. switch($goodBad) {
  3183. case 'good': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' = 'false'"); break;
  3184. case 'bad': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' = 'true'"); break;
  3185. case 'unclassified': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' is null"); break;
  3186. }
  3187. $startDate = $request->input('startDate');
  3188. if($startDate) {
  3189. $notes = $notes->where('effective_dateest', '>=', $startDate);
  3190. }
  3191. $endDate = $request->input('endDate');
  3192. if($endDate) {
  3193. $notes = $notes->where('effective_dateest', '<=', $endDate);
  3194. }
  3195. $mcPartB = $request->input('mcPartB');
  3196. if($mcPartB) {
  3197. // TODO
  3198. }
  3199. $notes = $notes->orderBy('effective_dateest')->paginate(10);
  3200. return view('app.practice-management.notes-processing-center', compact('notes'));
  3201. }
  3202. public function getNextNote(Request $request, $mode)
  3203. {
  3204. $note = null;
  3205. switch (+$mode) {
  3206. case 1:
  3207. $note = Note::where('is_cancelled', false)
  3208. ->where('is_signed_by_hcp', false)
  3209. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3210. ->whereNull('current_note_pickup_for_processing_id')
  3211. ->orderBy('effective_dateest', 'DESC')
  3212. ->first();
  3213. break;
  3214. case 2:
  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', false)
  3220. ->orderBy('effective_dateest', 'DESC')
  3221. ->first();
  3222. break;
  3223. case 3:
  3224. $note = Note::where('is_cancelled', false)
  3225. ->where('is_signed_by_hcp', true)
  3226. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3227. ->whereNull('current_note_pickup_for_processing_id')
  3228. ->where('is_billing_marked_done', true)
  3229. ->where('is_bill_closed', false)
  3230. ->orderBy('effective_dateest', 'DESC')
  3231. ->first();
  3232. break;
  3233. case 4: // claiming not closed
  3234. DB::enableQueryLog(); // Enable query log
  3235. $note = Note::where('is_cancelled', false)
  3236. ->where('is_signed_by_hcp', true)
  3237. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3238. ->whereNull('current_note_pickup_for_processing_id')
  3239. ->where('is_billing_marked_done', true)
  3240. ->where('is_bill_closed', true)
  3241. ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true' OR ((detail_json)::json->>'isGood')::text IS NULL)")
  3242. ->where('is_claim_closed', false)
  3243. ->orderBy('effective_dateest', 'DESC')
  3244. ->first();
  3245. // DB::enableQueryLog(); // Enable query log
  3246. // Your Eloquent query executed by using get()
  3247. // dd(DB::getQueryLog()); // Show results of log
  3248. break;
  3249. case 5:
  3250. $note = Note::where('is_cancelled', false)
  3251. ->where('is_signed_by_hcp', true)
  3252. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3253. ->whereNull('current_note_pickup_for_processing_id')
  3254. ->where('is_billing_marked_done', true)
  3255. ->where('is_bill_closed', true)
  3256. ->where('is_claim_closed', true)
  3257. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0")
  3258. ->orderBy('effective_dateest', 'DESC')
  3259. ->first();
  3260. break;
  3261. case 8:
  3262. $note = Note::where('is_cancelled', false)
  3263. ->where('is_signed_by_hcp', true)
  3264. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  3265. ->whereNull('current_note_pickup_for_processing_id')
  3266. ->where('is_billing_marked_done', true)
  3267. ->where('is_bill_closed', true)
  3268. ->where('is_claim_closed', false)
  3269. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  3270. ->orderBy('effective_dateest', 'DESC')
  3271. ->first();
  3272. break;
  3273. }
  3274. if($note) {
  3275. $note->client_uid = $note->client->uid;
  3276. }
  3277. return json_encode($note);
  3278. }
  3279. public function pickedNotes(Request $request) {
  3280. $counts = [
  3281. "unpicked" => Note::where('is_cancelled', false)
  3282. ->whereNull('current_note_pickup_for_processing_id')
  3283. ->count(),
  3284. ];
  3285. $notes = Note::where('is_cancelled', false)
  3286. ->whereNotNull('current_note_pickup_for_processing_id')
  3287. ->orderBy('effective_dateest', 'ASC')
  3288. ->paginate();
  3289. return view('app.practice-management.picked-notes', compact('counts', 'notes'));
  3290. }
  3291. public function badNotes(Request $request) {
  3292. $counts = [
  3293. "unpicked" => Note::where('is_cancelled', false)
  3294. ->whereNull('current_note_pickup_for_processing_id')
  3295. ->count(),
  3296. ];
  3297. $notes = Note::where('is_cancelled', false)
  3298. ->whereRaw("(detail_json)::json->>'isBad' = 'true'")
  3299. ->orderBy('effective_dateest', 'ASC')
  3300. ->paginate();
  3301. return view('app.practice-management.bad-notes', compact('counts', 'notes'));
  3302. }
  3303. public function doneNotes(Request $request) {
  3304. $counts = [
  3305. "unpicked" => Note::where('is_cancelled', false)
  3306. ->whereNull('current_note_pickup_for_processing_id')
  3307. ->count(),
  3308. ];
  3309. $notes = Note::where('is_cancelled', false)
  3310. ->where('is_signed_by_hcp', true)
  3311. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  3312. ->whereNull('current_note_pickup_for_processing_id')
  3313. ->where('is_billing_marked_done', true)
  3314. ->where('is_bill_closed', true)
  3315. ->where('is_claim_closed', true)
  3316. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id) > 0")
  3317. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0")
  3318. ->orderBy('effective_dateest', 'ASC')
  3319. ->paginate();
  3320. return view('app.practice-management.done-notes', compact('counts', 'notes'));
  3321. }
  3322. public function currentMbClaim(Request $request, $claimUid) {
  3323. $claim = Claim::where('uid', $claimUid)->first();
  3324. return json_encode(MBClaim::where('claim_version_id', $claim->currentVersion->id)->where('status', '!=', 'CANCELLED')->first());
  3325. }
  3326. public function currentClaimLines(Request $request, $claimUid) {
  3327. $claim = Claim::where('uid', $claimUid)->first();
  3328. if($request->input('json')) {
  3329. foreach ($claim->lines as $line) {
  3330. $line->expected_total = round($line->expected_total, 3);
  3331. $x = $line->claimLineIcds;
  3332. }
  3333. return json_encode($claim->lines);
  3334. }
  3335. return view('app.practice-management._claim-lines', compact('claim'));
  3336. }
  3337. public function packsMultiPrint(Request $request) {
  3338. $packs = Pack
  3339. ::select('pack.*')
  3340. ->leftJoin('shipment', function($join) {
  3341. $join->on('pack.shipment_id', '=', 'shipment.id');
  3342. })
  3343. ->whereNotIn('shipment.status', ['CANCELLED', 'DISPATCHED'])
  3344. ->where(function ($query) {
  3345. $query->where('pack.status', '<>', 'DELETED')->orWhereNull('pack.status'); // weird, but just the <> isn't working!
  3346. })
  3347. ->whereNotNull('pack.label_system_file_id')
  3348. ->orderBy('pack.created_at', 'ASC')
  3349. ->get();
  3350. return view('app.practice-management.packs-multi-print', compact('packs'));
  3351. }
  3352. public function packsMultiPDF(Request $request, $ids) {
  3353. $ids = array_map(function ($_x) {
  3354. return intval($_x);
  3355. }, explode("|", $ids));
  3356. $packs = Pack::whereIn('id', $ids)->get();
  3357. }
  3358. public function handouts(Request $request) {
  3359. $handouts = Handout::orderBy('display_name')->get();
  3360. return view('app.practice-management.handouts', compact('handouts'));
  3361. }
  3362. private function callJava($request, $endPoint, $data)
  3363. {
  3364. $url = config('stag.backendUrl') . $endPoint;
  3365. $response = Http::asForm()
  3366. ->withHeaders([
  3367. 'sessionKey' => $request->cookie('sessionKey')
  3368. ])
  3369. ->post($url, $data)
  3370. ->body();
  3371. dd($response);
  3372. return $response;
  3373. }
  3374. public function genericBills(Request $request)
  3375. {
  3376. return view('app.practice-management.generic-bills');
  3377. }
  3378. public function billsUnderProcessing(Request $request)
  3379. {
  3380. $bills = Bill::where('is_cancelled', false)
  3381. ->where(function ($query) { // mcp of any client program and program OB pending
  3382. $query
  3383. ->where(function ($_query) {
  3384. $_query->where('hcp_pro_id', $this->pro->id)
  3385. ->where('hcp_expected_payment_amount', '>', 0)
  3386. ->where('has_hcp_been_paid', false)
  3387. ->where('is_signed_by_hcp', true);
  3388. })
  3389. ->orWhere(function ($_query) {
  3390. $_query->where('cm_pro_id', $this->pro->id)
  3391. ->where('cm_expected_payment_amount', '>', 0)
  3392. ->where('has_cm_been_paid', false)
  3393. ->where('is_signed_by_cm', true);
  3394. })
  3395. ->orWhere(function ($_query) {
  3396. $_query->where('rme_pro_id', $this->pro->id)
  3397. ->where('rme_expected_payment_amount', '>', 0)
  3398. ->where('has_rme_been_paid', false)
  3399. ->where('is_signed_by_rme', true);
  3400. })
  3401. ->orWhere(function ($_query) {
  3402. $_query->where('rmm_pro_id', $this->pro->id)
  3403. ->where('rmm_expected_payment_amount', '>', 0)
  3404. ->where('has_rmm_been_paid', false)
  3405. ->where('is_signed_by_rmm', true);
  3406. })
  3407. ->orWhere(function ($_query) {
  3408. $_query->where('generic_pro_id', $this->pro->id)
  3409. ->where('generic_pro_expected_payment_amount', '>', 0)
  3410. ->where('has_generic_pro_been_paid', false)
  3411. ->where('is_signed_by_generic_pro', true);
  3412. });
  3413. })
  3414. ->orderBy('created_at', 'DESC')
  3415. ->paginate();
  3416. return view('app.practice-management.bills-under-processing', compact('bills'));
  3417. }
  3418. public function careMonthReport(Request $request) {
  3419. $m = $request->input('m');
  3420. $y = $request->input('y');
  3421. if(!$m || !$y) {
  3422. $date = date('Y-m-01');
  3423. }
  3424. else {
  3425. $date = date('Y-m-d', strtotime("$m/1/$y"));
  3426. }
  3427. $pro = $this->pro;
  3428. $records = DB::select("
  3429. SELECT cm.id as care_month_id,
  3430. cm.uid as care_month_uid,
  3431. c.id as client_id,
  3432. c.uid as client_uid,
  3433. cm.number_of_days_with_remote_measurements,
  3434. cm.rm_total_time_in_seconds_by_mcp,
  3435. cm.rm_total_time_in_seconds_by_rme_pro,
  3436. cm.rm_total_time_in_seconds_by_rmm_pro,
  3437. cm.mcp_pro_id,
  3438. cm.rme_pro_id,
  3439. cm.rmm_pro_id,
  3440. (c.name_first || ' ' || c.name_last) as client_name
  3441. FROM care_month cm
  3442. JOIN client c on cm.client_id = c.id
  3443. WHERE cm.start_date = :startDate
  3444. AND (cm.mcp_pro_id = :proID OR
  3445. cm.rme_pro_id = :proID OR
  3446. cm.rmm_pro_id = :proID)
  3447. ORDER BY c.name_last, c.name_first
  3448. ",
  3449. ['startDate' => $date, 'proID' => $pro->id]
  3450. );
  3451. return view('app.practice-management.care-month-report', compact('records', 'date'));
  3452. }
  3453. public function myTeams(Request $request) {
  3454. $pro = $this->pro;
  3455. // get all teams where the authed-pro is the assistant pro
  3456. $teams = ProTeam::where('assistant_pro_id', $pro->id)
  3457. ->where('is_active', true)
  3458. ->orderBy('slug')
  3459. ->get();
  3460. return view('app.practice-management.my-teams', compact('teams'));
  3461. }
  3462. public function patientsAccountsInvites(Request $request){
  3463. $filters = $request->all();
  3464. $accountInvites = AccountInvite::select('account_invite.*')
  3465. ->join('client', 'client.id', '=', 'account_invite.for_client_id');
  3466. if($this->performer->pro->pro_type !== 'ADMIN'){
  3467. $accountInvites = $accountInvites->where('client.mcp_pro_id', $this->performer->pro->id);
  3468. }
  3469. $this->filterMultiQuery($request, $accountInvites, 'account_invite.created_at', 'date_category', 'date_value_1', 'date_value_2');
  3470. $this->filterSimpleQuery($request, $accountInvites, 'account_invite.status', 'status');
  3471. $accountInvites = $accountInvites->orderBy('created_at', 'DESC')->paginate(20);
  3472. return view('app.practice-management.patients-accounts-invites', compact('accountInvites','filters'));
  3473. }
  3474. public function clientsBdtDevices(Request $request){
  3475. $filters = $request->all();
  3476. $devices = ClientBDTDevice::select(
  3477. 'client_bdt_device.*',
  3478. 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'))
  3479. // 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'))
  3480. ->join('client', 'client.id', '=', 'client_bdt_device.client_id');
  3481. if($this->performer->pro->pro_type !== 'ADMIN'){
  3482. $devices = $devices->where('client.mcp_pro_id', $this->performer->pro->id);
  3483. }
  3484. $this->filterMultiQuery($request, $devices, 'client_bdt_device.most_recent_measurement_at', 'date_category', 'date_value_1', 'date_value_2');
  3485. // $dateKeyName = $request->get('date_category');
  3486. // $date1 = $request->get('date_value_1');
  3487. // $date2 = $request->get('date_value_2');
  3488. // $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)";
  3489. // switch($dateKeyName) {
  3490. // case 'EXACTLY':
  3491. // if($date1) {
  3492. // $devices->whereRaw($dateColumnName." = '$date1'::DATE");
  3493. // }
  3494. // break;
  3495. // case 'LESS_THAN':
  3496. // if($date1) {
  3497. // $devices->whereRaw($dateColumnName. "< '$date1'::DATE" );
  3498. // }
  3499. // break;
  3500. // case 'GREATER_THAN':
  3501. // if($date1) {
  3502. // $devices->whereRaw($dateColumnName. "> '$date1'::DATE");
  3503. // }
  3504. // break;
  3505. // case 'BETWEEN':
  3506. // if($date1 && $date2) {
  3507. // $devices
  3508. // ->whereRaw($dateColumnName. ">= '$date1'::DATE")
  3509. // ->whereRaw($dateColumnName. "<= '$date2'::DATE");
  3510. // }
  3511. // break;
  3512. // case 'NOT_BETWEEN':
  3513. // if($date2 && $date1) {
  3514. // $devices
  3515. // ->where(function ($q) use ($request, $dateColumnName, $date1, $date2) {
  3516. // $q->whereRaw($dateColumnName. "< '$date1'::DATE")
  3517. // ->orWhereRaw($dateColumnName. "> '$date2'::DATE");
  3518. // });
  3519. // }
  3520. // break;
  3521. // }
  3522. $keyName = $request->get('measurement_count_category');
  3523. $value1 = $request->get('measurement_count_value_1');
  3524. $value2 = $request->get('measurement_count_value_2');
  3525. $columnName = "(SELECT COUNT(*) FROM bdt_measurement WHERE bdt_measurement.bdt_device_id = client_bdt_device.device_id AND is_cellular_zero IS FALSE)";
  3526. switch($keyName) {
  3527. case 'EXACTLY':
  3528. if($value1) {
  3529. $devices->whereRaw($columnName.'='.$value1);
  3530. }
  3531. break;
  3532. case 'LESS_THAN':
  3533. if($value1) {
  3534. $devices->whereRaw($columnName. '<' .$value1);
  3535. }
  3536. break;
  3537. case 'GREATER_THAN':
  3538. if($value1) {
  3539. $devices->whereRaw($columnName. '>'. $value1);
  3540. }
  3541. break;
  3542. case 'BETWEEN':
  3543. if($value1 && $value2) {
  3544. $devices
  3545. ->whereRaw($columnName. '>=' . $value1)
  3546. ->whereRaw($columnName. '<=' . $value1);
  3547. }
  3548. break;
  3549. case 'NOT_BETWEEN':
  3550. if($value1 && $value2) {
  3551. $devices
  3552. ->where(function ($q) use ($request, $columnName, $value1, $value2) {
  3553. $q->whereRaw($columnName. '<'. $value1)
  3554. ->orWhereRaw($columnName. '>'.$value2);
  3555. });
  3556. }
  3557. break;
  3558. }
  3559. $status = $request->get('status');
  3560. if($status){
  3561. if($status === 'ACTIVE') $devices = $devices->where('client_bdt_device.is_active', true);
  3562. if($status === 'DEACTIVATED') $devices = $devices->where('client_bdt_device.is_active', false);
  3563. }
  3564. $devices = $devices->orderBy('num_of_measurements', 'DESC')->paginate(20);
  3565. return view('app.practice-management.clients_bdt_devices', compact('devices','filters'));
  3566. }
  3567. public function memos(Request $request){
  3568. $filters = $request->all();
  3569. $memos = ClientMemo::select('client_memo.*')
  3570. ->join('client', 'client.id', '=', 'client_memo.client_id');
  3571. if($this->performer->pro->pro_type !== 'ADMIN'){
  3572. $memos = $memos->where('client.mcp_pro_id', $this->performer->pro->id);
  3573. }
  3574. $this->filterMultiQuery($request, $memos, 'client_memo.created_at', 'date_category', 'date_value_1', 'date_value_2');
  3575. $this->filterSimpleQuery($request, $memos, 'category', 'category');
  3576. $memos = $memos->orderBy('created_at', 'DESC')->paginate(20);
  3577. return view('app.practice-management.memos', compact('memos', 'filters'));
  3578. }
  3579. public function segmentTemplates(Request $request){
  3580. $segmentTemplates = SegmentTemplate::query();
  3581. $segmentTemplates = $segmentTemplates->orderBy('created_at', 'DESC');
  3582. $responseType = $request->get('response_type');
  3583. if($responseType && $responseType == 'json'){
  3584. $segmentTemplates = $segmentTemplates->where('is_active', true)->get();
  3585. return $this->pass($segmentTemplates);
  3586. }
  3587. $segmentTemplates = $segmentTemplates->paginate(30);
  3588. return view('app.practice-management.segment-templates.index', compact('segmentTemplates'));
  3589. }
  3590. public function visitTemplates(Request $request){
  3591. $visitTemplates = VisitTemplate::query();
  3592. $visitTemplates = $visitTemplates->orderBy('created_at', 'DESC');
  3593. $responseType = $request->get('response_type');
  3594. if($responseType && $responseType == 'json'){
  3595. $visitTemplates = $visitTemplates->where('is_active', true)->get();
  3596. return $this->pass($visitTemplates);
  3597. }
  3598. $visitTemplates = $visitTemplates->paginate(30);
  3599. return view('app.practice-management.visit-templates.index', compact('visitTemplates'));
  3600. }
  3601. public function visitTemplate(Request $request, VisitTemplate $visitTemplate){
  3602. $visitTemplateSegmentTemplates = VisitTemplateSegmentTemplate::query();
  3603. $visitTemplateSegmentTemplates = $visitTemplateSegmentTemplates->where('visit_template_id', $visitTemplate->id);
  3604. $visitTemplateSegmentTemplates = $visitTemplateSegmentTemplates->orderBy('position_index', 'ASC');
  3605. $visitTemplateSegmentTemplates = $visitTemplateSegmentTemplates->paginate(50);
  3606. return view('app.practice-management.visit-templates.visit-template-segment-templates.index', compact('visitTemplate','visitTemplateSegmentTemplates'));
  3607. }
  3608. public function visitTemplateAccess(Request $request, VisitTemplate $visitTemplate){
  3609. $visitTemplateAccesses = VisitTemplateAccess::where('visit_template_id', $visitTemplate->id)->paginate(50);
  3610. return view('app.practice-management.visit-templates.visit-template-accesses.index', compact('visitTemplate','visitTemplateAccesses'));
  3611. }
  3612. public function clientCcmRmStatus(Request $request){
  3613. $filters = $request->all();
  3614. $patients = Client::whereNull('shadow_pro_id');
  3615. $pro = $this->performer()->pro;
  3616. if($pro->pro_type !== 'ADMIN') {
  3617. if($pro->is_hcp){
  3618. $patients = $patients->where('mcp_pro_id', $this->performer()->pro->id);
  3619. }
  3620. if($pro->is_considered_for_dna){
  3621. $patients = $patients->where('default_na_pro_id', $this->performer()->pro->id);
  3622. }
  3623. }
  3624. // filters
  3625. /*
  3626. array:18 [▼
  3627. "age_category" => "LESS_THAN"
  3628. "age_value_1" => "34"
  3629. "age_value_2" => null
  3630. "sex" => "M"
  3631. "bmi_category" => "BETWEEN"
  3632. "bmi_value_1" => "20"
  3633. "bmi_value_2" => "25"
  3634. "last_visit_category" => "LESS_THAN"
  3635. "last_visit_value_1" => "2021-10-14"
  3636. "last_visit_value_2" => null
  3637. "next_appointment_category" => "LESS_THAN"
  3638. "next_appointment_value_1" => "2021-10-15"
  3639. "status" => "ACTIVE"
  3640. "last_weighed_in_category" => "EXACTLY"
  3641. "last_weighed_in_value_1" => "2021-10-07"
  3642. "last_bp_category" => "BETWEEN"
  3643. "last_bp_value_1" => "2021-10-01"
  3644. "last_bp_value_2" => "2021-10-31"
  3645. ]
  3646. */
  3647. $this->filterMultiQuery($request, $patients, 'age_in_years', 'age_category', 'age_value_1', 'age_value_2', false);
  3648. $this->filterSimpleQuery($request, $patients, 'sex', 'sex');
  3649. $this->filterMultiQuery($request, $patients, 'usual_bmi', 'bmi_category', 'bmi_value_1', 'bmi_value_2');
  3650. $this->filterMultiQuery($request, $patients, 'most_recent_weight_at', 'last_weighed_in_category', 'last_weighed_in_value_1', 'last_weighed_in_value_2');
  3651. $this->filterMultiQuery($request, $patients, 'most_recent_bp_at', 'last_bp_category', 'last_bp_value_1', 'last_bp_value_2');
  3652. switch($request->input('status')) {
  3653. case 'ACTIVE':
  3654. $patients->where('is_active', true)->where('has_mcp_done_onboarding_visit', true);
  3655. break;
  3656. case 'AWAITING_VISIT':
  3657. $patients->where('is_active', true)->where('has_mcp_done_onboarding_visit', false);
  3658. break;
  3659. case 'INACTIVE':
  3660. $patients->where('is_active', '<>', true);
  3661. break;
  3662. }
  3663. if($request->input('is_eligible_for_cm')){
  3664. $patients->where('is_eligible_for_cm', '=', $request->input('is_eligible_for_cm'));
  3665. }
  3666. if($request->input('is_enrolled_in_cm')){
  3667. $patients->where('is_enrolled_in_cm', '=', $request->input('is_enrolled_in_cm'));
  3668. }
  3669. if($request->input('has_cm_setup_been_performed')){
  3670. $patients->where('has_cm_setup_been_performed', '=', $request->input('has_cm_setup_been_performed')=='YES'? true : false);
  3671. }
  3672. if($request->input('is_eligible_for_rm')){
  3673. $patients->where('is_eligible_for_rm', '=', $request->input('is_eligible_for_rm'));
  3674. }
  3675. if($request->input('is_enrolled_in_rm')){ /*-- correct --*/
  3676. $patients->where('is_enrolled_in_rm', '=', $request->input('is_enrolled_in_rm')); /*-- correct --*/
  3677. }
  3678. if($request->input('has_rm_setup_been_performed')){
  3679. $patients->where('has_rm_setup_been_performed', '=', $request->input('has_rm_setup_been_performed') =='YES'? true : false);
  3680. }
  3681. $patients = $patients->orderBy('created_at', 'DESC')->paginate(20);
  3682. return view('app.admin.client-ccm-rm-status', compact('patients', 'filters'));
  3683. }
  3684. public function rmActionReport(Request $request){
  3685. $filters = $request->all();
  3686. $careMonthStartDate = $request->get('care_month_start_date');
  3687. $careMonthYear = $request->get('care_month_year');
  3688. if(!$careMonthStartDate){
  3689. $careMonthStartDate = '2022-01-01';
  3690. }
  3691. if($careMonthYear){
  3692. $careMonthStartDate = $careMonthYear . "-01";
  3693. }
  3694. $lastDateOfMonth = new DateTime(date("Y-m-t", strtotime(get_current_date())));
  3695. $today = new DateTime(get_current_date());
  3696. $diff = $lastDateOfMonth->diff($today);
  3697. $daysBetweenNowAndEndmonth = $diff->days;
  3698. $minRequiredMeasurements = 16 - $daysBetweenNowAndEndmonth -1;
  3699. $numOfMeasurements = $request->get('num_of_measurements'); //16_or_more, 12_or_more
  3700. $hasRecentVisit = $request->get('has_recent_visit'); //yes no
  3701. $hasBeenSpokenToThisMonth = $request->get('has_been_spoken_to'); //yes no
  3702. // default sort
  3703. if(!$request->input('sort_by')) {
  3704. $orderBy = "cm.start_date ASC NULLS LAST, cm.client_id ASC NULLS LAST";
  3705. }
  3706. else {
  3707. $sortBy = json_decode($request->input('sort_by'));
  3708. $orderByClause = [];
  3709. $includeDefaultKeys = true;
  3710. foreach ($sortBy as $sortCriteria) {
  3711. $orderByClause[] = "{$sortCriteria->key} {$sortCriteria->order} NULLS LAST";
  3712. }
  3713. $orderBy = implode(', ', $orderByClause);
  3714. }
  3715. $conditions = [];
  3716. // start date
  3717. $conditions[] = "(cm.start_date >= '$careMonthStartDate')";
  3718. if($request->input('rm_eligible')) {
  3719. $conditions[] = "(c.is_eligible_for_rm = '" . $request->input('rm_eligible') . "')";
  3720. }
  3721. if($request->input('rm_enrolled')) {
  3722. if($request->input('rm_enrolled') === 'YES') {
  3723. $conditions[] = "(cm.is_client_enrolled_in_rm IS TRUE)";
  3724. }
  3725. else {
  3726. $conditions[] = "(cm.is_client_enrolled_in_rm IS NOT TRUE)";
  3727. }
  3728. }
  3729. if($request->input('rm_setup')) {
  3730. $conditions[] = "(c.has_rm_setup_been_performed IS " . ($request->input('rm_setup') === 'YES' ? 'TRUE' : 'FALSE') . ")";
  3731. }
  3732. // measurement days
  3733. if($numOfMeasurements){
  3734. if($numOfMeasurements == '16_or_more') {
  3735. $conditions[] = "(cm.number_of_days_with_remote_measurements >= 16)";
  3736. }
  3737. elseif($numOfMeasurements == 'min_or_more') {
  3738. $conditions[] = "(cm.number_of_days_with_remote_measurements >= $minRequiredMeasurements AND cm.number_of_days_with_remote_measurements < 16)";
  3739. }
  3740. elseif($numOfMeasurements == 'less_than_min') {
  3741. $conditions[] = "(cm.number_of_days_with_remote_measurements < $minRequiredMeasurements)";
  3742. }
  3743. }
  3744. // days since last visit
  3745. if($hasRecentVisit){
  3746. if($hasRecentVisit == 'YES'){
  3747. $conditions[] = "(c.most_recent_completed_mcp_note_date >= ((NOW() - interval '90 days')::DATE))";
  3748. }else{
  3749. $conditions[] = "(c.most_recent_completed_mcp_note_date::DATE < ((NOW() - interval '90 days')::DATE))";
  3750. }
  3751. }
  3752. // communicated
  3753. if($hasBeenSpokenToThisMonth){
  3754. if($hasBeenSpokenToThisMonth == 'YES') {
  3755. $conditions[] = "(cm.has_anyone_interacted_with_client_about_rm_outside_note IS TRUE)";
  3756. }
  3757. else {
  3758. $conditions[] = "(cm.has_anyone_interacted_with_client_about_rm_outside_note IS NOT TRUE)";
  3759. }
  3760. }
  3761. // claiming closed
  3762. $claimingClosed = $request->get('claiming_closed');
  3763. if($claimingClosed){
  3764. if($claimingClosed === 'YES') {
  3765. $conditions[] = "(cm.is_claim_closed IS TRUE)";
  3766. }
  3767. elseif($claimingClosed === 'NO') {
  3768. $conditions[] = "(cm.is_claim_closed IS TRUE)";
  3769. }
  3770. }
  3771. // mcp
  3772. if($request->input('mcp_uid')) {
  3773. $mcp = Pro::where('uid', $request->input('mcp_uid'))->first();
  3774. if($mcp) {
  3775. $conditions[] = "(cm.mcp_pro_id = $mcp->id)";
  3776. }
  3777. }
  3778. // client status
  3779. if($request->input('status')) {
  3780. $v = trim($request->input('status'));
  3781. if($v === 'ACTIVE') {
  3782. $conditions[] = "(c.client_engagement_status_category IS NULL OR c.client_engagement_status_category = '{$v}')";
  3783. }
  3784. else {
  3785. $conditions[] = "(c.client_engagement_status_category = '{$v}')";
  3786. }
  3787. }
  3788. else {
  3789. $conditions[] = "(c.client_engagement_status_category IS NULL OR c.client_engagement_status_category = 'ACTIVE')";
  3790. }
  3791. $columns = "
  3792. cm.id as care_month_id,
  3793. cm.uid as care_month_uid,
  3794. cm.start_date,
  3795. c.uid as client_uid,
  3796. c.is_eligible_for_rm,
  3797. cm.is_client_enrolled_in_rm,
  3798. c.has_rm_setup_been_performed,
  3799. (c.name_first || ' ' || c.name_last) as client_name,
  3800. (mcp.name_first || ' ' || mcp.name_last) as mcp_name,
  3801. (rmm.name_first || ' ' || rmm.name_last) as rmm_name,
  3802. cm.number_of_days_with_remote_measurements,
  3803. DATE_PART('day', NOW() - c.most_recent_cellular_measurement_at) as dslm,
  3804. c.most_recent_completed_mcp_note_date as mr_note_date,
  3805. cm.days_between_most_recent_mcp_note_date_and_end_of_care_month,
  3806. mrnote.uid as mr_note_uid,
  3807. cm.rm_total_time_in_seconds,
  3808. cm.rm_total_time_in_seconds_by_mcp,
  3809. cm.rm_total_time_in_seconds_by_rmm_pro,
  3810. cm.has_admin_interacted_with_client_about_rm,
  3811. cm.has_mcp_interacted_with_client_about_rm,
  3812. cm.claim_suggestion_json,
  3813. cm.is_claim_closed,
  3814. (CASE
  3815. WHEN cm.mcp_rm_generic_bill_id IS NOT NULL AND mcp_rm_bill.is_cancelled IS NOT TRUE THEN TRUE
  3816. ELSE FALSE
  3817. END) as mcp_payable,
  3818. (CASE
  3819. WHEN cm.rmm_rm_generic_bill_id IS NOT NULL AND rmm_rm_bill.is_cancelled IS NOT TRUE THEN TRUE
  3820. ELSE FALSE
  3821. END) as rmm_payable,
  3822. mcp_rm_bill.uid as mcp_rm_bill_uid,
  3823. rmm_rm_bill.uid as rmm_rm_bill_uid,
  3824. mcp_rm_bill.code as mcp_rm_bill_code,
  3825. rmm_rm_bill.code as rmm_rm_bill_code,
  3826. cl.status as claim_status,
  3827. cl.uid as claim_uid,
  3828. array_to_string(
  3829. ARRAY(SELECT claim_line.cpt FROM claim_line WHERE claim_line.claim_id = cl.id),
  3830. ', '::text
  3831. ) AS cpts
  3832. ";
  3833. $from = "
  3834. care_month cm
  3835. join client c on cm.client_id = c.id
  3836. left join pro mcp on c.mcp_pro_id = mcp.id
  3837. left join pro rmm on c.rmm_pro_id = rmm.id
  3838. left join bill mcp_rm_bill on cm.mcp_rm_generic_bill_id = mcp_rm_bill.id
  3839. left join bill rmm_rm_bill on cm.rmm_rm_generic_bill_id = rmm_rm_bill.id
  3840. left join note mrnote on c.most_recent_completed_mcp_note_id = mrnote.id
  3841. left join claim cl on cl.care_month_id = cm.id AND cl.is_cancelled IS NOT TRUE
  3842. ";
  3843. $page = $request->input('page') ?: 1;
  3844. $perPage = $request->input('per_page') ?: 15;
  3845. $offset = ($page - 1) * $perPage;
  3846. $countSql = "
  3847. SELECT
  3848. COUNT(*)
  3849. FROM
  3850. $from
  3851. where " . implode(" AND ", $conditions) . "
  3852. AND cl.is_cancelled IS NOT TRUE
  3853. ";
  3854. $countResult = DB::select($countSql);
  3855. $total = $countResult[0]->count;
  3856. $sql = "
  3857. SELECT
  3858. $columns
  3859. FROM
  3860. $from
  3861. WHERE " . implode(" AND ", $conditions) . "
  3862. ORDER BY $orderBy
  3863. OFFSET {$offset} LIMIT {$perPage}
  3864. ";
  3865. $rows = DB::select($sql);
  3866. $paginator = new LengthAwarePaginator($rows, $total, $request->input('per_page') ?: 15, $request->input('page') ?: 1);
  3867. $perPage = $request->input('per_page') ?: 15;
  3868. $paginator->setPath(route('practice-management.rmActionReport'));
  3869. return view('app.practice-management.rm-action-report', compact('rows', 'filters', 'minRequiredMeasurements', 'paginator'));
  3870. }
  3871. public function myFlyers(Request $request){
  3872. $pro = $this->performer->pro;
  3873. $slug = $pro->slug ?? $pro->uid;
  3874. $url = config('app.stagfe6_url') . '/flyers/json-list?slug=' . $slug;
  3875. $arrContextOptions=array(
  3876. "ssl"=>array(
  3877. "verify_peer"=>false,
  3878. "verify_peer_name"=>false,
  3879. ),
  3880. );
  3881. $response = @file_get_contents($url, false, stream_context_create($arrContextOptions));
  3882. $response = @json_decode($response);
  3883. $flyerTemplates = [];
  3884. if(isset($response->data)){
  3885. $flyerTemplates = $response->data;
  3886. }
  3887. return view('app.my-flyers', compact('pro','flyerTemplates'));
  3888. }
  3889. public function notesPendingPhysicianSupervisorStamping(Request $request){
  3890. $hideTitle = $request->get('hideTitle');
  3891. $pro = $this->performer->pro;
  3892. //All companyProIds that I am supervisor
  3893. $flaggedNotes = Note::where('is_stamped_by_supervising_physician', false)->where('is_flagged_for_supervising_physician_review', true)->whereHas('hcpCompanyPro', function($qry) use($pro){
  3894. return $qry->whereHas('supervisingPhysicianCompanyPro', function($qr) use($pro){
  3895. return $qr->where('pro_id', $pro->id);
  3896. });
  3897. })->get();
  3898. return view('app.notes-pending-physician-supervisor-stamping', compact('flaggedNotes', 'hideTitle'));
  3899. }
  3900. public function clientsWithoutDefaultCompanyProPayer(Request $request){
  3901. $rows = \App\Models\Client::whereNull('shadow_pro_id')
  3902. ->where('is_active', true)
  3903. ->where(function ($q) {
  3904. $q->whereNull('client_engagement_status_category')
  3905. ->orWhere('client_engagement_status_category', 'ACTIVE');
  3906. })
  3907. ->whereRaw('(default_mcp_company_pro_payer_id IS NULL OR default_mcp_company_location_id IS NULL)')
  3908. ->orderBy('created_at', 'DESC')
  3909. ->paginate(25);
  3910. return view('app.clients-without-default-company-pro-payer', compact('rows'));
  3911. }
  3912. public function notesWithoutHcpCompanyProPayer(Request $request){
  3913. $rows = \App\Models\Note::where('is_cancelled', false)
  3914. ->where('is_core_note', false)
  3915. ->where('is_signed_by_hcp', true)
  3916. ->whereNull('hcp_company_pro_payer_id')
  3917. ->orderBy('created_at', 'DESC')
  3918. ->paginate(25);
  3919. return view('app.notes-without-hcp-company-pro-payer', compact('rows'));
  3920. }
  3921. public function noteHcpBillsWithoutCompanyPro(Request $request){
  3922. $rows = \App\Models\Bill::where('bill_service_type', 'NOTE')
  3923. ->where('is_cancelled', false)
  3924. ->whereNotNull('hcp_pro_id')
  3925. ->whereNull('hcp_company_pro_id')
  3926. ->where('has_hcp_been_paid', false)
  3927. ->orderBy('created_at', 'DESC')
  3928. ->paginate(25);
  3929. return view('app.note-hcp-bills-without-company-pro', compact('rows'));
  3930. }
  3931. public function rpmMcpBillsWithoutCompanyPro(Request $request){
  3932. $rows = \App\Models\Bill::where('bill_service_type', 'GENERIC')
  3933. ->where('is_cancelled', false)
  3934. ->whereNotNull('generic_pro_id')
  3935. ->whereNull('generic_company_pro_id')
  3936. ->where('has_generic_pro_been_paid', false)
  3937. ->where('code', 'RM MCP')
  3938. ->orderBy('created_at', 'DESC')
  3939. ->paginate(25);
  3940. return view('app.rpm-mcp-bills-without-company-pro', compact('rows'));
  3941. }
  3942. public function rpmRmmBillsWithoutCompanyPro(Request $request){
  3943. $rows = \App\Models\Bill::where('bill_service_type', 'GENERIC')
  3944. ->where('is_cancelled', false)
  3945. ->whereNotNull('generic_pro_id')
  3946. ->whereNull('generic_company_pro_id')
  3947. ->where('has_generic_pro_been_paid', false)
  3948. ->where('code', 'RM RMM')
  3949. ->orderBy('created_at', 'DESC')
  3950. ->paginate(25);
  3951. return view('app.rpm-rmm-bills-without-company-pro', compact('rows'));
  3952. }
  3953. public function notesResolutionCenter(Request $request) {
  3954. $columns = "(c.name_first || ' ' || c.name_last) as client_name,
  3955. (hcp.name_first || ' ' || hcp.name_last) as hcp_name,
  3956. (na.name_first || ' ' || na.name_last) as na_name,
  3957. c.chart_number,
  3958. c.uid as client_uid,
  3959. n.effective_dateest,
  3960. n.uid,
  3961. n.detail_json,
  3962. n.is_claim_closed,
  3963. n.visit_number,
  3964. ROUND(b.number_of_units * 60) as minutes,
  3965. n.note_reason_icd1 AS icd1,
  3966. n.note_reason_icd1description AS icd1description,
  3967. n.note_reason_icd2 AS icd2,
  3968. n.note_reason_icd2description AS icd2description,
  3969. n.note_reason_icd3 AS icd3,
  3970. n.note_reason_icd3description AS icd3description,
  3971. n.note_reason_icd4 AS icd4,
  3972. n.note_reason_icd4description AS icd4description,
  3973. n.note_reason_memo AS icd_memo,
  3974. n.visit_number
  3975. ";
  3976. $from = "FROM note AS n
  3977. LEFT JOIN pro AS hcp ON n.hcp_pro_id = hcp.id
  3978. LEFT JOIN pro AS na ON n.ally_pro_id = na.id
  3979. JOIN client AS c ON n.client_id = c.id
  3980. JOIN bill AS b ON (b.note_id = n.id AND b.is_cancelled IS NOT TRUE AND b.code ILIKE '%treatment%')
  3981. ";
  3982. $where = "WHERE
  3983. -- n.visit_number IN (1,2) AND
  3984. n.is_signed_by_hcp IS TRUE AND
  3985. -- n.is_claim_closed IS NOT TRUE AND
  3986. n.is_cancelled IS NOT TRUE AND
  3987. n.created_at::DATE >= '2022-01-01'::DATE AND
  3988. c.client_engagement_status_category <> 'DUMMY' AND
  3989. c.name_first NOT ILIKE '%test%' AND
  3990. c.name_last NOT ILIKE '%test%' AND
  3991. 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
  3992. -- n.id NOT IN (SELECT note_id FROM claim WHERE note_id IS NOT NULL) AND
  3993. c.is_part_b_primary = 'YES' AND
  3994. c.latest_eligible_refresh_at::DATE >= '2022-01-01' AND
  3995. c.mpb_remaining = 0 AND
  3996. c.created_at::DATE >= '2022-01-01'::DATE
  3997. ";
  3998. $filters = [];
  3999. if($request->input('f')) {
  4000. $filters[] = "(n.detail_json IS NOT NULL AND ((n.detail_json)::json->'farah_decision')::text = '\"" . $request->input('f') . "\"')";
  4001. }
  4002. if($request->input('s')) {
  4003. $filters[] = "(n.detail_json IS NOT NULL AND ((n.detail_json)::json->'shawn_decision')::text = '\"" . $request->input('s') . "\"')";
  4004. }
  4005. if(count($filters)) {
  4006. $filters = 'AND ' . implode(' AND ', $filters);
  4007. }
  4008. else {
  4009. $filters = '';
  4010. }
  4011. // $filters = '';
  4012. $orderBy = "ORDER BY c.id ASC, n.visit_number ASC";
  4013. $countQuery = "SELECT count(*) {$from} {$where} {$filters}";
  4014. // dd($countQuery);
  4015. $countResult = DB::select($countQuery);
  4016. $total = $countResult[0]->count;
  4017. $defaultPageSize = 25;
  4018. $page = $request->input('page') ?: 1;
  4019. $perPage = $request->input('per_page') ?: $defaultPageSize;
  4020. $offset = ($page - 1) * $perPage;
  4021. $dataQuery = "SELECT {$columns} {$from} {$where} {$filters} {$orderBy} OFFSET {$offset} LIMIT {$perPage}";
  4022. $rows = DB::select($dataQuery);
  4023. $paginator = new LengthAwarePaginator($rows, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  4024. $paginator->setPath(route('practice-management.notes-resolution-center'));
  4025. return view('app.practice-management.notes-resolution-center', compact('rows', 'paginator'));
  4026. }
  4027. public function notesResolutionCenterV2(Request $request) {
  4028. $columns = "(c.name_first || ' ' || c.name_last) as client_name,
  4029. (hcp.name_first || ' ' || hcp.name_last) as hcp_name,
  4030. (na.name_first || ' ' || na.name_last) as na_name,
  4031. c.chart_number,
  4032. c.uid as client_uid,
  4033. n.effective_dateest,
  4034. n.uid,
  4035. n.detail_json,
  4036. n.is_claim_closed,
  4037. n.visit_number,
  4038. ROUND(b.number_of_units * 60) as minutes,
  4039. n.note_reason_icd1 AS icd1,
  4040. n.note_reason_icd1description AS icd1description,
  4041. n.note_reason_icd2 AS icd2,
  4042. n.note_reason_icd2description AS icd2description,
  4043. n.note_reason_icd3 AS icd3,
  4044. n.note_reason_icd3description AS icd3description,
  4045. n.note_reason_icd4 AS icd4,
  4046. n.note_reason_icd4description AS icd4description,
  4047. n.note_reason_memo AS icd_memo
  4048. ";
  4049. $from = "FROM note AS n
  4050. LEFT JOIN pro AS hcp ON n.hcp_pro_id = hcp.id
  4051. LEFT JOIN pro AS na ON n.ally_pro_id = na.id
  4052. JOIN client AS c ON n.client_id = c.id
  4053. JOIN bill AS b ON (b.note_id = n.id AND b.is_cancelled IS NOT TRUE AND b.code ILIKE '%treatment%')
  4054. ";
  4055. $where = "WHERE
  4056. -- n.visit_number = 2 AND
  4057. n.is_signed_by_hcp IS TRUE AND
  4058. -- n.effective_dateest < '2022-03-01' AND
  4059. n.is_claim_closed IS NOT TRUE AND
  4060. n.is_cancelled IS NOT TRUE AND
  4061. c.client_engagement_status_category <> 'DUMMY' AND
  4062. c.name_first NOT ILIKE '%test%' AND
  4063. c.name_last NOT ILIKE '%test%' AND
  4064. 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)
  4065. -- AND
  4066. -- n.id NOT IN (SELECT note_id FROM claim WHERE note_id IS NOT NULL) AND
  4067. ";
  4068. $filters = [];
  4069. if(trim($request->input('f_pb_primary'))) {
  4070. $v = trim($request->input('f_pb_primary'));
  4071. if($v === 'yes') {
  4072. $filters[] = "(c.is_part_b_primary = 'YES')";
  4073. }
  4074. else if($v === 'no') {
  4075. $filters[] = "(c.is_part_b_primary != 'YES')";
  4076. }
  4077. }
  4078. if(trim($request->input('f_deductible_zero'))) {
  4079. $v = trim($request->input('f_deductible_zero'));
  4080. if($v === 'yes') {
  4081. $filters[] = "(c.mpb_remaining = 0)";
  4082. }
  4083. else if($v === 'no') {
  4084. $filters[] = "(c.mpb_remaining > 0)";
  4085. }
  4086. }
  4087. if(trim($request->input('f_note_hcp'))) {
  4088. $v = trim($request->input('f_note_hcp'));
  4089. $filters[] = "(n.hcp_pro_id IN (SELECT id FROM pro WHERE uid = '{$v}'))";
  4090. }
  4091. if(trim($request->input('f_2022_patient'))) {
  4092. $v = trim($request->input('f_2022_patient'));
  4093. if($v === 'yes') {
  4094. $filters[] = "(c.created_at::DATE >= '2022-01-01'::DATE)";
  4095. }
  4096. else if($v === 'no') {
  4097. $filters[] = "(c.created_at::DATE < '2022-01-01'::DATE)";
  4098. }
  4099. }
  4100. if(count($filters)) {
  4101. $filters = 'AND ' . implode(' AND ', $filters);
  4102. }
  4103. else {
  4104. $filters = '';
  4105. }
  4106. // $filters = '';
  4107. $orderBy = "ORDER BY
  4108. -- c.id ASC,
  4109. n.id ASC, n.effective_dateest ASC";
  4110. $countQuery = "SELECT count(*) {$from} {$where} {$filters}";
  4111. // dd($countQuery);
  4112. $countResult = DB::select($countQuery);
  4113. $total = $countResult[0]->count;
  4114. $defaultPageSize = 50;
  4115. $page = $request->input('page') ?: 1;
  4116. $perPage = $request->input('per_page') ?: $defaultPageSize;
  4117. $offset = ($page - 1) * $perPage;
  4118. $dataQuery = "SELECT {$columns} {$from} {$where} {$filters} {$orderBy} OFFSET {$offset} LIMIT {$perPage}";
  4119. $rows = DB::select($dataQuery);
  4120. $paginator = new LengthAwarePaginator($rows, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  4121. $paginator->setPath(route('practice-management.notes-resolution-center-v2'));
  4122. return view('app.practice-management.notes-resolution-center-v2', compact('rows', 'paginator'));
  4123. }
  4124. public function coverages(Request $request) {
  4125. $columns = "(c.name_first || ' ' || c.name_last) as client_name,
  4126. c.id,
  4127. c.uid,
  4128. c.created_at,
  4129. c.sex,
  4130. c.dob,
  4131. c.age_in_years,
  4132. row_to_json(lcpc.*) as latest_client_primary_coverage,
  4133. row_to_json(lacpc.*) as latest_auto_client_primary_coverage,
  4134. row_to_json(lmcpc.*) as latest_manual_client_primary_coverage,
  4135. row_to_json(lmcpc_payer.*) as latest_manual_client_primary_coverage_payer
  4136. ";
  4137. $from = "FROM client AS c
  4138. LEFT JOIN client_primary_coverage lcpc on c.effective_client_primary_coverage_id = lcpc.id
  4139. LEFT JOIN client_primary_coverage lacpc on c.latest_auto_refresh_client_primary_coverage_id = lacpc.id
  4140. LEFT JOIN client_primary_coverage lmcpc on c.latest_manual_client_primary_coverage_id = lmcpc.id
  4141. LEFT JOIN payer lmcpc_payer on lmcpc.commercial_payer_id = lmcpc_payer.id
  4142. ";
  4143. $where = "WHERE
  4144. c.client_engagement_status_category <> 'DUMMY' AND
  4145. c.name_first NOT ILIKE '%test%' AND
  4146. c.name_last NOT ILIKE '%test%' AND
  4147. c.created_at::DATE >= '2022-01-01'::DATE
  4148. -- lmcpc.id IS NOT NULL ANd lmcpc.plan_type != 'MEDICARE'
  4149. ";
  4150. $filters = [];
  4151. if(trim($request->input('f_name'))) {
  4152. $v = trim($request->input('f_name'));
  4153. $filters[] = "(c.name_first ILIKE '%{$v}%' OR c.name_last ILIKE '%{$v}%')";
  4154. }
  4155. if(trim($request->input('f_covered'))) {
  4156. $v = trim($request->input('f_covered'));
  4157. if($v !== 'any') {
  4158. switch($v) {
  4159. case 'covered':
  4160. $filters[] = "(
  4161. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.manual_determination_category = 'COVERED') OR
  4162. ((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')
  4163. )";
  4164. break;
  4165. case 'not-covered':
  4166. $filters[] = "(
  4167. (lmcpc.id IS NULL OR (lmcpc.is_cancelled IS TRUE OR lmcpc.manual_determination_category = 'NOT_COVERED')) AND
  4168. (lacpc.id IS NULL OR (lacpc.is_cancelled IS TRUE OR lacpc.auto_medicare_is_partbprimary = 'NO')) AND
  4169. (lmcpc.id IS NOT NULL OR lacpc.id IS NOT NULL)
  4170. )";
  4171. break;
  4172. case 'unknown':
  4173. $filters[] = "(
  4174. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.manual_determination_category = 'UNKNOWN') OR
  4175. ((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')
  4176. )";
  4177. break;
  4178. }
  4179. }
  4180. }
  4181. if(trim($request->input('f_covered'))) {
  4182. $v = trim($request->input('f_covered'));
  4183. if($v !== 'any') {
  4184. switch($v) {
  4185. case 'covered':
  4186. $filters[] = "(
  4187. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.manual_determination_category = 'COVERED') OR
  4188. ((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')
  4189. )";
  4190. break;
  4191. case 'not-covered':
  4192. $filters[] = "(
  4193. (lmcpc.id IS NULL OR (lmcpc.is_cancelled IS TRUE OR lmcpc.manual_determination_category = 'NOT_COVERED')) AND
  4194. (lacpc.id IS NULL OR (lacpc.is_cancelled IS TRUE OR lacpc.auto_medicare_is_partbprimary = 'NO')) AND
  4195. (lmcpc.id IS NOT NULL OR lacpc.id IS NOT NULL)
  4196. )";
  4197. break;
  4198. case 'unknown':
  4199. $filters[] = "(
  4200. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.manual_determination_category = 'UNKNOWN') OR
  4201. ((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')
  4202. )";
  4203. break;
  4204. }
  4205. }
  4206. }
  4207. if(trim($request->input('f_plan_type'))) {
  4208. $v = strtoupper(trim($request->input('f_plan_type')));
  4209. if($v !== 'ANY') {
  4210. $filters[] = "(
  4211. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.plan_type = '{$v}') OR
  4212. ((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}')
  4213. )";
  4214. }
  4215. }
  4216. if(trim($request->input('f_pb_primary'))) {
  4217. $v = trim($request->input('f_pb_primary'));
  4218. if($v !== 'any') {
  4219. switch($v) {
  4220. case 'primary':
  4221. $filters[] = "(
  4222. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.is_partbprimary = 'YES') OR
  4223. ((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')
  4224. )";
  4225. break;
  4226. case 'not-primary':
  4227. $filters[] = "(
  4228. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.is_partbprimary = 'NO') OR
  4229. ((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')
  4230. )";
  4231. break;
  4232. case 'unknown':
  4233. $filters[] = "(
  4234. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.is_partbprimary = 'UNKNOWN') OR
  4235. ((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')
  4236. )";
  4237. break;
  4238. }
  4239. }
  4240. }
  4241. if(trim($request->input('f_pb_active'))) {
  4242. $v = trim($request->input('f_pb_active'));
  4243. // TODO
  4244. }
  4245. if(trim($request->input('f_pc_active'))) {
  4246. $v = trim($request->input('f_pc_active'));
  4247. // TODO
  4248. }
  4249. if(trim($request->input('f_comm_payer'))) {
  4250. $v = trim($request->input('f_comm_payer'));
  4251. $filters[] = "(lmcpc_payer.name ILIKE '%{$v}%')";
  4252. }
  4253. if(trim($request->input('f_comm_member_id'))) {
  4254. $v = trim($request->input('f_comm_member_id'));
  4255. if($v !== 'any') {
  4256. $filters[] = "(
  4257. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.commercial_member_identifier 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_member_identifier ILIKE '%{$v}%')
  4259. )";
  4260. }
  4261. }
  4262. if(trim($request->input('f_comm_group_num'))) {
  4263. $v = trim($request->input('f_comm_group_num'));
  4264. if($v !== 'any') {
  4265. $filters[] = "(
  4266. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.commercial_group_number ILIKE '%{$v}%') OR
  4267. ((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}%')
  4268. )";
  4269. }
  4270. }
  4271. if(count($filters)) {
  4272. $filters = 'AND ' . implode(' AND ', $filters);
  4273. }
  4274. else {
  4275. $filters = '';
  4276. }
  4277. // $filters = '';
  4278. $orderBy = "ORDER BY client_name ASC";
  4279. $countQuery = "SELECT count(*) {$from} {$where} {$filters}";
  4280. // dd($countQuery);
  4281. $countResult = DB::select($countQuery);
  4282. $total = $countResult[0]->count;
  4283. $defaultPageSize = 10;
  4284. $page = $request->input('page') ?: 1;
  4285. $perPage = $request->input('per_page') ?: $defaultPageSize;
  4286. $offset = ($page - 1) * $perPage;
  4287. $dataQuery = "SELECT {$columns} {$from} {$where} {$filters} {$orderBy} OFFSET {$offset} LIMIT {$perPage}";
  4288. $rows = DB::select($dataQuery);
  4289. $paginator = new LengthAwarePaginator($rows, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  4290. $paginator->setPath(route('practice-management.coverages'));
  4291. // dd($rows);
  4292. return view('app.practice-management.coverages', compact('rows', 'paginator'));
  4293. }
  4294. public function clientReviewRequests(Request $request){
  4295. $pro = $this->performer->pro;
  4296. $reviewRequests = ClientReviewRequest::where('status', '!=', 'DONE');
  4297. if($pro->pro_type !== 'ADMIN'){
  4298. $reviewRequests = $reviewRequests->where('pro_id', $pro->id);
  4299. }
  4300. $reviewRequests = $reviewRequests->orderBy('created_at', 'DESC')->paginate(50);
  4301. return view('app.ps.review-requests.list', compact('reviewRequests'));
  4302. }
  4303. }