PracticeManagementController.php 183 KB

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