PracticeManagementController.php 162 KB

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