PracticeManagementController.php 187 KB

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