PracticeManagementController.php 142 KB

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