PracticeManagementController.php 217 KB

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