PracticeManagementController.php 209 KB

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