PracticeManagementController.php 178 KB

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