PracticeManagementController.php 237 KB

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