PracticeManagementController.php 208 KB

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