PracticeManagementController.php 181 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091
  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 = "left join bill on care_month.rme_pro_id = {$performer->pro->id}";
  1372. break;
  1373. }
  1374. $query = "
  1375. SELECT client.name_first, client.name_last,
  1376. (client.name_first || ' ' || client.name_last) as client_name,
  1377. client.uid as client_uid,
  1378. client.dob,
  1379. client.is_enrolled_in_rm,
  1380. client.most_recent_completed_mcp_note_date,
  1381. client.most_recent_completed_mcp_note_id,
  1382. mrmnote.effective_dateest::date as most_recent_completed_mcp_note_date_cm,
  1383. mrmnote.id as most_recent_completed_mcp_note_id_cm,
  1384. mrmnote.uid as most_recent_completed_mcp_note_uid_cm,
  1385. client.cell_number,
  1386. client.is_assigned_cellular_bp_device,
  1387. client.is_assigned_cellular_weight_scale_device,
  1388. care_month.uid as care_month_uid,
  1389. care_month.id as care_month_id,
  1390. care_month.start_date,
  1391. care_month.rm_total_time_in_seconds_by_mcp,
  1392. care_month.rm_total_time_in_seconds_by_rmm_pro,
  1393. care_month.number_of_days_with_remote_measurements,
  1394. care_month.has_mcp_interacted_with_client_about_rm,
  1395. care_month.rm_num_measurements_not_stamped_by_mcp,
  1396. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  1397. care_month.rm_num_measurements_not_stamped_by_rmm,
  1398. care_month.rm_num_measurements_not_stamped_by_rme,
  1399. care_month.mcp_pro_id as care_month_mcp_pro_id,
  1400. care_month.rmm_pro_id as care_month_rmm_pro_id,
  1401. client.mcp_pro_id,
  1402. client.default_na_pro_id,
  1403. client.rmm_pro_id,
  1404. client.rme_pro_id,
  1405. client.cell_number,
  1406. care_month.most_recent_cellular_bp_dbp_mm_hg,
  1407. care_month.most_recent_cellular_bp_sbp_mm_hg,
  1408. care_month.most_recent_cellular_bp_measurement_at,
  1409. care_month.most_recent_cellular_weight_value,
  1410. care_month.most_recent_cellular_weight_measurement_at,
  1411. mcp.name_last || ', ' || mcp.name_last AS mcp_name,
  1412. {$genericBillIdColumns}
  1413. 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
  1414. {$genericBillJoinClause}
  1415. left join note mrmnote on mrmnote.id = (
  1416. select max(n.id) from note n
  1417. where
  1418. n.client_id = client.id AND
  1419. n.is_cancelled = FALSE AND
  1420. (n.is_signed_by_hcp IS NOT NULL AND n.is_signed_by_hcp = TRUE) AND
  1421. n.effective_dateest::date >= care_month.start_date::date AND
  1422. n.effective_dateest::date < (care_month.start_date::date + INTERVAL '1 month')
  1423. )
  1424. WHERE
  1425. $proTypeCondition
  1426. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1427. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1428. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '') . "
  1429. $orderBy
  1430. ";
  1431. // dd($query);
  1432. $patients = DB::select($query);
  1433. $timestamp = strtotime(date('Y-m-d'));
  1434. $daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
  1435. return view('app.practice-management.rpm-matrix-by-pro-type', compact('patients', 'daysRemaining', 'careMonthStart', 'mode'));
  1436. }
  1437. public function rpmMatrixForAdmin(Request $request) {
  1438. $performer = $this->performer();
  1439. // abort_if($performer->pro->pro_type !== 'ADMIN' && !$performer->pro->can_view_rm_matrix, 403);
  1440. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1441. $careMonthStart = date($ym . '-01');
  1442. $rc = $request->input('rc') ?: 1;
  1443. $rc2 = $request->input('rc2') ?: 2;
  1444. $conditions = [];// $this->rpmConditions($performer, $rc, $rc2);
  1445. $sortBy = $request->input('sort_by') ?: 'name_first';
  1446. $sortDir = $request->input('sort_dir') ?: 'ASC';
  1447. $orderBy = "ORDER BY $sortBy $sortDir NULLS LAST";
  1448. // special case of if-bill-exists
  1449. if($sortBy === 'mcp_rm_generic_bill_id' || $sortBy === 'rmm_rm_generic_bill_id') {
  1450. if($sortDir === 'ASC') {
  1451. $orderBy = "ORDER BY $sortBy $sortDir NULLS FIRST";
  1452. }
  1453. else {
  1454. $orderBy = "ORDER BY $sortBy $sortDir NULLS LAST";
  1455. }
  1456. }
  1457. // default sort
  1458. if(!$request->input('sort_by')) {
  1459. $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";
  1460. }
  1461. else {
  1462. $sortBy = $request->input('sort_by');
  1463. $sortDir = $request->input('sort_dir');
  1464. if($sortBy && $sortDir) {
  1465. 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'])) {
  1466. $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, care_month.rm_total_time_in_seconds_by_rmm_pro DESC NULLS LAST";
  1467. }
  1468. else {
  1469. $orderBy = "ORDER BY $sortBy $sortDir NULLS LAST";
  1470. }
  1471. }
  1472. }
  1473. // filters from the UI
  1474. if(trim($request->input('f_ces'))) {
  1475. $v = trim($request->input('f_ces'));
  1476. if($v === 'ACTIVE') {
  1477. $conditions[] = "(client.client_engagement_status_category IS NULL OR client.client_engagement_status_category = '{$v}')";
  1478. }
  1479. else {
  1480. $conditions[] = "(client.client_engagement_status_category = '{$v}')";
  1481. }
  1482. }
  1483. if(trim($request->input('f_name'))) {
  1484. $v = trim($request->input('f_name'));
  1485. $conditions[] = "(client.name_first ILIKE '%{$v}%' OR client.name_last ILIKE '%{$v}%')";
  1486. }
  1487. if(trim($request->input('f_mcp'))) {
  1488. $v = trim($request->input('f_mcp'));
  1489. $conditions[] = "(mcpPro.uid = '{$v}')";
  1490. }
  1491. if(trim($request->input('f_dob_op')) && trim($request->input('f_dob'))) {
  1492. $o = trim($request->input('f_dob_op'));
  1493. $v = trim($request->input('f_dob'));
  1494. $conditions[] = "(client.dob {$o} '{$v}')";
  1495. }
  1496. if(trim($request->input('f_rpm'))) {
  1497. $v = trim($request->input('f_rpm'));
  1498. if($v === 'yes') {
  1499. $conditions[] = "(client.is_enrolled_in_rm IS NOT NULL AND client.is_enrolled_in_rm = 'YES')";
  1500. }
  1501. elseif($v === 'no') {
  1502. $conditions[] = "(client.is_enrolled_in_rm IS NULL OR client.is_enrolled_in_rm != 'YES')";
  1503. }
  1504. }
  1505. if(trim($request->input('f_cell_bp'))) {
  1506. $v = trim($request->input('f_cell_bp'));
  1507. if($v === 'yes') {
  1508. $conditions[] = "(client.is_assigned_cellular_bp_device IS NOT NULL AND client.is_assigned_cellular_bp_device = TRUE)";
  1509. }
  1510. elseif($v === 'no') {
  1511. $conditions[] = "(client.is_assigned_cellular_bp_device IS NULL OR client.is_assigned_cellular_bp_device = FALSE)";
  1512. }
  1513. }
  1514. if(trim($request->input('f_cell_wt'))) {
  1515. $v = trim($request->input('f_cell_wt'));
  1516. if($v === 'yes') {
  1517. $conditions[] = "(client.is_assigned_cellular_weight_scale_device IS NOT NULL AND client.is_assigned_cellular_weight_scale_device = TRUE)";
  1518. }
  1519. elseif($v === 'no') {
  1520. $conditions[] = "(client.is_assigned_cellular_weight_scale_device IS NULL OR client.is_assigned_cellular_weight_scale_device = FALSE)";
  1521. }
  1522. }
  1523. if(trim($request->input('f_lmb'))) {
  1524. $v = trim($request->input('f_lmb'));
  1525. switch($v) {
  1526. case '1':
  1527. $conditions[] = "(GREATEST(client.most_recent_cellular_bp_measurement_at::DATE, client.most_recent_cellular_weight_measurement_at::DATE)::DATE < (NOW() - INTERVAL '1 DAY')::DATE)";
  1528. break;
  1529. case '2':
  1530. $conditions[] = "(GREATEST(client.most_recent_cellular_bp_measurement_at::DATE, client.most_recent_cellular_weight_measurement_at::DATE)::DATE < (NOW() - INTERVAL '2 DAYS')::DATE)";
  1531. break;
  1532. case '3':
  1533. $conditions[] = "(GREATEST(client.most_recent_cellular_bp_measurement_at::DATE, client.most_recent_cellular_weight_measurement_at::DATE)::DATE < (NOW() - INTERVAL '3 DAYS')::DATE)";
  1534. break;
  1535. case '3+':
  1536. $conditions[] = "(GREATEST(client.most_recent_cellular_bp_measurement_at::DATE, client.most_recent_cellular_weight_measurement_at::DATE)::DATE < (NOW() - INTERVAL '4 DAYS')::DATE)";
  1537. break;
  1538. }
  1539. }
  1540. if(trim($request->input('f_comm'))) {
  1541. $v = trim($request->input('f_comm'));
  1542. if($v === 'yes') {
  1543. $conditions[] = "(care_month.has_mcp_interacted_with_client_about_rm IS NOT NULL AND care_month.has_mcp_interacted_with_client_about_rm = TRUE)";
  1544. }
  1545. elseif($v === 'no') {
  1546. $conditions[] = "(care_month.has_mcp_interacted_with_client_about_rm IS NULL OR care_month.has_mcp_interacted_with_client_about_rm = FALSE)";
  1547. }
  1548. }
  1549. if(trim($request->input('f_mcp_billable'))) {
  1550. $v = trim($request->input('f_mcp_billable'));
  1551. if($v === 'yes') {
  1552. $conditions[] = "(care_month.mcp_rm_generic_bill_id IS NOT NULL)";
  1553. }
  1554. elseif($v === 'no') {
  1555. $conditions[] = "(care_month.mcp_rm_generic_bill_id IS NULL)";
  1556. }
  1557. }
  1558. if(trim($request->input('f_rmm_billable'))) {
  1559. $v = trim($request->input('f_rmm_billable'));
  1560. if($v === 'yes') {
  1561. $conditions[] = "(care_month.rmm_rm_generic_bill_id IS NOT NULL)";
  1562. }
  1563. elseif($v === 'no') {
  1564. $conditions[] = "(care_month.rmm_rm_generic_bill_id IS NULL)";
  1565. }
  1566. }
  1567. if(trim($request->input('f_md_op')) && trim($request->input('f_md')) !== '') {
  1568. $o = trim($request->input('f_md_op'));
  1569. $v = trim($request->input('f_md'));
  1570. $conditions[] = "(care_month.number_of_days_with_remote_measurements {$o} {$v})";
  1571. }
  1572. if(trim($request->input('f_unst_op')) && trim($request->input('f_unst')) !== '') {
  1573. $o = trim($request->input('f_unst_op'));
  1574. $v = trim($request->input('f_unst'));
  1575. $conditions[] = "(care_month.rm_num_measurements_not_stamped_by_mcp {$o} {$v})";
  1576. }
  1577. if(trim($request->input('f_mcp_mins_op')) && trim($request->input('f_mcp_mins')) !== '') {
  1578. $o = trim($request->input('f_mcp_mins_op'));
  1579. $v = intval(trim($request->input('f_mcp_mins'))) * 60;
  1580. $conditions[] = "(care_month.rm_total_time_in_seconds_by_mcp {$o} {$v})";
  1581. }
  1582. if(trim($request->input('f_rmm_mins_op')) && trim($request->input('f_rmm_mins')) !== '') {
  1583. $o = trim($request->input('f_rmm_mins_op'));
  1584. $v = intval(trim($request->input('f_rmm_mins'))) * 60;
  1585. $conditions[] = "(care_month.rm_total_time_in_seconds_by_rmm_pro {$o} {$v})";
  1586. }
  1587. if($request->input('not-enrolled')) {
  1588. $conditions[] = "(client.is_enrolled_in_rm != 'YES')";
  1589. }
  1590. else {
  1591. $conditions[] = "(client.is_enrolled_in_rm = 'YES')";
  1592. }
  1593. $genericBillIdColumns = "care_month.mcp_rm_generic_bill_id,
  1594. mcpBill.uid as mcp_rm_generic_bill_uid,
  1595. mcpBill.generic_pro_id as mcp_rm_generic_bill_generic_pro_id,
  1596. mcpBill.generic_pro_expected_payment_amount as mcp_rm_generic_bill_expected_payment_amount,
  1597. mcpBill.is_signed_by_generic_pro as mcp_rm_generic_bill_signed,
  1598. care_month.rmm_rm_generic_bill_id,
  1599. rmmBill.uid as rmm_rm_generic_bill_uid,
  1600. rmmBill.generic_pro_id as rmm_rm_generic_bill_generic_pro_id,
  1601. rmmBill.generic_pro_expected_payment_amount as rmm_rm_generic_bill_expected_payment_amount,
  1602. rmmBill.is_signed_by_generic_pro as rmm_rm_generic_bill_signed";
  1603. $genericBillJoinClause = "left join bill mcpBill on care_month.mcp_rm_generic_bill_id = mcpBill.id
  1604. left join bill rmmBill on care_month.rmm_rm_generic_bill_id = rmmBill.id";
  1605. $defaultPageSize = 25;
  1606. $page = $request->input('page') ?: 1;
  1607. $perPage = $request->input('per_page') ?: $defaultPageSize;
  1608. $offset = ($page - 1) * $perPage;
  1609. $countQuery = "
  1610. SELECT COUNT(*)
  1611. FROM care_month join client on care_month.client_id = client.id
  1612. join note mrnote on client.most_recent_completed_mcp_note_id = mrnote.id
  1613. left join pro mcpPro on care_month.mcp_pro_id = mcpPro.id
  1614. left join pro rmmPro on care_month.rmm_pro_id = rmmPro.id
  1615. {$genericBillJoinClause}
  1616. WHERE
  1617. EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1618. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1619. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '') . "
  1620. ";
  1621. $countResult = DB::select($countQuery);
  1622. $total = $countResult[0]->count;
  1623. $query = "
  1624. SELECT client.name_first, client.name_last,
  1625. (client.name_first || ' ' || client.name_last) as client_name,
  1626. client.uid as client_uid,
  1627. client.dob,
  1628. client.age_in_years,
  1629. client.is_enrolled_in_rm,
  1630. client.most_recent_completed_mcp_note_date,
  1631. client.most_recent_completed_mcp_note_id,
  1632. client.cell_number,
  1633. client.is_assigned_cellular_bp_device,
  1634. client.is_assigned_cellular_weight_scale_device,
  1635. care_month.uid as care_month_uid,
  1636. care_month.id as care_month_id,
  1637. care_month.start_date,
  1638. care_month.rm_total_time_in_seconds_by_mcp,
  1639. care_month.rm_total_time_in_seconds_by_rmm_pro,
  1640. care_month.number_of_days_with_remote_measurements,
  1641. care_month.has_mcp_interacted_with_client_about_rm,
  1642. care_month.has_anyone_interacted_with_client_about_rm,
  1643. care_month.rm_num_measurements_not_stamped_by_mcp,
  1644. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  1645. care_month.rm_num_measurements_not_stamped_by_rmm,
  1646. care_month.rm_num_measurements_not_stamped_by_rme,
  1647. care_month.mcp_pro_id as care_month_mcp_pro_id,
  1648. care_month.rmm_pro_id as care_month_rmm_pro_id,
  1649. client.mcp_pro_id,
  1650. client.default_na_pro_id,
  1651. client.rmm_pro_id,
  1652. client.rme_pro_id,
  1653. client.cell_number,
  1654. care_month.most_recent_cellular_bp_dbp_mm_hg,
  1655. care_month.most_recent_cellular_bp_sbp_mm_hg,
  1656. care_month.most_recent_cellular_bp_measurement_at,
  1657. care_month.most_recent_cellular_weight_value,
  1658. care_month.most_recent_cellular_weight_measurement_at,
  1659. mcpPro.mcp_rpm_payment_strategy,
  1660. mcpPro.mcp_rpm_payment_amount,
  1661. (mcpPro.name_first || ' ' || mcpPro.name_last) as mcp_name,
  1662. rmmPro.rmm_payment_strategy,
  1663. rmmPro.rmm_payment_amount,
  1664. (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,
  1665. (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,
  1666. {$genericBillIdColumns}
  1667. FROM care_month join client on care_month.client_id = client.id
  1668. join note mrnote on client.most_recent_completed_mcp_note_id = mrnote.id
  1669. left join pro mcpPro on care_month.mcp_pro_id = mcpPro.id
  1670. left join pro rmmPro on care_month.rmm_pro_id = rmmPro.id
  1671. {$genericBillJoinClause}
  1672. WHERE
  1673. EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1674. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1675. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '') . "
  1676. {$orderBy} OFFSET {$offset} LIMIT {$perPage}
  1677. ";
  1678. // dd($query);
  1679. $patients = DB::select($query);
  1680. $timestamp = strtotime(date('Y-m-d'));
  1681. $daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
  1682. $paginator = new LengthAwarePaginator($patients, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  1683. $perPage = $request->input('per_page') ?: $defaultPageSize;
  1684. $paginator->setPath(route('practice-management.rpm-matrix-admin'));
  1685. return view('app.practice-management.rpm-matrix-for-admin', compact('patients', 'daysRemaining', 'careMonthStart', 'paginator', 'perPage'));
  1686. }
  1687. public function remoteMonitoringMCP(Request $request) {
  1688. return $this->rpmMatrixByProType($request, 'mcp');
  1689. }
  1690. public function remoteMonitoringRMM(Request $request) {
  1691. return $this->rpmMatrixByProType($request, 'rmm');
  1692. }
  1693. public function remoteMonitoringRME(Request $request) {
  1694. return $this->rpmMatrixByProType($request, 'rme');
  1695. }
  1696. public function remoteMonitoring_RowMCP(Request $request) {
  1697. return $this->remoteMonitoring_RowByProType($request, 'mcp');
  1698. }
  1699. public function remoteMonitoring_RowRMM(Request $request) {
  1700. return $this->remoteMonitoring_RowByProType($request, 'rmm');
  1701. }
  1702. public function remoteMonitoring_RowRME(Request $request) {
  1703. return $this->remoteMonitoring_RowByProType($request, 'rme');
  1704. }
  1705. public function remoteMonitoring_RowADMIN(Request $request) {
  1706. return $this->remoteMonitoring_RowForAdmin($request);
  1707. }
  1708. public function rpm_work_matrix(Request $request) {
  1709. // get the patient having most recent unstamped measurement
  1710. $performer = $this->performer();
  1711. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1712. $careMonthStart = date($ym . '-01');
  1713. $patient = null;
  1714. $careMonth = null;
  1715. if($request->input('patientUid') && $request->input('careMonthUid')) {
  1716. $patient = Client::where('uid', $request->input('patientUid'))->first();
  1717. $careMonth = CareMonth::where('uid', $request->input('careMonthUid'))->first();
  1718. }
  1719. if(!$patient && !$careMonth) {
  1720. $query = "
  1721. SELECT client.name_first, client.name_last,
  1722. (client.name_first || ' ' || client.name_last) as client_name,
  1723. client.uid as client_uid,
  1724. client.dob,
  1725. client.is_enrolled_in_rm,
  1726. client.most_recent_completed_mcp_note_date,
  1727. care_month.uid as care_month_uid,
  1728. care_month.id as care_month_id,
  1729. care_month.start_date,
  1730. care_month.rm_total_time_in_seconds_by_mcp,
  1731. care_month.number_of_days_with_remote_measurements,
  1732. care_month.rm_num_measurements_not_stamped_by_mcp,
  1733. care_month.rm_num_measurements_not_stamped_by_rmm,
  1734. client.mcp_pro_id,
  1735. client.default_na_pro_id,
  1736. client.rmm_pro_id,
  1737. client.rme_pro_id,
  1738. client.cell_number,
  1739. client.most_recent_cellular_bp_dbp_mm_hg,
  1740. client.most_recent_cellular_bp_sbp_mm_hg,
  1741. client.most_recent_cellular_bp_measurement_at,
  1742. client.most_recent_cellular_weight_value,
  1743. client.most_recent_cellular_weight_measurement_at,
  1744. GREATEST(client.most_recent_cellular_bp_measurement_at, client.most_recent_cellular_weight_measurement_at) as latest_measurement_at
  1745. FROM care_month join client on care_month.client_id = client.id
  1746. WHERE
  1747. (
  1748. (care_month.mcp_pro_id = {$performer->pro->id} AND care_month.rm_num_measurements_not_stamped_by_mcp > 0) OR
  1749. (care_month.rmm_pro_id = {$performer->pro->id} AND care_month.rm_num_measurements_not_stamped_by_rmm > 0)
  1750. )
  1751. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1752. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1753. ORDER BY latest_measurement_at DESC
  1754. LIMIT 1
  1755. ";
  1756. $patients = DB::select($query);
  1757. if (count($patients)) {
  1758. $patient = Client::where('uid', $patients[0]->client_uid)->first();
  1759. $careMonth = CareMonth::where('uid', $patients[0]->care_month_uid)->first();
  1760. }
  1761. }
  1762. return view('app.practice-management.rpm_work_matrix', compact('patient', 'careMonth'));
  1763. }
  1764. public function remoteMonitoringCount(Request $request) {
  1765. $performer = $this->performer();
  1766. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1767. $careMonthStart = date($ym . '-01');
  1768. $rc = $request->input('rc') ?: 1;
  1769. $rc2 = $request->input('rc2') ?: 2;
  1770. $conditions = $this->rpmConditions($performer, $rc, $rc2);
  1771. $count = DB::select(
  1772. DB::raw(
  1773. "
  1774. SELECT count(*)
  1775. FROM care_month join client on care_month.client_id = client.id
  1776. WHERE
  1777. client.mcp_pro_id = {$performer->pro->id}
  1778. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1779. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1780. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '')
  1781. )
  1782. );
  1783. return $count[0]->count;
  1784. }
  1785. public function remoteMonitoringAdmin(Request $request) {
  1786. $performer = $this->performer();
  1787. // abort_if($performer->pro->pro_type !== 'ADMIN' && !$performer->pro->can_view_rm_matrix, 403);
  1788. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1789. $careMonthStart = date($ym . '-01');
  1790. $rc = $request->input('rc') ?: 1;
  1791. $rc2 = $request->input('rc2') ?: 2;
  1792. $conditions = [];// $this->rpmConditions($performer, $rc, $rc2);
  1793. $sortBy = $request->input('sort_by') ?: 'name_first';
  1794. $sortDir = $request->input('sort_dir') ?: 'ASC';
  1795. $orderBy = "ORDER BY $sortBy $sortDir NULLS LAST";
  1796. $query = "
  1797. SELECT client.name_first, client.name_last,
  1798. (client.name_first || ' ' || client.name_last) as client_name,
  1799. (mcp_pro.name_first || ' ' || mcp_pro.name_last) as mcp_pro_name,
  1800. (rmm_pro.name_first || ' ' || rmm_pro.name_last) as rmm_pro_name,
  1801. client.uid as client_uid,
  1802. client.chart_number,
  1803. client.dob,
  1804. client.is_enrolled_in_rm,
  1805. client.most_recent_completed_mcp_note_date,
  1806. client.most_recent_completed_mcp_note_id,
  1807. mrmnote.effective_dateest::date as most_recent_completed_mcp_note_date_cm,
  1808. mrmnote.id as most_recent_completed_mcp_note_id_cm,
  1809. mrmnote.uid as most_recent_completed_mcp_note_uid_cm,
  1810. client.cell_number,
  1811. client.is_assigned_cellular_bp_device,
  1812. client.is_assigned_cellular_weight_scale_device,
  1813. care_month.uid as care_month_uid,
  1814. care_month.id as care_month_id,
  1815. care_month.start_date,
  1816. care_month.rm_total_time_in_seconds_by_mcp,
  1817. care_month.rm_total_time_in_seconds_by_rmm_pro,
  1818. care_month.number_of_days_with_remote_measurements,
  1819. care_month.has_anyone_interacted_with_client_about_rm,
  1820. care_month.has_mcp_interacted_with_client_about_rm,
  1821. care_month.rm_num_measurements_not_stamped_by_mcp,
  1822. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  1823. care_month.rm_num_measurements_not_stamped_by_rmm,
  1824. care_month.rm_num_measurements_not_stamped_by_rme,
  1825. care_month.mcp_pro_id as care_month_mcp_pro_id,
  1826. care_month.rmm_pro_id as care_month_rmm_pro_id,
  1827. client.mcp_pro_id,
  1828. client.default_na_pro_id,
  1829. client.rmm_pro_id,
  1830. client.rme_pro_id,
  1831. client.cell_number,
  1832. care_month.most_recent_cellular_bp_dbp_mm_hg,
  1833. care_month.most_recent_cellular_bp_sbp_mm_hg,
  1834. care_month.most_recent_cellular_bp_measurement_at,
  1835. care_month.most_recent_cellular_weight_value,
  1836. care_month.most_recent_cellular_weight_measurement_at
  1837. 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
  1838. left join note mrmnote on mrmnote.id = (
  1839. select max(n.id) from note n
  1840. where
  1841. n.client_id = client.id AND
  1842. n.is_cancelled = FALSE AND
  1843. (n.is_signed_by_hcp IS NOT NULL AND n.is_signed_by_hcp = TRUE) AND
  1844. n.effective_dateest::date >= care_month.start_date::date AND
  1845. n.effective_dateest::date < (care_month.start_date::date + INTERVAL '1 month')
  1846. )
  1847. left join pro mcp_pro on care_month.mcp_pro_id = mcp_pro.id
  1848. left join pro rmm_pro on care_month.rmm_pro_id = rmm_pro.id
  1849. WHERE
  1850. EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1851. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1852. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '') . "
  1853. $orderBy
  1854. ";
  1855. $patients = DB::select($query);
  1856. $timestamp = strtotime(date('Y-m-d'));
  1857. $daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
  1858. return view('app.practice-management.remote-monitoring-admin', compact('patients', 'daysRemaining', 'careMonthStart'));
  1859. }
  1860. public function remoteMonitoringAdminCount(Request $request) {
  1861. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1862. $careMonthStart = date($ym . '-01');
  1863. $rc = $request->input('rc') ?: 1;
  1864. $rc2 = $request->input('rc2') ?: 2;
  1865. $conditions = $this->rpmConditionsAdmin($this->performer(), $rc, $rc2);
  1866. $count = DB::select(
  1867. DB::raw(
  1868. "
  1869. SELECT count(*)
  1870. FROM care_month join client on care_month.client_id = client.id
  1871. WHERE
  1872. client.shadow_pro_id is null AND client.is_enrolled_in_rm = 'YES'
  1873. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1874. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1875. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '')
  1876. )
  1877. );
  1878. return $count[0]->count;
  1879. }
  1880. private function rpmConditions($performer, $rc, $rc2) {
  1881. $conditions = [];
  1882. $c_isMCP = "client.mcp_pro_id = {$performer->pro->id}";
  1883. $c_enrolledInRPM = "client.is_enrolled_in_rm = 'YES'";
  1884. $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";
  1885. $c_lastVisitBefore90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) > 90";
  1886. $c_lastVisitWithin90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) <= 90";
  1887. $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)";
  1888. $c_spokenToThisMonth = "care_month.has_anyone_interacted_with_client_about_rm_outside_note = TRUE";
  1889. $c_hasUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp > 0";
  1890. $c_hasNoUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp = 0";
  1891. $c_lt16MeasurementDays = "care_month.number_of_days_with_remote_measurements < 16";
  1892. $c_gte16MeasurementDays = "care_month.number_of_days_with_remote_measurements >= 16";
  1893. $c_subscribedToSMS = "client.send_sms_on_bdt_measurement = TRUE";
  1894. $c_deviceUsed = "(client.most_recent_cellular_bp_measurement_at IS NOT NULL OR most_recent_cellular_weight_measurement_at IS NOT NULL)";
  1895. $c_lt20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp < 1200";
  1896. $c_gte20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp >= 1200";
  1897. switch ($rc) {
  1898. case 1:
  1899. $conditions = [$c_isMCP];
  1900. break;
  1901. case 2:
  1902. $conditions = [$c_isMCP, $c_enrolledInRPM];
  1903. break;
  1904. case 3:
  1905. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice];
  1906. break;
  1907. case 4:
  1908. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, ($rc2 == 1 ? $c_lastVisitBefore90Days : $c_lastVisitWithin90Days)];
  1909. break;
  1910. case 5:
  1911. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, ($rc2 == 1 ? $c_notSpokenToThisMonth : $c_spokenToThisMonth)];
  1912. break;
  1913. case 6:
  1914. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_hasUnstamped : $c_hasNoUnstamped)];
  1915. break;
  1916. case 7:
  1917. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_lt16MeasurementDays : $c_gte16MeasurementDays)];
  1918. break;
  1919. case 10:
  1920. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, $c_gte16MeasurementDays, ($rc2 == 1 ? $c_lt20BillingMinutes : $c_gte20BillingMinutes)];
  1921. break;
  1922. case 8:
  1923. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_subscribedToSMS];
  1924. break;
  1925. case 9:
  1926. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_deviceUsed];
  1927. break;
  1928. }
  1929. return $conditions;
  1930. }
  1931. private function rpmConditionsAdmin($performer, $rc, $rc2) {
  1932. $conditions = [];
  1933. $c_enrolledInRPM = "client.is_enrolled_in_rm = 'YES'";
  1934. $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";
  1935. $c_lastVisitBefore90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) > 90";
  1936. $c_lastVisitWithin90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) <= 90";
  1937. $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)";
  1938. $c_spokenToThisMonth = "care_month.has_anyone_interacted_with_client_about_rm_outside_note = TRUE";
  1939. $c_hasUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp > 0";
  1940. $c_hasNoUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp = 0";
  1941. $c_lt16MeasurementDays = "care_month.number_of_days_with_remote_measurements < 16";
  1942. $c_gte16MeasurementDays = "care_month.number_of_days_with_remote_measurements >= 16";
  1943. $c_subscribedToSMS = "client.send_sms_on_bdt_measurement = TRUE";
  1944. $c_deviceUsed = "(client.most_recent_cellular_bp_measurement_at IS NOT NULL OR client.most_recent_cellular_weight_measurement_at IS NOT NULL)";
  1945. $c_lt20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp < 1200";
  1946. $c_gte20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp >= 1200";
  1947. switch ($rc) {
  1948. case 2:
  1949. $conditions = [$c_enrolledInRPM];
  1950. break;
  1951. case 3:
  1952. $conditions = [$c_enrolledInRPM, $c_hasDevice];
  1953. break;
  1954. case 4:
  1955. $conditions = [$c_enrolledInRPM, $c_hasDevice, ($rc2 == 1 ? $c_lastVisitBefore90Days : $c_lastVisitWithin90Days)];
  1956. break;
  1957. case 5:
  1958. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, ($rc2 == 1 ? $c_notSpokenToThisMonth : $c_spokenToThisMonth)];
  1959. break;
  1960. case 6:
  1961. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_hasUnstamped : $c_hasNoUnstamped)];
  1962. break;
  1963. case 7:
  1964. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_lt16MeasurementDays : $c_gte16MeasurementDays)];
  1965. break;
  1966. case 10:
  1967. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, $c_gte16MeasurementDays, ($rc2 == 1 ? $c_lt20BillingMinutes : $c_gte20BillingMinutes)];
  1968. break;
  1969. case 8:
  1970. $conditions = [$c_enrolledInRPM, $c_subscribedToSMS];
  1971. break;
  1972. case 9:
  1973. $conditions = [$c_enrolledInRPM, $c_deviceUsed];
  1974. break;
  1975. }
  1976. return $conditions;
  1977. }
  1978. public function remoteMonitoringMeasurements(Request $request, CareMonth $careMonth) {
  1979. $performer = $this->performer();
  1980. $measurements = DB::select(
  1981. DB::raw(
  1982. "
  1983. SELECT measurement.label,
  1984. measurement.ts,
  1985. measurement.effective_date,
  1986. measurement.sbp_mm_hg,
  1987. measurement.dbp_mm_hg,
  1988. measurement.value_pulse,
  1989. measurement.value_irregular,
  1990. measurement.numeric_value,
  1991. measurement.value,
  1992. measurement.uid,
  1993. client.name_first,
  1994. client.name_last,
  1995. client.mcp_pro_id,
  1996. client.default_na_pro_id,
  1997. client.rmm_pro_id,
  1998. client.rme_pro_id
  1999. FROM measurement RIGHT JOIN client on measurement.client_id = client.id
  2000. WHERE
  2001. client.id = {$careMonth->client_id}
  2002. AND measurement.label IS NOT NULL
  2003. AND measurement.label NOT IN ('SBP', 'DBP')
  2004. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  2005. AND measurement.is_removed IS FALSE
  2006. AND measurement.client_bdt_measurement_id IS NOT NULL
  2007. AND measurement.care_month_id = {$careMonth->id}
  2008. AND (
  2009. (client.mcp_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_mcp IS FALSE)
  2010. OR (client.rmm_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_rmm IS FALSE)
  2011. OR (client.rme_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_rme IS FALSE)
  2012. OR (client.default_na_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_non_hcp IS FALSE)
  2013. )
  2014. ORDER BY ts DESC
  2015. "
  2016. )
  2017. );
  2018. return view('app.practice-management.remote-monitoring-measurements', compact('careMonth', 'measurements'));
  2019. }
  2020. public function billMatrix(Request $request)
  2021. {
  2022. $bClients = [];
  2023. $bHCPPros = [];
  2024. $bNAPros = [];
  2025. $filters = [];
  2026. $filters['client'] = $request->input('client');
  2027. $filters['service'] = $request->input('service');
  2028. $filters['hcp'] = $request->input('hcp');
  2029. $filters['hcp_paid'] = $request->input('hcp_paid');
  2030. $filters['expected_op'] = $request->input('expected_op');
  2031. $filters['expected_value'] = $request->input('expected_value');
  2032. $filters['paid_op'] = $request->input('paid_op');
  2033. $filters['paid_value'] = $request->input('paid_value');
  2034. $filters['bal_post_date_op'] = $request->input('bal_post_date_op');
  2035. $filters['bal_post_date_value'] = $request->input('bal_post_date_value');
  2036. $filters['hcp_sign'] = $request->input('hcp_sign');
  2037. $filters['verified'] = $request->input('verified');
  2038. $filters['cancelled'] = $request->input('cancelled');
  2039. $bills = Bill::orderBy('effective_date')->paginate();
  2040. return view('app.practice-management.bill-matrix', compact('bills', 'bClients', 'bHCPPros', 'filters'));
  2041. }
  2042. public function medicarePartBClaims(Request $request)
  2043. {
  2044. $medicarePartBOnly = $request->get("medicare_part_b");
  2045. $allClaims = Claim::where('was_submitted', false)->orWhere('was_submitted', null)->orderBy('created_at', 'desc')->get();
  2046. //Only medicare claims
  2047. $claims = [];
  2048. foreach ($allClaims as $claim) {
  2049. if ($claim->client != null && $claim->client->getPrimaryCoverageStatus() == 'YES' && !$claim->edi) {
  2050. $claims[] = $claim;
  2051. }
  2052. }
  2053. $claimEDIs = ClaimEDI::all();
  2054. return view('app.practice-management.medicare-partb-claims', compact('claims', 'claimEDIs'));
  2055. }
  2056. // Generate PDF
  2057. public function downloadClaims()
  2058. {
  2059. $claims = Claim::where('was_submitted', false)->orWhere('was_submitted', null)->orderBy('created_at', 'desc')->limit(100)->get();
  2060. view()->share('claims', $claims);
  2061. $pdf = PDF::loadView('app.practice-management.claims-pdf', $claims);
  2062. return $pdf->download('pdf_file.pdf');
  2063. }
  2064. public function tickets(Request $request, $proUid = null)
  2065. {
  2066. $tickets = Ticket::orderBy('created_at', 'desc')->paginate();
  2067. return view('app.practice-management.tickets', compact('tickets'));
  2068. }
  2069. public function supplyOrders(Request $request)
  2070. {
  2071. // counts
  2072. $counts = $this->getSupplyOrderCounts();
  2073. // so clients
  2074. $soClientIDs = DB::table('supply_order')->select('client_id')->distinct()->get()->toArray();
  2075. $soClientIDs = array_map(function ($_x) {
  2076. return $_x->client_id;
  2077. }, $soClientIDs);
  2078. $soClients = Client::whereIn('id', $soClientIDs)->get();
  2079. // so products
  2080. $soProductIDs = DB::table('supply_order')->select('product_id')->distinct()->get()->toArray();
  2081. $soProductIDs = array_map(function ($_x) {
  2082. return $_x->product_id;
  2083. }, $soProductIDs);
  2084. $soProducts = Product::whereIn('id', $soProductIDs)->get();
  2085. $filters = [];
  2086. $filters['client'] = $request->input('client');
  2087. $filters['product'] = $request->input('product');
  2088. $filters['reason'] = $request->input('reason');
  2089. $filters['cu_memo'] = $request->input('cu_memo');
  2090. $filters['pro_sign'] = $request->input('pro_sign');
  2091. $filters['client_sign'] = $request->input('client_sign');
  2092. $filters['shipment'] = $request->input('shipment');
  2093. $filters['lot_number'] = $request->input('lot_number');
  2094. $filters['imei'] = $request->input('imei');
  2095. $filters['cancelled'] = $request->input('cancelled');
  2096. $supplyOrders = SupplyOrder::where('id', '>', 0);
  2097. // apply filters
  2098. if ($filters['client']) $supplyOrders->where('client_id', $filters['client']);
  2099. if ($filters['product']) $supplyOrders->where('product_id', $filters['product']);
  2100. if ($filters['reason']) $supplyOrders->where('reason', 'ILIKE', '%' . $filters['reason'] . '%');
  2101. if ($filters['cu_memo']) $supplyOrders->where('cu_memo', 'ILIKE', '%' . $filters['cu_memo'] . '%');
  2102. if ($filters['pro_sign']) $supplyOrders->where('is_signed_by_pro', ($filters['pro_sign'] === 'signed'));
  2103. if ($filters['client_sign']) {
  2104. if ($filters['client_sign'] === 'signed')
  2105. $supplyOrders->where('is_signed_by_client', true);
  2106. elseif ($filters['client_sign'] === 'waived')
  2107. $supplyOrders->where('is_client_signature_waived', true);
  2108. else
  2109. $supplyOrders->where('is_client_signature_waived', false)->where('is_signed_by_client', false);
  2110. }
  2111. if ($filters['shipment']) {
  2112. if ($filters['shipment'] === 'not_cleared_for_shipment')
  2113. $supplyOrders->whereNull('shipment_id')->where('is_cleared_for_shipment', false);
  2114. elseif ($filters['shipment'] === 'cleared_for_shipment')
  2115. $supplyOrders->whereNull('shipment_id')->where('is_cleared_for_shipment', true);
  2116. else
  2117. $supplyOrders
  2118. ->whereNotNull('shipment_id')
  2119. ->whereRaw('(SELECT status FROM shipment WHERE id = shipment_id LIMIT 1) = ?', [$filters['shipment']]);
  2120. }
  2121. if ($filters['lot_number']) $supplyOrders->where('lot_number', 'ILIKE', '%' . $filters['lot_number'] . '%');
  2122. if ($filters['imei']) $supplyOrders->where('imei', 'ILIKE', '%' . $filters['imei'] . '%');
  2123. if ($filters['cancelled']) $supplyOrders->where('is_cancelled', ($filters['cancelled'] === 'cancelled'));
  2124. $supplyOrders = $supplyOrders->orderBy('created_at', 'desc')->paginate();
  2125. return view('app.practice-management.supply-orders',
  2126. compact('supplyOrders', 'filters',
  2127. 'soClients', 'soProducts', 'counts'
  2128. )
  2129. );
  2130. }
  2131. public function shipments(Request $request, $filter = null)
  2132. {
  2133. // counts
  2134. $counts = $this->getShipmentCounts();
  2135. // so clients
  2136. $shClientIDs = DB::table('shipment')->select('client_id')->distinct()->get()->toArray();
  2137. $shClientIDs = array_map(function ($_x) {
  2138. return $_x->client_id;
  2139. }, $shClientIDs);
  2140. $shClients = Client::whereIn('id', $shClientIDs)->get();
  2141. $shipments = Shipment::where('id', '>', 0);
  2142. $filters = [];
  2143. $filters['client'] = $request->input('client');
  2144. $filters['courier'] = $request->input('courier');
  2145. $filters['tracking_num'] = $request->input('tracking_num');
  2146. $filters['label'] = $request->input('label');
  2147. $filters['status'] = $request->input('status');
  2148. $filters['cancelled'] = $request->input('cancelled');
  2149. if ($filters['client']) $shipments->where('client_id', $filters['client']);
  2150. if ($filters['courier']) $shipments->where('courier', 'ILIKE', '%' . $filters['courier'] . '%');
  2151. if ($filters['tracking_num']) $shipments->where('tracking_number', 'ILIKE', '%' . $filters['tracking_num'] . '%');
  2152. if ($filters['label']) {
  2153. if ($filters['label'] === 'yes')
  2154. $shipments->whereNotNull('label_system_file_id');
  2155. else
  2156. $shipments->whereNull('label_system_file_id');
  2157. }
  2158. if ($filters['status']) $shipments->where('status', $filters['status']);
  2159. if ($filters['cancelled']) $shipments->where('is_cancelled', ($filters['cancelled'] === 'cancelled'));
  2160. $shipments = $shipments->orderBy('created_at', 'desc')->paginate();
  2161. return view('app.practice-management.shipments', compact('shipments', 'filters', 'shClients', 'counts'));
  2162. }
  2163. public function cellularMeasurements(Request $request)
  2164. {
  2165. $measurements = Measurement::orderBy('ts', 'desc')->whereNotNull('ts')->paginate();
  2166. return view('app.practice-management.cellular-measurements', compact('measurements'));
  2167. }
  2168. // v2 supply-orders & shipments management (wh)
  2169. public function supplyOrdersReadyToShip(Request $request)
  2170. {
  2171. $counts = $this->getSupplyOrderCounts();
  2172. $supplyOrders = SupplyOrder
  2173. ::where('is_cleared_for_shipment', true)
  2174. ->where('is_cancelled', false)
  2175. ->whereNull('shipment_id')
  2176. ->join('client', 'client.id', '=', 'supply_order.client_id')
  2177. ->orderBy('client.name_last', 'ASC')
  2178. ->orderBy('client.name_first', 'ASC')
  2179. ->orderBy('supply_order.client_id', 'ASC')
  2180. ->orderBy('supply_order.mailing_address_full', 'ASC')
  2181. ->orderBy('supply_order.created_at', 'ASC')
  2182. ->select('supply_order.*')
  2183. ->paginate();
  2184. return view('app.practice-management.supply-orders-ready-to-ship', compact('supplyOrders', 'counts'));
  2185. }
  2186. public function supplyOrdersShipmentUnderway(Request $request)
  2187. {
  2188. $counts = $this->getSupplyOrderCounts();
  2189. $supplyOrders = SupplyOrder
  2190. ::where('is_cancelled', false)
  2191. ->whereNotNull('shipment_id')
  2192. ->orderBy('client_id', 'ASC')
  2193. ->orderBy('mailing_address_full', 'ASC')
  2194. ->orderBy('created_at', 'ASC')
  2195. ->paginate();
  2196. return view('app.practice-management.supply-orders-shipment-underway', compact('supplyOrders', 'counts'));
  2197. }
  2198. public function supplyOrdersHanging(Request $request)
  2199. {
  2200. $counts = $this->getSupplyOrderCounts();
  2201. $supplyOrders = SupplyOrder
  2202. ::select('supply_order.*')
  2203. ->leftJoin('shipment', function($join) {
  2204. $join->on('supply_order.shipment_id', '=', 'shipment.id');
  2205. })
  2206. ->where('shipment.status', 'CANCELLED')
  2207. ->where('supply_order.is_cancelled', false)
  2208. ->orderBy('supply_order.client_id', 'ASC')
  2209. ->orderBy('supply_order.mailing_address_full', 'ASC')
  2210. ->orderBy('supply_order.created_at', 'ASC')
  2211. ->paginate();
  2212. return view('app.practice-management.supply-orders-hanging', compact('supplyOrders', 'counts'));
  2213. }
  2214. public function supplyOrdersCancelledButUnacknowledged(Request $request)
  2215. {
  2216. $supplyOrders = SupplyOrder::where('signed_by_pro_id', $this->performer()->pro->id)
  2217. ->where('is_cancelled', true)
  2218. ->where('is_cancellation_acknowledged', false)
  2219. ->orderBy('created_at', 'desc')
  2220. ->paginate();
  2221. return view('app.practice-management.supply-orders-cancelled-but-unacknowledged', compact('supplyOrders'));
  2222. }
  2223. public function supplyOrdersUnsigned(Request $request)
  2224. {
  2225. $supplyOrders = SupplyOrder
  2226. ::where('is_cancelled', false)
  2227. ->where('is_signed_by_pro', false)
  2228. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$this->performer()->pro->id])
  2229. ->orderBy('created_at', 'desc')
  2230. ->paginate();
  2231. return view('app.practice-management.supply-orders-unsigned', compact('supplyOrders'));
  2232. }
  2233. private function getSupplyOrderCounts()
  2234. {
  2235. return [
  2236. "supplyOrders" => SupplyOrder::count(),
  2237. "supplyOrdersReadyToShip" => SupplyOrder
  2238. ::where('is_cleared_for_shipment', true)
  2239. ->where('is_cancelled', false)
  2240. ->whereNull('shipment_id')->count(),
  2241. "supplyOrdersShipmentUnderway" => SupplyOrder
  2242. ::where('is_cancelled', false)
  2243. ->whereNotNull('shipment_id')->count(),
  2244. "supplyOrdersHanging" => SupplyOrder
  2245. ::leftJoin('shipment', function($join) {
  2246. $join->on('supply_order.shipment_id', '=', 'shipment.id');
  2247. })
  2248. ->where('shipment.status', 'CANCELLED')
  2249. ->where('supply_order.is_cancelled', false)
  2250. ->count(),
  2251. ];
  2252. }
  2253. public function shipmentsReadyToPrint(Request $request)
  2254. {
  2255. $counts = $this->getShipmentCounts();
  2256. $shipments = Shipment
  2257. ::where('is_cancelled', false)
  2258. ->where('status', 'CREATED')
  2259. ->orderBy('created_at', 'ASC')
  2260. ->paginate();
  2261. return view('app.practice-management.shipments-ready-to-print', compact('shipments', 'counts'));
  2262. }
  2263. public function shipmentsShipmentUnderway(Request $request)
  2264. {
  2265. $counts = $this->getShipmentCounts();
  2266. $shipments = Shipment
  2267. ::where('is_cancelled', false)
  2268. ->where('status', 'PRINTED')
  2269. ->orderBy('created_at', 'ASC')
  2270. ->paginate();
  2271. return view('app.practice-management.shipments-waiting-for-picker', compact('shipments', 'counts'));
  2272. }
  2273. private function getShipmentCounts()
  2274. {
  2275. return [
  2276. "shipments" => Shipment::count(),
  2277. "shipmentsReadyToPrint" => Shipment
  2278. ::where('is_cancelled', false)
  2279. ->where('status', 'CREATED')
  2280. ->count(),
  2281. "shipmentsWaitingForPicker" => Shipment
  2282. ::where('is_cancelled', false)
  2283. ->where('status', 'PRINTED')
  2284. ->count()
  2285. ];
  2286. }
  2287. public function shipment(Request $request, Shipment $shipment)
  2288. {
  2289. return view('app.practice-management.shipment', compact('shipment'));
  2290. }
  2291. public function shipmentsMultiPrint(Request $request, $ids)
  2292. {
  2293. $ids = array_map(function ($_x) {
  2294. return intval($_x);
  2295. }, explode("|", $ids));
  2296. $shipments = Shipment::whereIn('id', $ids)->get();
  2297. return view('app.practice-management.shipments-multi-print', compact('shipments'));
  2298. }
  2299. public function patientClaimSummary(Request $request, $proUid = null)
  2300. {
  2301. $notesTotal = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE"))[0]->count;
  2302. $notesTotalWithBillingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE AND is_bill_closed IS TRUE"))[0]->count;
  2303. $notesTotalWithClaimingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE AND is_claim_closed IS TRUE"))[0]->count;
  2304. $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;
  2305. $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;
  2306. $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;
  2307. $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;
  2308. $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;
  2309. $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;
  2310. $performerPro = $this->performer->pro;
  2311. $allPros = [];
  2312. if ($performerPro->pro_type == 'ADMIN') {
  2313. $allPros = Pro::all();
  2314. } else {
  2315. $allPros = [$performerPro];
  2316. }
  2317. //Patient | MCP | # Notes Total | # Notes without Billing Closed | # Notes without Claiming Closed
  2318. $patientsQuery = Client::where('is_dummy', '=', false)
  2319. ->whereNull('shadow_pro_id')
  2320. ->select('id', 'uid', 'name_first', 'name_last', 'mcp_pro_id', 'is_part_b_primary', 'medicare_advantage_plan',
  2321. DB::raw("(SELECT name_first||' '||name_last FROM pro where pro.id = client.mcp_pro_id) as mcp"),
  2322. DB::raw("(SELECT uid FROM pro where pro.id = mcp_pro_id) as mcp_pro_uid"),
  2323. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id) as notes_total"),
  2324. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id AND is_bill_closed IS NOT true) as notes_without_billing_closed"),
  2325. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id AND is_claim_closed IS NOT true) as notes_without_claiming_closed")
  2326. )->orderBy('is_part_b_primary', 'asc')->orderBy('notes_without_claiming_closed', 'desc');
  2327. if ($proUid) {
  2328. $mcpPro = Pro::where('uid', $proUid)->first();
  2329. if ($mcpPro) {
  2330. $patientsQuery->where('client.mcp_pro_id', '=', $mcpPro->id);
  2331. }
  2332. }
  2333. $patientsQuery->whereRaw('(SELECT COUNT(*) FROM note where note.client_id = client.id) > 0');
  2334. $patientsQuery->orderBy('notes_total', 'DESC');
  2335. $patients = $patientsQuery->paginate(50);
  2336. $data = [
  2337. 'patients' => $patients,
  2338. 'proUid' => $proUid,
  2339. 'allPros' => $allPros,
  2340. 'notesTotal' => $notesTotal,
  2341. 'notesTotalWithBillingClosed' => $notesTotalWithBillingClosed,
  2342. 'notesTotalWithClaimingClosed' => $notesTotalWithClaimingClosed,
  2343. 'notes3rdPartyTotal' => $notes3rdPartyTotal,
  2344. 'notes3rdPartyTotalWithBillingClosed' => $notes3rdPartyTotalWithBillingClosed,
  2345. 'notes3rdPartyTotalWithClaimingClosed' => $notes3rdPartyTotalWithClaimingClosed,
  2346. 'patientsTotal' => $patientsTotal,
  2347. 'patientsTotalWithBillingClosed' => $patientsTotalWithBillingClosed,
  2348. 'patientsTotalWithClaimingClosed' => $patientsTotalWithClaimingClosed
  2349. ];
  2350. return view('app.practice-management.patient-claim-summary', $data);
  2351. }
  2352. public function claims(Request $request){
  2353. $status = $request->get('status');
  2354. $claims = [];
  2355. if(!$status){
  2356. $claims = Claim::orderBy('created_at', 'DESC')->paginate();
  2357. }else{
  2358. $claims = Claim::where('status', $status)->orderBy('created_at', 'DESC')->paginate();
  2359. }
  2360. return view('app.practice-management.claims', compact('claims', 'status'));
  2361. }
  2362. public function processClaims(Request $request) {
  2363. $status = '';
  2364. $q = $request->input('q') ? $request->input('q') : '';
  2365. $from = $request->input('from') ? $request->input('from') : '1900-01-01';
  2366. $to = $request->input('to') ? $request->input('to') : '2100-01-01';
  2367. $params = [
  2368. 'q' => '%' . $q . '%',
  2369. 'from' => $from,
  2370. 'to' => $to
  2371. ];
  2372. $hcpPro = $request->input('hcp') ? Pro::where('uid', $request->input('hcp'))->first() : null;
  2373. if($hcpPro) {
  2374. $params['hcp'] = $hcpPro->id;
  2375. }
  2376. $claims = DB::select(DB::raw("
  2377. SELECT claim.uid AS uid,
  2378. DATE(claim.created_at) AS created,
  2379. claim.status,
  2380. client.uid AS client_uid,
  2381. client.cell_number AS client_phone,
  2382. client.phone_home AS client_phone_home,
  2383. (client.name_last || ' ' || client.name_first) AS client ,
  2384. client.chart_number AS client_chart_number,
  2385. cp.id AS claim_pro_id,
  2386. (cp.name_last || ' ' || cp.name_first) AS claim_pro,
  2387. sp.id AS status_pro_id,
  2388. (sp.name_last || ' ' || sp.name_first) AS status_pro,
  2389. note.uid AS note_uid,
  2390. note.method,
  2391. note.new_or_fu_or_na,
  2392. care_month.uid AS care_month_uid,
  2393. care_month.start_date as care_month_start__date,
  2394. -- claim.status_updated_at,
  2395. (DATE(claim.status_updated_at) || ' ' ||
  2396. LPAD(EXTRACT(hour FROM claim.status_updated_at)::text, 2, '0') || ':' ||
  2397. LPAD(EXTRACT(minute FROM claim.status_updated_at)::text, 2, '0')) AS status_updated_at,
  2398. (SELECT string_agg(claim_line.cpt, ', ') FROM claim_line where claim_id = claim.id) AS cpts,
  2399. (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,
  2400. ROUND(claim.expected_total, 3) as expected_total
  2401. FROM claim
  2402. join client on claim.client_id = client.id
  2403. join pro cp on claim.pro_id = cp.id
  2404. left join note on claim.note_id = note.id
  2405. left join care_month on claim.care_month_id = care_month.id
  2406. left join app_session on claim.status_updated_by_session_id = app_session.id
  2407. left join pro sp on app_session.pro_id = sp.id
  2408. --WHERE claim.status IS NULL OR claim.status = 'NEW'
  2409. WHERE (claim.status is NULL OR claim.status NOT IN ('CANCELLED', 'ABANDONED'" . ($request->input('show-submitted') ? "" : ", 'SUBMITTED'") . "))
  2410. -- AND claim.current_version_id IS NOT NULL
  2411. AND (client.name_first ILIKE :q OR
  2412. client.name_last ILIKE :q OR
  2413. client.chart_number ILIKE :q OR
  2414. client.mcn ILIKE :q)
  2415. AND (claim.created_at >= :from AND claim.created_at <= :to)
  2416. " . ($hcpPro ? "AND claim.pro_id = :hcp" : '') . "
  2417. AND claim.id IN (SELECT mb_claim.claim_id FROM mb_claim)
  2418. ORDER BY claim.created_at DESC
  2419. --OFFSET 0 LIMIT 15
  2420. "), $params);
  2421. if($request->input('json')) {
  2422. return json_encode($claims);
  2423. }
  2424. return view('app.practice-management.process-claims', compact('claims', 'status'));
  2425. }
  2426. public function rmLaunchAndClean(Request $request) {
  2427. $keyNumbers = [];
  2428. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_40'] = CareMonth::where('is_bill_closed', false)
  2429. ->whereNotNull('company_pro_id')
  2430. ->whereNotNull('company_pro_payer_id')
  2431. ->whereNotNull('company_location_id')
  2432. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2433. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  2434. ->where('rm_total_time_in_seconds', '>=', 4200) // at 4200 (70 minutes, it becomes eligible for plus40)
  2435. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2436. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2437. ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS TRUE OR has_mcp_rm_interacted_by_note IS TRUE )')
  2438. ->count();
  2439. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_40_ifHadInteraction'] = 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 NOT TRUE AND has_mcp_rm_interacted_by_note IS NOT TRUE AND is_rm_interaction_waived IS NOT TRUE )')
  2449. ->count();
  2450. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_20'] = 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)
  2457. ->where('rm_total_time_in_seconds', '>=', 3000) // at 3000 (50 minutes, it becomes eligible for plus20)
  2458. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2459. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2460. ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS TRUE OR has_mcp_rm_interacted_by_note IS TRUE)')
  2461. ->count();
  2462. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_20_ifHadInteraction'] = CareMonth::where('is_bill_closed', false)
  2463. ->whereNotNull('company_pro_id')
  2464. ->whereNotNull('company_pro_payer_id')
  2465. ->whereNotNull('company_location_id')
  2466. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2467. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  2468. ->where('rm_total_time_in_seconds', '<', 4200)
  2469. ->where('rm_total_time_in_seconds', '>=', 3000) // at 3000 (50 minutes, it becomes eligible for plus20)
  2470. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2471. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2472. ->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 )')
  2473. ->count();
  2474. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP'] = CareMonth::where('is_bill_closed', false)
  2475. ->whereNotNull('company_pro_id')
  2476. ->whereNotNull('company_pro_payer_id')
  2477. ->whereNotNull('company_location_id')
  2478. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2479. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  2480. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2481. ->whereRaw('(rm_total_time_in_seconds < 3000 OR (rm_total_time_in_seconds >= 3000 AND is_rm_interaction_waived IS TRUE))')
  2482. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2483. ->count();
  2484. $keyNumbers['careMonthsEligibleForBillGeneration_RMB'] = CareMonth::where('is_bill_closed', false)
  2485. ->whereNotNull('company_pro_id')
  2486. ->whereNotNull('company_pro_payer_id')
  2487. ->whereNotNull('company_location_id')
  2488. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2489. ->whereRaw('is_rm_time_waived IS TRUE')
  2490. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2491. ->count();
  2492. $keyNumbers['careMonthsWith16OrMoreMeasurementDays'] = CareMonth::where('is_bill_closed', false)
  2493. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2494. ->count();
  2495. $careMonthsWith16PlusMeasurements = CareMonth::where('is_bill_closed', false)
  2496. ->where('number_of_days_with_remote_measurements', '>=', 16 )->get();
  2497. return view('app.practice-management.rm-launch-and-clean', compact('keyNumbers', 'careMonthsWith16PlusMeasurements'));
  2498. }
  2499. public function processNotes(Request $request) {
  2500. $mode = $request->input('mode') ? $request->input('mode') : '1';
  2501. if(($mode < 1 || $mode > 5) && $mode != 8) $mode = 1;
  2502. DB::enableQueryLog(); // Enable query log
  2503. $test = Note::where('is_cancelled', false)
  2504. ->where('is_signed_by_hcp', true)
  2505. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  2506. ->whereNull('current_note_pickup_for_processing_id')
  2507. ->where('is_billing_marked_done', true)
  2508. ->where('is_bill_closed', true)
  2509. ->where('is_claim_closed', true)
  2510. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  2511. ->count();
  2512. // var_dump($test);
  2513. // dd(DB::getQueryLog()); // Show results of log
  2514. // exit;
  2515. $counts = [
  2516. "picked" => Note::where('is_cancelled', false)
  2517. ->whereNotNull('current_note_pickup_for_processing_id')
  2518. ->count(),
  2519. "bad" => Note::where('is_cancelled', false)
  2520. ->whereRaw("((detail_json)::json->>'isBad' = 'true')")
  2521. ->count(),
  2522. // not yet signed
  2523. "mode-1" => Note::where('is_cancelled', false)
  2524. ->where('is_signed_by_hcp', false)
  2525. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2526. // ->whereNull('current_note_pickup_for_processing_id')
  2527. ->count(),
  2528. // billing not marked done
  2529. "mode-2" => Note::where('is_cancelled', false)
  2530. ->where('is_signed_by_hcp', true)
  2531. //->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2532. // ->whereNull('current_note_pickup_for_processing_id')
  2533. ->where('is_billing_marked_done', false)
  2534. ->count(),
  2535. // billing not closed
  2536. "mode-3" => Note::where('is_cancelled', false)
  2537. ->where('is_signed_by_hcp', true)
  2538. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2539. // ->whereNull('current_note_pickup_for_processing_id')
  2540. ->where('is_billing_marked_done', true)
  2541. ->where('is_bill_closed', false)
  2542. ->count(),
  2543. // claiming not closed
  2544. "mode-4" => Note::where('is_cancelled', false)
  2545. ->where('is_signed_by_hcp', true)
  2546. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2547. // ->whereNull('current_note_pickup_for_processing_id')
  2548. ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true' OR ((detail_json)::json->>'isGood')::text IS NULL)")
  2549. ->where('is_billing_marked_done', true)
  2550. ->where('is_bill_closed', true)
  2551. ->where('is_claim_closed', false)
  2552. ->count(),
  2553. // has unsubmitted claims
  2554. "mode-5" => Note::where('is_cancelled', false)
  2555. /*->where('is_signed_by_hcp', true)
  2556. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2557. ->whereNull('current_note_pickup_for_processing_id')
  2558. ->where('is_billing_marked_done', true)
  2559. ->where('is_bill_closed', true)
  2560. ->where('is_claim_closed', true)
  2561. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0")
  2562. */
  2563. ->where('is_signed_by_hcp', true)
  2564. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2565. // ->whereNull('current_note_pickup_for_processing_id')
  2566. ->where('is_billing_marked_done', true)
  2567. ->where('is_bill_closed', true)
  2568. // ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true')")
  2569. ->where('is_claim_closed', true)
  2570. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0)")
  2571. ->count(),
  2572. // has unsubmitted claims MARKED GOOD!
  2573. "mode-8" => Note::where('is_cancelled', false)
  2574. ->where('is_signed_by_hcp', true)
  2575. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  2576. ->whereNull('current_note_pickup_for_processing_id')
  2577. ->where('is_billing_marked_done', true)
  2578. ->where('is_bill_closed', true)
  2579. ->where('is_claim_closed', false)
  2580. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  2581. ->count(),
  2582. // all good
  2583. "mode-6" => Note::where('is_cancelled', false)
  2584. ->where('is_signed_by_hcp', true)
  2585. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2586. // ->whereNull('current_note_pickup_for_processing_id')
  2587. ->where('is_billing_marked_done', true)
  2588. ->where('is_bill_closed', true)
  2589. ->where('is_claim_closed', true)
  2590. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id) > 0)")
  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. "mode-7" => Note::where('is_cancelled', false)
  2594. ->whereRaw("(detail_json)::json->>'isBad' = 'true'")
  2595. ->count(),
  2596. ];
  2597. return view('app.practice-management.process-notes', compact('mode', 'counts'));
  2598. }
  2599. public function notesProcessingCenter(Request $request) {
  2600. $notes = Note::where('is_cancelled', false);
  2601. // filters
  2602. $proUid = $request->input('proUid');
  2603. if($proUid) {
  2604. $fPro = Pro::where('uid', $proUid)->first();
  2605. if($fPro) {
  2606. $notes = $notes->where('hcp_pro_id', $fPro->id);
  2607. }
  2608. }
  2609. $proSigned = $request->input('proSigned');
  2610. switch($proSigned) {
  2611. case 'yes': $notes = $notes->where('is_signed_by_hcp', true); break;
  2612. case 'no': $notes = $notes->where('is_signed_by_hcp', '!=', true); break;
  2613. }
  2614. $billingMarkedDone = $request->input('billingMarkedDone');
  2615. switch($billingMarkedDone) {
  2616. case 'yes': $notes = $notes->where('is_billing_marked_done', true); break;
  2617. case 'no': $notes = $notes->where('is_billing_marked_done', '!=', true); break;
  2618. }
  2619. $billingClosed = $request->input('billingClosed');
  2620. switch($billingClosed) {
  2621. case 'yes': $notes = $notes->where('is_bill_closed', true); break;
  2622. case 'no': $notes = $notes->where('is_bill_closed', '!=', true); break;
  2623. }
  2624. $claimingClosed = $request->input('claimingClosed');
  2625. switch($claimingClosed) {
  2626. case 'yes': $notes = $notes->where('is_claim_closed', true); break;
  2627. case 'no': $notes = $notes->where('is_claim_closed', '!=', true); break;
  2628. }
  2629. $allClaimsSubmitted = $request->input('allClaimsSubmitted');
  2630. if($allClaimsSubmitted) {
  2631. // TODO
  2632. }
  2633. $goodBad = $request->input('goodBad');
  2634. switch($goodBad) {
  2635. case 'good': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' = 'false'"); break;
  2636. case 'bad': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' = 'true'"); break;
  2637. case 'unclassified': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' is null"); break;
  2638. }
  2639. $startDate = $request->input('startDate');
  2640. if($startDate) {
  2641. $notes = $notes->where('effective_dateest', '>=', $startDate);
  2642. }
  2643. $endDate = $request->input('endDate');
  2644. if($endDate) {
  2645. $notes = $notes->where('effective_dateest', '<=', $endDate);
  2646. }
  2647. $mcPartB = $request->input('mcPartB');
  2648. if($mcPartB) {
  2649. // TODO
  2650. }
  2651. $notes = $notes->orderBy('effective_dateest')->paginate(10);
  2652. return view('app.practice-management.notes-processing-center', compact('notes'));
  2653. }
  2654. public function getNextNote(Request $request, $mode)
  2655. {
  2656. $note = null;
  2657. switch (+$mode) {
  2658. case 1:
  2659. $note = Note::where('is_cancelled', false)
  2660. ->where('is_signed_by_hcp', false)
  2661. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2662. ->whereNull('current_note_pickup_for_processing_id')
  2663. ->orderBy('effective_dateest', 'DESC')
  2664. ->first();
  2665. break;
  2666. case 2:
  2667. $note = Note::where('is_cancelled', false)
  2668. ->where('is_signed_by_hcp', true)
  2669. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2670. ->whereNull('current_note_pickup_for_processing_id')
  2671. ->where('is_billing_marked_done', false)
  2672. ->orderBy('effective_dateest', 'DESC')
  2673. ->first();
  2674. break;
  2675. case 3:
  2676. $note = Note::where('is_cancelled', false)
  2677. ->where('is_signed_by_hcp', true)
  2678. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2679. ->whereNull('current_note_pickup_for_processing_id')
  2680. ->where('is_billing_marked_done', true)
  2681. ->where('is_bill_closed', false)
  2682. ->orderBy('effective_dateest', 'DESC')
  2683. ->first();
  2684. break;
  2685. case 4: // claiming not closed
  2686. DB::enableQueryLog(); // Enable query log
  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', true)
  2693. ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true' OR ((detail_json)::json->>'isGood')::text IS NULL)")
  2694. ->where('is_claim_closed', false)
  2695. ->orderBy('effective_dateest', 'DESC')
  2696. ->first();
  2697. // DB::enableQueryLog(); // Enable query log
  2698. // Your Eloquent query executed by using get()
  2699. // dd(DB::getQueryLog()); // Show results of log
  2700. break;
  2701. case 5:
  2702. $note = Note::where('is_cancelled', false)
  2703. ->where('is_signed_by_hcp', true)
  2704. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2705. ->whereNull('current_note_pickup_for_processing_id')
  2706. ->where('is_billing_marked_done', true)
  2707. ->where('is_bill_closed', true)
  2708. ->where('is_claim_closed', true)
  2709. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0")
  2710. ->orderBy('effective_dateest', 'DESC')
  2711. ->first();
  2712. break;
  2713. case 8:
  2714. $note = Note::where('is_cancelled', false)
  2715. ->where('is_signed_by_hcp', true)
  2716. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  2717. ->whereNull('current_note_pickup_for_processing_id')
  2718. ->where('is_billing_marked_done', true)
  2719. ->where('is_bill_closed', true)
  2720. ->where('is_claim_closed', false)
  2721. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  2722. ->orderBy('effective_dateest', 'DESC')
  2723. ->first();
  2724. break;
  2725. }
  2726. if($note) {
  2727. $note->client_uid = $note->client->uid;
  2728. }
  2729. return json_encode($note);
  2730. }
  2731. public function pickedNotes(Request $request) {
  2732. $counts = [
  2733. "unpicked" => Note::where('is_cancelled', false)
  2734. ->whereNull('current_note_pickup_for_processing_id')
  2735. ->count(),
  2736. ];
  2737. $notes = Note::where('is_cancelled', false)
  2738. ->whereNotNull('current_note_pickup_for_processing_id')
  2739. ->orderBy('effective_dateest', 'ASC')
  2740. ->paginate();
  2741. return view('app.practice-management.picked-notes', compact('counts', 'notes'));
  2742. }
  2743. public function badNotes(Request $request) {
  2744. $counts = [
  2745. "unpicked" => Note::where('is_cancelled', false)
  2746. ->whereNull('current_note_pickup_for_processing_id')
  2747. ->count(),
  2748. ];
  2749. $notes = Note::where('is_cancelled', false)
  2750. ->whereRaw("(detail_json)::json->>'isBad' = 'true'")
  2751. ->orderBy('effective_dateest', 'ASC')
  2752. ->paginate();
  2753. return view('app.practice-management.bad-notes', compact('counts', 'notes'));
  2754. }
  2755. public function doneNotes(Request $request) {
  2756. $counts = [
  2757. "unpicked" => Note::where('is_cancelled', false)
  2758. ->whereNull('current_note_pickup_for_processing_id')
  2759. ->count(),
  2760. ];
  2761. $notes = Note::where('is_cancelled', false)
  2762. ->where('is_signed_by_hcp', true)
  2763. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2764. ->whereNull('current_note_pickup_for_processing_id')
  2765. ->where('is_billing_marked_done', true)
  2766. ->where('is_bill_closed', true)
  2767. ->where('is_claim_closed', true)
  2768. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id) > 0")
  2769. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0")
  2770. ->orderBy('effective_dateest', 'ASC')
  2771. ->paginate();
  2772. return view('app.practice-management.done-notes', compact('counts', 'notes'));
  2773. }
  2774. public function currentMbClaim(Request $request, $claimUid) {
  2775. $claim = Claim::where('uid', $claimUid)->first();
  2776. return json_encode(MBClaim::where('claim_version_id', $claim->currentVersion->id)->where('status', '!=', 'CANCELLED')->first());
  2777. }
  2778. public function currentClaimLines(Request $request, $claimUid) {
  2779. $claim = Claim::where('uid', $claimUid)->first();
  2780. if($request->input('json')) {
  2781. foreach ($claim->lines as $line) {
  2782. $line->expected_total = round($line->expected_total, 3);
  2783. $x = $line->claimLineIcds;
  2784. }
  2785. return json_encode($claim->lines);
  2786. }
  2787. return view('app.practice-management._claim-lines', compact('claim'));
  2788. }
  2789. public function packsMultiPrint(Request $request) {
  2790. $packs = Pack
  2791. ::select('pack.*')
  2792. ->leftJoin('shipment', function($join) {
  2793. $join->on('pack.shipment_id', '=', 'shipment.id');
  2794. })
  2795. ->whereNotIn('shipment.status', ['CANCELLED', 'DISPATCHED'])
  2796. ->where(function ($query) {
  2797. $query->where('pack.status', '<>', 'DELETED')->orWhereNull('pack.status'); // weird, but just the <> isn't working!
  2798. })
  2799. ->whereNotNull('pack.label_system_file_id')
  2800. ->orderBy('pack.created_at', 'ASC')
  2801. ->get();
  2802. return view('app.practice-management.packs-multi-print', compact('packs'));
  2803. }
  2804. public function packsMultiPDF(Request $request, $ids) {
  2805. $ids = array_map(function ($_x) {
  2806. return intval($_x);
  2807. }, explode("|", $ids));
  2808. $packs = Pack::whereIn('id', $ids)->get();
  2809. }
  2810. public function handouts(Request $request) {
  2811. $handouts = Handout::orderBy('display_name')->get();
  2812. return view('app.practice-management.handouts', compact('handouts'));
  2813. }
  2814. private function callJava($request, $endPoint, $data)
  2815. {
  2816. $url = config('stag.backendUrl') . $endPoint;
  2817. $response = Http::asForm()
  2818. ->withHeaders([
  2819. 'sessionKey' => $request->cookie('sessionKey')
  2820. ])
  2821. ->post($url, $data)
  2822. ->body();
  2823. dd($response);
  2824. return $response;
  2825. }
  2826. public function genericBills(Request $request)
  2827. {
  2828. return view('app.practice-management.generic-bills');
  2829. }
  2830. public function billsUnderProcessing(Request $request)
  2831. {
  2832. $bills = Bill::where('is_cancelled', false)
  2833. ->where(function ($query) { // mcp of any client program and program OB pending
  2834. $query
  2835. ->where(function ($_query) {
  2836. $_query->where('hcp_pro_id', $this->pro->id)
  2837. ->where('hcp_expected_payment_amount', '>', 0)
  2838. ->where('has_hcp_been_paid', false)
  2839. ->where('is_signed_by_hcp', true);
  2840. })
  2841. ->orWhere(function ($_query) {
  2842. $_query->where('cm_pro_id', $this->pro->id)
  2843. ->where('cm_expected_payment_amount', '>', 0)
  2844. ->where('has_cm_been_paid', false)
  2845. ->where('is_signed_by_cm', true);
  2846. })
  2847. ->orWhere(function ($_query) {
  2848. $_query->where('rme_pro_id', $this->pro->id)
  2849. ->where('rme_expected_payment_amount', '>', 0)
  2850. ->where('has_rme_been_paid', false)
  2851. ->where('is_signed_by_rme', true);
  2852. })
  2853. ->orWhere(function ($_query) {
  2854. $_query->where('rmm_pro_id', $this->pro->id)
  2855. ->where('rmm_expected_payment_amount', '>', 0)
  2856. ->where('has_rmm_been_paid', false)
  2857. ->where('is_signed_by_rmm', true);
  2858. })
  2859. ->orWhere(function ($_query) {
  2860. $_query->where('generic_pro_id', $this->pro->id)
  2861. ->where('generic_pro_expected_payment_amount', '>', 0)
  2862. ->where('has_generic_pro_been_paid', false)
  2863. ->where('is_signed_by_generic_pro', true);
  2864. });
  2865. })
  2866. ->orderBy('created_at', 'DESC')
  2867. ->paginate();
  2868. return view('app.practice-management.bills-under-processing', compact('bills'));
  2869. }
  2870. public function careMonthReport(Request $request) {
  2871. $m = $request->input('m');
  2872. $y = $request->input('y');
  2873. if(!$m || !$y) {
  2874. $date = date('Y-m-01');
  2875. }
  2876. else {
  2877. $date = date('Y-m-d', strtotime("$m/1/$y"));
  2878. }
  2879. $pro = $this->pro;
  2880. $records = DB::select("
  2881. SELECT cm.id as care_month_id,
  2882. cm.uid as care_month_uid,
  2883. c.id as client_id,
  2884. c.uid as client_uid,
  2885. cm.number_of_days_with_remote_measurements,
  2886. cm.rm_total_time_in_seconds_by_mcp,
  2887. cm.rm_total_time_in_seconds_by_rme_pro,
  2888. cm.rm_total_time_in_seconds_by_rmm_pro,
  2889. cm.mcp_pro_id,
  2890. cm.rme_pro_id,
  2891. cm.rmm_pro_id,
  2892. (c.name_first || ' ' || c.name_last) as client_name
  2893. FROM care_month cm
  2894. JOIN client c on cm.client_id = c.id
  2895. WHERE cm.start_date = :startDate
  2896. AND (cm.mcp_pro_id = :proID OR
  2897. cm.rme_pro_id = :proID OR
  2898. cm.rmm_pro_id = :proID)
  2899. ORDER BY c.name_last, c.name_first
  2900. ",
  2901. ['startDate' => $date, 'proID' => $pro->id]
  2902. );
  2903. return view('app.practice-management.care-month-report', compact('records', 'date'));
  2904. }
  2905. public function myTeams(Request $request) {
  2906. $pro = $this->pro;
  2907. // get all teams where the authed-pro is the assistant pro
  2908. $teams = ProTeam::where('assistant_pro_id', $pro->id)
  2909. ->where('is_active', true)
  2910. ->orderBy('slug')
  2911. ->get();
  2912. return view('app.practice-management.my-teams', compact('teams'));
  2913. }
  2914. public function patientsAccountsInvites(Request $request){
  2915. $filters = $request->all();
  2916. $accountInvites = AccountInvite::select('account_invite.*')
  2917. ->join('client', 'client.id', '=', 'account_invite.for_client_id');
  2918. if($this->performer->pro->pro_type !== 'ADMIN'){
  2919. $accountInvites = $accountInvites->where('client.mcp_pro_id', $this->performer->pro->id);
  2920. }
  2921. $this->filterMultiQuery($request, $accountInvites, 'account_invite.created_at', 'date_category', 'date_value_1', 'date_value_2');
  2922. $this->filterSimpleQuery($request, $accountInvites, 'account_invite.status', 'status');
  2923. $accountInvites = $accountInvites->orderBy('created_at', 'DESC')->paginate(20);
  2924. return view('app.practice-management.patients-accounts-invites', compact('accountInvites','filters'));
  2925. }
  2926. public function clientsBdtDevices(Request $request){
  2927. $filters = $request->all();
  2928. $devices = ClientBDTDevice::select(
  2929. 'client_bdt_device.*',
  2930. 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'))
  2931. // 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'))
  2932. ->join('client', 'client.id', '=', 'client_bdt_device.client_id');
  2933. if($this->performer->pro->pro_type !== 'ADMIN'){
  2934. $devices = $devices->where('client.mcp_pro_id', $this->performer->pro->id);
  2935. }
  2936. $this->filterMultiQuery($request, $devices, 'client_bdt_device.most_recent_measurement_at', 'date_category', 'date_value_1', 'date_value_2');
  2937. // $dateKeyName = $request->get('date_category');
  2938. // $date1 = $request->get('date_value_1');
  2939. // $date2 = $request->get('date_value_2');
  2940. // $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)";
  2941. // switch($dateKeyName) {
  2942. // case 'EXACTLY':
  2943. // if($date1) {
  2944. // $devices->whereRaw($dateColumnName." = '$date1'::DATE");
  2945. // }
  2946. // break;
  2947. // case 'LESS_THAN':
  2948. // if($date1) {
  2949. // $devices->whereRaw($dateColumnName. "< '$date1'::DATE" );
  2950. // }
  2951. // break;
  2952. // case 'GREATER_THAN':
  2953. // if($date1) {
  2954. // $devices->whereRaw($dateColumnName. "> '$date1'::DATE");
  2955. // }
  2956. // break;
  2957. // case 'BETWEEN':
  2958. // if($date1 && $date2) {
  2959. // $devices
  2960. // ->whereRaw($dateColumnName. ">= '$date1'::DATE")
  2961. // ->whereRaw($dateColumnName. "<= '$date2'::DATE");
  2962. // }
  2963. // break;
  2964. // case 'NOT_BETWEEN':
  2965. // if($date2 && $date1) {
  2966. // $devices
  2967. // ->where(function ($q) use ($request, $dateColumnName, $date1, $date2) {
  2968. // $q->whereRaw($dateColumnName. "< '$date1'::DATE")
  2969. // ->orWhereRaw($dateColumnName. "> '$date2'::DATE");
  2970. // });
  2971. // }
  2972. // break;
  2973. // }
  2974. $keyName = $request->get('measurement_count_category');
  2975. $value1 = $request->get('measurement_count_value_1');
  2976. $value2 = $request->get('measurement_count_value_2');
  2977. $columnName = "(SELECT COUNT(*) FROM bdt_measurement WHERE bdt_measurement.bdt_device_id = client_bdt_device.device_id AND is_cellular_zero IS FALSE)";
  2978. switch($keyName) {
  2979. case 'EXACTLY':
  2980. if($value1) {
  2981. $devices->whereRaw($columnName.'='.$value1);
  2982. }
  2983. break;
  2984. case 'LESS_THAN':
  2985. if($value1) {
  2986. $devices->whereRaw($columnName. '<' .$value1);
  2987. }
  2988. break;
  2989. case 'GREATER_THAN':
  2990. if($value1) {
  2991. $devices->whereRaw($columnName. '>'. $value1);
  2992. }
  2993. break;
  2994. case 'BETWEEN':
  2995. if($value1 && $value2) {
  2996. $devices
  2997. ->whereRaw($columnName. '>=' . $value1)
  2998. ->whereRaw($columnName. '<=' . $value1);
  2999. }
  3000. break;
  3001. case 'NOT_BETWEEN':
  3002. if($value1 && $value2) {
  3003. $devices
  3004. ->where(function ($q) use ($request, $columnName, $value1, $value2) {
  3005. $q->whereRaw($columnName. '<'. $value1)
  3006. ->orWhereRaw($columnName. '>'.$value2);
  3007. });
  3008. }
  3009. break;
  3010. }
  3011. $status = $request->get('status');
  3012. if($status){
  3013. if($status === 'ACTIVE') $devices = $devices->where('client_bdt_device.is_active', true);
  3014. if($status === 'DEACTIVATED') $devices = $devices->where('client_bdt_device.is_active', false);
  3015. }
  3016. $devices = $devices->orderBy('num_of_measurements', 'DESC')->paginate(20);
  3017. return view('app.practice-management.clients_bdt_devices', compact('devices','filters'));
  3018. }
  3019. public function memos(Request $request){
  3020. $filters = $request->all();
  3021. $memos = ClientMemo::select('client_memo.*')
  3022. ->join('client', 'client.id', '=', 'client_memo.client_id');
  3023. if($this->performer->pro->pro_type !== 'ADMIN'){
  3024. $memos = $memos->where('client.mcp_pro_id', $this->performer->pro->id);
  3025. }
  3026. $this->filterMultiQuery($request, $memos, 'client_memo.created_at', 'date_category', 'date_value_1', 'date_value_2');
  3027. $this->filterSimpleQuery($request, $memos, 'category', 'category');
  3028. $memos = $memos->orderBy('created_at', 'DESC')->paginate(20);
  3029. return view('app.practice-management.memos', compact('memos', 'filters'));
  3030. }
  3031. public function segmentTemplates(Request $request){
  3032. $segmentTemplates = SegmentTemplate::query();
  3033. $segmentTemplates = $segmentTemplates->orderBy('created_at', 'DESC');
  3034. $responseType = $request->get('response_type');
  3035. if($responseType && $responseType == 'json'){
  3036. $segmentTemplates = $segmentTemplates->where('is_active', true)->get();
  3037. return $this->pass($segmentTemplates);
  3038. }
  3039. $segmentTemplates = $segmentTemplates->paginate(30);
  3040. return view('app.practice-management.segment-templates.index', compact('segmentTemplates'));
  3041. }
  3042. public function visitTemplates(Request $request){
  3043. $visitTemplates = VisitTemplate::query();
  3044. $visitTemplates = $visitTemplates->orderBy('created_at', 'DESC');
  3045. $responseType = $request->get('response_type');
  3046. if($responseType && $responseType == 'json'){
  3047. $visitTemplates = $visitTemplates->where('is_active', true)->get();
  3048. return $this->pass($visitTemplates);
  3049. }
  3050. $visitTemplates = $visitTemplates->paginate(30);
  3051. return view('app.practice-management.visit-templates.index', compact('visitTemplates'));
  3052. }
  3053. public function visitTemplate(Request $request, VisitTemplate $visitTemplate){
  3054. $visitTemplateSegmentTemplates = VisitTemplateSegmentTemplate::query();
  3055. $visitTemplateSegmentTemplates = $visitTemplateSegmentTemplates->where('visit_template_id', $visitTemplate->id);
  3056. $visitTemplateSegmentTemplates = $visitTemplateSegmentTemplates->orderBy('position_index', 'ASC');
  3057. $visitTemplateSegmentTemplates = $visitTemplateSegmentTemplates->paginate(50);
  3058. return view('app.practice-management.visit-templates.visit-template-segment-templates.index', compact('visitTemplate','visitTemplateSegmentTemplates'));
  3059. }
  3060. public function visitTemplateAccess(Request $request, VisitTemplate $visitTemplate){
  3061. $visitTemplateAccesses = VisitTemplateAccess::where('visit_template_id', $visitTemplate->id)->paginate(50);
  3062. return view('app.practice-management.visit-templates.visit-template-accesses.index', compact('visitTemplate','visitTemplateAccesses'));
  3063. }
  3064. public function clientCcmRmStatus(Request $request){
  3065. $filters = $request->all();
  3066. $patients = Client::whereNull('shadow_pro_id');
  3067. $pro = $this->performer()->pro;
  3068. if($pro->pro_type !== 'ADMIN') {
  3069. $patients = $patients->where('mcp_pro_id', $this->performer()->pro->id);
  3070. }
  3071. // filters
  3072. /*
  3073. array:18 [▼
  3074. "age_category" => "LESS_THAN"
  3075. "age_value_1" => "34"
  3076. "age_value_2" => null
  3077. "sex" => "M"
  3078. "bmi_category" => "BETWEEN"
  3079. "bmi_value_1" => "20"
  3080. "bmi_value_2" => "25"
  3081. "last_visit_category" => "LESS_THAN"
  3082. "last_visit_value_1" => "2021-10-14"
  3083. "last_visit_value_2" => null
  3084. "next_appointment_category" => "LESS_THAN"
  3085. "next_appointment_value_1" => "2021-10-15"
  3086. "status" => "ACTIVE"
  3087. "last_weighed_in_category" => "EXACTLY"
  3088. "last_weighed_in_value_1" => "2021-10-07"
  3089. "last_bp_category" => "BETWEEN"
  3090. "last_bp_value_1" => "2021-10-01"
  3091. "last_bp_value_2" => "2021-10-31"
  3092. ]
  3093. */
  3094. $this->filterMultiQuery($request, $patients, 'age_in_years', 'age_category', 'age_value_1', 'age_value_2');
  3095. $this->filterSimpleQuery($request, $patients, 'sex', 'sex');
  3096. $this->filterMultiQuery($request, $patients, 'usual_bmi', 'bmi_category', 'bmi_value_1', 'bmi_value_2');
  3097. $this->filterMultiQuery($request, $patients, 'most_recent_weight_at', 'last_weighed_in_category', 'last_weighed_in_value_1', 'last_weighed_in_value_2');
  3098. $this->filterMultiQuery($request, $patients, 'most_recent_bp_at', 'last_bp_category', 'last_bp_value_1', 'last_bp_value_2');
  3099. switch($request->input('status')) {
  3100. case 'ACTIVE':
  3101. $patients->where('is_active', true)->where('has_mcp_done_onboarding_visit', true);
  3102. break;
  3103. case 'AWAITING_VISIT':
  3104. $patients->where('is_active', true)->where('has_mcp_done_onboarding_visit', false);
  3105. break;
  3106. case 'INACTIVE':
  3107. $patients->where('is_active', '<>', true);
  3108. break;
  3109. }
  3110. if($request->input('is_eligible_for_cm')){
  3111. $patients->where('is_eligible_for_cm', '=', $request->input('is_eligible_for_cm'));
  3112. }
  3113. if($request->input('is_enrolled_in_cm')){
  3114. $patients->where('is_enrolled_in_cm', '=', $request->input('is_enrolled_in_cm'));
  3115. }
  3116. if($request->input('has_cm_setup_been_performed')){
  3117. $patients->where('has_cm_setup_been_performed', '=', $request->input('has_cm_setup_been_performed')=='YES'? true : false);
  3118. }
  3119. if($request->input('is_eligible_for_rm')){
  3120. $patients->where('is_eligible_for_rm', '=', $request->input('is_eligible_for_rm'));
  3121. }
  3122. if($request->input('is_enrolled_in_rm')){
  3123. $patients->where('is_enrolled_in_rm', '=', $request->input('is_enrolled_in_rm'));
  3124. }
  3125. if($request->input('has_rm_setup_been_performed')){
  3126. $patients->where('has_rm_setup_been_performed', '=', $request->input('has_rm_setup_been_performed') =='YES'? true : false);
  3127. }
  3128. $patients = $patients->orderBy('created_at', 'DESC')->paginate(20);
  3129. return view('app.admin.client-ccm-rm-status', compact('patients', 'filters'));
  3130. }
  3131. public function rmActionReport(Request $request){
  3132. $filters = $request->all();
  3133. $careMonthStartDate = $request->get('care_month_start_date');
  3134. $careMonthYear = $request->get('care_month_year');
  3135. if(!$careMonthStartDate){
  3136. $careMonthStartDate = '2022-01-01';
  3137. }
  3138. if($careMonthYear){
  3139. $careMonthStartDate = $careMonthYear . "-01";
  3140. }
  3141. $lastDateOfMonth = new DateTime(date("Y-m-t", strtotime(get_current_date())));
  3142. $today = new DateTime(get_current_date());
  3143. $diff = $lastDateOfMonth->diff($today);
  3144. $daysBetweenNowAndEndmonth = $diff->days;
  3145. $minRequiredMeasurements = 16 - $daysBetweenNowAndEndmonth -1;
  3146. $numOfMeasurements = $request->get('num_of_measurements'); //16_or_more, 12_or_more
  3147. $hasRecentVisit = $request->get('has_recent_visit'); //yes no
  3148. $hasBeenSpokenToThisMonth = $request->get('has_been_spoken_to'); //yes no
  3149. $cmQuery = CareMonth::where('start_date', $careMonthStartDate);
  3150. //remove dummies
  3151. $cmQuery = $cmQuery->whereHas('client', function($clientQuery) {
  3152. return $clientQuery->where('client_engagement_status_category','<>', 'DUMMY')
  3153. ->orWhere('client_engagement_status_category', '=', null);
  3154. });
  3155. if($numOfMeasurements){
  3156. if($numOfMeasurements == '16_or_more'){
  3157. $cmQuery = $cmQuery->where('number_of_days_with_remote_measurements', '>=', 16);
  3158. }
  3159. if($numOfMeasurements == 'min_or_more'){
  3160. $cmQuery = $cmQuery->where('number_of_days_with_remote_measurements', '>=', $minRequiredMeasurements)
  3161. ->where('number_of_days_with_remote_measurements', '<', 16);
  3162. }
  3163. if($numOfMeasurements == 'less_than_min'){
  3164. $cmQuery = $cmQuery->where('number_of_days_with_remote_measurements', '<', $minRequiredMeasurements);
  3165. }
  3166. }
  3167. if($hasRecentVisit){
  3168. if($hasRecentVisit == 'YES'){
  3169. $cmQuery = $cmQuery->whereHas('client', function($clientQuery) {
  3170. return $clientQuery->whereRaw("most_recent_completed_mcp_note_date::DATE >= ((NOW() - interval '90 days')::DATE)");
  3171. });
  3172. }else{
  3173. $cmQuery = $cmQuery->whereHas('client', function($clientQuery) {
  3174. return $clientQuery->whereRaw("most_recent_completed_mcp_note_date::DATE < ((NOW() - interval '90 days')::DATE)");
  3175. });
  3176. }
  3177. }
  3178. if($hasBeenSpokenToThisMonth){
  3179. if($hasBeenSpokenToThisMonth == 'YES'){
  3180. $cmQuery = $cmQuery->where('has_anyone_interacted_with_client_about_rm_outside_note', '=', true);
  3181. }else{
  3182. $cmQuery = $cmQuery->where('has_anyone_interacted_with_client_about_rm_outside_note', '=', false);
  3183. }
  3184. }
  3185. $claimingClosed = $request->get('claiming_closed');
  3186. if($claimingClosed){
  3187. if($claimingClosed === 'YES') $cmQuery = $cmQuery->where('is_claim_closed', true);
  3188. if($claimingClosed === 'NO') $cmQuery = $cmQuery->where('is_claim_closed', false);
  3189. }
  3190. $cmQuery = $cmQuery->orderBy('start_date', 'DESC')->orderBy('client_id', 'ASC');
  3191. $rows =$cmQuery->paginate(15);
  3192. return view('app.practice-management.rm-action-report', compact('rows', 'filters', 'minRequiredMeasurements'));
  3193. }
  3194. public function myFlyers(Request $request){
  3195. $pro = $this->performer->pro;
  3196. $slug = $pro->slug ?? $pro->uid;
  3197. $url = config('app.stagfe6_url') . '/flyers/json-list?slug=' . $slug;
  3198. $arrContextOptions=array(
  3199. "ssl"=>array(
  3200. "verify_peer"=>false,
  3201. "verify_peer_name"=>false,
  3202. ),
  3203. );
  3204. $response = @file_get_contents($url, false, stream_context_create($arrContextOptions));
  3205. $response = @json_decode($response);
  3206. $flyerTemplates = [];
  3207. if(isset($response->data)){
  3208. $flyerTemplates = $response->data;
  3209. }
  3210. return view('app.my-flyers', compact('pro','flyerTemplates'));
  3211. }
  3212. public function notesPendingPhysicianSupervisorStamping(Request $request){
  3213. $hideTitle = $request->get('hideTitle');
  3214. $pro = $this->performer->pro;
  3215. //All companyProIds that I am supervisor
  3216. $flaggedNotes = Note::where('is_stamped_by_supervising_physician', false)->where('is_flagged_for_supervising_physician_review', true)->whereHas('hcpCompanyPro', function($qry) use($pro){
  3217. return $qry->whereHas('supervisingPhysicianCompanyPro', function($qr) use($pro){
  3218. return $qr->where('pro_id', $pro->id);
  3219. });
  3220. })->get();
  3221. return view('app.notes-pending-physician-supervisor-stamping', compact('flaggedNotes', 'hideTitle'));
  3222. }
  3223. public function notesResolutionCenter(Request $request) {
  3224. $columns = "(c.name_first || ' ' || c.name_last) as client_name,
  3225. (hcp.name_first || ' ' || hcp.name_last) as hcp_name,
  3226. (na.name_first || ' ' || na.name_last) as na_name,
  3227. c.chart_number,
  3228. c.uid as client_uid,
  3229. n.effective_dateest,
  3230. n.uid,
  3231. n.detail_json,
  3232. n.is_claim_closed,
  3233. n.visit_number,
  3234. ROUND(b.number_of_units * 60) as minutes,
  3235. n.note_reason_icd1 AS icd1,
  3236. n.note_reason_icd1description AS icd1description,
  3237. n.note_reason_icd2 AS icd2,
  3238. n.note_reason_icd2description AS icd2description,
  3239. n.note_reason_icd3 AS icd3,
  3240. n.note_reason_icd3description AS icd3description,
  3241. n.note_reason_icd4 AS icd4,
  3242. n.note_reason_icd4description AS icd4description,
  3243. n.note_reason_memo AS icd_memo,
  3244. n.visit_number
  3245. ";
  3246. $from = "FROM note AS n
  3247. LEFT JOIN pro AS hcp ON n.hcp_pro_id = hcp.id
  3248. LEFT JOIN pro AS na ON n.ally_pro_id = na.id
  3249. JOIN client AS c ON n.client_id = c.id
  3250. JOIN bill AS b ON (b.note_id = n.id AND b.is_cancelled IS NOT TRUE AND b.code ILIKE '%treatment%')
  3251. ";
  3252. $where = "WHERE
  3253. -- n.visit_number IN (1,2) AND
  3254. n.is_signed_by_hcp IS TRUE AND
  3255. -- n.is_claim_closed IS NOT TRUE AND
  3256. n.is_cancelled IS NOT TRUE AND
  3257. n.created_at::DATE >= '2022-01-01'::DATE AND
  3258. c.client_engagement_status_category <> 'DUMMY' AND
  3259. c.name_first NOT ILIKE '%test%' AND
  3260. c.name_last NOT ILIKE '%test%' AND
  3261. 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
  3262. -- n.id NOT IN (SELECT note_id FROM claim WHERE note_id IS NOT NULL) AND
  3263. c.is_part_b_primary = 'YES' AND
  3264. c.latest_eligible_refresh_at::DATE >= '2022-01-01' AND
  3265. c.mpb_remaining = 0 AND
  3266. c.created_at::DATE >= '2022-01-01'::DATE
  3267. ";
  3268. $filters = [];
  3269. if($request->input('f')) {
  3270. $filters[] = "(n.detail_json IS NOT NULL AND ((n.detail_json)::json->'farah_decision')::text = '\"" . $request->input('f') . "\"')";
  3271. }
  3272. if($request->input('s')) {
  3273. $filters[] = "(n.detail_json IS NOT NULL AND ((n.detail_json)::json->'shawn_decision')::text = '\"" . $request->input('s') . "\"')";
  3274. }
  3275. if(count($filters)) {
  3276. $filters = 'AND ' . implode(' AND ', $filters);
  3277. }
  3278. else {
  3279. $filters = '';
  3280. }
  3281. // $filters = '';
  3282. $orderBy = "ORDER BY c.id ASC, n.visit_number ASC";
  3283. $countQuery = "SELECT count(*) {$from} {$where} {$filters}";
  3284. // dd($countQuery);
  3285. $countResult = DB::select($countQuery);
  3286. $total = $countResult[0]->count;
  3287. $defaultPageSize = 25;
  3288. $page = $request->input('page') ?: 1;
  3289. $perPage = $request->input('per_page') ?: $defaultPageSize;
  3290. $offset = ($page - 1) * $perPage;
  3291. $dataQuery = "SELECT {$columns} {$from} {$where} {$filters} {$orderBy} OFFSET {$offset} LIMIT {$perPage}";
  3292. $rows = DB::select($dataQuery);
  3293. $paginator = new LengthAwarePaginator($rows, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  3294. $paginator->setPath(route('practice-management.notes-resolution-center'));
  3295. return view('app.practice-management.notes-resolution-center', compact('rows', 'paginator'));
  3296. }
  3297. public function notesResolutionCenterV2(Request $request) {
  3298. $columns = "(c.name_first || ' ' || c.name_last) as client_name,
  3299. (hcp.name_first || ' ' || hcp.name_last) as hcp_name,
  3300. (na.name_first || ' ' || na.name_last) as na_name,
  3301. c.chart_number,
  3302. c.uid as client_uid,
  3303. n.effective_dateest,
  3304. n.uid,
  3305. n.detail_json,
  3306. n.is_claim_closed,
  3307. n.visit_number,
  3308. ROUND(b.number_of_units * 60) as minutes,
  3309. n.note_reason_icd1 AS icd1,
  3310. n.note_reason_icd1description AS icd1description,
  3311. n.note_reason_icd2 AS icd2,
  3312. n.note_reason_icd2description AS icd2description,
  3313. n.note_reason_icd3 AS icd3,
  3314. n.note_reason_icd3description AS icd3description,
  3315. n.note_reason_icd4 AS icd4,
  3316. n.note_reason_icd4description AS icd4description,
  3317. n.note_reason_memo AS icd_memo
  3318. ";
  3319. $from = "FROM note AS n
  3320. LEFT JOIN pro AS hcp ON n.hcp_pro_id = hcp.id
  3321. LEFT JOIN pro AS na ON n.ally_pro_id = na.id
  3322. JOIN client AS c ON n.client_id = c.id
  3323. JOIN bill AS b ON (b.note_id = n.id AND b.is_cancelled IS NOT TRUE AND b.code ILIKE '%treatment%')
  3324. ";
  3325. $where = "WHERE
  3326. -- n.visit_number = 2 AND
  3327. n.is_signed_by_hcp IS TRUE AND
  3328. -- n.effective_dateest < '2022-03-01' AND
  3329. n.is_claim_closed IS NOT TRUE AND
  3330. n.is_cancelled IS NOT TRUE AND
  3331. c.client_engagement_status_category <> 'DUMMY' AND
  3332. c.name_first NOT ILIKE '%test%' AND
  3333. c.name_last NOT ILIKE '%test%' AND
  3334. 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)
  3335. -- AND
  3336. -- n.id NOT IN (SELECT note_id FROM claim WHERE note_id IS NOT NULL) AND
  3337. ";
  3338. $filters = [];
  3339. if(trim($request->input('f_pb_primary'))) {
  3340. $v = trim($request->input('f_pb_primary'));
  3341. if($v === 'yes') {
  3342. $filters[] = "(c.is_part_b_primary = 'YES')";
  3343. }
  3344. else if($v === 'no') {
  3345. $filters[] = "(c.is_part_b_primary != 'YES')";
  3346. }
  3347. }
  3348. if(trim($request->input('f_deductible_zero'))) {
  3349. $v = trim($request->input('f_deductible_zero'));
  3350. if($v === 'yes') {
  3351. $filters[] = "(c.mpb_remaining = 0)";
  3352. }
  3353. else if($v === 'no') {
  3354. $filters[] = "(c.mpb_remaining > 0)";
  3355. }
  3356. }
  3357. if(trim($request->input('f_note_hcp'))) {
  3358. $v = trim($request->input('f_note_hcp'));
  3359. $filters[] = "(n.hcp_pro_id IN (SELECT id FROM pro WHERE uid = '{$v}'))";
  3360. }
  3361. if(trim($request->input('f_2022_patient'))) {
  3362. $v = trim($request->input('f_2022_patient'));
  3363. if($v === 'yes') {
  3364. $filters[] = "(c.created_at::DATE >= '2022-01-01'::DATE)";
  3365. }
  3366. else if($v === 'no') {
  3367. $filters[] = "(c.created_at::DATE < '2022-01-01'::DATE)";
  3368. }
  3369. }
  3370. if(count($filters)) {
  3371. $filters = 'AND ' . implode(' AND ', $filters);
  3372. }
  3373. else {
  3374. $filters = '';
  3375. }
  3376. // $filters = '';
  3377. $orderBy = "ORDER BY
  3378. -- c.id ASC,
  3379. n.id ASC, n.effective_dateest ASC";
  3380. $countQuery = "SELECT count(*) {$from} {$where} {$filters}";
  3381. // dd($countQuery);
  3382. $countResult = DB::select($countQuery);
  3383. $total = $countResult[0]->count;
  3384. $defaultPageSize = 50;
  3385. $page = $request->input('page') ?: 1;
  3386. $perPage = $request->input('per_page') ?: $defaultPageSize;
  3387. $offset = ($page - 1) * $perPage;
  3388. $dataQuery = "SELECT {$columns} {$from} {$where} {$filters} {$orderBy} OFFSET {$offset} LIMIT {$perPage}";
  3389. $rows = DB::select($dataQuery);
  3390. $paginator = new LengthAwarePaginator($rows, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  3391. $paginator->setPath(route('practice-management.notes-resolution-center-v2'));
  3392. return view('app.practice-management.notes-resolution-center-v2', compact('rows', 'paginator'));
  3393. }
  3394. public function coverages(Request $request) {
  3395. $columns = "(c.name_first || ' ' || c.name_last) as client_name,
  3396. c.id,
  3397. c.uid,
  3398. c.created_at,
  3399. c.sex,
  3400. c.dob,
  3401. c.age_in_years,
  3402. row_to_json(lcpc.*) as latest_client_primary_coverage,
  3403. row_to_json(lacpc.*) as latest_auto_client_primary_coverage,
  3404. row_to_json(lmcpc.*) as latest_manual_client_primary_coverage,
  3405. row_to_json(lmcpc_payer.*) as latest_manual_client_primary_coverage_payer
  3406. ";
  3407. $from = "FROM client AS c
  3408. LEFT JOIN client_primary_coverage lcpc on c.effective_client_primary_coverage_id = lcpc.id
  3409. LEFT JOIN client_primary_coverage lacpc on c.latest_auto_refresh_client_primary_coverage_id = lacpc.id
  3410. LEFT JOIN client_primary_coverage lmcpc on c.latest_manual_client_primary_coverage_id = lmcpc.id
  3411. LEFT JOIN payer lmcpc_payer on lmcpc.commercial_payer_id = lmcpc_payer.id
  3412. ";
  3413. $where = "WHERE
  3414. c.client_engagement_status_category <> 'DUMMY' AND
  3415. c.name_first NOT ILIKE '%test%' AND
  3416. c.name_last NOT ILIKE '%test%' AND
  3417. c.created_at::DATE >= '2022-01-01'::DATE
  3418. -- lmcpc.id IS NOT NULL ANd lmcpc.plan_type != 'MEDICARE'
  3419. ";
  3420. $filters = [];
  3421. if(trim($request->input('f_name'))) {
  3422. $v = trim($request->input('f_name'));
  3423. $filters[] = "(c.name_first ILIKE '%{$v}%' OR c.name_last ILIKE '%{$v}%')";
  3424. }
  3425. if(trim($request->input('f_covered'))) {
  3426. $v = trim($request->input('f_covered'));
  3427. if($v !== 'any') {
  3428. switch($v) {
  3429. case 'covered':
  3430. $filters[] = "(
  3431. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.manual_determination_category = 'COVERED') OR
  3432. ((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')
  3433. )";
  3434. break;
  3435. case 'not-covered':
  3436. $filters[] = "(
  3437. (lmcpc.id IS NULL OR (lmcpc.is_cancelled IS TRUE OR lmcpc.manual_determination_category = 'NOT_COVERED')) AND
  3438. (lacpc.id IS NULL OR (lacpc.is_cancelled IS TRUE OR lacpc.auto_medicare_is_partbprimary = 'NO')) AND
  3439. (lmcpc.id IS NOT NULL OR lacpc.id IS NOT NULL)
  3440. )";
  3441. break;
  3442. case 'unknown':
  3443. $filters[] = "(
  3444. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.manual_determination_category = 'UNKNOWN') OR
  3445. ((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')
  3446. )";
  3447. break;
  3448. }
  3449. }
  3450. }
  3451. if(trim($request->input('f_covered'))) {
  3452. $v = trim($request->input('f_covered'));
  3453. if($v !== 'any') {
  3454. switch($v) {
  3455. case 'covered':
  3456. $filters[] = "(
  3457. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.manual_determination_category = 'COVERED') OR
  3458. ((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')
  3459. )";
  3460. break;
  3461. case 'not-covered':
  3462. $filters[] = "(
  3463. (lmcpc.id IS NULL OR (lmcpc.is_cancelled IS TRUE OR lmcpc.manual_determination_category = 'NOT_COVERED')) AND
  3464. (lacpc.id IS NULL OR (lacpc.is_cancelled IS TRUE OR lacpc.auto_medicare_is_partbprimary = 'NO')) AND
  3465. (lmcpc.id IS NOT NULL OR lacpc.id IS NOT NULL)
  3466. )";
  3467. break;
  3468. case 'unknown':
  3469. $filters[] = "(
  3470. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.manual_determination_category = 'UNKNOWN') OR
  3471. ((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')
  3472. )";
  3473. break;
  3474. }
  3475. }
  3476. }
  3477. if(trim($request->input('f_plan_type'))) {
  3478. $v = strtoupper(trim($request->input('f_plan_type')));
  3479. if($v !== 'ANY') {
  3480. $filters[] = "(
  3481. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.plan_type = '{$v}') 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.plan_type = '{$v}')
  3483. )";
  3484. }
  3485. }
  3486. if(trim($request->input('f_pb_primary'))) {
  3487. $v = trim($request->input('f_pb_primary'));
  3488. if($v !== 'any') {
  3489. switch($v) {
  3490. case 'primary':
  3491. $filters[] = "(
  3492. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.is_partbprimary = 'YES') OR
  3493. ((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')
  3494. )";
  3495. break;
  3496. case 'not-primary':
  3497. $filters[] = "(
  3498. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.is_partbprimary = 'NO') OR
  3499. ((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')
  3500. )";
  3501. break;
  3502. case 'unknown':
  3503. $filters[] = "(
  3504. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.is_partbprimary = 'UNKNOWN') OR
  3505. ((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')
  3506. )";
  3507. break;
  3508. }
  3509. }
  3510. }
  3511. if(trim($request->input('f_pb_active'))) {
  3512. $v = trim($request->input('f_pb_active'));
  3513. // TODO
  3514. }
  3515. if(trim($request->input('f_pc_active'))) {
  3516. $v = trim($request->input('f_pc_active'));
  3517. // TODO
  3518. }
  3519. if(trim($request->input('f_comm_payer'))) {
  3520. $v = trim($request->input('f_comm_payer'));
  3521. $filters[] = "(lmcpc_payer.name ILIKE '%{$v}%')";
  3522. }
  3523. if(trim($request->input('f_comm_member_id'))) {
  3524. $v = trim($request->input('f_comm_member_id'));
  3525. if($v !== 'any') {
  3526. $filters[] = "(
  3527. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.commercial_member_identifier ILIKE '%{$v}%') OR
  3528. ((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}%')
  3529. )";
  3530. }
  3531. }
  3532. if(trim($request->input('f_comm_group_num'))) {
  3533. $v = trim($request->input('f_comm_group_num'));
  3534. if($v !== 'any') {
  3535. $filters[] = "(
  3536. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.commercial_group_number ILIKE '%{$v}%') OR
  3537. ((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}%')
  3538. )";
  3539. }
  3540. }
  3541. if(count($filters)) {
  3542. $filters = 'AND ' . implode(' AND ', $filters);
  3543. }
  3544. else {
  3545. $filters = '';
  3546. }
  3547. // $filters = '';
  3548. $orderBy = "ORDER BY client_name ASC";
  3549. $countQuery = "SELECT count(*) {$from} {$where} {$filters}";
  3550. // dd($countQuery);
  3551. $countResult = DB::select($countQuery);
  3552. $total = $countResult[0]->count;
  3553. $defaultPageSize = 10;
  3554. $page = $request->input('page') ?: 1;
  3555. $perPage = $request->input('per_page') ?: $defaultPageSize;
  3556. $offset = ($page - 1) * $perPage;
  3557. $dataQuery = "SELECT {$columns} {$from} {$where} {$filters} {$orderBy} OFFSET {$offset} LIMIT {$perPage}";
  3558. $rows = DB::select($dataQuery);
  3559. $paginator = new LengthAwarePaginator($rows, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  3560. $paginator->setPath(route('practice-management.coverages'));
  3561. // dd($rows);
  3562. return view('app.practice-management.coverages', compact('rows', 'paginator'));
  3563. }
  3564. public function clientReviewRequests(Request $request){
  3565. $pro = $this->performer->pro;
  3566. $reviewRequests = ClientReviewRequest::where('status', '!=', 'DONE');
  3567. if($pro->pro_type !== 'ADMIN'){
  3568. $reviewRequests = $reviewRequests->where('pro_id', $pro->id);
  3569. }
  3570. $reviewRequests = $reviewRequests->orderBy('created_at', 'DESC')->paginate(50);
  3571. return view('app.ps.review-requests.list', compact('reviewRequests'));
  3572. }
  3573. }