PracticeManagementController.php 177 KB

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