PracticeManagementController.php 237 KB

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