PracticeManagementController.php 189 KB

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