PracticeManagementController.php 203 KB

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