PracticeManagementController.php 226 KB

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