PracticeManagementController.php 190 KB

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