PracticeManagementController.php 200 KB

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