PracticeManagementController.php 172 KB

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