PracticeManagementController.php 207 KB

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