PracticeManagementController.php 188 KB

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