PracticeManagementController.php 187 KB

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