PracticeManagementController.php 181 KB

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