PracticeManagementController.php 209 KB

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