PracticeManagementController.php 175 KB

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