PracticeManagementController.php 180 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065
  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. {$genericBillIdColumns}
  1411. 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
  1412. {$genericBillJoinClause}
  1413. left join note mrmnote on mrmnote.id = (
  1414. select max(n.id) from note n
  1415. where
  1416. n.client_id = client.id AND
  1417. n.is_cancelled = FALSE AND
  1418. (n.is_signed_by_hcp IS NOT NULL AND n.is_signed_by_hcp = TRUE) AND
  1419. n.effective_dateest::date >= care_month.start_date::date AND
  1420. n.effective_dateest::date < (care_month.start_date::date + INTERVAL '1 month')
  1421. )
  1422. WHERE
  1423. $proTypeCondition
  1424. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1425. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1426. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '') . "
  1427. $orderBy
  1428. ";
  1429. // dd($query);
  1430. $patients = DB::select($query);
  1431. $timestamp = strtotime(date('Y-m-d'));
  1432. $daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
  1433. return view('app.practice-management.rpm-matrix-by-pro-type', compact('patients', 'daysRemaining', 'careMonthStart', 'mode'));
  1434. }
  1435. public function rpmMatrixForAdmin(Request $request) {
  1436. $performer = $this->performer();
  1437. // abort_if($performer->pro->pro_type !== 'ADMIN' && !$performer->pro->can_view_rm_matrix, 403);
  1438. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1439. $careMonthStart = date($ym . '-01');
  1440. $rc = $request->input('rc') ?: 1;
  1441. $rc2 = $request->input('rc2') ?: 2;
  1442. $conditions = [];// $this->rpmConditions($performer, $rc, $rc2);
  1443. $sortBy = $request->input('sort_by') ?: 'name_first';
  1444. $sortDir = $request->input('sort_dir') ?: 'ASC';
  1445. $orderBy = "ORDER BY $sortBy $sortDir NULLS LAST";
  1446. // special case of if-bill-exists
  1447. if($sortBy === 'mcp_rm_generic_bill_id' || $sortBy === 'rmm_rm_generic_bill_id') {
  1448. if($sortDir === 'ASC') {
  1449. $orderBy = "ORDER BY $sortBy $sortDir NULLS FIRST";
  1450. }
  1451. else {
  1452. $orderBy = "ORDER BY $sortBy $sortDir NULLS LAST";
  1453. }
  1454. }
  1455. // default sort
  1456. if(!$request->input('sort_by')) {
  1457. $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";
  1458. }
  1459. else {
  1460. $sortBy = $request->input('sort_by');
  1461. $sortDir = $request->input('sort_dir');
  1462. if($sortBy && $sortDir) {
  1463. 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'])) {
  1464. $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";
  1465. }
  1466. else {
  1467. $orderBy = "ORDER BY $sortBy $sortDir NULLS LAST";
  1468. }
  1469. }
  1470. }
  1471. // filters from the UI
  1472. if(trim($request->input('f_ces'))) {
  1473. $v = trim($request->input('f_ces'));
  1474. if($v === 'ACTIVE') {
  1475. $conditions[] = "(client.client_engagement_status_category IS NULL OR client.client_engagement_status_category = '{$v}')";
  1476. }
  1477. else {
  1478. $conditions[] = "(client.client_engagement_status_category = '{$v}')";
  1479. }
  1480. }
  1481. if(trim($request->input('f_name'))) {
  1482. $v = trim($request->input('f_name'));
  1483. $conditions[] = "(client.name_first ILIKE '%{$v}%' OR client.name_last ILIKE '%{$v}%')";
  1484. }
  1485. if(trim($request->input('f_mcp'))) {
  1486. $v = trim($request->input('f_mcp'));
  1487. $conditions[] = "(mcpPro.uid = '{$v}')";
  1488. }
  1489. if(trim($request->input('f_dob_op')) && trim($request->input('f_dob'))) {
  1490. $o = trim($request->input('f_dob_op'));
  1491. $v = trim($request->input('f_dob'));
  1492. $conditions[] = "(client.dob {$o} '{$v}')";
  1493. }
  1494. if(trim($request->input('f_rpm'))) {
  1495. $v = trim($request->input('f_rpm'));
  1496. if($v === 'yes') {
  1497. $conditions[] = "(client.is_enrolled_in_rm IS NOT NULL AND client.is_enrolled_in_rm = 'YES')";
  1498. }
  1499. elseif($v === 'no') {
  1500. $conditions[] = "(client.is_enrolled_in_rm IS NULL OR client.is_enrolled_in_rm != 'YES')";
  1501. }
  1502. }
  1503. if(trim($request->input('f_cell_bp'))) {
  1504. $v = trim($request->input('f_cell_bp'));
  1505. if($v === 'yes') {
  1506. $conditions[] = "(client.is_assigned_cellular_bp_device IS NOT NULL AND client.is_assigned_cellular_bp_device = TRUE)";
  1507. }
  1508. elseif($v === 'no') {
  1509. $conditions[] = "(client.is_assigned_cellular_bp_device IS NULL OR client.is_assigned_cellular_bp_device = FALSE)";
  1510. }
  1511. }
  1512. if(trim($request->input('f_cell_wt'))) {
  1513. $v = trim($request->input('f_cell_wt'));
  1514. if($v === 'yes') {
  1515. $conditions[] = "(client.is_assigned_cellular_weight_scale_device IS NOT NULL AND client.is_assigned_cellular_weight_scale_device = TRUE)";
  1516. }
  1517. elseif($v === 'no') {
  1518. $conditions[] = "(client.is_assigned_cellular_weight_scale_device IS NULL OR client.is_assigned_cellular_weight_scale_device = FALSE)";
  1519. }
  1520. }
  1521. if(trim($request->input('f_lmb'))) {
  1522. $v = trim($request->input('f_lmb'));
  1523. switch($v) {
  1524. case '1':
  1525. $conditions[] = "(GREATEST(client.most_recent_cellular_bp_measurement_at::DATE, client.most_recent_cellular_weight_measurement_at::DATE)::DATE < (NOW() - INTERVAL '1 DAY')::DATE)";
  1526. break;
  1527. case '2':
  1528. $conditions[] = "(GREATEST(client.most_recent_cellular_bp_measurement_at::DATE, client.most_recent_cellular_weight_measurement_at::DATE)::DATE < (NOW() - INTERVAL '2 DAYS')::DATE)";
  1529. break;
  1530. case '3':
  1531. $conditions[] = "(GREATEST(client.most_recent_cellular_bp_measurement_at::DATE, client.most_recent_cellular_weight_measurement_at::DATE)::DATE < (NOW() - INTERVAL '3 DAYS')::DATE)";
  1532. break;
  1533. case '3+':
  1534. $conditions[] = "(GREATEST(client.most_recent_cellular_bp_measurement_at::DATE, client.most_recent_cellular_weight_measurement_at::DATE)::DATE < (NOW() - INTERVAL '4 DAYS')::DATE)";
  1535. break;
  1536. }
  1537. }
  1538. if(trim($request->input('f_comm'))) {
  1539. $v = trim($request->input('f_comm'));
  1540. if($v === 'yes') {
  1541. $conditions[] = "(care_month.has_mcp_interacted_with_client_about_rm IS NOT NULL AND care_month.has_mcp_interacted_with_client_about_rm = TRUE)";
  1542. }
  1543. elseif($v === 'no') {
  1544. $conditions[] = "(care_month.has_mcp_interacted_with_client_about_rm IS NULL OR care_month.has_mcp_interacted_with_client_about_rm = FALSE)";
  1545. }
  1546. }
  1547. if(trim($request->input('f_mcp_billable'))) {
  1548. $v = trim($request->input('f_mcp_billable'));
  1549. if($v === 'yes') {
  1550. $conditions[] = "(care_month.mcp_rm_generic_bill_id IS NOT NULL)";
  1551. }
  1552. elseif($v === 'no') {
  1553. $conditions[] = "(care_month.mcp_rm_generic_bill_id IS NULL)";
  1554. }
  1555. }
  1556. if(trim($request->input('f_rmm_billable'))) {
  1557. $v = trim($request->input('f_rmm_billable'));
  1558. if($v === 'yes') {
  1559. $conditions[] = "(care_month.rmm_rm_generic_bill_id IS NOT NULL)";
  1560. }
  1561. elseif($v === 'no') {
  1562. $conditions[] = "(care_month.rmm_rm_generic_bill_id IS NULL)";
  1563. }
  1564. }
  1565. if(trim($request->input('f_md_op')) && trim($request->input('f_md')) !== '') {
  1566. $o = trim($request->input('f_md_op'));
  1567. $v = trim($request->input('f_md'));
  1568. $conditions[] = "(care_month.number_of_days_with_remote_measurements {$o} {$v})";
  1569. }
  1570. if(trim($request->input('f_unst_op')) && trim($request->input('f_unst')) !== '') {
  1571. $o = trim($request->input('f_unst_op'));
  1572. $v = trim($request->input('f_unst'));
  1573. $conditions[] = "(care_month.rm_num_measurements_not_stamped_by_mcp {$o} {$v})";
  1574. }
  1575. if(trim($request->input('f_mcp_mins_op')) && trim($request->input('f_mcp_mins')) !== '') {
  1576. $o = trim($request->input('f_mcp_mins_op'));
  1577. $v = intval(trim($request->input('f_mcp_mins'))) * 60;
  1578. $conditions[] = "(care_month.rm_total_time_in_seconds_by_mcp {$o} {$v})";
  1579. }
  1580. if(trim($request->input('f_rmm_mins_op')) && trim($request->input('f_rmm_mins')) !== '') {
  1581. $o = trim($request->input('f_rmm_mins_op'));
  1582. $v = intval(trim($request->input('f_rmm_mins'))) * 60;
  1583. $conditions[] = "(care_month.rm_total_time_in_seconds_by_rmm_pro {$o} {$v})";
  1584. }
  1585. if($request->input('not-enrolled')) {
  1586. $conditions[] = "(client.is_enrolled_in_rm != 'YES')";
  1587. }
  1588. else {
  1589. $conditions[] = "(client.is_enrolled_in_rm = 'YES')";
  1590. }
  1591. $genericBillIdColumns = "care_month.mcp_rm_generic_bill_id,
  1592. mcpBill.uid as mcp_rm_generic_bill_uid,
  1593. mcpBill.generic_pro_id as mcp_rm_generic_bill_generic_pro_id,
  1594. mcpBill.generic_pro_expected_payment_amount as mcp_rm_generic_bill_expected_payment_amount,
  1595. mcpBill.is_signed_by_generic_pro as mcp_rm_generic_bill_signed,
  1596. care_month.rmm_rm_generic_bill_id,
  1597. rmmBill.uid as rmm_rm_generic_bill_uid,
  1598. rmmBill.generic_pro_id as rmm_rm_generic_bill_generic_pro_id,
  1599. rmmBill.generic_pro_expected_payment_amount as rmm_rm_generic_bill_expected_payment_amount,
  1600. rmmBill.is_signed_by_generic_pro as rmm_rm_generic_bill_signed";
  1601. $genericBillJoinClause = "left join bill mcpBill on care_month.mcp_rm_generic_bill_id = mcpBill.id
  1602. left join bill rmmBill on care_month.rmm_rm_generic_bill_id = rmmBill.id";
  1603. $defaultPageSize = 25;
  1604. $page = $request->input('page') ?: 1;
  1605. $perPage = $request->input('per_page') ?: $defaultPageSize;
  1606. $offset = ($page - 1) * $perPage;
  1607. $countQuery = "
  1608. SELECT COUNT(*)
  1609. FROM care_month join client on care_month.client_id = client.id
  1610. join note mrnote on client.most_recent_completed_mcp_note_id = mrnote.id
  1611. left join pro mcpPro on care_month.mcp_pro_id = mcpPro.id
  1612. left join pro rmmPro on care_month.rmm_pro_id = rmmPro.id
  1613. {$genericBillJoinClause}
  1614. WHERE
  1615. EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1616. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1617. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '') . "
  1618. ";
  1619. $countResult = DB::select($countQuery);
  1620. $total = $countResult[0]->count;
  1621. $query = "
  1622. SELECT client.name_first, client.name_last,
  1623. (client.name_first || ' ' || client.name_last) as client_name,
  1624. client.uid as client_uid,
  1625. client.dob,
  1626. client.age_in_years,
  1627. client.is_enrolled_in_rm,
  1628. client.most_recent_completed_mcp_note_date,
  1629. client.most_recent_completed_mcp_note_id,
  1630. client.cell_number,
  1631. client.is_assigned_cellular_bp_device,
  1632. client.is_assigned_cellular_weight_scale_device,
  1633. care_month.uid as care_month_uid,
  1634. care_month.id as care_month_id,
  1635. care_month.start_date,
  1636. care_month.rm_total_time_in_seconds_by_mcp,
  1637. care_month.rm_total_time_in_seconds_by_rmm_pro,
  1638. care_month.number_of_days_with_remote_measurements,
  1639. care_month.has_mcp_interacted_with_client_about_rm,
  1640. care_month.has_anyone_interacted_with_client_about_rm,
  1641. care_month.rm_num_measurements_not_stamped_by_mcp,
  1642. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  1643. care_month.rm_num_measurements_not_stamped_by_rmm,
  1644. care_month.rm_num_measurements_not_stamped_by_rme,
  1645. care_month.mcp_pro_id as care_month_mcp_pro_id,
  1646. care_month.rmm_pro_id as care_month_rmm_pro_id,
  1647. client.mcp_pro_id,
  1648. client.default_na_pro_id,
  1649. client.rmm_pro_id,
  1650. client.rme_pro_id,
  1651. client.cell_number,
  1652. care_month.most_recent_cellular_bp_dbp_mm_hg,
  1653. care_month.most_recent_cellular_bp_sbp_mm_hg,
  1654. care_month.most_recent_cellular_bp_measurement_at,
  1655. care_month.most_recent_cellular_weight_value,
  1656. care_month.most_recent_cellular_weight_measurement_at,
  1657. mcpPro.mcp_rpm_payment_strategy,
  1658. mcpPro.mcp_rpm_payment_amount,
  1659. (mcpPro.name_first || ' ' || mcpPro.name_last) as mcp_name,
  1660. rmmPro.rmm_payment_strategy,
  1661. rmmPro.rmm_payment_amount,
  1662. (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,
  1663. (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,
  1664. {$genericBillIdColumns}
  1665. FROM care_month join client on care_month.client_id = client.id
  1666. join note mrnote on client.most_recent_completed_mcp_note_id = mrnote.id
  1667. left join pro mcpPro on care_month.mcp_pro_id = mcpPro.id
  1668. left join pro rmmPro on care_month.rmm_pro_id = rmmPro.id
  1669. {$genericBillJoinClause}
  1670. WHERE
  1671. EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1672. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1673. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '') . "
  1674. {$orderBy} OFFSET {$offset} LIMIT {$perPage}
  1675. ";
  1676. // dd($query);
  1677. $patients = DB::select($query);
  1678. $timestamp = strtotime(date('Y-m-d'));
  1679. $daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
  1680. $paginator = new LengthAwarePaginator($patients, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  1681. $perPage = $request->input('per_page') ?: $defaultPageSize;
  1682. $paginator->setPath(route('practice-management.rpm-matrix-admin'));
  1683. return view('app.practice-management.rpm-matrix-for-admin', compact('patients', 'daysRemaining', 'careMonthStart', 'paginator', 'perPage'));
  1684. }
  1685. public function remoteMonitoringMCP(Request $request) {
  1686. return $this->rpmMatrixByProType($request, 'mcp');
  1687. }
  1688. public function remoteMonitoringRMM(Request $request) {
  1689. return $this->rpmMatrixByProType($request, 'rmm');
  1690. }
  1691. public function remoteMonitoringRME(Request $request) {
  1692. return $this->rpmMatrixByProType($request, 'rme');
  1693. }
  1694. public function remoteMonitoring_RowMCP(Request $request) {
  1695. return $this->remoteMonitoring_RowByProType($request, 'mcp');
  1696. }
  1697. public function remoteMonitoring_RowRMM(Request $request) {
  1698. return $this->remoteMonitoring_RowByProType($request, 'rmm');
  1699. }
  1700. public function remoteMonitoring_RowRME(Request $request) {
  1701. return $this->remoteMonitoring_RowByProType($request, 'rme');
  1702. }
  1703. public function remoteMonitoring_RowADMIN(Request $request) {
  1704. return $this->remoteMonitoring_RowForAdmin($request);
  1705. }
  1706. public function rpm_work_matrix(Request $request) {
  1707. // get the patient having most recent unstamped measurement
  1708. $performer = $this->performer();
  1709. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1710. $careMonthStart = date($ym . '-01');
  1711. $patient = null;
  1712. $careMonth = null;
  1713. if($request->input('patientUid') && $request->input('careMonthUid')) {
  1714. $patient = Client::where('uid', $request->input('patientUid'))->first();
  1715. $careMonth = CareMonth::where('uid', $request->input('careMonthUid'))->first();
  1716. }
  1717. if(!$patient && !$careMonth) {
  1718. $query = "
  1719. SELECT client.name_first, client.name_last,
  1720. (client.name_first || ' ' || client.name_last) as client_name,
  1721. client.uid as client_uid,
  1722. client.dob,
  1723. client.is_enrolled_in_rm,
  1724. client.most_recent_completed_mcp_note_date,
  1725. care_month.uid as care_month_uid,
  1726. care_month.id as care_month_id,
  1727. care_month.start_date,
  1728. care_month.rm_total_time_in_seconds_by_mcp,
  1729. care_month.number_of_days_with_remote_measurements,
  1730. care_month.rm_num_measurements_not_stamped_by_mcp,
  1731. care_month.rm_num_measurements_not_stamped_by_rmm,
  1732. client.mcp_pro_id,
  1733. client.default_na_pro_id,
  1734. client.rmm_pro_id,
  1735. client.rme_pro_id,
  1736. client.cell_number,
  1737. client.most_recent_cellular_bp_dbp_mm_hg,
  1738. client.most_recent_cellular_bp_sbp_mm_hg,
  1739. client.most_recent_cellular_bp_measurement_at,
  1740. client.most_recent_cellular_weight_value,
  1741. client.most_recent_cellular_weight_measurement_at,
  1742. GREATEST(client.most_recent_cellular_bp_measurement_at, client.most_recent_cellular_weight_measurement_at) as latest_measurement_at
  1743. FROM care_month join client on care_month.client_id = client.id
  1744. WHERE
  1745. (
  1746. (care_month.mcp_pro_id = {$performer->pro->id} AND care_month.rm_num_measurements_not_stamped_by_mcp > 0) OR
  1747. (care_month.rmm_pro_id = {$performer->pro->id} AND care_month.rm_num_measurements_not_stamped_by_rmm > 0)
  1748. )
  1749. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1750. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1751. ORDER BY latest_measurement_at DESC
  1752. LIMIT 1
  1753. ";
  1754. $patients = DB::select($query);
  1755. if (count($patients)) {
  1756. $patient = Client::where('uid', $patients[0]->client_uid)->first();
  1757. $careMonth = CareMonth::where('uid', $patients[0]->care_month_uid)->first();
  1758. }
  1759. }
  1760. return view('app.practice-management.rpm_work_matrix', compact('patient', 'careMonth'));
  1761. }
  1762. public function remoteMonitoringCount(Request $request) {
  1763. $performer = $this->performer();
  1764. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1765. $careMonthStart = date($ym . '-01');
  1766. $rc = $request->input('rc') ?: 1;
  1767. $rc2 = $request->input('rc2') ?: 2;
  1768. $conditions = $this->rpmConditions($performer, $rc, $rc2);
  1769. $count = DB::select(
  1770. DB::raw(
  1771. "
  1772. SELECT count(*)
  1773. FROM care_month join client on care_month.client_id = client.id
  1774. WHERE
  1775. client.mcp_pro_id = {$performer->pro->id}
  1776. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1777. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1778. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '')
  1779. )
  1780. );
  1781. return $count[0]->count;
  1782. }
  1783. public function remoteMonitoringAdmin(Request $request) {
  1784. $performer = $this->performer();
  1785. // abort_if($performer->pro->pro_type !== 'ADMIN' && !$performer->pro->can_view_rm_matrix, 403);
  1786. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1787. $careMonthStart = date($ym . '-01');
  1788. $rc = $request->input('rc') ?: 1;
  1789. $rc2 = $request->input('rc2') ?: 2;
  1790. $conditions = [];// $this->rpmConditions($performer, $rc, $rc2);
  1791. $sortBy = $request->input('sort_by') ?: 'name_first';
  1792. $sortDir = $request->input('sort_dir') ?: 'ASC';
  1793. $orderBy = "ORDER BY $sortBy $sortDir NULLS LAST";
  1794. $query = "
  1795. SELECT client.name_first, client.name_last,
  1796. (client.name_first || ' ' || client.name_last) as client_name,
  1797. (mcp_pro.name_first || ' ' || mcp_pro.name_last) as mcp_pro_name,
  1798. (rmm_pro.name_first || ' ' || rmm_pro.name_last) as rmm_pro_name,
  1799. client.uid as client_uid,
  1800. client.chart_number,
  1801. client.dob,
  1802. client.is_enrolled_in_rm,
  1803. client.most_recent_completed_mcp_note_date,
  1804. client.most_recent_completed_mcp_note_id,
  1805. mrmnote.effective_dateest::date as most_recent_completed_mcp_note_date_cm,
  1806. mrmnote.id as most_recent_completed_mcp_note_id_cm,
  1807. mrmnote.uid as most_recent_completed_mcp_note_uid_cm,
  1808. client.cell_number,
  1809. client.is_assigned_cellular_bp_device,
  1810. client.is_assigned_cellular_weight_scale_device,
  1811. care_month.uid as care_month_uid,
  1812. care_month.id as care_month_id,
  1813. care_month.start_date,
  1814. care_month.rm_total_time_in_seconds_by_mcp,
  1815. care_month.rm_total_time_in_seconds_by_rmm_pro,
  1816. care_month.number_of_days_with_remote_measurements,
  1817. care_month.has_anyone_interacted_with_client_about_rm,
  1818. care_month.has_mcp_interacted_with_client_about_rm,
  1819. care_month.rm_num_measurements_not_stamped_by_mcp,
  1820. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  1821. care_month.rm_num_measurements_not_stamped_by_rmm,
  1822. care_month.rm_num_measurements_not_stamped_by_rme,
  1823. care_month.mcp_pro_id as care_month_mcp_pro_id,
  1824. care_month.rmm_pro_id as care_month_rmm_pro_id,
  1825. client.mcp_pro_id,
  1826. client.default_na_pro_id,
  1827. client.rmm_pro_id,
  1828. client.rme_pro_id,
  1829. client.cell_number,
  1830. care_month.most_recent_cellular_bp_dbp_mm_hg,
  1831. care_month.most_recent_cellular_bp_sbp_mm_hg,
  1832. care_month.most_recent_cellular_bp_measurement_at,
  1833. care_month.most_recent_cellular_weight_value,
  1834. care_month.most_recent_cellular_weight_measurement_at
  1835. 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
  1836. left join note mrmnote on mrmnote.id = (
  1837. select max(n.id) from note n
  1838. where
  1839. n.client_id = client.id AND
  1840. n.is_cancelled = FALSE AND
  1841. (n.is_signed_by_hcp IS NOT NULL AND n.is_signed_by_hcp = TRUE) AND
  1842. n.effective_dateest::date >= care_month.start_date::date AND
  1843. n.effective_dateest::date < (care_month.start_date::date + INTERVAL '1 month')
  1844. )
  1845. left join pro mcp_pro on care_month.mcp_pro_id = mcp_pro.id
  1846. left join pro rmm_pro on care_month.rmm_pro_id = rmm_pro.id
  1847. WHERE
  1848. EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1849. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1850. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '') . "
  1851. $orderBy
  1852. ";
  1853. $patients = DB::select($query);
  1854. $timestamp = strtotime(date('Y-m-d'));
  1855. $daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
  1856. return view('app.practice-management.remote-monitoring-admin', compact('patients', 'daysRemaining', 'careMonthStart'));
  1857. }
  1858. public function remoteMonitoringAdminCount(Request $request) {
  1859. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1860. $careMonthStart = date($ym . '-01');
  1861. $rc = $request->input('rc') ?: 1;
  1862. $rc2 = $request->input('rc2') ?: 2;
  1863. $conditions = $this->rpmConditionsAdmin($this->performer(), $rc, $rc2);
  1864. $count = DB::select(
  1865. DB::raw(
  1866. "
  1867. SELECT count(*)
  1868. FROM care_month join client on care_month.client_id = client.id
  1869. WHERE
  1870. client.shadow_pro_id is null AND client.is_enrolled_in_rm = 'YES'
  1871. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1872. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1873. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '')
  1874. )
  1875. );
  1876. return $count[0]->count;
  1877. }
  1878. private function rpmConditions($performer, $rc, $rc2) {
  1879. $conditions = [];
  1880. $c_isMCP = "client.mcp_pro_id = {$performer->pro->id}";
  1881. $c_enrolledInRPM = "client.is_enrolled_in_rm = 'YES'";
  1882. $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";
  1883. $c_lastVisitBefore90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) > 90";
  1884. $c_lastVisitWithin90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) <= 90";
  1885. $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)";
  1886. $c_spokenToThisMonth = "care_month.has_anyone_interacted_with_client_about_rm_outside_note = TRUE";
  1887. $c_hasUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp > 0";
  1888. $c_hasNoUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp = 0";
  1889. $c_lt16MeasurementDays = "care_month.number_of_days_with_remote_measurements < 16";
  1890. $c_gte16MeasurementDays = "care_month.number_of_days_with_remote_measurements >= 16";
  1891. $c_subscribedToSMS = "client.send_sms_on_bdt_measurement = TRUE";
  1892. $c_deviceUsed = "(client.most_recent_cellular_bp_measurement_at IS NOT NULL OR most_recent_cellular_weight_measurement_at IS NOT NULL)";
  1893. $c_lt20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp < 1200";
  1894. $c_gte20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp >= 1200";
  1895. switch ($rc) {
  1896. case 1:
  1897. $conditions = [$c_isMCP];
  1898. break;
  1899. case 2:
  1900. $conditions = [$c_isMCP, $c_enrolledInRPM];
  1901. break;
  1902. case 3:
  1903. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice];
  1904. break;
  1905. case 4:
  1906. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, ($rc2 == 1 ? $c_lastVisitBefore90Days : $c_lastVisitWithin90Days)];
  1907. break;
  1908. case 5:
  1909. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, ($rc2 == 1 ? $c_notSpokenToThisMonth : $c_spokenToThisMonth)];
  1910. break;
  1911. case 6:
  1912. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_hasUnstamped : $c_hasNoUnstamped)];
  1913. break;
  1914. case 7:
  1915. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_lt16MeasurementDays : $c_gte16MeasurementDays)];
  1916. break;
  1917. case 10:
  1918. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, $c_gte16MeasurementDays, ($rc2 == 1 ? $c_lt20BillingMinutes : $c_gte20BillingMinutes)];
  1919. break;
  1920. case 8:
  1921. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_subscribedToSMS];
  1922. break;
  1923. case 9:
  1924. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_deviceUsed];
  1925. break;
  1926. }
  1927. return $conditions;
  1928. }
  1929. private function rpmConditionsAdmin($performer, $rc, $rc2) {
  1930. $conditions = [];
  1931. $c_enrolledInRPM = "client.is_enrolled_in_rm = 'YES'";
  1932. $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";
  1933. $c_lastVisitBefore90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) > 90";
  1934. $c_lastVisitWithin90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) <= 90";
  1935. $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)";
  1936. $c_spokenToThisMonth = "care_month.has_anyone_interacted_with_client_about_rm_outside_note = TRUE";
  1937. $c_hasUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp > 0";
  1938. $c_hasNoUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp = 0";
  1939. $c_lt16MeasurementDays = "care_month.number_of_days_with_remote_measurements < 16";
  1940. $c_gte16MeasurementDays = "care_month.number_of_days_with_remote_measurements >= 16";
  1941. $c_subscribedToSMS = "client.send_sms_on_bdt_measurement = TRUE";
  1942. $c_deviceUsed = "(client.most_recent_cellular_bp_measurement_at IS NOT NULL OR client.most_recent_cellular_weight_measurement_at IS NOT NULL)";
  1943. $c_lt20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp < 1200";
  1944. $c_gte20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp >= 1200";
  1945. switch ($rc) {
  1946. case 2:
  1947. $conditions = [$c_enrolledInRPM];
  1948. break;
  1949. case 3:
  1950. $conditions = [$c_enrolledInRPM, $c_hasDevice];
  1951. break;
  1952. case 4:
  1953. $conditions = [$c_enrolledInRPM, $c_hasDevice, ($rc2 == 1 ? $c_lastVisitBefore90Days : $c_lastVisitWithin90Days)];
  1954. break;
  1955. case 5:
  1956. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, ($rc2 == 1 ? $c_notSpokenToThisMonth : $c_spokenToThisMonth)];
  1957. break;
  1958. case 6:
  1959. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_hasUnstamped : $c_hasNoUnstamped)];
  1960. break;
  1961. case 7:
  1962. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_lt16MeasurementDays : $c_gte16MeasurementDays)];
  1963. break;
  1964. case 10:
  1965. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, $c_gte16MeasurementDays, ($rc2 == 1 ? $c_lt20BillingMinutes : $c_gte20BillingMinutes)];
  1966. break;
  1967. case 8:
  1968. $conditions = [$c_enrolledInRPM, $c_subscribedToSMS];
  1969. break;
  1970. case 9:
  1971. $conditions = [$c_enrolledInRPM, $c_deviceUsed];
  1972. break;
  1973. }
  1974. return $conditions;
  1975. }
  1976. public function remoteMonitoringMeasurements(Request $request, CareMonth $careMonth) {
  1977. $performer = $this->performer();
  1978. $measurements = DB::select(
  1979. DB::raw(
  1980. "
  1981. SELECT measurement.label,
  1982. measurement.ts,
  1983. measurement.effective_date,
  1984. measurement.sbp_mm_hg,
  1985. measurement.dbp_mm_hg,
  1986. measurement.value_pulse,
  1987. measurement.value_irregular,
  1988. measurement.numeric_value,
  1989. measurement.value,
  1990. measurement.uid,
  1991. client.name_first,
  1992. client.name_last,
  1993. client.mcp_pro_id,
  1994. client.default_na_pro_id,
  1995. client.rmm_pro_id,
  1996. client.rme_pro_id
  1997. FROM measurement RIGHT JOIN client on measurement.client_id = client.id
  1998. WHERE
  1999. client.id = {$careMonth->client_id}
  2000. AND measurement.label IS NOT NULL
  2001. AND measurement.label NOT IN ('SBP', 'DBP')
  2002. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  2003. AND measurement.is_removed IS FALSE
  2004. AND measurement.client_bdt_measurement_id IS NOT NULL
  2005. AND measurement.care_month_id = {$careMonth->id}
  2006. AND (
  2007. (client.mcp_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_mcp IS FALSE)
  2008. OR (client.rmm_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_rmm IS FALSE)
  2009. OR (client.rme_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_rme IS FALSE)
  2010. OR (client.default_na_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_non_hcp IS FALSE)
  2011. )
  2012. ORDER BY ts DESC
  2013. "
  2014. )
  2015. );
  2016. return view('app.practice-management.remote-monitoring-measurements', compact('careMonth', 'measurements'));
  2017. }
  2018. public function billMatrix(Request $request)
  2019. {
  2020. $bClients = [];
  2021. $bHCPPros = [];
  2022. $bNAPros = [];
  2023. $filters = [];
  2024. $filters['client'] = $request->input('client');
  2025. $filters['service'] = $request->input('service');
  2026. $filters['hcp'] = $request->input('hcp');
  2027. $filters['hcp_paid'] = $request->input('hcp_paid');
  2028. $filters['expected_op'] = $request->input('expected_op');
  2029. $filters['expected_value'] = $request->input('expected_value');
  2030. $filters['paid_op'] = $request->input('paid_op');
  2031. $filters['paid_value'] = $request->input('paid_value');
  2032. $filters['bal_post_date_op'] = $request->input('bal_post_date_op');
  2033. $filters['bal_post_date_value'] = $request->input('bal_post_date_value');
  2034. $filters['hcp_sign'] = $request->input('hcp_sign');
  2035. $filters['verified'] = $request->input('verified');
  2036. $filters['cancelled'] = $request->input('cancelled');
  2037. $bills = Bill::orderBy('effective_date')->paginate();
  2038. return view('app.practice-management.bill-matrix', compact('bills', 'bClients', 'bHCPPros', 'filters'));
  2039. }
  2040. public function medicarePartBClaims(Request $request)
  2041. {
  2042. $medicarePartBOnly = $request->get("medicare_part_b");
  2043. $allClaims = Claim::where('was_submitted', false)->orWhere('was_submitted', null)->orderBy('created_at', 'desc')->get();
  2044. //Only medicare claims
  2045. $claims = [];
  2046. foreach ($allClaims as $claim) {
  2047. if ($claim->client != null && $claim->client->getPrimaryCoverageStatus() == 'YES' && !$claim->edi) {
  2048. $claims[] = $claim;
  2049. }
  2050. }
  2051. $claimEDIs = ClaimEDI::all();
  2052. return view('app.practice-management.medicare-partb-claims', compact('claims', 'claimEDIs'));
  2053. }
  2054. // Generate PDF
  2055. public function downloadClaims()
  2056. {
  2057. $claims = Claim::where('was_submitted', false)->orWhere('was_submitted', null)->orderBy('created_at', 'desc')->limit(100)->get();
  2058. view()->share('claims', $claims);
  2059. $pdf = PDF::loadView('app.practice-management.claims-pdf', $claims);
  2060. return $pdf->download('pdf_file.pdf');
  2061. }
  2062. public function tickets(Request $request, $proUid = null)
  2063. {
  2064. $tickets = Ticket::orderBy('created_at', 'desc')->paginate();
  2065. return view('app.practice-management.tickets', compact('tickets'));
  2066. }
  2067. public function supplyOrders(Request $request)
  2068. {
  2069. // counts
  2070. $counts = $this->getSupplyOrderCounts();
  2071. // so clients
  2072. $soClientIDs = DB::table('supply_order')->select('client_id')->distinct()->get()->toArray();
  2073. $soClientIDs = array_map(function ($_x) {
  2074. return $_x->client_id;
  2075. }, $soClientIDs);
  2076. $soClients = Client::whereIn('id', $soClientIDs)->get();
  2077. // so products
  2078. $soProductIDs = DB::table('supply_order')->select('product_id')->distinct()->get()->toArray();
  2079. $soProductIDs = array_map(function ($_x) {
  2080. return $_x->product_id;
  2081. }, $soProductIDs);
  2082. $soProducts = Product::whereIn('id', $soProductIDs)->get();
  2083. $filters = [];
  2084. $filters['client'] = $request->input('client');
  2085. $filters['product'] = $request->input('product');
  2086. $filters['reason'] = $request->input('reason');
  2087. $filters['cu_memo'] = $request->input('cu_memo');
  2088. $filters['pro_sign'] = $request->input('pro_sign');
  2089. $filters['client_sign'] = $request->input('client_sign');
  2090. $filters['shipment'] = $request->input('shipment');
  2091. $filters['lot_number'] = $request->input('lot_number');
  2092. $filters['imei'] = $request->input('imei');
  2093. $filters['cancelled'] = $request->input('cancelled');
  2094. $supplyOrders = SupplyOrder::where('id', '>', 0);
  2095. // apply filters
  2096. if ($filters['client']) $supplyOrders->where('client_id', $filters['client']);
  2097. if ($filters['product']) $supplyOrders->where('product_id', $filters['product']);
  2098. if ($filters['reason']) $supplyOrders->where('reason', 'ILIKE', '%' . $filters['reason'] . '%');
  2099. if ($filters['cu_memo']) $supplyOrders->where('cu_memo', 'ILIKE', '%' . $filters['cu_memo'] . '%');
  2100. if ($filters['pro_sign']) $supplyOrders->where('is_signed_by_pro', ($filters['pro_sign'] === 'signed'));
  2101. if ($filters['client_sign']) {
  2102. if ($filters['client_sign'] === 'signed')
  2103. $supplyOrders->where('is_signed_by_client', true);
  2104. elseif ($filters['client_sign'] === 'waived')
  2105. $supplyOrders->where('is_client_signature_waived', true);
  2106. else
  2107. $supplyOrders->where('is_client_signature_waived', false)->where('is_signed_by_client', false);
  2108. }
  2109. if ($filters['shipment']) {
  2110. if ($filters['shipment'] === 'not_cleared_for_shipment')
  2111. $supplyOrders->whereNull('shipment_id')->where('is_cleared_for_shipment', false);
  2112. elseif ($filters['shipment'] === 'cleared_for_shipment')
  2113. $supplyOrders->whereNull('shipment_id')->where('is_cleared_for_shipment', true);
  2114. else
  2115. $supplyOrders
  2116. ->whereNotNull('shipment_id')
  2117. ->whereRaw('(SELECT status FROM shipment WHERE id = shipment_id LIMIT 1) = ?', [$filters['shipment']]);
  2118. }
  2119. if ($filters['lot_number']) $supplyOrders->where('lot_number', 'ILIKE', '%' . $filters['lot_number'] . '%');
  2120. if ($filters['imei']) $supplyOrders->where('imei', 'ILIKE', '%' . $filters['imei'] . '%');
  2121. if ($filters['cancelled']) $supplyOrders->where('is_cancelled', ($filters['cancelled'] === 'cancelled'));
  2122. $supplyOrders = $supplyOrders->orderBy('created_at', 'desc')->paginate();
  2123. return view('app.practice-management.supply-orders',
  2124. compact('supplyOrders', 'filters',
  2125. 'soClients', 'soProducts', 'counts'
  2126. )
  2127. );
  2128. }
  2129. public function shipments(Request $request, $filter = null)
  2130. {
  2131. // counts
  2132. $counts = $this->getShipmentCounts();
  2133. // so clients
  2134. $shClientIDs = DB::table('shipment')->select('client_id')->distinct()->get()->toArray();
  2135. $shClientIDs = array_map(function ($_x) {
  2136. return $_x->client_id;
  2137. }, $shClientIDs);
  2138. $shClients = Client::whereIn('id', $shClientIDs)->get();
  2139. $shipments = Shipment::where('id', '>', 0);
  2140. $filters = [];
  2141. $filters['client'] = $request->input('client');
  2142. $filters['courier'] = $request->input('courier');
  2143. $filters['tracking_num'] = $request->input('tracking_num');
  2144. $filters['label'] = $request->input('label');
  2145. $filters['status'] = $request->input('status');
  2146. $filters['cancelled'] = $request->input('cancelled');
  2147. if ($filters['client']) $shipments->where('client_id', $filters['client']);
  2148. if ($filters['courier']) $shipments->where('courier', 'ILIKE', '%' . $filters['courier'] . '%');
  2149. if ($filters['tracking_num']) $shipments->where('tracking_number', 'ILIKE', '%' . $filters['tracking_num'] . '%');
  2150. if ($filters['label']) {
  2151. if ($filters['label'] === 'yes')
  2152. $shipments->whereNotNull('label_system_file_id');
  2153. else
  2154. $shipments->whereNull('label_system_file_id');
  2155. }
  2156. if ($filters['status']) $shipments->where('status', $filters['status']);
  2157. if ($filters['cancelled']) $shipments->where('is_cancelled', ($filters['cancelled'] === 'cancelled'));
  2158. $shipments = $shipments->orderBy('created_at', 'desc')->paginate();
  2159. return view('app.practice-management.shipments', compact('shipments', 'filters', 'shClients', 'counts'));
  2160. }
  2161. public function cellularMeasurements(Request $request)
  2162. {
  2163. $measurements = Measurement::orderBy('ts', 'desc')->whereNotNull('ts')->paginate();
  2164. return view('app.practice-management.cellular-measurements', compact('measurements'));
  2165. }
  2166. // v2 supply-orders & shipments management (wh)
  2167. public function supplyOrdersReadyToShip(Request $request)
  2168. {
  2169. $counts = $this->getSupplyOrderCounts();
  2170. $supplyOrders = SupplyOrder
  2171. ::where('is_cleared_for_shipment', true)
  2172. ->where('is_cancelled', false)
  2173. ->whereNull('shipment_id')
  2174. ->join('client', 'client.id', '=', 'supply_order.client_id')
  2175. ->orderBy('client.name_last', 'ASC')
  2176. ->orderBy('client.name_first', 'ASC')
  2177. ->orderBy('supply_order.client_id', 'ASC')
  2178. ->orderBy('supply_order.mailing_address_full', 'ASC')
  2179. ->orderBy('supply_order.created_at', 'ASC')
  2180. ->select('supply_order.*')
  2181. ->paginate();
  2182. return view('app.practice-management.supply-orders-ready-to-ship', compact('supplyOrders', 'counts'));
  2183. }
  2184. public function supplyOrdersShipmentUnderway(Request $request)
  2185. {
  2186. $counts = $this->getSupplyOrderCounts();
  2187. $supplyOrders = SupplyOrder
  2188. ::where('is_cancelled', false)
  2189. ->whereNotNull('shipment_id')
  2190. ->orderBy('client_id', 'ASC')
  2191. ->orderBy('mailing_address_full', 'ASC')
  2192. ->orderBy('created_at', 'ASC')
  2193. ->paginate();
  2194. return view('app.practice-management.supply-orders-shipment-underway', compact('supplyOrders', 'counts'));
  2195. }
  2196. public function supplyOrdersHanging(Request $request)
  2197. {
  2198. $counts = $this->getSupplyOrderCounts();
  2199. $supplyOrders = SupplyOrder
  2200. ::select('supply_order.*')
  2201. ->leftJoin('shipment', function($join) {
  2202. $join->on('supply_order.shipment_id', '=', 'shipment.id');
  2203. })
  2204. ->where('shipment.status', 'CANCELLED')
  2205. ->where('supply_order.is_cancelled', false)
  2206. ->orderBy('supply_order.client_id', 'ASC')
  2207. ->orderBy('supply_order.mailing_address_full', 'ASC')
  2208. ->orderBy('supply_order.created_at', 'ASC')
  2209. ->paginate();
  2210. return view('app.practice-management.supply-orders-hanging', compact('supplyOrders', 'counts'));
  2211. }
  2212. public function supplyOrdersCancelledButUnacknowledged(Request $request)
  2213. {
  2214. $supplyOrders = SupplyOrder::where('signed_by_pro_id', $this->performer()->pro->id)
  2215. ->where('is_cancelled', true)
  2216. ->where('is_cancellation_acknowledged', false)
  2217. ->orderBy('created_at', 'desc')
  2218. ->paginate();
  2219. return view('app.practice-management.supply-orders-cancelled-but-unacknowledged', compact('supplyOrders'));
  2220. }
  2221. public function supplyOrdersUnsigned(Request $request)
  2222. {
  2223. $supplyOrders = SupplyOrder
  2224. ::where('is_cancelled', false)
  2225. ->where('is_signed_by_pro', false)
  2226. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$this->performer()->pro->id])
  2227. ->orderBy('created_at', 'desc')
  2228. ->paginate();
  2229. return view('app.practice-management.supply-orders-unsigned', compact('supplyOrders'));
  2230. }
  2231. private function getSupplyOrderCounts()
  2232. {
  2233. return [
  2234. "supplyOrders" => SupplyOrder::count(),
  2235. "supplyOrdersReadyToShip" => SupplyOrder
  2236. ::where('is_cleared_for_shipment', true)
  2237. ->where('is_cancelled', false)
  2238. ->whereNull('shipment_id')->count(),
  2239. "supplyOrdersShipmentUnderway" => SupplyOrder
  2240. ::where('is_cancelled', false)
  2241. ->whereNotNull('shipment_id')->count(),
  2242. "supplyOrdersHanging" => SupplyOrder
  2243. ::leftJoin('shipment', function($join) {
  2244. $join->on('supply_order.shipment_id', '=', 'shipment.id');
  2245. })
  2246. ->where('shipment.status', 'CANCELLED')
  2247. ->where('supply_order.is_cancelled', false)
  2248. ->count(),
  2249. ];
  2250. }
  2251. public function shipmentsReadyToPrint(Request $request)
  2252. {
  2253. $counts = $this->getShipmentCounts();
  2254. $shipments = Shipment
  2255. ::where('is_cancelled', false)
  2256. ->where('status', 'CREATED')
  2257. ->orderBy('created_at', 'ASC')
  2258. ->paginate();
  2259. return view('app.practice-management.shipments-ready-to-print', compact('shipments', 'counts'));
  2260. }
  2261. public function shipmentsShipmentUnderway(Request $request)
  2262. {
  2263. $counts = $this->getShipmentCounts();
  2264. $shipments = Shipment
  2265. ::where('is_cancelled', false)
  2266. ->where('status', 'PRINTED')
  2267. ->orderBy('created_at', 'ASC')
  2268. ->paginate();
  2269. return view('app.practice-management.shipments-waiting-for-picker', compact('shipments', 'counts'));
  2270. }
  2271. private function getShipmentCounts()
  2272. {
  2273. return [
  2274. "shipments" => Shipment::count(),
  2275. "shipmentsReadyToPrint" => Shipment
  2276. ::where('is_cancelled', false)
  2277. ->where('status', 'CREATED')
  2278. ->count(),
  2279. "shipmentsWaitingForPicker" => Shipment
  2280. ::where('is_cancelled', false)
  2281. ->where('status', 'PRINTED')
  2282. ->count()
  2283. ];
  2284. }
  2285. public function shipment(Request $request, Shipment $shipment)
  2286. {
  2287. return view('app.practice-management.shipment', compact('shipment'));
  2288. }
  2289. public function shipmentsMultiPrint(Request $request, $ids)
  2290. {
  2291. $ids = array_map(function ($_x) {
  2292. return intval($_x);
  2293. }, explode("|", $ids));
  2294. $shipments = Shipment::whereIn('id', $ids)->get();
  2295. return view('app.practice-management.shipments-multi-print', compact('shipments'));
  2296. }
  2297. public function patientClaimSummary(Request $request, $proUid = null)
  2298. {
  2299. $notesTotal = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE"))[0]->count;
  2300. $notesTotalWithBillingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE AND is_bill_closed IS TRUE"))[0]->count;
  2301. $notesTotalWithClaimingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE AND is_claim_closed IS TRUE"))[0]->count;
  2302. $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;
  2303. $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;
  2304. $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;
  2305. $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;
  2306. $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;
  2307. $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;
  2308. $performerPro = $this->performer->pro;
  2309. $allPros = [];
  2310. if ($performerPro->pro_type == 'ADMIN') {
  2311. $allPros = Pro::all();
  2312. } else {
  2313. $allPros = [$performerPro];
  2314. }
  2315. //Patient | MCP | # Notes Total | # Notes without Billing Closed | # Notes without Claiming Closed
  2316. $patientsQuery = Client::where('is_dummy', '=', false)
  2317. ->whereNull('shadow_pro_id')
  2318. ->select('id', 'uid', 'name_first', 'name_last', 'mcp_pro_id', 'is_part_b_primary', 'medicare_advantage_plan',
  2319. DB::raw("(SELECT name_first||' '||name_last FROM pro where pro.id = client.mcp_pro_id) as mcp"),
  2320. DB::raw("(SELECT uid FROM pro where pro.id = mcp_pro_id) as mcp_pro_uid"),
  2321. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id) as notes_total"),
  2322. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id AND is_bill_closed IS NOT true) as notes_without_billing_closed"),
  2323. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id AND is_claim_closed IS NOT true) as notes_without_claiming_closed")
  2324. )->orderBy('is_part_b_primary', 'asc')->orderBy('notes_without_claiming_closed', 'desc');
  2325. if ($proUid) {
  2326. $mcpPro = Pro::where('uid', $proUid)->first();
  2327. if ($mcpPro) {
  2328. $patientsQuery->where('client.mcp_pro_id', '=', $mcpPro->id);
  2329. }
  2330. }
  2331. $patientsQuery->whereRaw('(SELECT COUNT(*) FROM note where note.client_id = client.id) > 0');
  2332. $patientsQuery->orderBy('notes_total', 'DESC');
  2333. $patients = $patientsQuery->paginate(50);
  2334. $data = [
  2335. 'patients' => $patients,
  2336. 'proUid' => $proUid,
  2337. 'allPros' => $allPros,
  2338. 'notesTotal' => $notesTotal,
  2339. 'notesTotalWithBillingClosed' => $notesTotalWithBillingClosed,
  2340. 'notesTotalWithClaimingClosed' => $notesTotalWithClaimingClosed,
  2341. 'notes3rdPartyTotal' => $notes3rdPartyTotal,
  2342. 'notes3rdPartyTotalWithBillingClosed' => $notes3rdPartyTotalWithBillingClosed,
  2343. 'notes3rdPartyTotalWithClaimingClosed' => $notes3rdPartyTotalWithClaimingClosed,
  2344. 'patientsTotal' => $patientsTotal,
  2345. 'patientsTotalWithBillingClosed' => $patientsTotalWithBillingClosed,
  2346. 'patientsTotalWithClaimingClosed' => $patientsTotalWithClaimingClosed
  2347. ];
  2348. return view('app.practice-management.patient-claim-summary', $data);
  2349. }
  2350. public function claims(Request $request){
  2351. $status = $request->get('status');
  2352. $claims = [];
  2353. if(!$status){
  2354. $claims = Claim::orderBy('created_at', 'DESC')->paginate();
  2355. }else{
  2356. $claims = Claim::where('status', $status)->orderBy('created_at', 'DESC')->paginate();
  2357. }
  2358. return view('app.practice-management.claims', compact('claims', 'status'));
  2359. }
  2360. public function processClaims(Request $request) {
  2361. $status = '';
  2362. $q = $request->input('q') ? $request->input('q') : '';
  2363. $from = $request->input('from') ? $request->input('from') : '1900-01-01';
  2364. $to = $request->input('to') ? $request->input('to') : '2100-01-01';
  2365. $params = [
  2366. 'q' => '%' . $q . '%',
  2367. 'from' => $from,
  2368. 'to' => $to
  2369. ];
  2370. $hcpPro = $request->input('hcp') ? Pro::where('uid', $request->input('hcp'))->first() : null;
  2371. if($hcpPro) {
  2372. $params['hcp'] = $hcpPro->id;
  2373. }
  2374. $claims = DB::select(DB::raw("
  2375. SELECT claim.uid AS uid,
  2376. DATE(claim.created_at) AS created,
  2377. claim.status,
  2378. client.uid AS client_uid,
  2379. client.cell_number AS client_phone,
  2380. client.phone_home AS client_phone_home,
  2381. (client.name_last || ' ' || client.name_first) AS client ,
  2382. client.chart_number AS client_chart_number,
  2383. cp.id AS claim_pro_id,
  2384. (cp.name_last || ' ' || cp.name_first) AS claim_pro,
  2385. sp.id AS status_pro_id,
  2386. (sp.name_last || ' ' || sp.name_first) AS status_pro,
  2387. note.uid AS note_uid,
  2388. note.method,
  2389. note.new_or_fu_or_na,
  2390. care_month.uid AS care_month_uid,
  2391. care_month.start_date as care_month_start__date,
  2392. -- claim.status_updated_at,
  2393. (DATE(claim.status_updated_at) || ' ' ||
  2394. LPAD(EXTRACT(hour FROM claim.status_updated_at)::text, 2, '0') || ':' ||
  2395. LPAD(EXTRACT(minute FROM claim.status_updated_at)::text, 2, '0')) AS status_updated_at,
  2396. (SELECT string_agg(claim_line.cpt, ', ') FROM claim_line where claim_id = claim.id) AS cpts,
  2397. (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,
  2398. ROUND(claim.expected_total, 3) as expected_total
  2399. FROM claim
  2400. join client on claim.client_id = client.id
  2401. join pro cp on claim.pro_id = cp.id
  2402. left join note on claim.note_id = note.id
  2403. left join care_month on claim.care_month_id = care_month.id
  2404. left join app_session on claim.status_updated_by_session_id = app_session.id
  2405. left join pro sp on app_session.pro_id = sp.id
  2406. --WHERE claim.status IS NULL OR claim.status = 'NEW'
  2407. WHERE (claim.status is NULL OR claim.status NOT IN ('CANCELLED', 'ABANDONED'" . ($request->input('show-submitted') ? "" : ", 'SUBMITTED'") . "))
  2408. -- AND claim.current_version_id IS NOT NULL
  2409. AND (client.name_first ILIKE :q OR
  2410. client.name_last ILIKE :q OR
  2411. client.chart_number ILIKE :q OR
  2412. client.mcn ILIKE :q)
  2413. AND (claim.created_at >= :from AND claim.created_at <= :to)
  2414. " . ($hcpPro ? "AND claim.pro_id = :hcp" : '') . "
  2415. AND claim.id IN (SELECT mb_claim.claim_id FROM mb_claim)
  2416. ORDER BY claim.created_at DESC
  2417. --OFFSET 0 LIMIT 15
  2418. "), $params);
  2419. if($request->input('json')) {
  2420. return json_encode($claims);
  2421. }
  2422. return view('app.practice-management.process-claims', compact('claims', 'status'));
  2423. }
  2424. public function rmLaunchAndClean(Request $request) {
  2425. $keyNumbers = [];
  2426. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_40'] = CareMonth::where('is_bill_closed', false)
  2427. ->whereNotNull('company_pro_id')
  2428. ->whereNotNull('company_pro_payer_id')
  2429. ->whereNotNull('company_location_id')
  2430. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2431. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  2432. ->where('rm_total_time_in_seconds', '>=', 4200) // at 4200 (70 minutes, it becomes eligible for plus40)
  2433. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2434. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2435. ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS TRUE OR has_mcp_rm_interacted_by_note IS TRUE )')
  2436. ->count();
  2437. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_40_ifHadInteraction'] = CareMonth::where('is_bill_closed', false)
  2438. ->whereNotNull('company_pro_id')
  2439. ->whereNotNull('company_pro_payer_id')
  2440. ->whereNotNull('company_location_id')
  2441. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2442. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  2443. ->where('rm_total_time_in_seconds', '>=', 4200) // at 4200 (70 minutes, it becomes eligible for plus40)
  2444. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2445. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2446. ->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 )')
  2447. ->count();
  2448. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_20'] = CareMonth::where('is_bill_closed', false)
  2449. ->whereNotNull('company_pro_id')
  2450. ->whereNotNull('company_pro_payer_id')
  2451. ->whereNotNull('company_location_id')
  2452. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2453. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  2454. ->where('rm_total_time_in_seconds', '<', 4200)
  2455. ->where('rm_total_time_in_seconds', '>=', 3000) // at 3000 (50 minutes, it becomes eligible for plus20)
  2456. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2457. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2458. ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS TRUE OR has_mcp_rm_interacted_by_note IS TRUE)')
  2459. ->count();
  2460. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_20_ifHadInteraction'] = CareMonth::where('is_bill_closed', false)
  2461. ->whereNotNull('company_pro_id')
  2462. ->whereNotNull('company_pro_payer_id')
  2463. ->whereNotNull('company_location_id')
  2464. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2465. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  2466. ->where('rm_total_time_in_seconds', '<', 4200)
  2467. ->where('rm_total_time_in_seconds', '>=', 3000) // at 3000 (50 minutes, it becomes eligible for plus20)
  2468. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2469. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2470. ->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 )')
  2471. ->count();
  2472. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP'] = CareMonth::where('is_bill_closed', false)
  2473. ->whereNotNull('company_pro_id')
  2474. ->whereNotNull('company_pro_payer_id')
  2475. ->whereNotNull('company_location_id')
  2476. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2477. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  2478. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2479. ->whereRaw('(rm_total_time_in_seconds < 3000 OR (rm_total_time_in_seconds >= 3000 AND is_rm_interaction_waived IS TRUE))')
  2480. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2481. ->count();
  2482. $keyNumbers['careMonthsEligibleForBillGeneration_RMB'] = CareMonth::where('is_bill_closed', false)
  2483. ->whereNotNull('company_pro_id')
  2484. ->whereNotNull('company_pro_payer_id')
  2485. ->whereNotNull('company_location_id')
  2486. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2487. ->whereRaw('is_rm_time_waived IS TRUE')
  2488. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2489. ->count();
  2490. $keyNumbers['careMonthsWith16OrMoreMeasurementDays'] = CareMonth::where('is_bill_closed', false)
  2491. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2492. ->count();
  2493. $careMonthsWith16PlusMeasurements = CareMonth::where('is_bill_closed', false)
  2494. ->where('number_of_days_with_remote_measurements', '>=', 16 )->get();
  2495. return view('app.practice-management.rm-launch-and-clean', compact('keyNumbers', 'careMonthsWith16PlusMeasurements'));
  2496. }
  2497. public function processNotes(Request $request) {
  2498. $mode = $request->input('mode') ? $request->input('mode') : '1';
  2499. if(($mode < 1 || $mode > 5) && $mode != 8) $mode = 1;
  2500. DB::enableQueryLog(); // Enable query log
  2501. $test = Note::where('is_cancelled', false)
  2502. ->where('is_signed_by_hcp', true)
  2503. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  2504. ->whereNull('current_note_pickup_for_processing_id')
  2505. ->where('is_billing_marked_done', true)
  2506. ->where('is_bill_closed', true)
  2507. ->where('is_claim_closed', true)
  2508. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  2509. ->count();
  2510. // var_dump($test);
  2511. // dd(DB::getQueryLog()); // Show results of log
  2512. // exit;
  2513. $counts = [
  2514. "picked" => Note::where('is_cancelled', false)
  2515. ->whereNotNull('current_note_pickup_for_processing_id')
  2516. ->count(),
  2517. "bad" => Note::where('is_cancelled', false)
  2518. ->whereRaw("((detail_json)::json->>'isBad' = 'true')")
  2519. ->count(),
  2520. // not yet signed
  2521. "mode-1" => Note::where('is_cancelled', false)
  2522. ->where('is_signed_by_hcp', false)
  2523. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2524. // ->whereNull('current_note_pickup_for_processing_id')
  2525. ->count(),
  2526. // billing not marked done
  2527. "mode-2" => Note::where('is_cancelled', false)
  2528. ->where('is_signed_by_hcp', true)
  2529. //->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2530. // ->whereNull('current_note_pickup_for_processing_id')
  2531. ->where('is_billing_marked_done', false)
  2532. ->count(),
  2533. // billing not closed
  2534. "mode-3" => Note::where('is_cancelled', false)
  2535. ->where('is_signed_by_hcp', true)
  2536. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2537. // ->whereNull('current_note_pickup_for_processing_id')
  2538. ->where('is_billing_marked_done', true)
  2539. ->where('is_bill_closed', false)
  2540. ->count(),
  2541. // claiming not closed
  2542. "mode-4" => Note::where('is_cancelled', false)
  2543. ->where('is_signed_by_hcp', true)
  2544. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2545. // ->whereNull('current_note_pickup_for_processing_id')
  2546. ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true' OR ((detail_json)::json->>'isGood')::text IS NULL)")
  2547. ->where('is_billing_marked_done', true)
  2548. ->where('is_bill_closed', true)
  2549. ->where('is_claim_closed', false)
  2550. ->count(),
  2551. // has unsubmitted claims
  2552. "mode-5" => Note::where('is_cancelled', false)
  2553. /*->where('is_signed_by_hcp', true)
  2554. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2555. ->whereNull('current_note_pickup_for_processing_id')
  2556. ->where('is_billing_marked_done', true)
  2557. ->where('is_bill_closed', true)
  2558. ->where('is_claim_closed', true)
  2559. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0")
  2560. */
  2561. ->where('is_signed_by_hcp', true)
  2562. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2563. // ->whereNull('current_note_pickup_for_processing_id')
  2564. ->where('is_billing_marked_done', true)
  2565. ->where('is_bill_closed', true)
  2566. // ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true')")
  2567. ->where('is_claim_closed', true)
  2568. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0)")
  2569. ->count(),
  2570. // has unsubmitted claims MARKED GOOD!
  2571. "mode-8" => Note::where('is_cancelled', false)
  2572. ->where('is_signed_by_hcp', true)
  2573. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  2574. ->whereNull('current_note_pickup_for_processing_id')
  2575. ->where('is_billing_marked_done', true)
  2576. ->where('is_bill_closed', true)
  2577. ->where('is_claim_closed', false)
  2578. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  2579. ->count(),
  2580. // all good
  2581. "mode-6" => Note::where('is_cancelled', false)
  2582. ->where('is_signed_by_hcp', true)
  2583. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2584. // ->whereNull('current_note_pickup_for_processing_id')
  2585. ->where('is_billing_marked_done', true)
  2586. ->where('is_bill_closed', true)
  2587. ->where('is_claim_closed', true)
  2588. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id) > 0)")
  2589. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  2590. ->count(),
  2591. "mode-7" => Note::where('is_cancelled', false)
  2592. ->whereRaw("(detail_json)::json->>'isBad' = 'true'")
  2593. ->count(),
  2594. ];
  2595. return view('app.practice-management.process-notes', compact('mode', 'counts'));
  2596. }
  2597. public function notesProcessingCenter(Request $request) {
  2598. $notes = Note::where('is_cancelled', false);
  2599. // filters
  2600. $proUid = $request->input('proUid');
  2601. if($proUid) {
  2602. $fPro = Pro::where('uid', $proUid)->first();
  2603. if($fPro) {
  2604. $notes = $notes->where('hcp_pro_id', $fPro->id);
  2605. }
  2606. }
  2607. $proSigned = $request->input('proSigned');
  2608. switch($proSigned) {
  2609. case 'yes': $notes = $notes->where('is_signed_by_hcp', true); break;
  2610. case 'no': $notes = $notes->where('is_signed_by_hcp', '!=', true); break;
  2611. }
  2612. $billingMarkedDone = $request->input('billingMarkedDone');
  2613. switch($billingMarkedDone) {
  2614. case 'yes': $notes = $notes->where('is_billing_marked_done', true); break;
  2615. case 'no': $notes = $notes->where('is_billing_marked_done', '!=', true); break;
  2616. }
  2617. $billingClosed = $request->input('billingClosed');
  2618. switch($billingClosed) {
  2619. case 'yes': $notes = $notes->where('is_bill_closed', true); break;
  2620. case 'no': $notes = $notes->where('is_bill_closed', '!=', true); break;
  2621. }
  2622. $claimingClosed = $request->input('claimingClosed');
  2623. switch($claimingClosed) {
  2624. case 'yes': $notes = $notes->where('is_claim_closed', true); break;
  2625. case 'no': $notes = $notes->where('is_claim_closed', '!=', true); break;
  2626. }
  2627. $allClaimsSubmitted = $request->input('allClaimsSubmitted');
  2628. if($allClaimsSubmitted) {
  2629. // TODO
  2630. }
  2631. $goodBad = $request->input('goodBad');
  2632. switch($goodBad) {
  2633. case 'good': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' = 'false'"); break;
  2634. case 'bad': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' = 'true'"); break;
  2635. case 'unclassified': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' is null"); break;
  2636. }
  2637. $startDate = $request->input('startDate');
  2638. if($startDate) {
  2639. $notes = $notes->where('effective_dateest', '>=', $startDate);
  2640. }
  2641. $endDate = $request->input('endDate');
  2642. if($endDate) {
  2643. $notes = $notes->where('effective_dateest', '<=', $endDate);
  2644. }
  2645. $mcPartB = $request->input('mcPartB');
  2646. if($mcPartB) {
  2647. // TODO
  2648. }
  2649. $notes = $notes->orderBy('effective_dateest')->paginate(10);
  2650. return view('app.practice-management.notes-processing-center', compact('notes'));
  2651. }
  2652. public function getNextNote(Request $request, $mode)
  2653. {
  2654. $note = null;
  2655. switch (+$mode) {
  2656. case 1:
  2657. $note = Note::where('is_cancelled', false)
  2658. ->where('is_signed_by_hcp', false)
  2659. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2660. ->whereNull('current_note_pickup_for_processing_id')
  2661. ->orderBy('effective_dateest', 'DESC')
  2662. ->first();
  2663. break;
  2664. case 2:
  2665. $note = Note::where('is_cancelled', false)
  2666. ->where('is_signed_by_hcp', true)
  2667. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2668. ->whereNull('current_note_pickup_for_processing_id')
  2669. ->where('is_billing_marked_done', false)
  2670. ->orderBy('effective_dateest', 'DESC')
  2671. ->first();
  2672. break;
  2673. case 3:
  2674. $note = Note::where('is_cancelled', false)
  2675. ->where('is_signed_by_hcp', true)
  2676. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2677. ->whereNull('current_note_pickup_for_processing_id')
  2678. ->where('is_billing_marked_done', true)
  2679. ->where('is_bill_closed', false)
  2680. ->orderBy('effective_dateest', 'DESC')
  2681. ->first();
  2682. break;
  2683. case 4: // claiming not closed
  2684. DB::enableQueryLog(); // Enable query log
  2685. $note = Note::where('is_cancelled', false)
  2686. ->where('is_signed_by_hcp', true)
  2687. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2688. ->whereNull('current_note_pickup_for_processing_id')
  2689. ->where('is_billing_marked_done', true)
  2690. ->where('is_bill_closed', true)
  2691. ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true' OR ((detail_json)::json->>'isGood')::text IS NULL)")
  2692. ->where('is_claim_closed', false)
  2693. ->orderBy('effective_dateest', 'DESC')
  2694. ->first();
  2695. // DB::enableQueryLog(); // Enable query log
  2696. // Your Eloquent query executed by using get()
  2697. // dd(DB::getQueryLog()); // Show results of log
  2698. break;
  2699. case 5:
  2700. $note = Note::where('is_cancelled', false)
  2701. ->where('is_signed_by_hcp', true)
  2702. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2703. ->whereNull('current_note_pickup_for_processing_id')
  2704. ->where('is_billing_marked_done', true)
  2705. ->where('is_bill_closed', true)
  2706. ->where('is_claim_closed', true)
  2707. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0")
  2708. ->orderBy('effective_dateest', 'DESC')
  2709. ->first();
  2710. break;
  2711. case 8:
  2712. $note = Note::where('is_cancelled', false)
  2713. ->where('is_signed_by_hcp', true)
  2714. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  2715. ->whereNull('current_note_pickup_for_processing_id')
  2716. ->where('is_billing_marked_done', true)
  2717. ->where('is_bill_closed', true)
  2718. ->where('is_claim_closed', false)
  2719. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  2720. ->orderBy('effective_dateest', 'DESC')
  2721. ->first();
  2722. break;
  2723. }
  2724. if($note) {
  2725. $note->client_uid = $note->client->uid;
  2726. }
  2727. return json_encode($note);
  2728. }
  2729. public function pickedNotes(Request $request) {
  2730. $counts = [
  2731. "unpicked" => Note::where('is_cancelled', false)
  2732. ->whereNull('current_note_pickup_for_processing_id')
  2733. ->count(),
  2734. ];
  2735. $notes = Note::where('is_cancelled', false)
  2736. ->whereNotNull('current_note_pickup_for_processing_id')
  2737. ->orderBy('effective_dateest', 'ASC')
  2738. ->paginate();
  2739. return view('app.practice-management.picked-notes', compact('counts', 'notes'));
  2740. }
  2741. public function badNotes(Request $request) {
  2742. $counts = [
  2743. "unpicked" => Note::where('is_cancelled', false)
  2744. ->whereNull('current_note_pickup_for_processing_id')
  2745. ->count(),
  2746. ];
  2747. $notes = Note::where('is_cancelled', false)
  2748. ->whereRaw("(detail_json)::json->>'isBad' = 'true'")
  2749. ->orderBy('effective_dateest', 'ASC')
  2750. ->paginate();
  2751. return view('app.practice-management.bad-notes', compact('counts', 'notes'));
  2752. }
  2753. public function doneNotes(Request $request) {
  2754. $counts = [
  2755. "unpicked" => Note::where('is_cancelled', false)
  2756. ->whereNull('current_note_pickup_for_processing_id')
  2757. ->count(),
  2758. ];
  2759. $notes = Note::where('is_cancelled', false)
  2760. ->where('is_signed_by_hcp', true)
  2761. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2762. ->whereNull('current_note_pickup_for_processing_id')
  2763. ->where('is_billing_marked_done', true)
  2764. ->where('is_bill_closed', true)
  2765. ->where('is_claim_closed', true)
  2766. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id) > 0")
  2767. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0")
  2768. ->orderBy('effective_dateest', 'ASC')
  2769. ->paginate();
  2770. return view('app.practice-management.done-notes', compact('counts', 'notes'));
  2771. }
  2772. public function currentMbClaim(Request $request, $claimUid) {
  2773. $claim = Claim::where('uid', $claimUid)->first();
  2774. return json_encode(MBClaim::where('claim_version_id', $claim->currentVersion->id)->where('status', '!=', 'CANCELLED')->first());
  2775. }
  2776. public function currentClaimLines(Request $request, $claimUid) {
  2777. $claim = Claim::where('uid', $claimUid)->first();
  2778. if($request->input('json')) {
  2779. foreach ($claim->lines as $line) {
  2780. $line->expected_total = round($line->expected_total, 3);
  2781. $x = $line->claimLineIcds;
  2782. }
  2783. return json_encode($claim->lines);
  2784. }
  2785. return view('app.practice-management._claim-lines', compact('claim'));
  2786. }
  2787. public function packsMultiPrint(Request $request) {
  2788. $packs = Pack
  2789. ::select('pack.*')
  2790. ->leftJoin('shipment', function($join) {
  2791. $join->on('pack.shipment_id', '=', 'shipment.id');
  2792. })
  2793. ->whereNotIn('shipment.status', ['CANCELLED', 'DISPATCHED'])
  2794. ->where(function ($query) {
  2795. $query->where('pack.status', '<>', 'DELETED')->orWhereNull('pack.status'); // weird, but just the <> isn't working!
  2796. })
  2797. ->whereNotNull('pack.label_system_file_id')
  2798. ->orderBy('pack.created_at', 'ASC')
  2799. ->get();
  2800. return view('app.practice-management.packs-multi-print', compact('packs'));
  2801. }
  2802. public function packsMultiPDF(Request $request, $ids) {
  2803. $ids = array_map(function ($_x) {
  2804. return intval($_x);
  2805. }, explode("|", $ids));
  2806. $packs = Pack::whereIn('id', $ids)->get();
  2807. }
  2808. public function handouts(Request $request) {
  2809. $handouts = Handout::orderBy('display_name')->get();
  2810. return view('app.practice-management.handouts', compact('handouts'));
  2811. }
  2812. private function callJava($request, $endPoint, $data)
  2813. {
  2814. $url = config('stag.backendUrl') . $endPoint;
  2815. $response = Http::asForm()
  2816. ->withHeaders([
  2817. 'sessionKey' => $request->cookie('sessionKey')
  2818. ])
  2819. ->post($url, $data)
  2820. ->body();
  2821. dd($response);
  2822. return $response;
  2823. }
  2824. public function genericBills(Request $request)
  2825. {
  2826. return view('app.practice-management.generic-bills');
  2827. }
  2828. public function billsUnderProcessing(Request $request)
  2829. {
  2830. $bills = Bill::where('is_cancelled', false)
  2831. ->where(function ($query) { // mcp of any client program and program OB pending
  2832. $query
  2833. ->where(function ($_query) {
  2834. $_query->where('hcp_pro_id', $this->pro->id)
  2835. ->where('hcp_expected_payment_amount', '>', 0)
  2836. ->where('has_hcp_been_paid', false)
  2837. ->where('is_signed_by_hcp', true);
  2838. })
  2839. ->orWhere(function ($_query) {
  2840. $_query->where('cm_pro_id', $this->pro->id)
  2841. ->where('cm_expected_payment_amount', '>', 0)
  2842. ->where('has_cm_been_paid', false)
  2843. ->where('is_signed_by_cm', true);
  2844. })
  2845. ->orWhere(function ($_query) {
  2846. $_query->where('rme_pro_id', $this->pro->id)
  2847. ->where('rme_expected_payment_amount', '>', 0)
  2848. ->where('has_rme_been_paid', false)
  2849. ->where('is_signed_by_rme', true);
  2850. })
  2851. ->orWhere(function ($_query) {
  2852. $_query->where('rmm_pro_id', $this->pro->id)
  2853. ->where('rmm_expected_payment_amount', '>', 0)
  2854. ->where('has_rmm_been_paid', false)
  2855. ->where('is_signed_by_rmm', true);
  2856. })
  2857. ->orWhere(function ($_query) {
  2858. $_query->where('generic_pro_id', $this->pro->id)
  2859. ->where('generic_pro_expected_payment_amount', '>', 0)
  2860. ->where('has_generic_pro_been_paid', false)
  2861. ->where('is_signed_by_generic_pro', true);
  2862. });
  2863. })
  2864. ->orderBy('created_at', 'DESC')
  2865. ->paginate();
  2866. return view('app.practice-management.bills-under-processing', compact('bills'));
  2867. }
  2868. public function careMonthReport(Request $request) {
  2869. $m = $request->input('m');
  2870. $y = $request->input('y');
  2871. if(!$m || !$y) {
  2872. $date = date('Y-m-01');
  2873. }
  2874. else {
  2875. $date = date('Y-m-d', strtotime("$m/1/$y"));
  2876. }
  2877. $pro = $this->pro;
  2878. $records = DB::select("
  2879. SELECT cm.id as care_month_id,
  2880. cm.uid as care_month_uid,
  2881. c.id as client_id,
  2882. c.uid as client_uid,
  2883. cm.number_of_days_with_remote_measurements,
  2884. cm.rm_total_time_in_seconds_by_mcp,
  2885. cm.rm_total_time_in_seconds_by_rme_pro,
  2886. cm.rm_total_time_in_seconds_by_rmm_pro,
  2887. cm.mcp_pro_id,
  2888. cm.rme_pro_id,
  2889. cm.rmm_pro_id,
  2890. (c.name_first || ' ' || c.name_last) as client_name
  2891. FROM care_month cm
  2892. JOIN client c on cm.client_id = c.id
  2893. WHERE cm.start_date = :startDate
  2894. AND (cm.mcp_pro_id = :proID OR
  2895. cm.rme_pro_id = :proID OR
  2896. cm.rmm_pro_id = :proID)
  2897. ORDER BY c.name_last, c.name_first
  2898. ",
  2899. ['startDate' => $date, 'proID' => $pro->id]
  2900. );
  2901. return view('app.practice-management.care-month-report', compact('records', 'date'));
  2902. }
  2903. public function myTeams(Request $request) {
  2904. $pro = $this->pro;
  2905. // get all teams where the authed-pro is the assistant pro
  2906. $teams = ProTeam::where('assistant_pro_id', $pro->id)
  2907. ->where('is_active', true)
  2908. ->orderBy('slug')
  2909. ->get();
  2910. return view('app.practice-management.my-teams', compact('teams'));
  2911. }
  2912. public function patientsAccountsInvites(Request $request){
  2913. $filters = $request->all();
  2914. $accountInvites = AccountInvite::select('account_invite.*')
  2915. ->join('client', 'client.id', '=', 'account_invite.for_client_id');
  2916. if($this->performer->pro->pro_type !== 'ADMIN'){
  2917. $accountInvites = $accountInvites->where('client.mcp_pro_id', $this->performer->pro->id);
  2918. }
  2919. $this->filterMultiQuery($request, $accountInvites, 'account_invite.created_at', 'date_category', 'date_value_1', 'date_value_2');
  2920. $this->filterSimpleQuery($request, $accountInvites, 'account_invite.status', 'status');
  2921. $accountInvites = $accountInvites->orderBy('created_at', 'DESC')->paginate(20);
  2922. return view('app.practice-management.patients-accounts-invites', compact('accountInvites','filters'));
  2923. }
  2924. public function clientsBdtDevices(Request $request){
  2925. $filters = $request->all();
  2926. $devices = ClientBDTDevice::select(
  2927. 'client_bdt_device.*',
  2928. 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'))
  2929. // 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'))
  2930. ->join('client', 'client.id', '=', 'client_bdt_device.client_id');
  2931. if($this->performer->pro->pro_type !== 'ADMIN'){
  2932. $devices = $devices->where('client.mcp_pro_id', $this->performer->pro->id);
  2933. }
  2934. $this->filterMultiQuery($request, $devices, 'client_bdt_device.most_recent_measurement_at', 'date_category', 'date_value_1', 'date_value_2');
  2935. // $dateKeyName = $request->get('date_category');
  2936. // $date1 = $request->get('date_value_1');
  2937. // $date2 = $request->get('date_value_2');
  2938. // $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)";
  2939. // switch($dateKeyName) {
  2940. // case 'EXACTLY':
  2941. // if($date1) {
  2942. // $devices->whereRaw($dateColumnName." = '$date1'::DATE");
  2943. // }
  2944. // break;
  2945. // case 'LESS_THAN':
  2946. // if($date1) {
  2947. // $devices->whereRaw($dateColumnName. "< '$date1'::DATE" );
  2948. // }
  2949. // break;
  2950. // case 'GREATER_THAN':
  2951. // if($date1) {
  2952. // $devices->whereRaw($dateColumnName. "> '$date1'::DATE");
  2953. // }
  2954. // break;
  2955. // case 'BETWEEN':
  2956. // if($date1 && $date2) {
  2957. // $devices
  2958. // ->whereRaw($dateColumnName. ">= '$date1'::DATE")
  2959. // ->whereRaw($dateColumnName. "<= '$date2'::DATE");
  2960. // }
  2961. // break;
  2962. // case 'NOT_BETWEEN':
  2963. // if($date2 && $date1) {
  2964. // $devices
  2965. // ->where(function ($q) use ($request, $dateColumnName, $date1, $date2) {
  2966. // $q->whereRaw($dateColumnName. "< '$date1'::DATE")
  2967. // ->orWhereRaw($dateColumnName. "> '$date2'::DATE");
  2968. // });
  2969. // }
  2970. // break;
  2971. // }
  2972. $keyName = $request->get('measurement_count_category');
  2973. $value1 = $request->get('measurement_count_value_1');
  2974. $value2 = $request->get('measurement_count_value_2');
  2975. $columnName = "(SELECT COUNT(*) FROM bdt_measurement WHERE bdt_measurement.bdt_device_id = client_bdt_device.device_id AND is_cellular_zero IS FALSE)";
  2976. switch($keyName) {
  2977. case 'EXACTLY':
  2978. if($value1) {
  2979. $devices->whereRaw($columnName.'='.$value1);
  2980. }
  2981. break;
  2982. case 'LESS_THAN':
  2983. if($value1) {
  2984. $devices->whereRaw($columnName. '<' .$value1);
  2985. }
  2986. break;
  2987. case 'GREATER_THAN':
  2988. if($value1) {
  2989. $devices->whereRaw($columnName. '>'. $value1);
  2990. }
  2991. break;
  2992. case 'BETWEEN':
  2993. if($value1 && $value2) {
  2994. $devices
  2995. ->whereRaw($columnName. '>=' . $value1)
  2996. ->whereRaw($columnName. '<=' . $value1);
  2997. }
  2998. break;
  2999. case 'NOT_BETWEEN':
  3000. if($value1 && $value2) {
  3001. $devices
  3002. ->where(function ($q) use ($request, $columnName, $value1, $value2) {
  3003. $q->whereRaw($columnName. '<'. $value1)
  3004. ->orWhereRaw($columnName. '>'.$value2);
  3005. });
  3006. }
  3007. break;
  3008. }
  3009. $status = $request->get('status');
  3010. if($status){
  3011. if($status === 'ACTIVE') $devices = $devices->where('client_bdt_device.is_active', true);
  3012. if($status === 'DEACTIVATED') $devices = $devices->where('client_bdt_device.is_active', false);
  3013. }
  3014. $devices = $devices->orderBy('num_of_measurements', 'DESC')->paginate(20);
  3015. return view('app.practice-management.clients_bdt_devices', compact('devices','filters'));
  3016. }
  3017. public function memos(Request $request){
  3018. $filters = $request->all();
  3019. $memos = ClientMemo::select('client_memo.*')
  3020. ->join('client', 'client.id', '=', 'client_memo.client_id');
  3021. if($this->performer->pro->pro_type !== 'ADMIN'){
  3022. $memos = $memos->where('client.mcp_pro_id', $this->performer->pro->id);
  3023. }
  3024. $this->filterMultiQuery($request, $memos, 'client_memo.created_at', 'date_category', 'date_value_1', 'date_value_2');
  3025. $this->filterSimpleQuery($request, $memos, 'category', 'category');
  3026. $memos = $memos->orderBy('created_at', 'DESC')->paginate(20);
  3027. return view('app.practice-management.memos', compact('memos', 'filters'));
  3028. }
  3029. public function segmentTemplates(Request $request){
  3030. $segmentTemplates = SegmentTemplate::query();
  3031. $segmentTemplates = $segmentTemplates->orderBy('created_at', 'DESC');
  3032. $responseType = $request->get('response_type');
  3033. if($responseType && $responseType == 'json'){
  3034. $segmentTemplates = $segmentTemplates->where('is_active', true)->get();
  3035. return $this->pass($segmentTemplates);
  3036. }
  3037. $segmentTemplates = $segmentTemplates->paginate(30);
  3038. return view('app.practice-management.segment-templates.index', compact('segmentTemplates'));
  3039. }
  3040. public function visitTemplates(Request $request){
  3041. $visitTemplates = VisitTemplate::query();
  3042. $visitTemplates = $visitTemplates->orderBy('created_at', 'DESC');
  3043. $responseType = $request->get('response_type');
  3044. if($responseType && $responseType == 'json'){
  3045. $visitTemplates = $visitTemplates->where('is_active', true)->get();
  3046. return $this->pass($visitTemplates);
  3047. }
  3048. $visitTemplates = $visitTemplates->paginate(30);
  3049. return view('app.practice-management.visit-templates.index', compact('visitTemplates'));
  3050. }
  3051. public function visitTemplate(Request $request, VisitTemplate $visitTemplate){
  3052. $visitTemplateSegmentTemplates = VisitTemplateSegmentTemplate::query();
  3053. $visitTemplateSegmentTemplates = $visitTemplateSegmentTemplates->where('visit_template_id', $visitTemplate->id);
  3054. $visitTemplateSegmentTemplates = $visitTemplateSegmentTemplates->orderBy('position_index', 'ASC');
  3055. $visitTemplateSegmentTemplates = $visitTemplateSegmentTemplates->paginate(50);
  3056. return view('app.practice-management.visit-templates.visit-template-segment-templates.index', compact('visitTemplate','visitTemplateSegmentTemplates'));
  3057. }
  3058. public function visitTemplateAccess(Request $request, VisitTemplate $visitTemplate){
  3059. $visitTemplateAccesses = VisitTemplateAccess::where('visit_template_id', $visitTemplate->id)->paginate(50);
  3060. return view('app.practice-management.visit-templates.visit-template-accesses.index', compact('visitTemplate','visitTemplateAccesses'));
  3061. }
  3062. public function clientCcmRmStatus(Request $request){
  3063. $filters = $request->all();
  3064. $patients = Client::whereNull('shadow_pro_id');
  3065. $pro = $this->performer()->pro;
  3066. if($pro->pro_type !== 'ADMIN') {
  3067. $patients = $patients->where('mcp_pro_id', $this->performer()->pro->id);
  3068. }
  3069. // filters
  3070. /*
  3071. array:18 [▼
  3072. "age_category" => "LESS_THAN"
  3073. "age_value_1" => "34"
  3074. "age_value_2" => null
  3075. "sex" => "M"
  3076. "bmi_category" => "BETWEEN"
  3077. "bmi_value_1" => "20"
  3078. "bmi_value_2" => "25"
  3079. "last_visit_category" => "LESS_THAN"
  3080. "last_visit_value_1" => "2021-10-14"
  3081. "last_visit_value_2" => null
  3082. "next_appointment_category" => "LESS_THAN"
  3083. "next_appointment_value_1" => "2021-10-15"
  3084. "status" => "ACTIVE"
  3085. "last_weighed_in_category" => "EXACTLY"
  3086. "last_weighed_in_value_1" => "2021-10-07"
  3087. "last_bp_category" => "BETWEEN"
  3088. "last_bp_value_1" => "2021-10-01"
  3089. "last_bp_value_2" => "2021-10-31"
  3090. ]
  3091. */
  3092. $this->filterMultiQuery($request, $patients, 'age_in_years', 'age_category', 'age_value_1', 'age_value_2');
  3093. $this->filterSimpleQuery($request, $patients, 'sex', 'sex');
  3094. $this->filterMultiQuery($request, $patients, 'usual_bmi', 'bmi_category', 'bmi_value_1', 'bmi_value_2');
  3095. $this->filterMultiQuery($request, $patients, 'most_recent_weight_at', 'last_weighed_in_category', 'last_weighed_in_value_1', 'last_weighed_in_value_2');
  3096. $this->filterMultiQuery($request, $patients, 'most_recent_bp_at', 'last_bp_category', 'last_bp_value_1', 'last_bp_value_2');
  3097. switch($request->input('status')) {
  3098. case 'ACTIVE':
  3099. $patients->where('is_active', true)->where('has_mcp_done_onboarding_visit', true);
  3100. break;
  3101. case 'AWAITING_VISIT':
  3102. $patients->where('is_active', true)->where('has_mcp_done_onboarding_visit', false);
  3103. break;
  3104. case 'INACTIVE':
  3105. $patients->where('is_active', '<>', true);
  3106. break;
  3107. }
  3108. if($request->input('is_eligible_for_cm')){
  3109. $patients->where('is_eligible_for_cm', '=', $request->input('is_eligible_for_cm'));
  3110. }
  3111. if($request->input('is_enrolled_in_cm')){
  3112. $patients->where('is_enrolled_in_cm', '=', $request->input('is_enrolled_in_cm'));
  3113. }
  3114. if($request->input('has_cm_setup_been_performed')){
  3115. $patients->where('has_cm_setup_been_performed', '=', $request->input('has_cm_setup_been_performed')=='YES'? true : false);
  3116. }
  3117. if($request->input('is_eligible_for_rm')){
  3118. $patients->where('is_eligible_for_rm', '=', $request->input('is_eligible_for_rm'));
  3119. }
  3120. if($request->input('is_enrolled_in_rm')){
  3121. $patients->where('is_enrolled_in_rm', '=', $request->input('is_enrolled_in_rm'));
  3122. }
  3123. if($request->input('has_rm_setup_been_performed')){
  3124. $patients->where('has_rm_setup_been_performed', '=', $request->input('has_rm_setup_been_performed') =='YES'? true : false);
  3125. }
  3126. $patients = $patients->orderBy('created_at', 'DESC')->paginate(20);
  3127. return view('app.admin.client-ccm-rm-status', compact('patients', 'filters'));
  3128. }
  3129. public function rmActionReport(Request $request){
  3130. $filters = $request->all();
  3131. $careMonthStartDate = $request->get('care_month_start_date');
  3132. $careMonthYear = $request->get('care_month_year');
  3133. if(!$careMonthStartDate){
  3134. $careMonthStartDate = '2022-01-01';
  3135. }
  3136. if($careMonthYear){
  3137. $careMonthStartDate = $careMonthYear . "-01";
  3138. }
  3139. $lastDateOfMonth = new DateTime(date("Y-m-t", strtotime(get_current_date())));
  3140. $today = new DateTime(get_current_date());
  3141. $diff = $lastDateOfMonth->diff($today);
  3142. $daysBetweenNowAndEndmonth = $diff->days;
  3143. $minRequiredMeasurements = 16 - $daysBetweenNowAndEndmonth -1;
  3144. $numOfMeasurements = $request->get('num_of_measurements'); //16_or_more, 12_or_more
  3145. $hasRecentVisit = $request->get('has_recent_visit'); //yes no
  3146. $hasBeenSpokenToThisMonth = $request->get('has_been_spoken_to'); //yes no
  3147. $cmQuery = CareMonth::where('start_date', $careMonthStartDate);
  3148. //remove dummies
  3149. $cmQuery = $cmQuery->whereHas('client', function($clientQuery) {
  3150. return $clientQuery->where('client_engagement_status_category','<>', 'DUMMY')
  3151. ->orWhere('client_engagement_status_category', '=', null);
  3152. });
  3153. if($numOfMeasurements){
  3154. if($numOfMeasurements == '16_or_more'){
  3155. $cmQuery = $cmQuery->where('number_of_days_with_remote_measurements', '>=', 16);
  3156. }
  3157. if($numOfMeasurements == 'min_or_more'){
  3158. $cmQuery = $cmQuery->where('number_of_days_with_remote_measurements', '>=', $minRequiredMeasurements)
  3159. ->where('number_of_days_with_remote_measurements', '<', 16);
  3160. }
  3161. if($numOfMeasurements == 'less_than_min'){
  3162. $cmQuery = $cmQuery->where('number_of_days_with_remote_measurements', '<', $minRequiredMeasurements);
  3163. }
  3164. }
  3165. if($hasRecentVisit){
  3166. if($hasRecentVisit == 'YES'){
  3167. $cmQuery = $cmQuery->whereHas('client', function($clientQuery) {
  3168. return $clientQuery->whereRaw("most_recent_completed_mcp_note_date::DATE >= ((NOW() - interval '90 days')::DATE)");
  3169. });
  3170. }else{
  3171. $cmQuery = $cmQuery->whereHas('client', function($clientQuery) {
  3172. return $clientQuery->whereRaw("most_recent_completed_mcp_note_date::DATE < ((NOW() - interval '90 days')::DATE)");
  3173. });
  3174. }
  3175. }
  3176. if($hasBeenSpokenToThisMonth){
  3177. if($hasBeenSpokenToThisMonth == 'YES'){
  3178. $cmQuery = $cmQuery->where('has_anyone_interacted_with_client_about_rm_outside_note', '=', true);
  3179. }else{
  3180. $cmQuery = $cmQuery->where('has_anyone_interacted_with_client_about_rm_outside_note', '=', false);
  3181. }
  3182. }
  3183. $claimingClosed = $request->get('claiming_closed');
  3184. if($claimingClosed){
  3185. if($claimingClosed === 'YES') $cmQuery = $cmQuery->where('is_claim_closed', true);
  3186. if($claimingClosed === 'NO') $cmQuery = $cmQuery->where('is_claim_closed', false);
  3187. }
  3188. $cmQuery = $cmQuery->orderBy('start_date', 'DESC')->orderBy('client_id', 'ASC');
  3189. $rows =$cmQuery->paginate(15);
  3190. return view('app.practice-management.rm-action-report', compact('rows', 'filters', 'minRequiredMeasurements'));
  3191. }
  3192. public function myFlyers(Request $request){
  3193. $pro = $this->performer->pro;
  3194. $slug = $pro->slug ?? $pro->uid;
  3195. $url = config('app.stagfe6_url') . '/flyers/json-list?slug=' . $slug;
  3196. $arrContextOptions=array(
  3197. "ssl"=>array(
  3198. "verify_peer"=>false,
  3199. "verify_peer_name"=>false,
  3200. ),
  3201. );
  3202. $response = @file_get_contents($url, false, stream_context_create($arrContextOptions));
  3203. $response = @json_decode($response);
  3204. $flyerTemplates = [];
  3205. if(isset($response->data)){
  3206. $flyerTemplates = $response->data;
  3207. }
  3208. return view('app.my-flyers', compact('pro','flyerTemplates'));
  3209. }
  3210. public function notesResolutionCenter(Request $request) {
  3211. $columns = "(c.name_first || ' ' || c.name_last) as client_name,
  3212. (hcp.name_first || ' ' || hcp.name_last) as hcp_name,
  3213. (na.name_first || ' ' || na.name_last) as na_name,
  3214. c.chart_number,
  3215. c.uid as client_uid,
  3216. n.effective_dateest,
  3217. n.uid,
  3218. n.detail_json,
  3219. n.is_claim_closed,
  3220. n.visit_number,
  3221. ROUND(b.number_of_units * 60) as minutes,
  3222. n.note_reason_icd1 AS icd1,
  3223. n.note_reason_icd1description AS icd1description,
  3224. n.note_reason_icd2 AS icd2,
  3225. n.note_reason_icd2description AS icd2description,
  3226. n.note_reason_icd3 AS icd3,
  3227. n.note_reason_icd3description AS icd3description,
  3228. n.note_reason_icd4 AS icd4,
  3229. n.note_reason_icd4description AS icd4description,
  3230. n.note_reason_memo AS icd_memo,
  3231. n.visit_number
  3232. ";
  3233. $from = "FROM note AS n
  3234. LEFT JOIN pro AS hcp ON n.hcp_pro_id = hcp.id
  3235. LEFT JOIN pro AS na ON n.ally_pro_id = na.id
  3236. JOIN client AS c ON n.client_id = c.id
  3237. JOIN bill AS b ON (b.note_id = n.id AND b.is_cancelled IS NOT TRUE AND b.code ILIKE '%treatment%')
  3238. ";
  3239. $where = "WHERE
  3240. -- n.visit_number IN (1,2) AND
  3241. n.is_signed_by_hcp IS TRUE AND
  3242. -- n.is_claim_closed IS NOT TRUE AND
  3243. n.is_cancelled IS NOT TRUE AND
  3244. n.created_at::DATE >= '2022-01-01'::DATE AND
  3245. c.client_engagement_status_category <> 'DUMMY' AND
  3246. c.name_first NOT ILIKE '%test%' AND
  3247. c.name_last NOT ILIKE '%test%' AND
  3248. 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
  3249. -- n.id NOT IN (SELECT note_id FROM claim WHERE note_id IS NOT NULL) AND
  3250. c.is_part_b_primary = 'YES' AND
  3251. c.latest_eligible_refresh_at::DATE >= '2022-01-01' AND
  3252. c.mpb_remaining = 0 AND
  3253. c.created_at::DATE >= '2022-01-01'::DATE
  3254. ";
  3255. $filters = [];
  3256. if($request->input('f')) {
  3257. $filters[] = "(n.detail_json IS NOT NULL AND ((n.detail_json)::json->'farah_decision')::text = '\"" . $request->input('f') . "\"')";
  3258. }
  3259. if($request->input('s')) {
  3260. $filters[] = "(n.detail_json IS NOT NULL AND ((n.detail_json)::json->'shawn_decision')::text = '\"" . $request->input('s') . "\"')";
  3261. }
  3262. if(count($filters)) {
  3263. $filters = 'AND ' . implode(' AND ', $filters);
  3264. }
  3265. else {
  3266. $filters = '';
  3267. }
  3268. // $filters = '';
  3269. $orderBy = "ORDER BY c.id ASC, n.visit_number ASC";
  3270. $countQuery = "SELECT count(*) {$from} {$where} {$filters}";
  3271. // dd($countQuery);
  3272. $countResult = DB::select($countQuery);
  3273. $total = $countResult[0]->count;
  3274. $defaultPageSize = 25;
  3275. $page = $request->input('page') ?: 1;
  3276. $perPage = $request->input('per_page') ?: $defaultPageSize;
  3277. $offset = ($page - 1) * $perPage;
  3278. $dataQuery = "SELECT {$columns} {$from} {$where} {$filters} {$orderBy} OFFSET {$offset} LIMIT {$perPage}";
  3279. $rows = DB::select($dataQuery);
  3280. $paginator = new LengthAwarePaginator($rows, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  3281. $paginator->setPath(route('practice-management.notes-resolution-center'));
  3282. return view('app.practice-management.notes-resolution-center', compact('rows', 'paginator'));
  3283. }
  3284. public function notesResolutionCenterV2(Request $request) {
  3285. $columns = "(c.name_first || ' ' || c.name_last) as client_name,
  3286. (hcp.name_first || ' ' || hcp.name_last) as hcp_name,
  3287. (na.name_first || ' ' || na.name_last) as na_name,
  3288. c.chart_number,
  3289. c.uid as client_uid,
  3290. n.effective_dateest,
  3291. n.uid,
  3292. n.detail_json,
  3293. n.is_claim_closed,
  3294. n.visit_number,
  3295. ROUND(b.number_of_units * 60) as minutes,
  3296. n.note_reason_icd1 AS icd1,
  3297. n.note_reason_icd1description AS icd1description,
  3298. n.note_reason_icd2 AS icd2,
  3299. n.note_reason_icd2description AS icd2description,
  3300. n.note_reason_icd3 AS icd3,
  3301. n.note_reason_icd3description AS icd3description,
  3302. n.note_reason_icd4 AS icd4,
  3303. n.note_reason_icd4description AS icd4description,
  3304. n.note_reason_memo AS icd_memo
  3305. ";
  3306. $from = "FROM note AS n
  3307. LEFT JOIN pro AS hcp ON n.hcp_pro_id = hcp.id
  3308. LEFT JOIN pro AS na ON n.ally_pro_id = na.id
  3309. JOIN client AS c ON n.client_id = c.id
  3310. JOIN bill AS b ON (b.note_id = n.id AND b.is_cancelled IS NOT TRUE AND b.code ILIKE '%treatment%')
  3311. ";
  3312. $where = "WHERE
  3313. -- n.visit_number = 2 AND
  3314. n.is_signed_by_hcp IS TRUE AND
  3315. -- n.effective_dateest < '2022-03-01' AND
  3316. n.is_claim_closed IS NOT TRUE AND
  3317. n.is_cancelled IS NOT TRUE AND
  3318. c.client_engagement_status_category <> 'DUMMY' AND
  3319. c.name_first NOT ILIKE '%test%' AND
  3320. c.name_last NOT ILIKE '%test%' AND
  3321. 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)
  3322. -- AND
  3323. -- n.id NOT IN (SELECT note_id FROM claim WHERE note_id IS NOT NULL) AND
  3324. ";
  3325. $filters = [];
  3326. if(trim($request->input('f_pb_primary'))) {
  3327. $v = trim($request->input('f_pb_primary'));
  3328. if($v === 'yes') {
  3329. $filters[] = "(c.is_part_b_primary = 'YES')";
  3330. }
  3331. else if($v === 'no') {
  3332. $filters[] = "(c.is_part_b_primary != 'YES')";
  3333. }
  3334. }
  3335. if(trim($request->input('f_deductible_zero'))) {
  3336. $v = trim($request->input('f_deductible_zero'));
  3337. if($v === 'yes') {
  3338. $filters[] = "(c.mpb_remaining = 0)";
  3339. }
  3340. else if($v === 'no') {
  3341. $filters[] = "(c.mpb_remaining > 0)";
  3342. }
  3343. }
  3344. if(trim($request->input('f_note_hcp'))) {
  3345. $v = trim($request->input('f_note_hcp'));
  3346. $filters[] = "(n.hcp_pro_id IN (SELECT id FROM pro WHERE uid = '{$v}'))";
  3347. }
  3348. if(trim($request->input('f_2022_patient'))) {
  3349. $v = trim($request->input('f_2022_patient'));
  3350. if($v === 'yes') {
  3351. $filters[] = "(c.created_at::DATE >= '2022-01-01'::DATE)";
  3352. }
  3353. else if($v === 'no') {
  3354. $filters[] = "(c.created_at::DATE < '2022-01-01'::DATE)";
  3355. }
  3356. }
  3357. if(count($filters)) {
  3358. $filters = 'AND ' . implode(' AND ', $filters);
  3359. }
  3360. else {
  3361. $filters = '';
  3362. }
  3363. // $filters = '';
  3364. $orderBy = "ORDER BY
  3365. -- c.id ASC,
  3366. n.id ASC, n.effective_dateest ASC";
  3367. $countQuery = "SELECT count(*) {$from} {$where} {$filters}";
  3368. // dd($countQuery);
  3369. $countResult = DB::select($countQuery);
  3370. $total = $countResult[0]->count;
  3371. $defaultPageSize = 50;
  3372. $page = $request->input('page') ?: 1;
  3373. $perPage = $request->input('per_page') ?: $defaultPageSize;
  3374. $offset = ($page - 1) * $perPage;
  3375. $dataQuery = "SELECT {$columns} {$from} {$where} {$filters} {$orderBy} OFFSET {$offset} LIMIT {$perPage}";
  3376. $rows = DB::select($dataQuery);
  3377. $paginator = new LengthAwarePaginator($rows, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  3378. $paginator->setPath(route('practice-management.notes-resolution-center-v2'));
  3379. return view('app.practice-management.notes-resolution-center-v2', compact('rows', 'paginator'));
  3380. }
  3381. public function coverages(Request $request) {
  3382. $columns = "(c.name_first || ' ' || c.name_last) as client_name,
  3383. c.id,
  3384. c.uid,
  3385. c.created_at,
  3386. c.sex,
  3387. c.dob,
  3388. c.age_in_years,
  3389. row_to_json(lcpc.*) as latest_client_primary_coverage,
  3390. row_to_json(lacpc.*) as latest_auto_client_primary_coverage,
  3391. row_to_json(lmcpc.*) as latest_manual_client_primary_coverage,
  3392. row_to_json(lmcpc_payer.*) as latest_manual_client_primary_coverage_payer
  3393. ";
  3394. $from = "FROM client AS c
  3395. LEFT JOIN client_primary_coverage lcpc on c.effective_client_primary_coverage_id = lcpc.id
  3396. LEFT JOIN client_primary_coverage lacpc on c.latest_auto_refresh_client_primary_coverage_id = lacpc.id
  3397. LEFT JOIN client_primary_coverage lmcpc on c.latest_manual_client_primary_coverage_id = lmcpc.id
  3398. LEFT JOIN payer lmcpc_payer on lmcpc.commercial_payer_id = lmcpc_payer.id
  3399. ";
  3400. $where = "WHERE
  3401. c.client_engagement_status_category <> 'DUMMY' AND
  3402. c.name_first NOT ILIKE '%test%' AND
  3403. c.name_last NOT ILIKE '%test%' AND
  3404. c.created_at::DATE >= '2022-01-01'::DATE
  3405. -- lmcpc.id IS NOT NULL ANd lmcpc.plan_type != 'MEDICARE'
  3406. ";
  3407. $filters = [];
  3408. if(trim($request->input('f_name'))) {
  3409. $v = trim($request->input('f_name'));
  3410. $filters[] = "(c.name_first ILIKE '%{$v}%' OR c.name_last ILIKE '%{$v}%')";
  3411. }
  3412. if(trim($request->input('f_covered'))) {
  3413. $v = trim($request->input('f_covered'));
  3414. if($v !== 'any') {
  3415. switch($v) {
  3416. case 'covered':
  3417. $filters[] = "(
  3418. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.manual_determination_category = 'COVERED') OR
  3419. ((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')
  3420. )";
  3421. break;
  3422. case 'not-covered':
  3423. $filters[] = "(
  3424. (lmcpc.id IS NULL OR (lmcpc.is_cancelled IS TRUE OR lmcpc.manual_determination_category = 'NOT_COVERED')) AND
  3425. (lacpc.id IS NULL OR (lacpc.is_cancelled IS TRUE OR lacpc.auto_medicare_is_partbprimary = 'NO')) AND
  3426. (lmcpc.id IS NOT NULL OR lacpc.id IS NOT NULL)
  3427. )";
  3428. break;
  3429. case 'unknown':
  3430. $filters[] = "(
  3431. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.manual_determination_category = 'UNKNOWN') OR
  3432. ((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')
  3433. )";
  3434. break;
  3435. }
  3436. }
  3437. }
  3438. if(trim($request->input('f_covered'))) {
  3439. $v = trim($request->input('f_covered'));
  3440. if($v !== 'any') {
  3441. switch($v) {
  3442. case 'covered':
  3443. $filters[] = "(
  3444. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.manual_determination_category = 'COVERED') OR
  3445. ((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')
  3446. )";
  3447. break;
  3448. case 'not-covered':
  3449. $filters[] = "(
  3450. (lmcpc.id IS NULL OR (lmcpc.is_cancelled IS TRUE OR lmcpc.manual_determination_category = 'NOT_COVERED')) AND
  3451. (lacpc.id IS NULL OR (lacpc.is_cancelled IS TRUE OR lacpc.auto_medicare_is_partbprimary = 'NO')) AND
  3452. (lmcpc.id IS NOT NULL OR lacpc.id IS NOT NULL)
  3453. )";
  3454. break;
  3455. case 'unknown':
  3456. $filters[] = "(
  3457. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.manual_determination_category = 'UNKNOWN') OR
  3458. ((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')
  3459. )";
  3460. break;
  3461. }
  3462. }
  3463. }
  3464. if(trim($request->input('f_plan_type'))) {
  3465. $v = strtoupper(trim($request->input('f_plan_type')));
  3466. if($v !== 'ANY') {
  3467. $filters[] = "(
  3468. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.plan_type = '{$v}') OR
  3469. ((lmcpc.id IS NULL OR lmcpc.is_cancelled IS TRUE) AND lacpc.id IS NOT NULL AND lacpc.is_cancelled IS NOT TRUE AND lacpc.plan_type = '{$v}')
  3470. )";
  3471. }
  3472. }
  3473. if(trim($request->input('f_pb_primary'))) {
  3474. $v = trim($request->input('f_pb_primary'));
  3475. if($v !== 'any') {
  3476. switch($v) {
  3477. case 'primary':
  3478. $filters[] = "(
  3479. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.is_partbprimary = 'YES') OR
  3480. ((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')
  3481. )";
  3482. break;
  3483. case 'not-primary':
  3484. $filters[] = "(
  3485. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.is_partbprimary = 'NO') OR
  3486. ((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')
  3487. )";
  3488. break;
  3489. case 'unknown':
  3490. $filters[] = "(
  3491. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.is_partbprimary = 'UNKNOWN') OR
  3492. ((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')
  3493. )";
  3494. break;
  3495. }
  3496. }
  3497. }
  3498. if(trim($request->input('f_pb_active'))) {
  3499. $v = trim($request->input('f_pb_active'));
  3500. // TODO
  3501. }
  3502. if(trim($request->input('f_pc_active'))) {
  3503. $v = trim($request->input('f_pc_active'));
  3504. // TODO
  3505. }
  3506. if(trim($request->input('f_comm_payer'))) {
  3507. $v = trim($request->input('f_comm_payer'));
  3508. $filters[] = "(lmcpc_payer.name ILIKE '%{$v}%')";
  3509. }
  3510. if(trim($request->input('f_comm_member_id'))) {
  3511. $v = trim($request->input('f_comm_member_id'));
  3512. if($v !== 'any') {
  3513. $filters[] = "(
  3514. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.commercial_member_identifier ILIKE '%{$v}%') OR
  3515. ((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}%')
  3516. )";
  3517. }
  3518. }
  3519. if(trim($request->input('f_comm_group_num'))) {
  3520. $v = trim($request->input('f_comm_group_num'));
  3521. if($v !== 'any') {
  3522. $filters[] = "(
  3523. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.commercial_group_number ILIKE '%{$v}%') OR
  3524. ((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}%')
  3525. )";
  3526. }
  3527. }
  3528. if(count($filters)) {
  3529. $filters = 'AND ' . implode(' AND ', $filters);
  3530. }
  3531. else {
  3532. $filters = '';
  3533. }
  3534. // $filters = '';
  3535. $orderBy = "ORDER BY client_name ASC";
  3536. $countQuery = "SELECT count(*) {$from} {$where} {$filters}";
  3537. // dd($countQuery);
  3538. $countResult = DB::select($countQuery);
  3539. $total = $countResult[0]->count;
  3540. $defaultPageSize = 10;
  3541. $page = $request->input('page') ?: 1;
  3542. $perPage = $request->input('per_page') ?: $defaultPageSize;
  3543. $offset = ($page - 1) * $perPage;
  3544. $dataQuery = "SELECT {$columns} {$from} {$where} {$filters} {$orderBy} OFFSET {$offset} LIMIT {$perPage}";
  3545. $rows = DB::select($dataQuery);
  3546. $paginator = new LengthAwarePaginator($rows, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  3547. $paginator->setPath(route('practice-management.coverages'));
  3548. // dd($rows);
  3549. return view('app.practice-management.coverages', compact('rows', 'paginator'));
  3550. }
  3551. }