PracticeManagementController.php 187 KB

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