PracticeManagementController.php 217 KB

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