PracticeManagementController.php 215 KB

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