PracticeManagementController.php 180 KB

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