PracticeManagementController.php 237 KB

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