PracticeManagementController.php 237 KB

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