PracticeManagementController.php 182 KB

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