PracticeManagementController.php 174 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961
  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. // filters from the UI
  1440. if(trim($request->input('f_name'))) {
  1441. $v = trim($request->input('f_name'));
  1442. $conditions[] = "(client.name_first ILIKE '%{$v}%' OR client.name_last ILIKE '%{$v}%')";
  1443. }
  1444. if(trim($request->input('f_dob_op')) && trim($request->input('f_dob'))) {
  1445. $o = trim($request->input('f_dob_op'));
  1446. $v = trim($request->input('f_dob'));
  1447. $conditions[] = "(client.dob {$o} '{$v}')";
  1448. }
  1449. if(trim($request->input('f_rpm'))) {
  1450. $v = trim($request->input('f_rpm'));
  1451. if($v === 'yes') {
  1452. $conditions[] = "(client.is_enrolled_in_rm IS NOT NULL AND client.is_enrolled_in_rm = 'YES')";
  1453. }
  1454. elseif($v === 'no') {
  1455. $conditions[] = "(client.is_enrolled_in_rm IS NULL OR client.is_enrolled_in_rm != 'YES')";
  1456. }
  1457. }
  1458. if(trim($request->input('f_cell_bp'))) {
  1459. $v = trim($request->input('f_cell_bp'));
  1460. if($v === 'yes') {
  1461. $conditions[] = "(client.is_assigned_cellular_bp_device IS NOT NULL AND client.is_assigned_cellular_bp_device = TRUE)";
  1462. }
  1463. elseif($v === 'no') {
  1464. $conditions[] = "(client.is_assigned_cellular_bp_device IS NULL OR client.is_assigned_cellular_bp_device = FALSE)";
  1465. }
  1466. }
  1467. if(trim($request->input('f_cell_wt'))) {
  1468. $v = trim($request->input('f_cell_wt'));
  1469. if($v === 'yes') {
  1470. $conditions[] = "(client.is_assigned_cellular_weight_scale_device IS NOT NULL AND client.is_assigned_cellular_weight_scale_device = TRUE)";
  1471. }
  1472. elseif($v === 'no') {
  1473. $conditions[] = "(client.is_assigned_cellular_weight_scale_device IS NULL OR client.is_assigned_cellular_weight_scale_device = FALSE)";
  1474. }
  1475. }
  1476. if(trim($request->input('f_comm'))) {
  1477. $v = trim($request->input('f_comm'));
  1478. if($v === 'yes') {
  1479. $conditions[] = "(care_month.has_mcp_interacted_with_client_about_rm IS NOT NULL AND care_month.has_mcp_interacted_with_client_about_rm = TRUE)";
  1480. }
  1481. elseif($v === 'no') {
  1482. $conditions[] = "(care_month.has_mcp_interacted_with_client_about_rm IS NULL OR care_month.has_mcp_interacted_with_client_about_rm = FALSE)";
  1483. }
  1484. }
  1485. if(trim($request->input('f_mcp_billable'))) {
  1486. $v = trim($request->input('f_mcp_billable'));
  1487. if($v === 'yes') {
  1488. $conditions[] = "(care_month.mcp_rm_generic_bill_id IS NOT NULL)";
  1489. }
  1490. elseif($v === 'no') {
  1491. $conditions[] = "(care_month.mcp_rm_generic_bill_id IS NULL)";
  1492. }
  1493. }
  1494. if(trim($request->input('f_rmm_billable'))) {
  1495. $v = trim($request->input('f_rmm_billable'));
  1496. if($v === 'yes') {
  1497. $conditions[] = "(care_month.rmm_rm_generic_bill_id IS NOT NULL)";
  1498. }
  1499. elseif($v === 'no') {
  1500. $conditions[] = "(care_month.rmm_rm_generic_bill_id IS NULL)";
  1501. }
  1502. }
  1503. if(trim($request->input('f_md_op')) && trim($request->input('f_md')) !== '') {
  1504. $o = trim($request->input('f_md_op'));
  1505. $v = trim($request->input('f_md'));
  1506. $conditions[] = "(care_month.number_of_days_with_remote_measurements {$o} {$v})";
  1507. }
  1508. if(trim($request->input('f_unst_op')) && trim($request->input('f_unst')) !== '') {
  1509. $o = trim($request->input('f_unst_op'));
  1510. $v = trim($request->input('f_unst'));
  1511. $conditions[] = "(care_month.rm_num_measurements_not_stamped_by_mcp {$o} {$v})";
  1512. }
  1513. if(trim($request->input('f_mcp_mins_op')) && trim($request->input('f_mcp_mins')) !== '') {
  1514. $o = trim($request->input('f_mcp_mins_op'));
  1515. $v = intval(trim($request->input('f_mcp_mins'))) * 60;
  1516. $conditions[] = "(care_month.rm_total_time_in_seconds_by_mcp {$o} {$v})";
  1517. }
  1518. if(trim($request->input('f_rmm_mins_op')) && trim($request->input('f_rmm_mins')) !== '') {
  1519. $o = trim($request->input('f_rmm_mins_op'));
  1520. $v = intval(trim($request->input('f_rmm_mins'))) * 60;
  1521. $conditions[] = "(care_month.rm_total_time_in_seconds_by_rmm_pro {$o} {$v})";
  1522. }
  1523. $genericBillIdColumns = "care_month.mcp_rm_generic_bill_id,
  1524. mcpBill.uid as mcp_rm_generic_bill_uid,
  1525. mcpBill.generic_pro_id as mcp_rm_generic_bill_generic_pro_id,
  1526. mcpBill.generic_pro_expected_payment_amount as mcp_rm_generic_bill_expected_payment_amount,
  1527. mcpBill.is_signed_by_generic_pro as mcp_rm_generic_bill_signed,
  1528. care_month.rmm_rm_generic_bill_id,
  1529. rmmBill.uid as rmm_rm_generic_bill_uid,
  1530. rmmBill.generic_pro_id as rmm_rm_generic_bill_generic_pro_id,
  1531. rmmBill.generic_pro_expected_payment_amount as rmm_rm_generic_bill_expected_payment_amount,
  1532. rmmBill.is_signed_by_generic_pro as rmm_rm_generic_bill_signed";
  1533. $genericBillJoinClause = "left join bill mcpBill on care_month.mcp_rm_generic_bill_id = mcpBill.id
  1534. left join bill rmmBill on care_month.rmm_rm_generic_bill_id = rmmBill.id";
  1535. $query = "
  1536. SELECT client.name_first, client.name_last,
  1537. (client.name_first || ' ' || client.name_last) as client_name,
  1538. client.uid as client_uid,
  1539. client.dob,
  1540. client.is_enrolled_in_rm,
  1541. client.most_recent_completed_mcp_note_date,
  1542. client.most_recent_completed_mcp_note_id,
  1543. client.cell_number,
  1544. client.is_assigned_cellular_bp_device,
  1545. client.is_assigned_cellular_weight_scale_device,
  1546. care_month.uid as care_month_uid,
  1547. care_month.id as care_month_id,
  1548. care_month.start_date,
  1549. care_month.rm_total_time_in_seconds_by_mcp,
  1550. care_month.rm_total_time_in_seconds_by_rmm_pro,
  1551. care_month.number_of_days_with_remote_measurements,
  1552. care_month.has_mcp_interacted_with_client_about_rm,
  1553. care_month.rm_num_measurements_not_stamped_by_mcp,
  1554. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  1555. care_month.rm_num_measurements_not_stamped_by_rmm,
  1556. care_month.rm_num_measurements_not_stamped_by_rme,
  1557. care_month.mcp_pro_id as care_month_mcp_pro_id,
  1558. care_month.rmm_pro_id as care_month_rmm_pro_id,
  1559. client.mcp_pro_id,
  1560. client.default_na_pro_id,
  1561. client.rmm_pro_id,
  1562. client.rme_pro_id,
  1563. client.cell_number,
  1564. care_month.most_recent_cellular_bp_dbp_mm_hg,
  1565. care_month.most_recent_cellular_bp_sbp_mm_hg,
  1566. care_month.most_recent_cellular_bp_measurement_at,
  1567. care_month.most_recent_cellular_weight_value,
  1568. care_month.most_recent_cellular_weight_measurement_at,
  1569. mcpPro.mcp_rpm_payment_strategy,
  1570. mcpPro.mcp_rpm_payment_amount,
  1571. rmmPro.rmm_payment_strategy,
  1572. rmmPro.rmm_payment_amount,
  1573. {$genericBillIdColumns}
  1574. FROM care_month join client on care_month.client_id = client.id
  1575. join note mrnote on client.most_recent_completed_mcp_note_id = mrnote.id
  1576. left join pro mcpPro on care_month.mcp_pro_id = mcpPro.id
  1577. left join pro rmmPro on care_month.rmm_pro_id = rmmPro.id
  1578. {$genericBillJoinClause}
  1579. WHERE
  1580. EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1581. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1582. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '') . "
  1583. $orderBy
  1584. ";
  1585. // dd($query);
  1586. $patients = DB::select($query);
  1587. $timestamp = strtotime(date('Y-m-d'));
  1588. $daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
  1589. return view('app.practice-management.rpm-matrix-for-admin', compact('patients', 'daysRemaining', 'careMonthStart'));
  1590. }
  1591. public function remoteMonitoringMCP(Request $request) {
  1592. return $this->rpmMatrixByProType($request, 'mcp');
  1593. }
  1594. public function remoteMonitoringRMM(Request $request) {
  1595. return $this->rpmMatrixByProType($request, 'rmm');
  1596. }
  1597. public function remoteMonitoringRME(Request $request) {
  1598. return $this->rpmMatrixByProType($request, 'rme');
  1599. }
  1600. public function remoteMonitoring_RowMCP(Request $request) {
  1601. return $this->remoteMonitoring_RowByProType($request, 'mcp');
  1602. }
  1603. public function remoteMonitoring_RowRMM(Request $request) {
  1604. return $this->remoteMonitoring_RowByProType($request, 'rmm');
  1605. }
  1606. public function remoteMonitoring_RowRME(Request $request) {
  1607. return $this->remoteMonitoring_RowByProType($request, 'rme');
  1608. }
  1609. public function remoteMonitoring_RowADMIN(Request $request) {
  1610. return $this->remoteMonitoring_RowForAdmin($request);
  1611. }
  1612. public function rpm_work_matrix(Request $request) {
  1613. // get the patient having most recent unstamped measurement
  1614. $performer = $this->performer();
  1615. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1616. $careMonthStart = date($ym . '-01');
  1617. $patient = null;
  1618. $careMonth = null;
  1619. if($request->input('patientUid') && $request->input('careMonthUid')) {
  1620. $patient = Client::where('uid', $request->input('patientUid'))->first();
  1621. $careMonth = CareMonth::where('uid', $request->input('careMonthUid'))->first();
  1622. }
  1623. if(!$patient && !$careMonth) {
  1624. $query = "
  1625. SELECT client.name_first, client.name_last,
  1626. (client.name_first || ' ' || client.name_last) as client_name,
  1627. client.uid as client_uid,
  1628. client.dob,
  1629. client.is_enrolled_in_rm,
  1630. client.most_recent_completed_mcp_note_date,
  1631. care_month.uid as care_month_uid,
  1632. care_month.id as care_month_id,
  1633. care_month.start_date,
  1634. care_month.rm_total_time_in_seconds_by_mcp,
  1635. care_month.number_of_days_with_remote_measurements,
  1636. care_month.rm_num_measurements_not_stamped_by_mcp,
  1637. care_month.rm_num_measurements_not_stamped_by_rmm,
  1638. client.mcp_pro_id,
  1639. client.default_na_pro_id,
  1640. client.rmm_pro_id,
  1641. client.rme_pro_id,
  1642. client.cell_number,
  1643. client.most_recent_cellular_bp_dbp_mm_hg,
  1644. client.most_recent_cellular_bp_sbp_mm_hg,
  1645. client.most_recent_cellular_bp_measurement_at,
  1646. client.most_recent_cellular_weight_value,
  1647. client.most_recent_cellular_weight_measurement_at,
  1648. GREATEST(client.most_recent_cellular_bp_measurement_at, client.most_recent_cellular_weight_measurement_at) as latest_measurement_at
  1649. FROM care_month join client on care_month.client_id = client.id
  1650. WHERE
  1651. (
  1652. (care_month.mcp_pro_id = {$performer->pro->id} AND care_month.rm_num_measurements_not_stamped_by_mcp > 0) OR
  1653. (care_month.rmm_pro_id = {$performer->pro->id} AND care_month.rm_num_measurements_not_stamped_by_rmm > 0)
  1654. )
  1655. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1656. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1657. ORDER BY latest_measurement_at DESC
  1658. LIMIT 1
  1659. ";
  1660. $patients = DB::select($query);
  1661. if (count($patients)) {
  1662. $patient = Client::where('uid', $patients[0]->client_uid)->first();
  1663. $careMonth = CareMonth::where('uid', $patients[0]->care_month_uid)->first();
  1664. }
  1665. }
  1666. return view('app.practice-management.rpm_work_matrix', compact('patient', 'careMonth'));
  1667. }
  1668. public function remoteMonitoringCount(Request $request) {
  1669. $performer = $this->performer();
  1670. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1671. $careMonthStart = date($ym . '-01');
  1672. $rc = $request->input('rc') ?: 1;
  1673. $rc2 = $request->input('rc2') ?: 2;
  1674. $conditions = $this->rpmConditions($performer, $rc, $rc2);
  1675. $count = DB::select(
  1676. DB::raw(
  1677. "
  1678. SELECT count(*)
  1679. FROM care_month join client on care_month.client_id = client.id
  1680. WHERE
  1681. client.mcp_pro_id = {$performer->pro->id}
  1682. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1683. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1684. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '')
  1685. )
  1686. );
  1687. return $count[0]->count;
  1688. }
  1689. public function remoteMonitoringAdmin(Request $request) {
  1690. $performer = $this->performer();
  1691. // abort_if($performer->pro->pro_type !== 'ADMIN' && !$performer->pro->can_view_rm_matrix, 403);
  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. $sortBy = $request->input('sort_by') ?: 'name_first';
  1698. $sortDir = $request->input('sort_dir') ?: 'ASC';
  1699. $orderBy = "ORDER BY $sortBy $sortDir NULLS LAST";
  1700. $query = "
  1701. SELECT client.name_first, client.name_last,
  1702. (client.name_first || ' ' || client.name_last) as client_name,
  1703. (mcp_pro.name_first || ' ' || mcp_pro.name_last) as mcp_pro_name,
  1704. (rmm_pro.name_first || ' ' || rmm_pro.name_last) as rmm_pro_name,
  1705. client.uid as client_uid,
  1706. client.chart_number,
  1707. client.dob,
  1708. client.is_enrolled_in_rm,
  1709. client.most_recent_completed_mcp_note_date,
  1710. client.most_recent_completed_mcp_note_id,
  1711. mrmnote.effective_dateest::date as most_recent_completed_mcp_note_date_cm,
  1712. mrmnote.id as most_recent_completed_mcp_note_id_cm,
  1713. mrmnote.uid as most_recent_completed_mcp_note_uid_cm,
  1714. client.cell_number,
  1715. client.is_assigned_cellular_bp_device,
  1716. client.is_assigned_cellular_weight_scale_device,
  1717. care_month.uid as care_month_uid,
  1718. care_month.id as care_month_id,
  1719. care_month.start_date,
  1720. care_month.rm_total_time_in_seconds_by_mcp,
  1721. care_month.rm_total_time_in_seconds_by_rmm_pro,
  1722. care_month.number_of_days_with_remote_measurements,
  1723. care_month.has_anyone_interacted_with_client_about_rm,
  1724. care_month.has_mcp_interacted_with_client_about_rm,
  1725. care_month.rm_num_measurements_not_stamped_by_mcp,
  1726. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  1727. care_month.rm_num_measurements_not_stamped_by_rmm,
  1728. care_month.rm_num_measurements_not_stamped_by_rme,
  1729. care_month.mcp_pro_id as care_month_mcp_pro_id,
  1730. care_month.rmm_pro_id as care_month_rmm_pro_id,
  1731. client.mcp_pro_id,
  1732. client.default_na_pro_id,
  1733. client.rmm_pro_id,
  1734. client.rme_pro_id,
  1735. client.cell_number,
  1736. care_month.most_recent_cellular_bp_dbp_mm_hg,
  1737. care_month.most_recent_cellular_bp_sbp_mm_hg,
  1738. care_month.most_recent_cellular_bp_measurement_at,
  1739. care_month.most_recent_cellular_weight_value,
  1740. care_month.most_recent_cellular_weight_measurement_at
  1741. 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
  1742. left join note mrmnote on mrmnote.id = (
  1743. select max(n.id) from note n
  1744. where
  1745. n.client_id = client.id AND
  1746. n.is_cancelled = FALSE AND
  1747. (n.is_signed_by_hcp IS NOT NULL AND n.is_signed_by_hcp = TRUE) AND
  1748. n.effective_dateest::date >= care_month.start_date::date AND
  1749. n.effective_dateest::date < (care_month.start_date::date + INTERVAL '1 month')
  1750. )
  1751. left join pro mcp_pro on care_month.mcp_pro_id = mcp_pro.id
  1752. left join pro rmm_pro on care_month.rmm_pro_id = rmm_pro.id
  1753. WHERE
  1754. EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1755. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1756. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '') . "
  1757. $orderBy
  1758. ";
  1759. $patients = DB::select($query);
  1760. $timestamp = strtotime(date('Y-m-d'));
  1761. $daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
  1762. return view('app.practice-management.remote-monitoring-admin', compact('patients', 'daysRemaining', 'careMonthStart'));
  1763. }
  1764. public function remoteMonitoringAdminCount(Request $request) {
  1765. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1766. $careMonthStart = date($ym . '-01');
  1767. $rc = $request->input('rc') ?: 1;
  1768. $rc2 = $request->input('rc2') ?: 2;
  1769. $conditions = $this->rpmConditionsAdmin($this->performer(), $rc, $rc2);
  1770. $count = DB::select(
  1771. DB::raw(
  1772. "
  1773. SELECT count(*)
  1774. FROM care_month join client on care_month.client_id = client.id
  1775. WHERE
  1776. client.shadow_pro_id is null AND client.is_enrolled_in_rm = 'YES'
  1777. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1778. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1779. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '')
  1780. )
  1781. );
  1782. return $count[0]->count;
  1783. }
  1784. private function rpmConditions($performer, $rc, $rc2) {
  1785. $conditions = [];
  1786. $c_isMCP = "client.mcp_pro_id = {$performer->pro->id}";
  1787. $c_enrolledInRPM = "client.is_enrolled_in_rm = 'YES'";
  1788. $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";
  1789. $c_lastVisitBefore90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) > 90";
  1790. $c_lastVisitWithin90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) <= 90";
  1791. $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)";
  1792. $c_spokenToThisMonth = "care_month.has_anyone_interacted_with_client_about_rm_outside_note = TRUE";
  1793. $c_hasUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp > 0";
  1794. $c_hasNoUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp = 0";
  1795. $c_lt16MeasurementDays = "care_month.number_of_days_with_remote_measurements < 16";
  1796. $c_gte16MeasurementDays = "care_month.number_of_days_with_remote_measurements >= 16";
  1797. $c_subscribedToSMS = "client.send_sms_on_bdt_measurement = TRUE";
  1798. $c_deviceUsed = "(client.most_recent_cellular_bp_measurement_at IS NOT NULL OR most_recent_cellular_weight_measurement_at IS NOT NULL)";
  1799. $c_lt20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp < 1200";
  1800. $c_gte20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp >= 1200";
  1801. switch ($rc) {
  1802. case 1:
  1803. $conditions = [$c_isMCP];
  1804. break;
  1805. case 2:
  1806. $conditions = [$c_isMCP, $c_enrolledInRPM];
  1807. break;
  1808. case 3:
  1809. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice];
  1810. break;
  1811. case 4:
  1812. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, ($rc2 == 1 ? $c_lastVisitBefore90Days : $c_lastVisitWithin90Days)];
  1813. break;
  1814. case 5:
  1815. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, ($rc2 == 1 ? $c_notSpokenToThisMonth : $c_spokenToThisMonth)];
  1816. break;
  1817. case 6:
  1818. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_hasUnstamped : $c_hasNoUnstamped)];
  1819. break;
  1820. case 7:
  1821. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_lt16MeasurementDays : $c_gte16MeasurementDays)];
  1822. break;
  1823. case 10:
  1824. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, $c_gte16MeasurementDays, ($rc2 == 1 ? $c_lt20BillingMinutes : $c_gte20BillingMinutes)];
  1825. break;
  1826. case 8:
  1827. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_subscribedToSMS];
  1828. break;
  1829. case 9:
  1830. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_deviceUsed];
  1831. break;
  1832. }
  1833. return $conditions;
  1834. }
  1835. private function rpmConditionsAdmin($performer, $rc, $rc2) {
  1836. $conditions = [];
  1837. $c_enrolledInRPM = "client.is_enrolled_in_rm = 'YES'";
  1838. $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";
  1839. $c_lastVisitBefore90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) > 90";
  1840. $c_lastVisitWithin90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) <= 90";
  1841. $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)";
  1842. $c_spokenToThisMonth = "care_month.has_anyone_interacted_with_client_about_rm_outside_note = TRUE";
  1843. $c_hasUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp > 0";
  1844. $c_hasNoUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp = 0";
  1845. $c_lt16MeasurementDays = "care_month.number_of_days_with_remote_measurements < 16";
  1846. $c_gte16MeasurementDays = "care_month.number_of_days_with_remote_measurements >= 16";
  1847. $c_subscribedToSMS = "client.send_sms_on_bdt_measurement = TRUE";
  1848. $c_deviceUsed = "(client.most_recent_cellular_bp_measurement_at IS NOT NULL OR client.most_recent_cellular_weight_measurement_at IS NOT NULL)";
  1849. $c_lt20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp < 1200";
  1850. $c_gte20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp >= 1200";
  1851. switch ($rc) {
  1852. case 2:
  1853. $conditions = [$c_enrolledInRPM];
  1854. break;
  1855. case 3:
  1856. $conditions = [$c_enrolledInRPM, $c_hasDevice];
  1857. break;
  1858. case 4:
  1859. $conditions = [$c_enrolledInRPM, $c_hasDevice, ($rc2 == 1 ? $c_lastVisitBefore90Days : $c_lastVisitWithin90Days)];
  1860. break;
  1861. case 5:
  1862. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, ($rc2 == 1 ? $c_notSpokenToThisMonth : $c_spokenToThisMonth)];
  1863. break;
  1864. case 6:
  1865. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_hasUnstamped : $c_hasNoUnstamped)];
  1866. break;
  1867. case 7:
  1868. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_lt16MeasurementDays : $c_gte16MeasurementDays)];
  1869. break;
  1870. case 10:
  1871. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, $c_gte16MeasurementDays, ($rc2 == 1 ? $c_lt20BillingMinutes : $c_gte20BillingMinutes)];
  1872. break;
  1873. case 8:
  1874. $conditions = [$c_enrolledInRPM, $c_subscribedToSMS];
  1875. break;
  1876. case 9:
  1877. $conditions = [$c_enrolledInRPM, $c_deviceUsed];
  1878. break;
  1879. }
  1880. return $conditions;
  1881. }
  1882. public function remoteMonitoringMeasurements(Request $request, CareMonth $careMonth) {
  1883. $performer = $this->performer();
  1884. $measurements = DB::select(
  1885. DB::raw(
  1886. "
  1887. SELECT measurement.label,
  1888. measurement.ts,
  1889. measurement.effective_date,
  1890. measurement.sbp_mm_hg,
  1891. measurement.dbp_mm_hg,
  1892. measurement.value_pulse,
  1893. measurement.value_irregular,
  1894. measurement.numeric_value,
  1895. measurement.value,
  1896. measurement.uid,
  1897. client.name_first,
  1898. client.name_last,
  1899. client.mcp_pro_id,
  1900. client.default_na_pro_id,
  1901. client.rmm_pro_id,
  1902. client.rme_pro_id
  1903. FROM measurement RIGHT JOIN client on measurement.client_id = client.id
  1904. WHERE
  1905. client.id = {$careMonth->client_id}
  1906. AND measurement.label IS NOT NULL
  1907. AND measurement.label NOT IN ('SBP', 'DBP')
  1908. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  1909. AND measurement.is_removed IS FALSE
  1910. AND measurement.client_bdt_measurement_id IS NOT NULL
  1911. AND measurement.care_month_id = {$careMonth->id}
  1912. AND (
  1913. (client.mcp_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_mcp IS FALSE)
  1914. OR (client.rmm_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_rmm IS FALSE)
  1915. OR (client.rme_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_rme IS FALSE)
  1916. OR (client.default_na_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_non_hcp IS FALSE)
  1917. )
  1918. ORDER BY ts DESC
  1919. "
  1920. )
  1921. );
  1922. return view('app.practice-management.remote-monitoring-measurements', compact('careMonth', 'measurements'));
  1923. }
  1924. public function billMatrix(Request $request)
  1925. {
  1926. $bClients = [];
  1927. $bHCPPros = [];
  1928. $bNAPros = [];
  1929. $filters = [];
  1930. $filters['client'] = $request->input('client');
  1931. $filters['service'] = $request->input('service');
  1932. $filters['hcp'] = $request->input('hcp');
  1933. $filters['hcp_paid'] = $request->input('hcp_paid');
  1934. $filters['expected_op'] = $request->input('expected_op');
  1935. $filters['expected_value'] = $request->input('expected_value');
  1936. $filters['paid_op'] = $request->input('paid_op');
  1937. $filters['paid_value'] = $request->input('paid_value');
  1938. $filters['bal_post_date_op'] = $request->input('bal_post_date_op');
  1939. $filters['bal_post_date_value'] = $request->input('bal_post_date_value');
  1940. $filters['hcp_sign'] = $request->input('hcp_sign');
  1941. $filters['verified'] = $request->input('verified');
  1942. $filters['cancelled'] = $request->input('cancelled');
  1943. $bills = Bill::orderBy('effective_date')->paginate();
  1944. return view('app.practice-management.bill-matrix', compact('bills', 'bClients', 'bHCPPros', 'filters'));
  1945. }
  1946. public function medicarePartBClaims(Request $request)
  1947. {
  1948. $medicarePartBOnly = $request->get("medicare_part_b");
  1949. $allClaims = Claim::where('was_submitted', false)->orWhere('was_submitted', null)->orderBy('created_at', 'desc')->get();
  1950. //Only medicare claims
  1951. $claims = [];
  1952. foreach ($allClaims as $claim) {
  1953. if ($claim->client != null && $claim->client->getPrimaryCoverageStatus() == 'YES' && !$claim->edi) {
  1954. $claims[] = $claim;
  1955. }
  1956. }
  1957. $claimEDIs = ClaimEDI::all();
  1958. return view('app.practice-management.medicare-partb-claims', compact('claims', 'claimEDIs'));
  1959. }
  1960. // Generate PDF
  1961. public function downloadClaims()
  1962. {
  1963. $claims = Claim::where('was_submitted', false)->orWhere('was_submitted', null)->orderBy('created_at', 'desc')->limit(100)->get();
  1964. view()->share('claims', $claims);
  1965. $pdf = PDF::loadView('app.practice-management.claims-pdf', $claims);
  1966. return $pdf->download('pdf_file.pdf');
  1967. }
  1968. public function tickets(Request $request, $proUid = null)
  1969. {
  1970. $tickets = Ticket::orderBy('created_at', 'desc')->paginate();
  1971. return view('app.practice-management.tickets', compact('tickets'));
  1972. }
  1973. public function supplyOrders(Request $request)
  1974. {
  1975. // counts
  1976. $counts = $this->getSupplyOrderCounts();
  1977. // so clients
  1978. $soClientIDs = DB::table('supply_order')->select('client_id')->distinct()->get()->toArray();
  1979. $soClientIDs = array_map(function ($_x) {
  1980. return $_x->client_id;
  1981. }, $soClientIDs);
  1982. $soClients = Client::whereIn('id', $soClientIDs)->get();
  1983. // so products
  1984. $soProductIDs = DB::table('supply_order')->select('product_id')->distinct()->get()->toArray();
  1985. $soProductIDs = array_map(function ($_x) {
  1986. return $_x->product_id;
  1987. }, $soProductIDs);
  1988. $soProducts = Product::whereIn('id', $soProductIDs)->get();
  1989. $filters = [];
  1990. $filters['client'] = $request->input('client');
  1991. $filters['product'] = $request->input('product');
  1992. $filters['reason'] = $request->input('reason');
  1993. $filters['cu_memo'] = $request->input('cu_memo');
  1994. $filters['pro_sign'] = $request->input('pro_sign');
  1995. $filters['client_sign'] = $request->input('client_sign');
  1996. $filters['shipment'] = $request->input('shipment');
  1997. $filters['lot_number'] = $request->input('lot_number');
  1998. $filters['imei'] = $request->input('imei');
  1999. $filters['cancelled'] = $request->input('cancelled');
  2000. $supplyOrders = SupplyOrder::where('id', '>', 0);
  2001. // apply filters
  2002. if ($filters['client']) $supplyOrders->where('client_id', $filters['client']);
  2003. if ($filters['product']) $supplyOrders->where('product_id', $filters['product']);
  2004. if ($filters['reason']) $supplyOrders->where('reason', 'ILIKE', '%' . $filters['reason'] . '%');
  2005. if ($filters['cu_memo']) $supplyOrders->where('cu_memo', 'ILIKE', '%' . $filters['cu_memo'] . '%');
  2006. if ($filters['pro_sign']) $supplyOrders->where('is_signed_by_pro', ($filters['pro_sign'] === 'signed'));
  2007. if ($filters['client_sign']) {
  2008. if ($filters['client_sign'] === 'signed')
  2009. $supplyOrders->where('is_signed_by_client', true);
  2010. elseif ($filters['client_sign'] === 'waived')
  2011. $supplyOrders->where('is_client_signature_waived', true);
  2012. else
  2013. $supplyOrders->where('is_client_signature_waived', false)->where('is_signed_by_client', false);
  2014. }
  2015. if ($filters['shipment']) {
  2016. if ($filters['shipment'] === 'not_cleared_for_shipment')
  2017. $supplyOrders->whereNull('shipment_id')->where('is_cleared_for_shipment', false);
  2018. elseif ($filters['shipment'] === 'cleared_for_shipment')
  2019. $supplyOrders->whereNull('shipment_id')->where('is_cleared_for_shipment', true);
  2020. else
  2021. $supplyOrders
  2022. ->whereNotNull('shipment_id')
  2023. ->whereRaw('(SELECT status FROM shipment WHERE id = shipment_id LIMIT 1) = ?', [$filters['shipment']]);
  2024. }
  2025. if ($filters['lot_number']) $supplyOrders->where('lot_number', 'ILIKE', '%' . $filters['lot_number'] . '%');
  2026. if ($filters['imei']) $supplyOrders->where('imei', 'ILIKE', '%' . $filters['imei'] . '%');
  2027. if ($filters['cancelled']) $supplyOrders->where('is_cancelled', ($filters['cancelled'] === 'cancelled'));
  2028. $supplyOrders = $supplyOrders->orderBy('created_at', 'desc')->paginate();
  2029. return view('app.practice-management.supply-orders',
  2030. compact('supplyOrders', 'filters',
  2031. 'soClients', 'soProducts', 'counts'
  2032. )
  2033. );
  2034. }
  2035. public function shipments(Request $request, $filter = null)
  2036. {
  2037. // counts
  2038. $counts = $this->getShipmentCounts();
  2039. // so clients
  2040. $shClientIDs = DB::table('shipment')->select('client_id')->distinct()->get()->toArray();
  2041. $shClientIDs = array_map(function ($_x) {
  2042. return $_x->client_id;
  2043. }, $shClientIDs);
  2044. $shClients = Client::whereIn('id', $shClientIDs)->get();
  2045. $shipments = Shipment::where('id', '>', 0);
  2046. $filters = [];
  2047. $filters['client'] = $request->input('client');
  2048. $filters['courier'] = $request->input('courier');
  2049. $filters['tracking_num'] = $request->input('tracking_num');
  2050. $filters['label'] = $request->input('label');
  2051. $filters['status'] = $request->input('status');
  2052. $filters['cancelled'] = $request->input('cancelled');
  2053. if ($filters['client']) $shipments->where('client_id', $filters['client']);
  2054. if ($filters['courier']) $shipments->where('courier', 'ILIKE', '%' . $filters['courier'] . '%');
  2055. if ($filters['tracking_num']) $shipments->where('tracking_number', 'ILIKE', '%' . $filters['tracking_num'] . '%');
  2056. if ($filters['label']) {
  2057. if ($filters['label'] === 'yes')
  2058. $shipments->whereNotNull('label_system_file_id');
  2059. else
  2060. $shipments->whereNull('label_system_file_id');
  2061. }
  2062. if ($filters['status']) $shipments->where('status', $filters['status']);
  2063. if ($filters['cancelled']) $shipments->where('is_cancelled', ($filters['cancelled'] === 'cancelled'));
  2064. $shipments = $shipments->orderBy('created_at', 'desc')->paginate();
  2065. return view('app.practice-management.shipments', compact('shipments', 'filters', 'shClients', 'counts'));
  2066. }
  2067. public function cellularMeasurements(Request $request)
  2068. {
  2069. $measurements = Measurement::orderBy('ts', 'desc')->whereNotNull('ts')->paginate();
  2070. return view('app.practice-management.cellular-measurements', compact('measurements'));
  2071. }
  2072. // v2 supply-orders & shipments management (wh)
  2073. public function supplyOrdersReadyToShip(Request $request)
  2074. {
  2075. $counts = $this->getSupplyOrderCounts();
  2076. $supplyOrders = SupplyOrder
  2077. ::where('is_cleared_for_shipment', true)
  2078. ->where('is_cancelled', false)
  2079. ->whereNull('shipment_id')
  2080. ->join('client', 'client.id', '=', 'supply_order.client_id')
  2081. ->orderBy('client.name_last', 'ASC')
  2082. ->orderBy('client.name_first', 'ASC')
  2083. ->orderBy('supply_order.client_id', 'ASC')
  2084. ->orderBy('supply_order.mailing_address_full', 'ASC')
  2085. ->orderBy('supply_order.created_at', 'ASC')
  2086. ->select('supply_order.*')
  2087. ->paginate();
  2088. return view('app.practice-management.supply-orders-ready-to-ship', compact('supplyOrders', 'counts'));
  2089. }
  2090. public function supplyOrdersShipmentUnderway(Request $request)
  2091. {
  2092. $counts = $this->getSupplyOrderCounts();
  2093. $supplyOrders = SupplyOrder
  2094. ::where('is_cancelled', false)
  2095. ->whereNotNull('shipment_id')
  2096. ->orderBy('client_id', 'ASC')
  2097. ->orderBy('mailing_address_full', 'ASC')
  2098. ->orderBy('created_at', 'ASC')
  2099. ->paginate();
  2100. return view('app.practice-management.supply-orders-shipment-underway', compact('supplyOrders', 'counts'));
  2101. }
  2102. public function supplyOrdersHanging(Request $request)
  2103. {
  2104. $counts = $this->getSupplyOrderCounts();
  2105. $supplyOrders = SupplyOrder
  2106. ::select('supply_order.*')
  2107. ->leftJoin('shipment', function($join) {
  2108. $join->on('supply_order.shipment_id', '=', 'shipment.id');
  2109. })
  2110. ->where('shipment.status', 'CANCELLED')
  2111. ->where('supply_order.is_cancelled', false)
  2112. ->orderBy('supply_order.client_id', 'ASC')
  2113. ->orderBy('supply_order.mailing_address_full', 'ASC')
  2114. ->orderBy('supply_order.created_at', 'ASC')
  2115. ->paginate();
  2116. return view('app.practice-management.supply-orders-hanging', compact('supplyOrders', 'counts'));
  2117. }
  2118. public function supplyOrdersCancelledButUnacknowledged(Request $request)
  2119. {
  2120. $supplyOrders = SupplyOrder::where('signed_by_pro_id', $this->performer()->pro->id)
  2121. ->where('is_cancelled', true)
  2122. ->where('is_cancellation_acknowledged', false)
  2123. ->orderBy('created_at', 'desc')
  2124. ->paginate();
  2125. return view('app.practice-management.supply-orders-cancelled-but-unacknowledged', compact('supplyOrders'));
  2126. }
  2127. public function supplyOrdersUnsigned(Request $request)
  2128. {
  2129. $supplyOrders = SupplyOrder
  2130. ::where('is_cancelled', false)
  2131. ->where('is_signed_by_pro', false)
  2132. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$this->performer()->pro->id])
  2133. ->orderBy('created_at', 'desc')
  2134. ->paginate();
  2135. return view('app.practice-management.supply-orders-unsigned', compact('supplyOrders'));
  2136. }
  2137. private function getSupplyOrderCounts()
  2138. {
  2139. return [
  2140. "supplyOrders" => SupplyOrder::count(),
  2141. "supplyOrdersReadyToShip" => SupplyOrder
  2142. ::where('is_cleared_for_shipment', true)
  2143. ->where('is_cancelled', false)
  2144. ->whereNull('shipment_id')->count(),
  2145. "supplyOrdersShipmentUnderway" => SupplyOrder
  2146. ::where('is_cancelled', false)
  2147. ->whereNotNull('shipment_id')->count(),
  2148. "supplyOrdersHanging" => SupplyOrder
  2149. ::leftJoin('shipment', function($join) {
  2150. $join->on('supply_order.shipment_id', '=', 'shipment.id');
  2151. })
  2152. ->where('shipment.status', 'CANCELLED')
  2153. ->where('supply_order.is_cancelled', false)
  2154. ->count(),
  2155. ];
  2156. }
  2157. public function shipmentsReadyToPrint(Request $request)
  2158. {
  2159. $counts = $this->getShipmentCounts();
  2160. $shipments = Shipment
  2161. ::where('is_cancelled', false)
  2162. ->where('status', 'CREATED')
  2163. ->orderBy('created_at', 'ASC')
  2164. ->paginate();
  2165. return view('app.practice-management.shipments-ready-to-print', compact('shipments', 'counts'));
  2166. }
  2167. public function shipmentsShipmentUnderway(Request $request)
  2168. {
  2169. $counts = $this->getShipmentCounts();
  2170. $shipments = Shipment
  2171. ::where('is_cancelled', false)
  2172. ->where('status', 'PRINTED')
  2173. ->orderBy('created_at', 'ASC')
  2174. ->paginate();
  2175. return view('app.practice-management.shipments-waiting-for-picker', compact('shipments', 'counts'));
  2176. }
  2177. private function getShipmentCounts()
  2178. {
  2179. return [
  2180. "shipments" => Shipment::count(),
  2181. "shipmentsReadyToPrint" => Shipment
  2182. ::where('is_cancelled', false)
  2183. ->where('status', 'CREATED')
  2184. ->count(),
  2185. "shipmentsWaitingForPicker" => Shipment
  2186. ::where('is_cancelled', false)
  2187. ->where('status', 'PRINTED')
  2188. ->count()
  2189. ];
  2190. }
  2191. public function shipment(Request $request, Shipment $shipment)
  2192. {
  2193. return view('app.practice-management.shipment', compact('shipment'));
  2194. }
  2195. public function shipmentsMultiPrint(Request $request, $ids)
  2196. {
  2197. $ids = array_map(function ($_x) {
  2198. return intval($_x);
  2199. }, explode("|", $ids));
  2200. $shipments = Shipment::whereIn('id', $ids)->get();
  2201. return view('app.practice-management.shipments-multi-print', compact('shipments'));
  2202. }
  2203. public function patientClaimSummary(Request $request, $proUid = null)
  2204. {
  2205. $notesTotal = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE"))[0]->count;
  2206. $notesTotalWithBillingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE AND is_bill_closed IS TRUE"))[0]->count;
  2207. $notesTotalWithClaimingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE AND is_claim_closed IS TRUE"))[0]->count;
  2208. $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;
  2209. $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;
  2210. $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;
  2211. $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;
  2212. $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;
  2213. $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;
  2214. $performerPro = $this->performer->pro;
  2215. $allPros = [];
  2216. if ($performerPro->pro_type == 'ADMIN') {
  2217. $allPros = Pro::all();
  2218. } else {
  2219. $allPros = [$performerPro];
  2220. }
  2221. //Patient | MCP | # Notes Total | # Notes without Billing Closed | # Notes without Claiming Closed
  2222. $patientsQuery = Client::where('is_dummy', '=', false)
  2223. ->whereNull('shadow_pro_id')
  2224. ->select('id', 'uid', 'name_first', 'name_last', 'mcp_pro_id', 'is_part_b_primary', 'medicare_advantage_plan',
  2225. DB::raw("(SELECT name_first||' '||name_last FROM pro where pro.id = client.mcp_pro_id) as mcp"),
  2226. DB::raw("(SELECT uid FROM pro where pro.id = mcp_pro_id) as mcp_pro_uid"),
  2227. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id) as notes_total"),
  2228. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id AND is_bill_closed IS NOT true) as notes_without_billing_closed"),
  2229. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id AND is_claim_closed IS NOT true) as notes_without_claiming_closed")
  2230. )->orderBy('is_part_b_primary', 'asc')->orderBy('notes_without_claiming_closed', 'desc');
  2231. if ($proUid) {
  2232. $mcpPro = Pro::where('uid', $proUid)->first();
  2233. if ($mcpPro) {
  2234. $patientsQuery->where('client.mcp_pro_id', '=', $mcpPro->id);
  2235. }
  2236. }
  2237. $patientsQuery->whereRaw('(SELECT COUNT(*) FROM note where note.client_id = client.id) > 0');
  2238. $patientsQuery->orderBy('notes_total', 'DESC');
  2239. $patients = $patientsQuery->paginate(50);
  2240. $data = [
  2241. 'patients' => $patients,
  2242. 'proUid' => $proUid,
  2243. 'allPros' => $allPros,
  2244. 'notesTotal' => $notesTotal,
  2245. 'notesTotalWithBillingClosed' => $notesTotalWithBillingClosed,
  2246. 'notesTotalWithClaimingClosed' => $notesTotalWithClaimingClosed,
  2247. 'notes3rdPartyTotal' => $notes3rdPartyTotal,
  2248. 'notes3rdPartyTotalWithBillingClosed' => $notes3rdPartyTotalWithBillingClosed,
  2249. 'notes3rdPartyTotalWithClaimingClosed' => $notes3rdPartyTotalWithClaimingClosed,
  2250. 'patientsTotal' => $patientsTotal,
  2251. 'patientsTotalWithBillingClosed' => $patientsTotalWithBillingClosed,
  2252. 'patientsTotalWithClaimingClosed' => $patientsTotalWithClaimingClosed
  2253. ];
  2254. return view('app.practice-management.patient-claim-summary', $data);
  2255. }
  2256. public function claims(Request $request){
  2257. $status = $request->get('status');
  2258. $claims = [];
  2259. if(!$status){
  2260. $claims = Claim::orderBy('created_at', 'DESC')->paginate();
  2261. }else{
  2262. $claims = Claim::where('status', $status)->orderBy('created_at', 'DESC')->paginate();
  2263. }
  2264. return view('app.practice-management.claims', compact('claims', 'status'));
  2265. }
  2266. public function processClaims(Request $request) {
  2267. $status = '';
  2268. $q = $request->input('q') ? $request->input('q') : '';
  2269. $from = $request->input('from') ? $request->input('from') : '1900-01-01';
  2270. $to = $request->input('to') ? $request->input('to') : '2100-01-01';
  2271. $params = [
  2272. 'q' => '%' . $q . '%',
  2273. 'from' => $from,
  2274. 'to' => $to
  2275. ];
  2276. $hcpPro = $request->input('hcp') ? Pro::where('uid', $request->input('hcp'))->first() : null;
  2277. if($hcpPro) {
  2278. $params['hcp'] = $hcpPro->id;
  2279. }
  2280. $claims = DB::select(DB::raw("
  2281. SELECT claim.uid AS uid,
  2282. DATE(claim.created_at) AS created,
  2283. claim.status,
  2284. client.uid AS client_uid,
  2285. client.cell_number AS client_phone,
  2286. client.phone_home AS client_phone_home,
  2287. (client.name_last || ' ' || client.name_first) AS client ,
  2288. client.chart_number AS client_chart_number,
  2289. cp.id AS claim_pro_id,
  2290. (cp.name_last || ' ' || cp.name_first) AS claim_pro,
  2291. sp.id AS status_pro_id,
  2292. (sp.name_last || ' ' || sp.name_first) AS status_pro,
  2293. note.uid AS note_uid,
  2294. note.method,
  2295. note.new_or_fu_or_na,
  2296. care_month.uid AS care_month_uid,
  2297. care_month.start_date as care_month_start__date,
  2298. -- claim.status_updated_at,
  2299. (DATE(claim.status_updated_at) || ' ' ||
  2300. LPAD(EXTRACT(hour FROM claim.status_updated_at)::text, 2, '0') || ':' ||
  2301. LPAD(EXTRACT(minute FROM claim.status_updated_at)::text, 2, '0')) AS status_updated_at,
  2302. (SELECT string_agg(claim_line.cpt, ', ') FROM claim_line where claim_id = claim.id) AS cpts,
  2303. (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,
  2304. ROUND(claim.expected_total, 3) as expected_total
  2305. FROM claim
  2306. join client on claim.client_id = client.id
  2307. join pro cp on claim.pro_id = cp.id
  2308. left join note on claim.note_id = note.id
  2309. left join care_month on claim.care_month_id = care_month.id
  2310. left join app_session on claim.status_updated_by_session_id = app_session.id
  2311. left join pro sp on app_session.pro_id = sp.id
  2312. --WHERE claim.status IS NULL OR claim.status = 'NEW'
  2313. WHERE (claim.status is NULL OR claim.status NOT IN ('CANCELLED', 'ABANDONED'" . ($request->input('show-submitted') ? "" : ", 'SUBMITTED'") . "))
  2314. -- AND claim.current_version_id IS NOT NULL
  2315. AND (client.name_first ILIKE :q OR
  2316. client.name_last ILIKE :q OR
  2317. client.chart_number ILIKE :q OR
  2318. client.mcn ILIKE :q)
  2319. AND (claim.created_at >= :from AND claim.created_at <= :to)
  2320. " . ($hcpPro ? "AND claim.pro_id = :hcp" : '') . "
  2321. AND claim.id IN (SELECT mb_claim.claim_id FROM mb_claim)
  2322. ORDER BY claim.created_at DESC
  2323. --OFFSET 0 LIMIT 15
  2324. "), $params);
  2325. if($request->input('json')) {
  2326. return json_encode($claims);
  2327. }
  2328. return view('app.practice-management.process-claims', compact('claims', 'status'));
  2329. }
  2330. public function rmLaunchAndClean(Request $request) {
  2331. $keyNumbers = [];
  2332. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_40'] = CareMonth::where('is_bill_closed', false)
  2333. ->whereNotNull('company_pro_id')
  2334. ->whereNotNull('company_pro_payer_id')
  2335. ->whereNotNull('company_location_id')
  2336. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2337. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  2338. ->where('rm_total_time_in_seconds', '>=', 4200) // at 4200 (70 minutes, it becomes eligible for plus40)
  2339. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2340. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2341. ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS TRUE OR has_mcp_rm_interacted_by_note IS TRUE )')
  2342. ->count();
  2343. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_40_ifHadInteraction'] = CareMonth::where('is_bill_closed', false)
  2344. ->whereNotNull('company_pro_id')
  2345. ->whereNotNull('company_pro_payer_id')
  2346. ->whereNotNull('company_location_id')
  2347. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2348. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  2349. ->where('rm_total_time_in_seconds', '>=', 4200) // at 4200 (70 minutes, it becomes eligible for plus40)
  2350. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2351. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2352. ->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 )')
  2353. ->count();
  2354. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_20'] = 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)
  2361. ->where('rm_total_time_in_seconds', '>=', 3000) // at 3000 (50 minutes, it becomes eligible for plus20)
  2362. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2363. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2364. ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS TRUE OR has_mcp_rm_interacted_by_note IS TRUE)')
  2365. ->count();
  2366. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_20_ifHadInteraction'] = CareMonth::where('is_bill_closed', false)
  2367. ->whereNotNull('company_pro_id')
  2368. ->whereNotNull('company_pro_payer_id')
  2369. ->whereNotNull('company_location_id')
  2370. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2371. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  2372. ->where('rm_total_time_in_seconds', '<', 4200)
  2373. ->where('rm_total_time_in_seconds', '>=', 3000) // at 3000 (50 minutes, it becomes eligible for plus20)
  2374. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2375. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2376. ->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 )')
  2377. ->count();
  2378. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP'] = CareMonth::where('is_bill_closed', false)
  2379. ->whereNotNull('company_pro_id')
  2380. ->whereNotNull('company_pro_payer_id')
  2381. ->whereNotNull('company_location_id')
  2382. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2383. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  2384. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2385. ->whereRaw('(rm_total_time_in_seconds < 3000 OR (rm_total_time_in_seconds >= 3000 AND is_rm_interaction_waived IS TRUE))')
  2386. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2387. ->count();
  2388. $keyNumbers['careMonthsEligibleForBillGeneration_RMB'] = 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. ->whereRaw('is_rm_time_waived IS TRUE')
  2394. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2395. ->count();
  2396. $keyNumbers['careMonthsWith16OrMoreMeasurementDays'] = CareMonth::where('is_bill_closed', false)
  2397. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2398. ->count();
  2399. $careMonthsWith16PlusMeasurements = CareMonth::where('is_bill_closed', false)
  2400. ->where('number_of_days_with_remote_measurements', '>=', 16 )->get();
  2401. return view('app.practice-management.rm-launch-and-clean', compact('keyNumbers', 'careMonthsWith16PlusMeasurements'));
  2402. }
  2403. public function processNotes(Request $request) {
  2404. $mode = $request->input('mode') ? $request->input('mode') : '1';
  2405. if(($mode < 1 || $mode > 5) && $mode != 8) $mode = 1;
  2406. DB::enableQueryLog(); // Enable query log
  2407. $test = Note::where('is_cancelled', false)
  2408. ->where('is_signed_by_hcp', true)
  2409. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  2410. ->whereNull('current_note_pickup_for_processing_id')
  2411. ->where('is_billing_marked_done', true)
  2412. ->where('is_bill_closed', true)
  2413. ->where('is_claim_closed', true)
  2414. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  2415. ->count();
  2416. // var_dump($test);
  2417. // dd(DB::getQueryLog()); // Show results of log
  2418. // exit;
  2419. $counts = [
  2420. "picked" => Note::where('is_cancelled', false)
  2421. ->whereNotNull('current_note_pickup_for_processing_id')
  2422. ->count(),
  2423. "bad" => Note::where('is_cancelled', false)
  2424. ->whereRaw("((detail_json)::json->>'isBad' = 'true')")
  2425. ->count(),
  2426. // not yet signed
  2427. "mode-1" => Note::where('is_cancelled', false)
  2428. ->where('is_signed_by_hcp', false)
  2429. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2430. // ->whereNull('current_note_pickup_for_processing_id')
  2431. ->count(),
  2432. // billing not marked done
  2433. "mode-2" => Note::where('is_cancelled', false)
  2434. ->where('is_signed_by_hcp', true)
  2435. //->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2436. // ->whereNull('current_note_pickup_for_processing_id')
  2437. ->where('is_billing_marked_done', false)
  2438. ->count(),
  2439. // billing not closed
  2440. "mode-3" => Note::where('is_cancelled', false)
  2441. ->where('is_signed_by_hcp', true)
  2442. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2443. // ->whereNull('current_note_pickup_for_processing_id')
  2444. ->where('is_billing_marked_done', true)
  2445. ->where('is_bill_closed', false)
  2446. ->count(),
  2447. // claiming not closed
  2448. "mode-4" => Note::where('is_cancelled', false)
  2449. ->where('is_signed_by_hcp', true)
  2450. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2451. // ->whereNull('current_note_pickup_for_processing_id')
  2452. ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true' OR ((detail_json)::json->>'isGood')::text IS NULL)")
  2453. ->where('is_billing_marked_done', true)
  2454. ->where('is_bill_closed', true)
  2455. ->where('is_claim_closed', false)
  2456. ->count(),
  2457. // has unsubmitted claims
  2458. "mode-5" => Note::where('is_cancelled', false)
  2459. /*->where('is_signed_by_hcp', true)
  2460. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2461. ->whereNull('current_note_pickup_for_processing_id')
  2462. ->where('is_billing_marked_done', true)
  2463. ->where('is_bill_closed', true)
  2464. ->where('is_claim_closed', true)
  2465. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0")
  2466. */
  2467. ->where('is_signed_by_hcp', true)
  2468. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2469. // ->whereNull('current_note_pickup_for_processing_id')
  2470. ->where('is_billing_marked_done', true)
  2471. ->where('is_bill_closed', true)
  2472. // ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true')")
  2473. ->where('is_claim_closed', true)
  2474. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0)")
  2475. ->count(),
  2476. // has unsubmitted claims MARKED GOOD!
  2477. "mode-8" => Note::where('is_cancelled', false)
  2478. ->where('is_signed_by_hcp', true)
  2479. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  2480. ->whereNull('current_note_pickup_for_processing_id')
  2481. ->where('is_billing_marked_done', true)
  2482. ->where('is_bill_closed', true)
  2483. ->where('is_claim_closed', false)
  2484. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  2485. ->count(),
  2486. // all good
  2487. "mode-6" => Note::where('is_cancelled', false)
  2488. ->where('is_signed_by_hcp', true)
  2489. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2490. // ->whereNull('current_note_pickup_for_processing_id')
  2491. ->where('is_billing_marked_done', true)
  2492. ->where('is_bill_closed', true)
  2493. ->where('is_claim_closed', true)
  2494. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id) > 0)")
  2495. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  2496. ->count(),
  2497. "mode-7" => Note::where('is_cancelled', false)
  2498. ->whereRaw("(detail_json)::json->>'isBad' = 'true'")
  2499. ->count(),
  2500. ];
  2501. return view('app.practice-management.process-notes', compact('mode', 'counts'));
  2502. }
  2503. public function notesProcessingCenter(Request $request) {
  2504. $notes = Note::where('is_cancelled', false);
  2505. // filters
  2506. $proUid = $request->input('proUid');
  2507. if($proUid) {
  2508. $fPro = Pro::where('uid', $proUid)->first();
  2509. if($fPro) {
  2510. $notes = $notes->where('hcp_pro_id', $fPro->id);
  2511. }
  2512. }
  2513. $proSigned = $request->input('proSigned');
  2514. switch($proSigned) {
  2515. case 'yes': $notes = $notes->where('is_signed_by_hcp', true); break;
  2516. case 'no': $notes = $notes->where('is_signed_by_hcp', '!=', true); break;
  2517. }
  2518. $billingMarkedDone = $request->input('billingMarkedDone');
  2519. switch($billingMarkedDone) {
  2520. case 'yes': $notes = $notes->where('is_billing_marked_done', true); break;
  2521. case 'no': $notes = $notes->where('is_billing_marked_done', '!=', true); break;
  2522. }
  2523. $billingClosed = $request->input('billingClosed');
  2524. switch($billingClosed) {
  2525. case 'yes': $notes = $notes->where('is_bill_closed', true); break;
  2526. case 'no': $notes = $notes->where('is_bill_closed', '!=', true); break;
  2527. }
  2528. $claimingClosed = $request->input('claimingClosed');
  2529. switch($claimingClosed) {
  2530. case 'yes': $notes = $notes->where('is_claim_closed', true); break;
  2531. case 'no': $notes = $notes->where('is_claim_closed', '!=', true); break;
  2532. }
  2533. $allClaimsSubmitted = $request->input('allClaimsSubmitted');
  2534. if($allClaimsSubmitted) {
  2535. // TODO
  2536. }
  2537. $goodBad = $request->input('goodBad');
  2538. switch($goodBad) {
  2539. case 'good': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' = 'false'"); break;
  2540. case 'bad': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' = 'true'"); break;
  2541. case 'unclassified': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' is null"); break;
  2542. }
  2543. $startDate = $request->input('startDate');
  2544. if($startDate) {
  2545. $notes = $notes->where('effective_dateest', '>=', $startDate);
  2546. }
  2547. $endDate = $request->input('endDate');
  2548. if($endDate) {
  2549. $notes = $notes->where('effective_dateest', '<=', $endDate);
  2550. }
  2551. $mcPartB = $request->input('mcPartB');
  2552. if($mcPartB) {
  2553. // TODO
  2554. }
  2555. $notes = $notes->orderBy('effective_dateest')->paginate(10);
  2556. return view('app.practice-management.notes-processing-center', compact('notes'));
  2557. }
  2558. public function getNextNote(Request $request, $mode)
  2559. {
  2560. $note = null;
  2561. switch (+$mode) {
  2562. case 1:
  2563. $note = Note::where('is_cancelled', false)
  2564. ->where('is_signed_by_hcp', false)
  2565. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2566. ->whereNull('current_note_pickup_for_processing_id')
  2567. ->orderBy('effective_dateest', 'DESC')
  2568. ->first();
  2569. break;
  2570. case 2:
  2571. $note = Note::where('is_cancelled', false)
  2572. ->where('is_signed_by_hcp', true)
  2573. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2574. ->whereNull('current_note_pickup_for_processing_id')
  2575. ->where('is_billing_marked_done', false)
  2576. ->orderBy('effective_dateest', 'DESC')
  2577. ->first();
  2578. break;
  2579. case 3:
  2580. $note = Note::where('is_cancelled', false)
  2581. ->where('is_signed_by_hcp', true)
  2582. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2583. ->whereNull('current_note_pickup_for_processing_id')
  2584. ->where('is_billing_marked_done', true)
  2585. ->where('is_bill_closed', false)
  2586. ->orderBy('effective_dateest', 'DESC')
  2587. ->first();
  2588. break;
  2589. case 4: // claiming not closed
  2590. DB::enableQueryLog(); // Enable query log
  2591. $note = Note::where('is_cancelled', false)
  2592. ->where('is_signed_by_hcp', true)
  2593. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2594. ->whereNull('current_note_pickup_for_processing_id')
  2595. ->where('is_billing_marked_done', true)
  2596. ->where('is_bill_closed', true)
  2597. ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true' OR ((detail_json)::json->>'isGood')::text IS NULL)")
  2598. ->where('is_claim_closed', false)
  2599. ->orderBy('effective_dateest', 'DESC')
  2600. ->first();
  2601. // DB::enableQueryLog(); // Enable query log
  2602. // Your Eloquent query executed by using get()
  2603. // dd(DB::getQueryLog()); // Show results of log
  2604. break;
  2605. case 5:
  2606. $note = Note::where('is_cancelled', false)
  2607. ->where('is_signed_by_hcp', true)
  2608. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2609. ->whereNull('current_note_pickup_for_processing_id')
  2610. ->where('is_billing_marked_done', true)
  2611. ->where('is_bill_closed', true)
  2612. ->where('is_claim_closed', true)
  2613. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0")
  2614. ->orderBy('effective_dateest', 'DESC')
  2615. ->first();
  2616. break;
  2617. case 8:
  2618. $note = Note::where('is_cancelled', false)
  2619. ->where('is_signed_by_hcp', true)
  2620. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  2621. ->whereNull('current_note_pickup_for_processing_id')
  2622. ->where('is_billing_marked_done', true)
  2623. ->where('is_bill_closed', true)
  2624. ->where('is_claim_closed', false)
  2625. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  2626. ->orderBy('effective_dateest', 'DESC')
  2627. ->first();
  2628. break;
  2629. }
  2630. if($note) {
  2631. $note->client_uid = $note->client->uid;
  2632. }
  2633. return json_encode($note);
  2634. }
  2635. public function pickedNotes(Request $request) {
  2636. $counts = [
  2637. "unpicked" => Note::where('is_cancelled', false)
  2638. ->whereNull('current_note_pickup_for_processing_id')
  2639. ->count(),
  2640. ];
  2641. $notes = Note::where('is_cancelled', false)
  2642. ->whereNotNull('current_note_pickup_for_processing_id')
  2643. ->orderBy('effective_dateest', 'ASC')
  2644. ->paginate();
  2645. return view('app.practice-management.picked-notes', compact('counts', 'notes'));
  2646. }
  2647. public function badNotes(Request $request) {
  2648. $counts = [
  2649. "unpicked" => Note::where('is_cancelled', false)
  2650. ->whereNull('current_note_pickup_for_processing_id')
  2651. ->count(),
  2652. ];
  2653. $notes = Note::where('is_cancelled', false)
  2654. ->whereRaw("(detail_json)::json->>'isBad' = 'true'")
  2655. ->orderBy('effective_dateest', 'ASC')
  2656. ->paginate();
  2657. return view('app.practice-management.bad-notes', compact('counts', 'notes'));
  2658. }
  2659. public function doneNotes(Request $request) {
  2660. $counts = [
  2661. "unpicked" => Note::where('is_cancelled', false)
  2662. ->whereNull('current_note_pickup_for_processing_id')
  2663. ->count(),
  2664. ];
  2665. $notes = Note::where('is_cancelled', false)
  2666. ->where('is_signed_by_hcp', true)
  2667. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2668. ->whereNull('current_note_pickup_for_processing_id')
  2669. ->where('is_billing_marked_done', true)
  2670. ->where('is_bill_closed', true)
  2671. ->where('is_claim_closed', true)
  2672. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id) > 0")
  2673. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0")
  2674. ->orderBy('effective_dateest', 'ASC')
  2675. ->paginate();
  2676. return view('app.practice-management.done-notes', compact('counts', 'notes'));
  2677. }
  2678. public function currentMbClaim(Request $request, $claimUid) {
  2679. $claim = Claim::where('uid', $claimUid)->first();
  2680. return json_encode(MBClaim::where('claim_version_id', $claim->currentVersion->id)->where('status', '!=', 'CANCELLED')->first());
  2681. }
  2682. public function currentClaimLines(Request $request, $claimUid) {
  2683. $claim = Claim::where('uid', $claimUid)->first();
  2684. if($request->input('json')) {
  2685. foreach ($claim->lines as $line) {
  2686. $line->expected_total = round($line->expected_total, 3);
  2687. $x = $line->claimLineIcds;
  2688. }
  2689. return json_encode($claim->lines);
  2690. }
  2691. return view('app.practice-management._claim-lines', compact('claim'));
  2692. }
  2693. public function packsMultiPrint(Request $request) {
  2694. $packs = Pack
  2695. ::select('pack.*')
  2696. ->leftJoin('shipment', function($join) {
  2697. $join->on('pack.shipment_id', '=', 'shipment.id');
  2698. })
  2699. ->whereNotIn('shipment.status', ['CANCELLED', 'DISPATCHED'])
  2700. ->where(function ($query) {
  2701. $query->where('pack.status', '<>', 'DELETED')->orWhereNull('pack.status'); // weird, but just the <> isn't working!
  2702. })
  2703. ->whereNotNull('pack.label_system_file_id')
  2704. ->orderBy('pack.created_at', 'ASC')
  2705. ->get();
  2706. return view('app.practice-management.packs-multi-print', compact('packs'));
  2707. }
  2708. public function packsMultiPDF(Request $request, $ids) {
  2709. $ids = array_map(function ($_x) {
  2710. return intval($_x);
  2711. }, explode("|", $ids));
  2712. $packs = Pack::whereIn('id', $ids)->get();
  2713. }
  2714. public function handouts(Request $request) {
  2715. $handouts = Handout::orderBy('display_name')->get();
  2716. return view('app.practice-management.handouts', compact('handouts'));
  2717. }
  2718. private function callJava($request, $endPoint, $data)
  2719. {
  2720. $url = config('stag.backendUrl') . $endPoint;
  2721. $response = Http::asForm()
  2722. ->withHeaders([
  2723. 'sessionKey' => $request->cookie('sessionKey')
  2724. ])
  2725. ->post($url, $data)
  2726. ->body();
  2727. dd($response);
  2728. return $response;
  2729. }
  2730. public function genericBills(Request $request)
  2731. {
  2732. return view('app.practice-management.generic-bills');
  2733. }
  2734. public function billsUnderProcessing(Request $request)
  2735. {
  2736. $bills = Bill::where('is_cancelled', false)
  2737. ->where(function ($query) { // mcp of any client program and program OB pending
  2738. $query
  2739. ->where(function ($_query) {
  2740. $_query->where('hcp_pro_id', $this->pro->id)
  2741. ->where('hcp_expected_payment_amount', '>', 0)
  2742. ->where('has_hcp_been_paid', false)
  2743. ->where('is_signed_by_hcp', true);
  2744. })
  2745. ->orWhere(function ($_query) {
  2746. $_query->where('cm_pro_id', $this->pro->id)
  2747. ->where('cm_expected_payment_amount', '>', 0)
  2748. ->where('has_cm_been_paid', false)
  2749. ->where('is_signed_by_cm', true);
  2750. })
  2751. ->orWhere(function ($_query) {
  2752. $_query->where('rme_pro_id', $this->pro->id)
  2753. ->where('rme_expected_payment_amount', '>', 0)
  2754. ->where('has_rme_been_paid', false)
  2755. ->where('is_signed_by_rme', true);
  2756. })
  2757. ->orWhere(function ($_query) {
  2758. $_query->where('rmm_pro_id', $this->pro->id)
  2759. ->where('rmm_expected_payment_amount', '>', 0)
  2760. ->where('has_rmm_been_paid', false)
  2761. ->where('is_signed_by_rmm', true);
  2762. })
  2763. ->orWhere(function ($_query) {
  2764. $_query->where('generic_pro_id', $this->pro->id)
  2765. ->where('generic_pro_expected_payment_amount', '>', 0)
  2766. ->where('has_generic_pro_been_paid', false)
  2767. ->where('is_signed_by_generic_pro', true);
  2768. });
  2769. })
  2770. ->orderBy('created_at', 'DESC')
  2771. ->paginate();
  2772. return view('app.practice-management.bills-under-processing', compact('bills'));
  2773. }
  2774. public function careMonthReport(Request $request) {
  2775. $m = $request->input('m');
  2776. $y = $request->input('y');
  2777. if(!$m || !$y) {
  2778. $date = date('Y-m-01');
  2779. }
  2780. else {
  2781. $date = date('Y-m-d', strtotime("$m/1/$y"));
  2782. }
  2783. $pro = $this->pro;
  2784. $records = DB::select("
  2785. SELECT cm.id as care_month_id,
  2786. cm.uid as care_month_uid,
  2787. c.id as client_id,
  2788. c.uid as client_uid,
  2789. cm.number_of_days_with_remote_measurements,
  2790. cm.rm_total_time_in_seconds_by_mcp,
  2791. cm.rm_total_time_in_seconds_by_rme_pro,
  2792. cm.rm_total_time_in_seconds_by_rmm_pro,
  2793. cm.mcp_pro_id,
  2794. cm.rme_pro_id,
  2795. cm.rmm_pro_id,
  2796. (c.name_first || ' ' || c.name_last) as client_name
  2797. FROM care_month cm
  2798. JOIN client c on cm.client_id = c.id
  2799. WHERE cm.start_date = :startDate
  2800. AND (cm.mcp_pro_id = :proID OR
  2801. cm.rme_pro_id = :proID OR
  2802. cm.rmm_pro_id = :proID)
  2803. ORDER BY c.name_last, c.name_first
  2804. ",
  2805. ['startDate' => $date, 'proID' => $pro->id]
  2806. );
  2807. return view('app.practice-management.care-month-report', compact('records', 'date'));
  2808. }
  2809. public function myTeams(Request $request) {
  2810. $pro = $this->pro;
  2811. // get all teams where the authed-pro is the assistant pro
  2812. $teams = ProTeam::where('assistant_pro_id', $pro->id)
  2813. ->where('is_active', true)
  2814. ->orderBy('slug')
  2815. ->get();
  2816. return view('app.practice-management.my-teams', compact('teams'));
  2817. }
  2818. public function patientsAccountsInvites(Request $request){
  2819. $filters = $request->all();
  2820. $accountInvites = AccountInvite::select('account_invite.*')
  2821. ->join('client', 'client.id', '=', 'account_invite.for_client_id');
  2822. if($this->performer->pro->pro_type !== 'ADMIN'){
  2823. $accountInvites = $accountInvites->where('client.mcp_pro_id', $this->performer->pro->id);
  2824. }
  2825. $this->filterMultiQuery($request, $accountInvites, 'account_invite.created_at', 'date_category', 'date_value_1', 'date_value_2');
  2826. $this->filterSimpleQuery($request, $accountInvites, 'account_invite.status', 'status');
  2827. $accountInvites = $accountInvites->orderBy('created_at', 'DESC')->paginate(20);
  2828. return view('app.practice-management.patients-accounts-invites', compact('accountInvites','filters'));
  2829. }
  2830. public function clientsBdtDevices(Request $request){
  2831. $filters = $request->all();
  2832. $devices = ClientBDTDevice::select(
  2833. 'client_bdt_device.*',
  2834. 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'))
  2835. // 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'))
  2836. ->join('client', 'client.id', '=', 'client_bdt_device.client_id');
  2837. if($this->performer->pro->pro_type !== 'ADMIN'){
  2838. $devices = $devices->where('client.mcp_pro_id', $this->performer->pro->id);
  2839. }
  2840. $this->filterMultiQuery($request, $devices, 'client_bdt_device.most_recent_measurement_at', 'date_category', 'date_value_1', 'date_value_2');
  2841. // $dateKeyName = $request->get('date_category');
  2842. // $date1 = $request->get('date_value_1');
  2843. // $date2 = $request->get('date_value_2');
  2844. // $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)";
  2845. // switch($dateKeyName) {
  2846. // case 'EXACTLY':
  2847. // if($date1) {
  2848. // $devices->whereRaw($dateColumnName." = '$date1'::DATE");
  2849. // }
  2850. // break;
  2851. // case 'LESS_THAN':
  2852. // if($date1) {
  2853. // $devices->whereRaw($dateColumnName. "< '$date1'::DATE" );
  2854. // }
  2855. // break;
  2856. // case 'GREATER_THAN':
  2857. // if($date1) {
  2858. // $devices->whereRaw($dateColumnName. "> '$date1'::DATE");
  2859. // }
  2860. // break;
  2861. // case 'BETWEEN':
  2862. // if($date1 && $date2) {
  2863. // $devices
  2864. // ->whereRaw($dateColumnName. ">= '$date1'::DATE")
  2865. // ->whereRaw($dateColumnName. "<= '$date2'::DATE");
  2866. // }
  2867. // break;
  2868. // case 'NOT_BETWEEN':
  2869. // if($date2 && $date1) {
  2870. // $devices
  2871. // ->where(function ($q) use ($request, $dateColumnName, $date1, $date2) {
  2872. // $q->whereRaw($dateColumnName. "< '$date1'::DATE")
  2873. // ->orWhereRaw($dateColumnName. "> '$date2'::DATE");
  2874. // });
  2875. // }
  2876. // break;
  2877. // }
  2878. $keyName = $request->get('measurement_count_category');
  2879. $value1 = $request->get('measurement_count_value_1');
  2880. $value2 = $request->get('measurement_count_value_2');
  2881. $columnName = "(SELECT COUNT(*) FROM bdt_measurement WHERE bdt_measurement.bdt_device_id = client_bdt_device.device_id AND is_cellular_zero IS FALSE)";
  2882. switch($keyName) {
  2883. case 'EXACTLY':
  2884. if($value1) {
  2885. $devices->whereRaw($columnName.'='.$value1);
  2886. }
  2887. break;
  2888. case 'LESS_THAN':
  2889. if($value1) {
  2890. $devices->whereRaw($columnName. '<' .$value1);
  2891. }
  2892. break;
  2893. case 'GREATER_THAN':
  2894. if($value1) {
  2895. $devices->whereRaw($columnName. '>'. $value1);
  2896. }
  2897. break;
  2898. case 'BETWEEN':
  2899. if($value1 && $value2) {
  2900. $devices
  2901. ->whereRaw($columnName. '>=' . $value1)
  2902. ->whereRaw($columnName. '<=' . $value1);
  2903. }
  2904. break;
  2905. case 'NOT_BETWEEN':
  2906. if($value1 && $value2) {
  2907. $devices
  2908. ->where(function ($q) use ($request, $columnName, $value1, $value2) {
  2909. $q->whereRaw($columnName. '<'. $value1)
  2910. ->orWhereRaw($columnName. '>'.$value2);
  2911. });
  2912. }
  2913. break;
  2914. }
  2915. $status = $request->get('status');
  2916. if($status){
  2917. if($status === 'ACTIVE') $devices = $devices->where('client_bdt_device.is_active', true);
  2918. if($status === 'DEACTIVATED') $devices = $devices->where('client_bdt_device.is_active', false);
  2919. }
  2920. $devices = $devices->orderBy('num_of_measurements', 'DESC')->paginate(20);
  2921. return view('app.practice-management.clients_bdt_devices', compact('devices','filters'));
  2922. }
  2923. public function memos(Request $request){
  2924. $filters = $request->all();
  2925. $memos = ClientMemo::select('client_memo.*')
  2926. ->join('client', 'client.id', '=', 'client_memo.client_id');
  2927. if($this->performer->pro->pro_type !== 'ADMIN'){
  2928. $memos = $memos->where('client.mcp_pro_id', $this->performer->pro->id);
  2929. }
  2930. $this->filterMultiQuery($request, $memos, 'client_memo.created_at', 'date_category', 'date_value_1', 'date_value_2');
  2931. $this->filterSimpleQuery($request, $memos, 'category', 'category');
  2932. $memos = $memos->orderBy('created_at', 'DESC')->paginate(20);
  2933. return view('app.practice-management.memos', compact('memos', 'filters'));
  2934. }
  2935. public function segmentTemplates(Request $request){
  2936. $segmentTemplates = SegmentTemplate::query();
  2937. $segmentTemplates = $segmentTemplates->orderBy('created_at', 'DESC');
  2938. $responseType = $request->get('response_type');
  2939. if($responseType && $responseType == 'json'){
  2940. $segmentTemplates = $segmentTemplates->where('is_active', true)->get();
  2941. return $this->pass($segmentTemplates);
  2942. }
  2943. $segmentTemplates = $segmentTemplates->paginate(30);
  2944. return view('app.practice-management.segment-templates.index', compact('segmentTemplates'));
  2945. }
  2946. public function visitTemplates(Request $request){
  2947. $visitTemplates = VisitTemplate::query();
  2948. $visitTemplates = $visitTemplates->orderBy('created_at', 'DESC');
  2949. $responseType = $request->get('response_type');
  2950. if($responseType && $responseType == 'json'){
  2951. $visitTemplates = $visitTemplates->where('is_active', true)->get();
  2952. return $this->pass($visitTemplates);
  2953. }
  2954. $visitTemplates = $visitTemplates->paginate(30);
  2955. return view('app.practice-management.visit-templates.index', compact('visitTemplates'));
  2956. }
  2957. public function visitTemplate(Request $request, VisitTemplate $visitTemplate){
  2958. $visitTemplateSegmentTemplates = VisitTemplateSegmentTemplate::query();
  2959. $visitTemplateSegmentTemplates = $visitTemplateSegmentTemplates->where('visit_template_id', $visitTemplate->id);
  2960. $visitTemplateSegmentTemplates = $visitTemplateSegmentTemplates->orderBy('position_index', 'ASC');
  2961. $visitTemplateSegmentTemplates = $visitTemplateSegmentTemplates->paginate(50);
  2962. return view('app.practice-management.visit-templates.visit-template-segment-templates.index', compact('visitTemplate','visitTemplateSegmentTemplates'));
  2963. }
  2964. public function visitTemplateAccess(Request $request, VisitTemplate $visitTemplate){
  2965. $visitTemplateAccesses = VisitTemplateAccess::where('visit_template_id', $visitTemplate->id)->paginate(50);
  2966. return view('app.practice-management.visit-templates.visit-template-accesses.index', compact('visitTemplate','visitTemplateAccesses'));
  2967. }
  2968. public function clientCcmRmStatus(Request $request){
  2969. $filters = $request->all();
  2970. $patients = Client::whereNull('shadow_pro_id');
  2971. $pro = $this->performer()->pro;
  2972. if($pro->pro_type !== 'ADMIN') {
  2973. $patients = $patients->where('mcp_pro_id', $this->performer()->pro->id);
  2974. }
  2975. // filters
  2976. /*
  2977. array:18 [▼
  2978. "age_category" => "LESS_THAN"
  2979. "age_value_1" => "34"
  2980. "age_value_2" => null
  2981. "sex" => "M"
  2982. "bmi_category" => "BETWEEN"
  2983. "bmi_value_1" => "20"
  2984. "bmi_value_2" => "25"
  2985. "last_visit_category" => "LESS_THAN"
  2986. "last_visit_value_1" => "2021-10-14"
  2987. "last_visit_value_2" => null
  2988. "next_appointment_category" => "LESS_THAN"
  2989. "next_appointment_value_1" => "2021-10-15"
  2990. "status" => "ACTIVE"
  2991. "last_weighed_in_category" => "EXACTLY"
  2992. "last_weighed_in_value_1" => "2021-10-07"
  2993. "last_bp_category" => "BETWEEN"
  2994. "last_bp_value_1" => "2021-10-01"
  2995. "last_bp_value_2" => "2021-10-31"
  2996. ]
  2997. */
  2998. $this->filterMultiQuery($request, $patients, 'age_in_years', 'age_category', 'age_value_1', 'age_value_2');
  2999. $this->filterSimpleQuery($request, $patients, 'sex', 'sex');
  3000. $this->filterMultiQuery($request, $patients, 'usual_bmi', 'bmi_category', 'bmi_value_1', 'bmi_value_2');
  3001. $this->filterMultiQuery($request, $patients, 'most_recent_weight_at', 'last_weighed_in_category', 'last_weighed_in_value_1', 'last_weighed_in_value_2');
  3002. $this->filterMultiQuery($request, $patients, 'most_recent_bp_at', 'last_bp_category', 'last_bp_value_1', 'last_bp_value_2');
  3003. switch($request->input('status')) {
  3004. case 'ACTIVE':
  3005. $patients->where('is_active', true)->where('has_mcp_done_onboarding_visit', true);
  3006. break;
  3007. case 'AWAITING_VISIT':
  3008. $patients->where('is_active', true)->where('has_mcp_done_onboarding_visit', false);
  3009. break;
  3010. case 'INACTIVE':
  3011. $patients->where('is_active', '<>', true);
  3012. break;
  3013. }
  3014. if($request->input('is_eligible_for_cm')){
  3015. $patients->where('is_eligible_for_cm', '=', $request->input('is_eligible_for_cm'));
  3016. }
  3017. if($request->input('is_enrolled_in_cm')){
  3018. $patients->where('is_enrolled_in_cm', '=', $request->input('is_enrolled_in_cm'));
  3019. }
  3020. if($request->input('has_cm_setup_been_performed')){
  3021. $patients->where('has_cm_setup_been_performed', '=', $request->input('has_cm_setup_been_performed')=='YES'? true : false);
  3022. }
  3023. if($request->input('is_eligible_for_rm')){
  3024. $patients->where('is_eligible_for_rm', '=', $request->input('is_eligible_for_rm'));
  3025. }
  3026. if($request->input('is_enrolled_in_rm')){
  3027. $patients->where('is_enrolled_in_rm', '=', $request->input('is_enrolled_in_rm'));
  3028. }
  3029. if($request->input('has_rm_setup_been_performed')){
  3030. $patients->where('has_rm_setup_been_performed', '=', $request->input('has_rm_setup_been_performed') =='YES'? true : false);
  3031. }
  3032. $patients = $patients->orderBy('created_at', 'DESC')->paginate(20);
  3033. return view('app.admin.client-ccm-rm-status', compact('patients', 'filters'));
  3034. }
  3035. public function rmActionReport(Request $request){
  3036. $filters = $request->all();
  3037. $careMonthStartDate = $request->get('care_month_start_date');
  3038. $careMonthYear = $request->get('care_month_year');
  3039. if(!$careMonthStartDate){
  3040. $careMonthStartDate = '2022-01-01';
  3041. }
  3042. if($careMonthYear){
  3043. $careMonthStartDate = $careMonthYear . "-01";
  3044. }
  3045. $lastDateOfMonth = new DateTime(date("Y-m-t", strtotime(get_current_date())));
  3046. $today = new DateTime(get_current_date());
  3047. $diff = $lastDateOfMonth->diff($today);
  3048. $daysBetweenNowAndEndmonth = $diff->days;
  3049. $minRequiredMeasurements = 16 - $daysBetweenNowAndEndmonth -1;
  3050. $numOfMeasurements = $request->get('num_of_measurements'); //16_or_more, 12_or_more
  3051. $hasRecentVisit = $request->get('has_recent_visit'); //yes no
  3052. $hasBeenSpokenToThisMonth = $request->get('has_been_spoken_to'); //yes no
  3053. $cmQuery = CareMonth::where('start_date', $careMonthStartDate);
  3054. //remove dummies
  3055. $cmQuery = $cmQuery->whereHas('client', function($clientQuery) {
  3056. return $clientQuery->where('client_engagement_status_category','<>', 'DUMMY')
  3057. ->orWhere('client_engagement_status_category', '=', null);
  3058. });
  3059. if($numOfMeasurements){
  3060. if($numOfMeasurements == '16_or_more'){
  3061. $cmQuery = $cmQuery->where('number_of_days_with_remote_measurements', '>=', 16);
  3062. }
  3063. if($numOfMeasurements == 'min_or_more'){
  3064. $cmQuery = $cmQuery->where('number_of_days_with_remote_measurements', '>=', $minRequiredMeasurements)
  3065. ->where('number_of_days_with_remote_measurements', '<', 16);
  3066. }
  3067. if($numOfMeasurements == 'less_than_min'){
  3068. $cmQuery = $cmQuery->where('number_of_days_with_remote_measurements', '<', $minRequiredMeasurements);
  3069. }
  3070. }
  3071. if($hasRecentVisit){
  3072. if($hasRecentVisit == 'YES'){
  3073. $cmQuery = $cmQuery->whereHas('client', function($clientQuery) {
  3074. return $clientQuery->whereRaw("most_recent_completed_mcp_note_date::DATE >= ((NOW() - interval '90 days')::DATE)");
  3075. });
  3076. }else{
  3077. $cmQuery = $cmQuery->whereHas('client', function($clientQuery) {
  3078. return $clientQuery->whereRaw("most_recent_completed_mcp_note_date::DATE < ((NOW() - interval '90 days')::DATE)");
  3079. });
  3080. }
  3081. }
  3082. if($hasBeenSpokenToThisMonth){
  3083. if($hasBeenSpokenToThisMonth == 'YES'){
  3084. $cmQuery = $cmQuery->where('has_anyone_interacted_with_client_about_rm_outside_note', '=', true);
  3085. }else{
  3086. $cmQuery = $cmQuery->where('has_anyone_interacted_with_client_about_rm_outside_note', '=', false);
  3087. }
  3088. }
  3089. $claimingClosed = $request->get('claiming_closed');
  3090. if($claimingClosed){
  3091. if($claimingClosed === 'YES') $cmQuery = $cmQuery->where('is_claim_closed', true);
  3092. if($claimingClosed === 'NO') $cmQuery = $cmQuery->where('is_claim_closed', false);
  3093. }
  3094. $cmQuery = $cmQuery->orderBy('start_date', 'DESC')->orderBy('client_id', 'ASC');
  3095. $rows =$cmQuery->paginate(15);
  3096. return view('app.practice-management.rm-action-report', compact('rows', 'filters', 'minRequiredMeasurements'));
  3097. }
  3098. public function myFlyers(Request $request){
  3099. $pro = $this->performer->pro;
  3100. $slug = $pro->slug ?? $pro->uid;
  3101. $url = config('app.stagfe6_url') . '/flyers/json-list?slug=' . $slug;
  3102. $arrContextOptions=array(
  3103. "ssl"=>array(
  3104. "verify_peer"=>false,
  3105. "verify_peer_name"=>false,
  3106. ),
  3107. );
  3108. $response = @file_get_contents($url, false, stream_context_create($arrContextOptions));
  3109. $response = @json_decode($response);
  3110. $flyerTemplates = [];
  3111. if(isset($response->data)){
  3112. $flyerTemplates = $response->data;
  3113. }
  3114. return view('app.my-flyers', compact('pro','flyerTemplates'));
  3115. }
  3116. public function notesResolutionCenter(Request $request) {
  3117. $columns = "(c.name_first || ' ' || c.name_last) as client_name,
  3118. (hcp.name_first || ' ' || hcp.name_last) as hcp_name,
  3119. (na.name_first || ' ' || na.name_last) as na_name,
  3120. c.chart_number,
  3121. c.uid as client_uid,
  3122. n.effective_dateest,
  3123. n.uid,
  3124. n.detail_json,
  3125. n.is_claim_closed,
  3126. n.visit_number,
  3127. ROUND(b.number_of_units * 60) as minutes,
  3128. n.note_reason_icd1 AS icd1,
  3129. n.note_reason_icd1description AS icd1description,
  3130. n.note_reason_icd2 AS icd2,
  3131. n.note_reason_icd2description AS icd2description,
  3132. n.note_reason_icd3 AS icd3,
  3133. n.note_reason_icd3description AS icd3description,
  3134. n.note_reason_icd4 AS icd4,
  3135. n.note_reason_icd4description AS icd4description,
  3136. n.note_reason_memo AS icd_memo,
  3137. n.visit_number
  3138. ";
  3139. $from = "FROM note AS n
  3140. LEFT JOIN pro AS hcp ON n.hcp_pro_id = hcp.id
  3141. LEFT JOIN pro AS na ON n.ally_pro_id = na.id
  3142. JOIN client AS c ON n.client_id = c.id
  3143. JOIN bill AS b ON (b.note_id = n.id AND b.is_cancelled IS NOT TRUE AND b.code ILIKE '%treatment%')
  3144. ";
  3145. $where = "WHERE
  3146. -- n.visit_number IN (1,2) AND
  3147. n.is_signed_by_hcp IS TRUE AND
  3148. -- n.is_claim_closed IS NOT TRUE AND
  3149. n.is_cancelled IS NOT TRUE AND
  3150. n.created_at::DATE >= '2022-01-01'::DATE AND
  3151. c.client_engagement_status_category <> 'DUMMY' AND
  3152. c.name_first NOT ILIKE '%test%' AND
  3153. c.name_last NOT ILIKE '%test%' AND
  3154. 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
  3155. -- n.id NOT IN (SELECT note_id FROM claim WHERE note_id IS NOT NULL) AND
  3156. c.is_part_b_primary = 'YES' AND
  3157. c.latest_eligible_refresh_at::DATE >= '2022-01-01' AND
  3158. c.mpb_remaining = 0 AND
  3159. c.created_at::DATE >= '2022-01-01'::DATE
  3160. ";
  3161. $filters = [];
  3162. if($request->input('f')) {
  3163. $filters[] = "(n.detail_json IS NOT NULL AND ((n.detail_json)::json->'farah_decision')::text = '\"" . $request->input('f') . "\"')";
  3164. }
  3165. if($request->input('s')) {
  3166. $filters[] = "(n.detail_json IS NOT NULL AND ((n.detail_json)::json->'shawn_decision')::text = '\"" . $request->input('s') . "\"')";
  3167. }
  3168. if(count($filters)) {
  3169. $filters = 'AND ' . implode(' AND ', $filters);
  3170. }
  3171. else {
  3172. $filters = '';
  3173. }
  3174. // $filters = '';
  3175. $orderBy = "ORDER BY c.id ASC, n.visit_number ASC";
  3176. $countQuery = "SELECT count(*) {$from} {$where} {$filters}";
  3177. // dd($countQuery);
  3178. $countResult = DB::select($countQuery);
  3179. $total = $countResult[0]->count;
  3180. $defaultPageSize = 25;
  3181. $page = $request->input('page') ?: 1;
  3182. $perPage = $request->input('per_page') ?: $defaultPageSize;
  3183. $offset = ($page - 1) * $perPage;
  3184. $dataQuery = "SELECT {$columns} {$from} {$where} {$filters} {$orderBy} OFFSET {$offset} LIMIT {$perPage}";
  3185. $rows = DB::select($dataQuery);
  3186. $paginator = new LengthAwarePaginator($rows, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  3187. $paginator->setPath(route('practice-management.notes-resolution-center'));
  3188. return view('app.practice-management.notes-resolution-center', compact('rows', 'paginator'));
  3189. }
  3190. public function notesResolutionCenterV2(Request $request) {
  3191. $columns = "(c.name_first || ' ' || c.name_last) as client_name,
  3192. (hcp.name_first || ' ' || hcp.name_last) as hcp_name,
  3193. (na.name_first || ' ' || na.name_last) as na_name,
  3194. c.chart_number,
  3195. c.uid as client_uid,
  3196. n.effective_dateest,
  3197. n.uid,
  3198. n.detail_json,
  3199. n.is_claim_closed,
  3200. n.visit_number,
  3201. ROUND(b.number_of_units * 60) as minutes,
  3202. n.note_reason_icd1 AS icd1,
  3203. n.note_reason_icd1description AS icd1description,
  3204. n.note_reason_icd2 AS icd2,
  3205. n.note_reason_icd2description AS icd2description,
  3206. n.note_reason_icd3 AS icd3,
  3207. n.note_reason_icd3description AS icd3description,
  3208. n.note_reason_icd4 AS icd4,
  3209. n.note_reason_icd4description AS icd4description,
  3210. n.note_reason_memo AS icd_memo
  3211. ";
  3212. $from = "FROM note AS n
  3213. LEFT JOIN pro AS hcp ON n.hcp_pro_id = hcp.id
  3214. LEFT JOIN pro AS na ON n.ally_pro_id = na.id
  3215. JOIN client AS c ON n.client_id = c.id
  3216. JOIN bill AS b ON (b.note_id = n.id AND b.is_cancelled IS NOT TRUE AND b.code ILIKE '%treatment%')
  3217. ";
  3218. $where = "WHERE
  3219. -- n.visit_number = 2 AND
  3220. n.is_signed_by_hcp IS TRUE AND
  3221. -- n.effective_dateest < '2022-03-01' AND
  3222. n.is_claim_closed IS NOT TRUE AND
  3223. n.is_cancelled IS NOT TRUE AND
  3224. c.client_engagement_status_category <> 'DUMMY' AND
  3225. c.name_first NOT ILIKE '%test%' AND
  3226. c.name_last NOT ILIKE '%test%' AND
  3227. 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)
  3228. -- AND
  3229. -- n.id NOT IN (SELECT note_id FROM claim WHERE note_id IS NOT NULL) AND
  3230. ";
  3231. $filters = [];
  3232. if(trim($request->input('f_pb_primary'))) {
  3233. $v = trim($request->input('f_pb_primary'));
  3234. if($v === 'yes') {
  3235. $filters[] = "(c.is_part_b_primary = 'YES')";
  3236. }
  3237. else if($v === 'no') {
  3238. $filters[] = "(c.is_part_b_primary != 'YES')";
  3239. }
  3240. }
  3241. if(trim($request->input('f_deductible_zero'))) {
  3242. $v = trim($request->input('f_deductible_zero'));
  3243. if($v === 'yes') {
  3244. $filters[] = "(c.mpb_remaining = 0)";
  3245. }
  3246. else if($v === 'no') {
  3247. $filters[] = "(c.mpb_remaining > 0)";
  3248. }
  3249. }
  3250. if(trim($request->input('f_note_hcp'))) {
  3251. $v = trim($request->input('f_note_hcp'));
  3252. $filters[] = "(n.hcp_pro_id IN (SELECT id FROM pro WHERE uid = '{$v}'))";
  3253. }
  3254. if(trim($request->input('f_2022_patient'))) {
  3255. $v = trim($request->input('f_2022_patient'));
  3256. if($v === 'yes') {
  3257. $filters[] = "(c.created_at::DATE >= '2022-01-01'::DATE)";
  3258. }
  3259. else if($v === 'no') {
  3260. $filters[] = "(c.created_at::DATE < '2022-01-01'::DATE)";
  3261. }
  3262. }
  3263. if(count($filters)) {
  3264. $filters = 'AND ' . implode(' AND ', $filters);
  3265. }
  3266. else {
  3267. $filters = '';
  3268. }
  3269. // $filters = '';
  3270. $orderBy = "ORDER BY
  3271. -- c.id ASC,
  3272. n.id ASC, n.effective_dateest ASC";
  3273. $countQuery = "SELECT count(*) {$from} {$where} {$filters}";
  3274. // dd($countQuery);
  3275. $countResult = DB::select($countQuery);
  3276. $total = $countResult[0]->count;
  3277. $defaultPageSize = 50;
  3278. $page = $request->input('page') ?: 1;
  3279. $perPage = $request->input('per_page') ?: $defaultPageSize;
  3280. $offset = ($page - 1) * $perPage;
  3281. $dataQuery = "SELECT {$columns} {$from} {$where} {$filters} {$orderBy} OFFSET {$offset} LIMIT {$perPage}";
  3282. $rows = DB::select($dataQuery);
  3283. $paginator = new LengthAwarePaginator($rows, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  3284. $paginator->setPath(route('practice-management.notes-resolution-center-v2'));
  3285. return view('app.practice-management.notes-resolution-center-v2', compact('rows', 'paginator'));
  3286. }
  3287. public function coverages(Request $request) {
  3288. $columns = "(c.name_first || ' ' || c.name_last) as client_name,
  3289. c.id,
  3290. c.uid,
  3291. c.created_at,
  3292. c.sex,
  3293. c.dob,
  3294. c.age_in_years,
  3295. row_to_json(lcpc.*) as latest_client_primary_coverage,
  3296. row_to_json(lacpc.*) as latest_auto_client_primary_coverage,
  3297. row_to_json(lmcpc.*) as latest_manual_client_primary_coverage,
  3298. row_to_json(lmcpc_payer.*) as latest_manual_client_primary_coverage_payer
  3299. ";
  3300. $from = "FROM client AS c
  3301. LEFT JOIN client_primary_coverage lcpc on c.latest_client_primary_coverage_id = lcpc.id
  3302. LEFT JOIN client_primary_coverage lacpc on c.latest_auto_refresh_client_primary_coverage_id = lacpc.id
  3303. LEFT JOIN client_primary_coverage lmcpc on c.latest_manual_client_primary_coverage_id = lmcpc.id
  3304. LEFT JOIN payer lmcpc_payer on lmcpc.commercial_payer_id = lmcpc_payer.id
  3305. ";
  3306. $where = "WHERE
  3307. c.client_engagement_status_category <> 'DUMMY' AND
  3308. c.name_first NOT ILIKE '%test%' AND
  3309. c.name_last NOT ILIKE '%test%' AND
  3310. c.created_at::DATE >= '2022-01-01'::DATE
  3311. -- lmcpc.id IS NOT NULL ANd lmcpc.plan_type != 'MEDICARE'
  3312. ";
  3313. $filters = [];
  3314. if(trim($request->input('f_name'))) {
  3315. $v = trim($request->input('f_name'));
  3316. $filters[] = "(c.name_first ILIKE '%{$v}%' OR c.name_last ILIKE '%{$v}%')";
  3317. }
  3318. if(trim($request->input('f_covered'))) {
  3319. $v = trim($request->input('f_covered'));
  3320. if($v !== 'any') {
  3321. switch($v) {
  3322. case 'covered':
  3323. $filters[] = "(
  3324. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.manual_determination_category = 'COVERED') OR
  3325. ((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')
  3326. )";
  3327. break;
  3328. case 'not-covered':
  3329. $filters[] = "(
  3330. (lmcpc.id IS NULL OR (lmcpc.is_cancelled IS TRUE OR lmcpc.manual_determination_category = 'NOT_COVERED')) AND
  3331. (lacpc.id IS NULL OR (lacpc.is_cancelled IS TRUE OR lacpc.auto_medicare_is_partbprimary = 'NO')) AND
  3332. (lmcpc.id IS NOT NULL OR lacpc.id IS NOT NULL)
  3333. )";
  3334. break;
  3335. case 'unknown':
  3336. $filters[] = "(
  3337. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.manual_determination_category = 'UNKNOWN') OR
  3338. ((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')
  3339. )";
  3340. break;
  3341. }
  3342. }
  3343. }
  3344. if(trim($request->input('f_covered'))) {
  3345. $v = trim($request->input('f_covered'));
  3346. if($v !== 'any') {
  3347. switch($v) {
  3348. case 'covered':
  3349. $filters[] = "(
  3350. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.manual_determination_category = 'COVERED') OR
  3351. ((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')
  3352. )";
  3353. break;
  3354. case 'not-covered':
  3355. $filters[] = "(
  3356. (lmcpc.id IS NULL OR (lmcpc.is_cancelled IS TRUE OR lmcpc.manual_determination_category = 'NOT_COVERED')) AND
  3357. (lacpc.id IS NULL OR (lacpc.is_cancelled IS TRUE OR lacpc.auto_medicare_is_partbprimary = 'NO')) AND
  3358. (lmcpc.id IS NOT NULL OR lacpc.id IS NOT NULL)
  3359. )";
  3360. break;
  3361. case 'unknown':
  3362. $filters[] = "(
  3363. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.manual_determination_category = 'UNKNOWN') OR
  3364. ((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')
  3365. )";
  3366. break;
  3367. }
  3368. }
  3369. }
  3370. if(trim($request->input('f_plan_type'))) {
  3371. $v = strtoupper(trim($request->input('f_plan_type')));
  3372. if($v !== 'ANY') {
  3373. $filters[] = "(
  3374. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.plan_type = '{$v}') OR
  3375. ((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}')
  3376. )";
  3377. }
  3378. }
  3379. if(trim($request->input('f_pb_primary'))) {
  3380. $v = trim($request->input('f_pb_primary'));
  3381. if($v !== 'any') {
  3382. switch($v) {
  3383. case 'primary':
  3384. $filters[] = "(
  3385. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.is_partbprimary = 'YES') 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 = 'YES')
  3387. )";
  3388. break;
  3389. case 'not-primary':
  3390. $filters[] = "(
  3391. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.is_partbprimary = 'NO') OR
  3392. ((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')
  3393. )";
  3394. break;
  3395. case 'unknown':
  3396. $filters[] = "(
  3397. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.is_partbprimary = 'UNKNOWN') OR
  3398. ((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')
  3399. )";
  3400. break;
  3401. }
  3402. }
  3403. }
  3404. if(trim($request->input('f_pb_active'))) {
  3405. $v = trim($request->input('f_pb_active'));
  3406. // TODO
  3407. }
  3408. if(trim($request->input('f_pc_active'))) {
  3409. $v = trim($request->input('f_pc_active'));
  3410. // TODO
  3411. }
  3412. if(trim($request->input('f_comm_payer'))) {
  3413. $v = trim($request->input('f_comm_payer'));
  3414. $filters[] = "(lmcpc_payer.name ILIKE '%{$v}%')";
  3415. }
  3416. if(trim($request->input('f_comm_member_id'))) {
  3417. $v = trim($request->input('f_comm_member_id'));
  3418. if($v !== 'any') {
  3419. $filters[] = "(
  3420. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.commercial_member_identifier ILIKE '%{$v}%') OR
  3421. ((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}%')
  3422. )";
  3423. }
  3424. }
  3425. if(trim($request->input('f_comm_group_num'))) {
  3426. $v = trim($request->input('f_comm_group_num'));
  3427. if($v !== 'any') {
  3428. $filters[] = "(
  3429. (lmcpc.id IS NOT NULL AND lmcpc.is_cancelled IS NOT TRUE AND lmcpc.commercial_group_number ILIKE '%{$v}%') OR
  3430. ((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}%')
  3431. )";
  3432. }
  3433. }
  3434. if(count($filters)) {
  3435. $filters = 'AND ' . implode(' AND ', $filters);
  3436. }
  3437. else {
  3438. $filters = '';
  3439. }
  3440. // $filters = '';
  3441. $orderBy = "ORDER BY client_name ASC";
  3442. $countQuery = "SELECT count(*) {$from} {$where} {$filters}";
  3443. // dd($countQuery);
  3444. $countResult = DB::select($countQuery);
  3445. $total = $countResult[0]->count;
  3446. $defaultPageSize = 10;
  3447. $page = $request->input('page') ?: 1;
  3448. $perPage = $request->input('per_page') ?: $defaultPageSize;
  3449. $offset = ($page - 1) * $perPage;
  3450. $dataQuery = "SELECT {$columns} {$from} {$where} {$filters} {$orderBy} OFFSET {$offset} LIMIT {$perPage}";
  3451. $rows = DB::select($dataQuery);
  3452. $paginator = new LengthAwarePaginator($rows, $total, $request->input('per_page') ?: $defaultPageSize, $request->input('page') ?: 1);
  3453. $paginator->setPath(route('practice-management.coverages'));
  3454. // dd($rows);
  3455. return view('app.practice-management.coverages', compact('rows', 'paginator'));
  3456. }
  3457. }