PracticeManagementController.php 237 KB

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