PracticeManagementController.php 144 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288
  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. // special case of if-bill-exists
  1146. if($sortBy === 'mcp_rm_generic_bill_id' || $sortBy === 'rmm_rm_generic_bill_id') {
  1147. if($sortDir === 'ASC') {
  1148. $orderBy = "ORDER BY $sortBy $sortDir NULLS FIRST";
  1149. }
  1150. else {
  1151. $orderBy = "ORDER BY $sortBy $sortDir NULLS LAST";
  1152. }
  1153. }
  1154. // filters from the UI
  1155. if(trim($request->input('f_name'))) {
  1156. $v = trim($request->input('f_name'));
  1157. $conditions[] = "(client.name_first ILIKE '%{$v}%' OR client.name_last ILIKE '%{$v}%')";
  1158. }
  1159. if(trim($request->input('f_dob_op')) && trim($request->input('f_dob'))) {
  1160. $o = trim($request->input('f_dob_op'));
  1161. $v = trim($request->input('f_dob'));
  1162. $conditions[] = "(client.dob {$o} '{$v}')";
  1163. }
  1164. if(trim($request->input('f_rpm'))) {
  1165. $v = trim($request->input('f_rpm'));
  1166. if($v === 'yes') {
  1167. $conditions[] = "(client.is_enrolled_in_rm IS NOT NULL AND client.is_enrolled_in_rm = 'YES')";
  1168. }
  1169. elseif($v === 'no') {
  1170. $conditions[] = "(client.is_enrolled_in_rm IS NULL OR client.is_enrolled_in_rm != 'YES')";
  1171. }
  1172. }
  1173. if(trim($request->input('f_cell_bp'))) {
  1174. $v = trim($request->input('f_cell_bp'));
  1175. if($v === 'yes') {
  1176. $conditions[] = "(client.is_assigned_cellular_bp_device IS NOT NULL AND client.is_assigned_cellular_bp_device = TRUE)";
  1177. }
  1178. elseif($v === 'no') {
  1179. $conditions[] = "(client.is_assigned_cellular_bp_device IS NULL OR client.is_assigned_cellular_bp_device = FALSE)";
  1180. }
  1181. }
  1182. if(trim($request->input('f_cell_wt'))) {
  1183. $v = trim($request->input('f_cell_wt'));
  1184. if($v === 'yes') {
  1185. $conditions[] = "(client.is_assigned_cellular_weight_scale_device IS NOT NULL AND client.is_assigned_cellular_weight_scale_device = TRUE)";
  1186. }
  1187. elseif($v === 'no') {
  1188. $conditions[] = "(client.is_assigned_cellular_weight_scale_device IS NULL OR client.is_assigned_cellular_weight_scale_device = FALSE)";
  1189. }
  1190. }
  1191. if(trim($request->input('f_comm'))) {
  1192. $v = trim($request->input('f_comm'));
  1193. if($v === 'yes') {
  1194. $conditions[] = "(care_month.has_mcp_interacted_with_client_about_rm IS NOT NULL AND care_month.has_mcp_interacted_with_client_about_rm = TRUE)";
  1195. }
  1196. elseif($v === 'no') {
  1197. $conditions[] = "(care_month.has_mcp_interacted_with_client_about_rm IS NULL OR care_month.has_mcp_interacted_with_client_about_rm = FALSE)";
  1198. }
  1199. }
  1200. if($mode === 'mcp' || $mode === 'rmm') {
  1201. if(trim($request->input('f_billable'))) {
  1202. $v = trim($request->input('f_billable'));
  1203. if($v === 'yes') {
  1204. $conditions[] = "(care_month.{$mode}_rm_generic_bill_id IS NOT NULL)";
  1205. }
  1206. elseif($v === 'no') {
  1207. $conditions[] = "(care_month.{$mode}_rm_generic_bill_id IS NULL)";
  1208. }
  1209. }
  1210. }
  1211. if(trim($request->input('f_md_op')) && trim($request->input('f_md')) !== '') {
  1212. $o = trim($request->input('f_md_op'));
  1213. $v = trim($request->input('f_md'));
  1214. $conditions[] = "(care_month.number_of_days_with_remote_measurements {$o} {$v})";
  1215. }
  1216. if(trim($request->input('f_unst_op')) && trim($request->input('f_unst')) !== '') {
  1217. $o = trim($request->input('f_unst_op'));
  1218. $v = trim($request->input('f_unst'));
  1219. $conditions[] = "(care_month.rm_num_measurements_not_stamped_by_mcp {$o} {$v})";
  1220. }
  1221. if(trim($request->input('f_mins_op')) && trim($request->input('f_mins')) !== '') {
  1222. $o = trim($request->input('f_mins_op'));
  1223. $v = intval(trim($request->input('f_mins'))) * 60;
  1224. $field = 'rm_total_time_in_seconds_by_mcp';
  1225. switch($mode) {
  1226. case 'mcp':
  1227. $field = 'rm_total_time_in_seconds_by_mcp';
  1228. break;
  1229. case 'rmm':
  1230. $field = 'rm_total_time_in_seconds_by_rmm_pro';
  1231. break;
  1232. break;
  1233. }
  1234. $conditions[] = "(care_month.{$field} {$o} {$v})";
  1235. }
  1236. $proTypeCondition = '';
  1237. $genericBillIdColumns = '';
  1238. $genericBillJoinClause = '';
  1239. switch($mode) {
  1240. case 'mcp':
  1241. $proTypeCondition = "care_month.mcp_pro_id = {$performer->pro->id}";
  1242. $genericBillIdColumns = "care_month.mcp_rm_generic_bill_id,
  1243. bill.uid as mcp_rm_generic_bill_uid,
  1244. bill.generic_pro_id as mcp_rm_generic_bill_generic_pro_id,
  1245. bill.generic_pro_expected_payment_amount as mcp_rm_generic_bill_expected_payment_amount,
  1246. bill.is_signed_by_generic_pro as mcp_rm_generic_bill_signed";
  1247. $genericBillJoinClause = 'left join bill on care_month.mcp_rm_generic_bill_id = bill.id';
  1248. break;
  1249. case 'rmm':
  1250. $proTypeCondition = "care_month.rmm_pro_id = {$performer->pro->id}";
  1251. $genericBillIdColumns = "care_month.rmm_rm_generic_bill_id,
  1252. bill.uid as rmm_rm_generic_bill_uid,
  1253. bill.generic_pro_id as rmm_rm_generic_bill_generic_pro_id,
  1254. bill.generic_pro_expected_payment_amount as rmm_rm_generic_bill_expected_payment_amount,
  1255. bill.is_signed_by_generic_pro as rmm_rm_generic_bill_signed";
  1256. $genericBillJoinClause = 'left join bill on care_month.rmm_rm_generic_bill_id = bill.id';
  1257. break;
  1258. case 'rme':
  1259. $proTypeCondition = "left join bill on care_month.rme_pro_id = {$performer->pro->id}";
  1260. break;
  1261. }
  1262. $query = "
  1263. SELECT client.name_first, client.name_last,
  1264. (client.name_first || ' ' || client.name_last) as client_name,
  1265. client.uid as client_uid,
  1266. client.dob,
  1267. client.is_enrolled_in_rm,
  1268. client.most_recent_completed_mcp_note_date,
  1269. client.most_recent_completed_mcp_note_id,
  1270. mrmnote.effective_dateest::date as most_recent_completed_mcp_note_date_cm,
  1271. mrmnote.id as most_recent_completed_mcp_note_id_cm,
  1272. mrmnote.uid as most_recent_completed_mcp_note_uid_cm,
  1273. client.cell_number,
  1274. client.is_assigned_cellular_bp_device,
  1275. client.is_assigned_cellular_weight_scale_device,
  1276. care_month.uid as care_month_uid,
  1277. care_month.id as care_month_id,
  1278. care_month.start_date,
  1279. care_month.rm_total_time_in_seconds_by_mcp,
  1280. care_month.rm_total_time_in_seconds_by_rmm_pro,
  1281. care_month.number_of_days_with_remote_measurements,
  1282. care_month.has_mcp_interacted_with_client_about_rm,
  1283. care_month.rm_num_measurements_not_stamped_by_mcp,
  1284. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  1285. care_month.rm_num_measurements_not_stamped_by_rmm,
  1286. care_month.rm_num_measurements_not_stamped_by_rme,
  1287. care_month.mcp_pro_id as care_month_mcp_pro_id,
  1288. care_month.rmm_pro_id as care_month_rmm_pro_id,
  1289. client.mcp_pro_id,
  1290. client.default_na_pro_id,
  1291. client.rmm_pro_id,
  1292. client.rme_pro_id,
  1293. client.cell_number,
  1294. care_month.most_recent_cellular_bp_dbp_mm_hg,
  1295. care_month.most_recent_cellular_bp_sbp_mm_hg,
  1296. care_month.most_recent_cellular_bp_measurement_at,
  1297. care_month.most_recent_cellular_weight_value,
  1298. care_month.most_recent_cellular_weight_measurement_at,
  1299. {$genericBillIdColumns}
  1300. 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
  1301. {$genericBillJoinClause}
  1302. left join note mrmnote on mrmnote.id = (
  1303. select max(n.id) from note n
  1304. where
  1305. n.client_id = client.id AND
  1306. n.is_cancelled = FALSE AND
  1307. (n.is_signed_by_hcp IS NOT NULL AND n.is_signed_by_hcp = TRUE) AND
  1308. n.effective_dateest::date >= care_month.start_date::date AND
  1309. n.effective_dateest::date < (care_month.start_date::date + INTERVAL '1 month')
  1310. )
  1311. WHERE
  1312. $proTypeCondition
  1313. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1314. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1315. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '') . "
  1316. $orderBy
  1317. ";
  1318. // dd($query);
  1319. $patients = DB::select($query);
  1320. $timestamp = strtotime(date('Y-m-d'));
  1321. $daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
  1322. return view('app.practice-management.rpm-matrix-by-pro-type', compact('patients', 'daysRemaining', 'careMonthStart', 'mode'));
  1323. }
  1324. public function remoteMonitoringMCP(Request $request) {
  1325. return $this->rpmMatrixByProType($request, 'mcp');
  1326. }
  1327. public function remoteMonitoringRMM(Request $request) {
  1328. return $this->rpmMatrixByProType($request, 'rmm');
  1329. }
  1330. public function remoteMonitoringRME(Request $request) {
  1331. return $this->rpmMatrixByProType($request, 'rme');
  1332. }
  1333. public function remoteMonitoring_RowMCP(Request $request) {
  1334. return $this->remoteMonitoring_RowByProType($request, 'mcp');
  1335. }
  1336. public function remoteMonitoring_RowRMM(Request $request) {
  1337. return $this->remoteMonitoring_RowByProType($request, 'rmm');
  1338. }
  1339. public function remoteMonitoring_RowRME(Request $request) {
  1340. return $this->remoteMonitoring_RowByProType($request, 'rme');
  1341. }
  1342. public function rpm_work_matrix(Request $request) {
  1343. // get the patient having most recent unstamped measurement
  1344. $performer = $this->performer();
  1345. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1346. $careMonthStart = date($ym . '-01');
  1347. $patient = null;
  1348. $careMonth = null;
  1349. if($request->input('patientUid') && $request->input('careMonthUid')) {
  1350. $patient = Client::where('uid', $request->input('patientUid'))->first();
  1351. $careMonth = CareMonth::where('uid', $request->input('careMonthUid'))->first();
  1352. }
  1353. if(!$patient && !$careMonth) {
  1354. $query = "
  1355. SELECT client.name_first, client.name_last,
  1356. (client.name_first || ' ' || client.name_last) as client_name,
  1357. client.uid as client_uid,
  1358. client.dob,
  1359. client.is_enrolled_in_rm,
  1360. client.most_recent_completed_mcp_note_date,
  1361. care_month.uid as care_month_uid,
  1362. care_month.id as care_month_id,
  1363. care_month.start_date,
  1364. care_month.rm_total_time_in_seconds_by_mcp,
  1365. care_month.number_of_days_with_remote_measurements,
  1366. care_month.rm_num_measurements_not_stamped_by_mcp,
  1367. care_month.rm_num_measurements_not_stamped_by_rmm,
  1368. client.mcp_pro_id,
  1369. client.default_na_pro_id,
  1370. client.rmm_pro_id,
  1371. client.rme_pro_id,
  1372. client.cell_number,
  1373. client.most_recent_cellular_bp_dbp_mm_hg,
  1374. client.most_recent_cellular_bp_sbp_mm_hg,
  1375. client.most_recent_cellular_bp_measurement_at,
  1376. client.most_recent_cellular_weight_value,
  1377. client.most_recent_cellular_weight_measurement_at,
  1378. GREATEST(client.most_recent_cellular_bp_measurement_at, client.most_recent_cellular_weight_measurement_at) as latest_measurement_at
  1379. FROM care_month join client on care_month.client_id = client.id
  1380. WHERE
  1381. (
  1382. (care_month.mcp_pro_id = {$performer->pro->id} AND care_month.rm_num_measurements_not_stamped_by_mcp > 0) OR
  1383. (care_month.rmm_pro_id = {$performer->pro->id} AND care_month.rm_num_measurements_not_stamped_by_rmm > 0)
  1384. )
  1385. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1386. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1387. ORDER BY latest_measurement_at DESC
  1388. LIMIT 1
  1389. ";
  1390. $patients = DB::select($query);
  1391. if (count($patients)) {
  1392. $patient = Client::where('uid', $patients[0]->client_uid)->first();
  1393. $careMonth = CareMonth::where('uid', $patients[0]->care_month_uid)->first();
  1394. }
  1395. }
  1396. return view('app.practice-management.rpm_work_matrix', compact('patient', 'careMonth'));
  1397. }
  1398. public function remoteMonitoringCount(Request $request) {
  1399. $performer = $this->performer();
  1400. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1401. $careMonthStart = date($ym . '-01');
  1402. $rc = $request->input('rc') ?: 1;
  1403. $rc2 = $request->input('rc2') ?: 2;
  1404. $conditions = $this->rpmConditions($performer, $rc, $rc2);
  1405. $count = DB::select(
  1406. DB::raw(
  1407. "
  1408. SELECT count(*)
  1409. FROM care_month join client on care_month.client_id = client.id
  1410. WHERE
  1411. client.mcp_pro_id = {$performer->pro->id}
  1412. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1413. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1414. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '')
  1415. )
  1416. );
  1417. return $count[0]->count;
  1418. }
  1419. public function remoteMonitoringAdmin(Request $request) {
  1420. $performer = $this->performer();
  1421. // abort_if($performer->pro->pro_type !== 'ADMIN' && !$performer->pro->can_view_rm_matrix, 403);
  1422. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1423. $careMonthStart = date($ym . '-01');
  1424. $rc = $request->input('rc') ?: 1;
  1425. $rc2 = $request->input('rc2') ?: 2;
  1426. $conditions = [];// $this->rpmConditions($performer, $rc, $rc2);
  1427. $sortBy = $request->input('sort_by') ?: 'name_first';
  1428. $sortDir = $request->input('sort_dir') ?: 'ASC';
  1429. $orderBy = "ORDER BY $sortBy $sortDir NULLS LAST";
  1430. $query = "
  1431. SELECT client.name_first, client.name_last,
  1432. (client.name_first || ' ' || client.name_last) as client_name,
  1433. (mcp_pro.name_first || ' ' || mcp_pro.name_last) as mcp_pro_name,
  1434. (rmm_pro.name_first || ' ' || rmm_pro.name_last) as rmm_pro_name,
  1435. client.uid as client_uid,
  1436. client.chart_number,
  1437. client.dob,
  1438. client.is_enrolled_in_rm,
  1439. client.most_recent_completed_mcp_note_date,
  1440. client.most_recent_completed_mcp_note_id,
  1441. mrmnote.effective_dateest::date as most_recent_completed_mcp_note_date_cm,
  1442. mrmnote.id as most_recent_completed_mcp_note_id_cm,
  1443. mrmnote.uid as most_recent_completed_mcp_note_uid_cm,
  1444. client.cell_number,
  1445. client.is_assigned_cellular_bp_device,
  1446. client.is_assigned_cellular_weight_scale_device,
  1447. care_month.uid as care_month_uid,
  1448. care_month.id as care_month_id,
  1449. care_month.start_date,
  1450. care_month.rm_total_time_in_seconds_by_mcp,
  1451. care_month.rm_total_time_in_seconds_by_rmm_pro,
  1452. care_month.number_of_days_with_remote_measurements,
  1453. care_month.has_anyone_interacted_with_client_about_rm,
  1454. care_month.has_mcp_interacted_with_client_about_rm,
  1455. care_month.rm_num_measurements_not_stamped_by_mcp,
  1456. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  1457. care_month.rm_num_measurements_not_stamped_by_rmm,
  1458. care_month.rm_num_measurements_not_stamped_by_rme,
  1459. care_month.mcp_pro_id as care_month_mcp_pro_id,
  1460. care_month.rmm_pro_id as care_month_rmm_pro_id,
  1461. client.mcp_pro_id,
  1462. client.default_na_pro_id,
  1463. client.rmm_pro_id,
  1464. client.rme_pro_id,
  1465. client.cell_number,
  1466. care_month.most_recent_cellular_bp_dbp_mm_hg,
  1467. care_month.most_recent_cellular_bp_sbp_mm_hg,
  1468. care_month.most_recent_cellular_bp_measurement_at,
  1469. care_month.most_recent_cellular_weight_value,
  1470. care_month.most_recent_cellular_weight_measurement_at
  1471. 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
  1472. left join note mrmnote on mrmnote.id = (
  1473. select max(n.id) from note n
  1474. where
  1475. n.client_id = client.id AND
  1476. n.is_cancelled = FALSE AND
  1477. (n.is_signed_by_hcp IS NOT NULL AND n.is_signed_by_hcp = TRUE) AND
  1478. n.effective_dateest::date >= care_month.start_date::date AND
  1479. n.effective_dateest::date < (care_month.start_date::date + INTERVAL '1 month')
  1480. )
  1481. left join pro mcp_pro on care_month.mcp_pro_id = mcp_pro.id
  1482. left join pro rmm_pro on care_month.rmm_pro_id = rmm_pro.id
  1483. WHERE
  1484. EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1485. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1486. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '') . "
  1487. $orderBy
  1488. ";
  1489. $patients = DB::select($query);
  1490. $timestamp = strtotime(date('Y-m-d'));
  1491. $daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
  1492. return view('app.practice-management.remote-monitoring-admin', compact('patients', 'daysRemaining', 'careMonthStart'));
  1493. }
  1494. public function remoteMonitoringAdminCount(Request $request) {
  1495. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1496. $careMonthStart = date($ym . '-01');
  1497. $rc = $request->input('rc') ?: 1;
  1498. $rc2 = $request->input('rc2') ?: 2;
  1499. $conditions = $this->rpmConditionsAdmin($this->performer(), $rc, $rc2);
  1500. $count = DB::select(
  1501. DB::raw(
  1502. "
  1503. SELECT count(*)
  1504. FROM care_month join client on care_month.client_id = client.id
  1505. WHERE
  1506. client.shadow_pro_id is null AND client.is_enrolled_in_rm = 'YES'
  1507. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1508. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1509. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '')
  1510. )
  1511. );
  1512. return $count[0]->count;
  1513. }
  1514. private function rpmConditions($performer, $rc, $rc2) {
  1515. $conditions = [];
  1516. $c_isMCP = "client.mcp_pro_id = {$performer->pro->id}";
  1517. $c_enrolledInRPM = "client.is_enrolled_in_rm = 'YES'";
  1518. $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";
  1519. $c_lastVisitBefore90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) > 90";
  1520. $c_lastVisitWithin90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) <= 90";
  1521. $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)";
  1522. $c_spokenToThisMonth = "care_month.has_anyone_interacted_with_client_about_rm_outside_note = TRUE";
  1523. $c_hasUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp > 0";
  1524. $c_hasNoUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp = 0";
  1525. $c_lt16MeasurementDays = "care_month.number_of_days_with_remote_measurements < 16";
  1526. $c_gte16MeasurementDays = "care_month.number_of_days_with_remote_measurements >= 16";
  1527. $c_subscribedToSMS = "client.send_sms_on_bdt_measurement = TRUE";
  1528. $c_deviceUsed = "(client.most_recent_cellular_bp_measurement_at IS NOT NULL OR most_recent_cellular_weight_measurement_at IS NOT NULL)";
  1529. $c_lt20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp < 1200";
  1530. $c_gte20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp >= 1200";
  1531. switch ($rc) {
  1532. case 1:
  1533. $conditions = [$c_isMCP];
  1534. break;
  1535. case 2:
  1536. $conditions = [$c_isMCP, $c_enrolledInRPM];
  1537. break;
  1538. case 3:
  1539. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice];
  1540. break;
  1541. case 4:
  1542. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, ($rc2 == 1 ? $c_lastVisitBefore90Days : $c_lastVisitWithin90Days)];
  1543. break;
  1544. case 5:
  1545. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, ($rc2 == 1 ? $c_notSpokenToThisMonth : $c_spokenToThisMonth)];
  1546. break;
  1547. case 6:
  1548. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_hasUnstamped : $c_hasNoUnstamped)];
  1549. break;
  1550. case 7:
  1551. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_lt16MeasurementDays : $c_gte16MeasurementDays)];
  1552. break;
  1553. case 10:
  1554. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, $c_gte16MeasurementDays, ($rc2 == 1 ? $c_lt20BillingMinutes : $c_gte20BillingMinutes)];
  1555. break;
  1556. case 8:
  1557. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_subscribedToSMS];
  1558. break;
  1559. case 9:
  1560. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_deviceUsed];
  1561. break;
  1562. }
  1563. return $conditions;
  1564. }
  1565. private function rpmConditionsAdmin($performer, $rc, $rc2) {
  1566. $conditions = [];
  1567. $c_enrolledInRPM = "client.is_enrolled_in_rm = 'YES'";
  1568. $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";
  1569. $c_lastVisitBefore90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) > 90";
  1570. $c_lastVisitWithin90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) <= 90";
  1571. $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)";
  1572. $c_spokenToThisMonth = "care_month.has_anyone_interacted_with_client_about_rm_outside_note = TRUE";
  1573. $c_hasUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp > 0";
  1574. $c_hasNoUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp = 0";
  1575. $c_lt16MeasurementDays = "care_month.number_of_days_with_remote_measurements < 16";
  1576. $c_gte16MeasurementDays = "care_month.number_of_days_with_remote_measurements >= 16";
  1577. $c_subscribedToSMS = "client.send_sms_on_bdt_measurement = TRUE";
  1578. $c_deviceUsed = "(client.most_recent_cellular_bp_measurement_at IS NOT NULL OR client.most_recent_cellular_weight_measurement_at IS NOT NULL)";
  1579. $c_lt20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp < 1200";
  1580. $c_gte20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp >= 1200";
  1581. switch ($rc) {
  1582. case 2:
  1583. $conditions = [$c_enrolledInRPM];
  1584. break;
  1585. case 3:
  1586. $conditions = [$c_enrolledInRPM, $c_hasDevice];
  1587. break;
  1588. case 4:
  1589. $conditions = [$c_enrolledInRPM, $c_hasDevice, ($rc2 == 1 ? $c_lastVisitBefore90Days : $c_lastVisitWithin90Days)];
  1590. break;
  1591. case 5:
  1592. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, ($rc2 == 1 ? $c_notSpokenToThisMonth : $c_spokenToThisMonth)];
  1593. break;
  1594. case 6:
  1595. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_hasUnstamped : $c_hasNoUnstamped)];
  1596. break;
  1597. case 7:
  1598. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_lt16MeasurementDays : $c_gte16MeasurementDays)];
  1599. break;
  1600. case 10:
  1601. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, $c_gte16MeasurementDays, ($rc2 == 1 ? $c_lt20BillingMinutes : $c_gte20BillingMinutes)];
  1602. break;
  1603. case 8:
  1604. $conditions = [$c_enrolledInRPM, $c_subscribedToSMS];
  1605. break;
  1606. case 9:
  1607. $conditions = [$c_enrolledInRPM, $c_deviceUsed];
  1608. break;
  1609. }
  1610. return $conditions;
  1611. }
  1612. public function remoteMonitoringMeasurements(Request $request, CareMonth $careMonth) {
  1613. $performer = $this->performer();
  1614. $measurements = DB::select(
  1615. DB::raw(
  1616. "
  1617. SELECT measurement.label,
  1618. measurement.ts,
  1619. measurement.effective_date,
  1620. measurement.sbp_mm_hg,
  1621. measurement.dbp_mm_hg,
  1622. measurement.value_pulse,
  1623. measurement.value_irregular,
  1624. measurement.numeric_value,
  1625. measurement.value,
  1626. measurement.uid,
  1627. client.name_first,
  1628. client.name_last,
  1629. client.mcp_pro_id,
  1630. client.default_na_pro_id,
  1631. client.rmm_pro_id,
  1632. client.rme_pro_id
  1633. FROM measurement RIGHT JOIN client on measurement.client_id = client.id
  1634. WHERE
  1635. client.id = {$careMonth->client_id}
  1636. AND measurement.label IS NOT NULL
  1637. AND measurement.label NOT IN ('SBP', 'DBP')
  1638. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  1639. AND measurement.is_removed IS FALSE
  1640. AND measurement.client_bdt_measurement_id IS NOT NULL
  1641. AND measurement.care_month_id = {$careMonth->id}
  1642. AND (
  1643. (client.mcp_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_mcp IS FALSE)
  1644. OR (client.rmm_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_rmm IS FALSE)
  1645. OR (client.rme_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_rme IS FALSE)
  1646. OR (client.default_na_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_non_hcp IS FALSE)
  1647. )
  1648. ORDER BY ts DESC
  1649. "
  1650. )
  1651. );
  1652. return view('app.practice-management.remote-monitoring-measurements', compact('careMonth', 'measurements'));
  1653. }
  1654. public function billMatrix(Request $request)
  1655. {
  1656. $bClients = [];
  1657. $bHCPPros = [];
  1658. $bNAPros = [];
  1659. $filters = [];
  1660. $filters['client'] = $request->input('client');
  1661. $filters['service'] = $request->input('service');
  1662. $filters['hcp'] = $request->input('hcp');
  1663. $filters['hcp_paid'] = $request->input('hcp_paid');
  1664. $filters['expected_op'] = $request->input('expected_op');
  1665. $filters['expected_value'] = $request->input('expected_value');
  1666. $filters['paid_op'] = $request->input('paid_op');
  1667. $filters['paid_value'] = $request->input('paid_value');
  1668. $filters['bal_post_date_op'] = $request->input('bal_post_date_op');
  1669. $filters['bal_post_date_value'] = $request->input('bal_post_date_value');
  1670. $filters['hcp_sign'] = $request->input('hcp_sign');
  1671. $filters['verified'] = $request->input('verified');
  1672. $filters['cancelled'] = $request->input('cancelled');
  1673. $bills = Bill::orderBy('effective_date')->paginate();
  1674. return view('app.practice-management.bill-matrix', compact('bills', 'bClients', 'bHCPPros', 'filters'));
  1675. }
  1676. public function medicarePartBClaims(Request $request)
  1677. {
  1678. $medicarePartBOnly = $request->get("medicare_part_b");
  1679. $allClaims = Claim::where('was_submitted', false)->orWhere('was_submitted', null)->orderBy('created_at', 'desc')->get();
  1680. //Only medicare claims
  1681. $claims = [];
  1682. foreach ($allClaims as $claim) {
  1683. if ($claim->client != null && $claim->client->getPrimaryCoverageStatus() == 'YES' && !$claim->edi) {
  1684. $claims[] = $claim;
  1685. }
  1686. }
  1687. $claimEDIs = ClaimEDI::all();
  1688. return view('app.practice-management.medicare-partb-claims', compact('claims', 'claimEDIs'));
  1689. }
  1690. // Generate PDF
  1691. public function downloadClaims()
  1692. {
  1693. $claims = Claim::where('was_submitted', false)->orWhere('was_submitted', null)->orderBy('created_at', 'desc')->limit(100)->get();
  1694. view()->share('claims', $claims);
  1695. $pdf = PDF::loadView('app.practice-management.claims-pdf', $claims);
  1696. return $pdf->download('pdf_file.pdf');
  1697. }
  1698. public function tickets(Request $request, $proUid = null)
  1699. {
  1700. $tickets = Ticket::orderBy('created_at', 'desc')->paginate();
  1701. return view('app.practice-management.tickets', compact('tickets'));
  1702. }
  1703. public function supplyOrders(Request $request)
  1704. {
  1705. // counts
  1706. $counts = $this->getSupplyOrderCounts();
  1707. // so clients
  1708. $soClientIDs = DB::table('supply_order')->select('client_id')->distinct()->get()->toArray();
  1709. $soClientIDs = array_map(function ($_x) {
  1710. return $_x->client_id;
  1711. }, $soClientIDs);
  1712. $soClients = Client::whereIn('id', $soClientIDs)->get();
  1713. // so products
  1714. $soProductIDs = DB::table('supply_order')->select('product_id')->distinct()->get()->toArray();
  1715. $soProductIDs = array_map(function ($_x) {
  1716. return $_x->product_id;
  1717. }, $soProductIDs);
  1718. $soProducts = Product::whereIn('id', $soProductIDs)->get();
  1719. $filters = [];
  1720. $filters['client'] = $request->input('client');
  1721. $filters['product'] = $request->input('product');
  1722. $filters['reason'] = $request->input('reason');
  1723. $filters['cu_memo'] = $request->input('cu_memo');
  1724. $filters['pro_sign'] = $request->input('pro_sign');
  1725. $filters['client_sign'] = $request->input('client_sign');
  1726. $filters['shipment'] = $request->input('shipment');
  1727. $filters['lot_number'] = $request->input('lot_number');
  1728. $filters['imei'] = $request->input('imei');
  1729. $filters['cancelled'] = $request->input('cancelled');
  1730. $supplyOrders = SupplyOrder::where('id', '>', 0);
  1731. // apply filters
  1732. if ($filters['client']) $supplyOrders->where('client_id', $filters['client']);
  1733. if ($filters['product']) $supplyOrders->where('product_id', $filters['product']);
  1734. if ($filters['reason']) $supplyOrders->where('reason', 'ILIKE', '%' . $filters['reason'] . '%');
  1735. if ($filters['cu_memo']) $supplyOrders->where('cu_memo', 'ILIKE', '%' . $filters['cu_memo'] . '%');
  1736. if ($filters['pro_sign']) $supplyOrders->where('is_signed_by_pro', ($filters['pro_sign'] === 'signed'));
  1737. if ($filters['client_sign']) {
  1738. if ($filters['client_sign'] === 'signed')
  1739. $supplyOrders->where('is_signed_by_client', true);
  1740. elseif ($filters['client_sign'] === 'waived')
  1741. $supplyOrders->where('is_client_signature_waived', true);
  1742. else
  1743. $supplyOrders->where('is_client_signature_waived', false)->where('is_signed_by_client', false);
  1744. }
  1745. if ($filters['shipment']) {
  1746. if ($filters['shipment'] === 'not_cleared_for_shipment')
  1747. $supplyOrders->whereNull('shipment_id')->where('is_cleared_for_shipment', false);
  1748. elseif ($filters['shipment'] === 'cleared_for_shipment')
  1749. $supplyOrders->whereNull('shipment_id')->where('is_cleared_for_shipment', true);
  1750. else
  1751. $supplyOrders
  1752. ->whereNotNull('shipment_id')
  1753. ->whereRaw('(SELECT status FROM shipment WHERE id = shipment_id LIMIT 1) = ?', [$filters['shipment']]);
  1754. }
  1755. if ($filters['lot_number']) $supplyOrders->where('lot_number', 'ILIKE', '%' . $filters['lot_number'] . '%');
  1756. if ($filters['imei']) $supplyOrders->where('imei', 'ILIKE', '%' . $filters['imei'] . '%');
  1757. if ($filters['cancelled']) $supplyOrders->where('is_cancelled', ($filters['cancelled'] === 'cancelled'));
  1758. $supplyOrders = $supplyOrders->orderBy('created_at', 'desc')->paginate();
  1759. return view('app.practice-management.supply-orders',
  1760. compact('supplyOrders', 'filters',
  1761. 'soClients', 'soProducts', 'counts'
  1762. )
  1763. );
  1764. }
  1765. public function shipments(Request $request, $filter = null)
  1766. {
  1767. // counts
  1768. $counts = $this->getShipmentCounts();
  1769. // so clients
  1770. $shClientIDs = DB::table('shipment')->select('client_id')->distinct()->get()->toArray();
  1771. $shClientIDs = array_map(function ($_x) {
  1772. return $_x->client_id;
  1773. }, $shClientIDs);
  1774. $shClients = Client::whereIn('id', $shClientIDs)->get();
  1775. $shipments = Shipment::where('id', '>', 0);
  1776. $filters = [];
  1777. $filters['client'] = $request->input('client');
  1778. $filters['courier'] = $request->input('courier');
  1779. $filters['tracking_num'] = $request->input('tracking_num');
  1780. $filters['label'] = $request->input('label');
  1781. $filters['status'] = $request->input('status');
  1782. $filters['cancelled'] = $request->input('cancelled');
  1783. if ($filters['client']) $shipments->where('client_id', $filters['client']);
  1784. if ($filters['courier']) $shipments->where('courier', 'ILIKE', '%' . $filters['courier'] . '%');
  1785. if ($filters['tracking_num']) $shipments->where('tracking_number', 'ILIKE', '%' . $filters['tracking_num'] . '%');
  1786. if ($filters['label']) {
  1787. if ($filters['label'] === 'yes')
  1788. $shipments->whereNotNull('label_system_file_id');
  1789. else
  1790. $shipments->whereNull('label_system_file_id');
  1791. }
  1792. if ($filters['status']) $shipments->where('status', $filters['status']);
  1793. if ($filters['cancelled']) $shipments->where('is_cancelled', ($filters['cancelled'] === 'cancelled'));
  1794. $shipments = $shipments->orderBy('created_at', 'desc')->paginate();
  1795. return view('app.practice-management.shipments', compact('shipments', 'filters', 'shClients', 'counts'));
  1796. }
  1797. public function cellularMeasurements(Request $request)
  1798. {
  1799. $measurements = Measurement::orderBy('ts', 'desc')->whereNotNull('ts')->paginate();
  1800. return view('app.practice-management.cellular-measurements', compact('measurements'));
  1801. }
  1802. // v2 supply-orders & shipments management (wh)
  1803. public function supplyOrdersReadyToShip(Request $request)
  1804. {
  1805. $counts = $this->getSupplyOrderCounts();
  1806. $supplyOrders = SupplyOrder
  1807. ::where('is_cleared_for_shipment', true)
  1808. ->where('is_cancelled', false)
  1809. ->whereNull('shipment_id')
  1810. ->join('client', 'client.id', '=', 'supply_order.client_id')
  1811. ->orderBy('client.name_last', 'ASC')
  1812. ->orderBy('client.name_first', 'ASC')
  1813. ->orderBy('supply_order.client_id', 'ASC')
  1814. ->orderBy('supply_order.mailing_address_full', 'ASC')
  1815. ->orderBy('supply_order.created_at', 'ASC')
  1816. ->select('supply_order.*')
  1817. ->paginate();
  1818. return view('app.practice-management.supply-orders-ready-to-ship', compact('supplyOrders', 'counts'));
  1819. }
  1820. public function supplyOrdersShipmentUnderway(Request $request)
  1821. {
  1822. $counts = $this->getSupplyOrderCounts();
  1823. $supplyOrders = SupplyOrder
  1824. ::where('is_cancelled', false)
  1825. ->whereNotNull('shipment_id')
  1826. ->orderBy('client_id', 'ASC')
  1827. ->orderBy('mailing_address_full', 'ASC')
  1828. ->orderBy('created_at', 'ASC')
  1829. ->paginate();
  1830. return view('app.practice-management.supply-orders-shipment-underway', compact('supplyOrders', 'counts'));
  1831. }
  1832. public function supplyOrdersHanging(Request $request)
  1833. {
  1834. $counts = $this->getSupplyOrderCounts();
  1835. $supplyOrders = SupplyOrder
  1836. ::select('supply_order.*')
  1837. ->leftJoin('shipment', function($join) {
  1838. $join->on('supply_order.shipment_id', '=', 'shipment.id');
  1839. })
  1840. ->where('shipment.status', 'CANCELLED')
  1841. ->where('supply_order.is_cancelled', false)
  1842. ->orderBy('supply_order.client_id', 'ASC')
  1843. ->orderBy('supply_order.mailing_address_full', 'ASC')
  1844. ->orderBy('supply_order.created_at', 'ASC')
  1845. ->paginate();
  1846. return view('app.practice-management.supply-orders-hanging', compact('supplyOrders', 'counts'));
  1847. }
  1848. public function supplyOrdersCancelledButUnacknowledged(Request $request)
  1849. {
  1850. $supplyOrders = SupplyOrder::where('signed_by_pro_id', $this->performer()->pro->id)
  1851. ->where('is_cancelled', true)
  1852. ->where('is_cancellation_acknowledged', false)
  1853. ->orderBy('created_at', 'desc')
  1854. ->paginate();
  1855. return view('app.practice-management.supply-orders-cancelled-but-unacknowledged', compact('supplyOrders'));
  1856. }
  1857. public function supplyOrdersUnsigned(Request $request)
  1858. {
  1859. $supplyOrders = SupplyOrder
  1860. ::where('is_cancelled', false)
  1861. ->where('is_signed_by_pro', false)
  1862. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$this->performer()->pro->id])
  1863. ->orderBy('created_at', 'desc')
  1864. ->paginate();
  1865. return view('app.practice-management.supply-orders-unsigned', compact('supplyOrders'));
  1866. }
  1867. private function getSupplyOrderCounts()
  1868. {
  1869. return [
  1870. "supplyOrders" => SupplyOrder::count(),
  1871. "supplyOrdersReadyToShip" => SupplyOrder
  1872. ::where('is_cleared_for_shipment', true)
  1873. ->where('is_cancelled', false)
  1874. ->whereNull('shipment_id')->count(),
  1875. "supplyOrdersShipmentUnderway" => SupplyOrder
  1876. ::where('is_cancelled', false)
  1877. ->whereNotNull('shipment_id')->count(),
  1878. "supplyOrdersHanging" => SupplyOrder
  1879. ::leftJoin('shipment', function($join) {
  1880. $join->on('supply_order.shipment_id', '=', 'shipment.id');
  1881. })
  1882. ->where('shipment.status', 'CANCELLED')
  1883. ->where('supply_order.is_cancelled', false)
  1884. ->count(),
  1885. ];
  1886. }
  1887. public function shipmentsReadyToPrint(Request $request)
  1888. {
  1889. $counts = $this->getShipmentCounts();
  1890. $shipments = Shipment
  1891. ::where('is_cancelled', false)
  1892. ->where('status', 'CREATED')
  1893. ->orderBy('created_at', 'ASC')
  1894. ->paginate();
  1895. return view('app.practice-management.shipments-ready-to-print', compact('shipments', 'counts'));
  1896. }
  1897. public function shipmentsShipmentUnderway(Request $request)
  1898. {
  1899. $counts = $this->getShipmentCounts();
  1900. $shipments = Shipment
  1901. ::where('is_cancelled', false)
  1902. ->where('status', 'PRINTED')
  1903. ->orderBy('created_at', 'ASC')
  1904. ->paginate();
  1905. return view('app.practice-management.shipments-waiting-for-picker', compact('shipments', 'counts'));
  1906. }
  1907. private function getShipmentCounts()
  1908. {
  1909. return [
  1910. "shipments" => Shipment::count(),
  1911. "shipmentsReadyToPrint" => Shipment
  1912. ::where('is_cancelled', false)
  1913. ->where('status', 'CREATED')
  1914. ->count(),
  1915. "shipmentsWaitingForPicker" => Shipment
  1916. ::where('is_cancelled', false)
  1917. ->where('status', 'PRINTED')
  1918. ->count()
  1919. ];
  1920. }
  1921. public function shipment(Request $request, Shipment $shipment)
  1922. {
  1923. return view('app.practice-management.shipment', compact('shipment'));
  1924. }
  1925. public function shipmentsMultiPrint(Request $request, $ids)
  1926. {
  1927. $ids = array_map(function ($_x) {
  1928. return intval($_x);
  1929. }, explode("|", $ids));
  1930. $shipments = Shipment::whereIn('id', $ids)->get();
  1931. return view('app.practice-management.shipments-multi-print', compact('shipments'));
  1932. }
  1933. public function patientClaimSummary(Request $request, $proUid = null)
  1934. {
  1935. $notesTotal = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE"))[0]->count;
  1936. $notesTotalWithBillingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE AND is_bill_closed IS TRUE"))[0]->count;
  1937. $notesTotalWithClaimingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE AND is_claim_closed IS TRUE"))[0]->count;
  1938. $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;
  1939. $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;
  1940. $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;
  1941. $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;
  1942. $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;
  1943. $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;
  1944. $performerPro = $this->performer->pro;
  1945. $allPros = [];
  1946. if ($performerPro->pro_type == 'ADMIN') {
  1947. $allPros = Pro::all();
  1948. } else {
  1949. $allPros = [$performerPro];
  1950. }
  1951. //Patient | MCP | # Notes Total | # Notes without Billing Closed | # Notes without Claiming Closed
  1952. $patientsQuery = Client::where('is_dummy', '=', false)
  1953. ->whereNull('shadow_pro_id')
  1954. ->select('id', 'uid', 'name_first', 'name_last', 'mcp_pro_id', 'is_part_b_primary', 'medicare_advantage_plan',
  1955. DB::raw("(SELECT name_first||' '||name_last FROM pro where pro.id = client.mcp_pro_id) as mcp"),
  1956. DB::raw("(SELECT uid FROM pro where pro.id = mcp_pro_id) as mcp_pro_uid"),
  1957. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id) as notes_total"),
  1958. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id AND is_bill_closed IS NOT true) as notes_without_billing_closed"),
  1959. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id AND is_claim_closed IS NOT true) as notes_without_claiming_closed")
  1960. )->orderBy('is_part_b_primary', 'asc')->orderBy('notes_without_claiming_closed', 'desc');
  1961. if ($proUid) {
  1962. $mcpPro = Pro::where('uid', $proUid)->first();
  1963. if ($mcpPro) {
  1964. $patientsQuery->where('client.mcp_pro_id', '=', $mcpPro->id);
  1965. }
  1966. }
  1967. $patientsQuery->whereRaw('(SELECT COUNT(*) FROM note where note.client_id = client.id) > 0');
  1968. $patientsQuery->orderBy('notes_total', 'DESC');
  1969. $patients = $patientsQuery->paginate(50);
  1970. $data = [
  1971. 'patients' => $patients,
  1972. 'proUid' => $proUid,
  1973. 'allPros' => $allPros,
  1974. 'notesTotal' => $notesTotal,
  1975. 'notesTotalWithBillingClosed' => $notesTotalWithBillingClosed,
  1976. 'notesTotalWithClaimingClosed' => $notesTotalWithClaimingClosed,
  1977. 'notes3rdPartyTotal' => $notes3rdPartyTotal,
  1978. 'notes3rdPartyTotalWithBillingClosed' => $notes3rdPartyTotalWithBillingClosed,
  1979. 'notes3rdPartyTotalWithClaimingClosed' => $notes3rdPartyTotalWithClaimingClosed,
  1980. 'patientsTotal' => $patientsTotal,
  1981. 'patientsTotalWithBillingClosed' => $patientsTotalWithBillingClosed,
  1982. 'patientsTotalWithClaimingClosed' => $patientsTotalWithClaimingClosed
  1983. ];
  1984. return view('app.practice-management.patient-claim-summary', $data);
  1985. }
  1986. public function claims(Request $request){
  1987. $status = $request->get('status');
  1988. $claims = [];
  1989. if(!$status){
  1990. $claims = Claim::orderBy('created_at', 'DESC')->paginate();
  1991. }else{
  1992. $claims = Claim::where('status', $status)->orderBy('created_at', 'DESC')->paginate();
  1993. }
  1994. return view('app.practice-management.claims', compact('claims', 'status'));
  1995. }
  1996. public function processClaims(Request $request) {
  1997. $status = '';
  1998. $q = $request->input('q') ? $request->input('q') : '';
  1999. $from = $request->input('from') ? $request->input('from') : '1900-01-01';
  2000. $to = $request->input('to') ? $request->input('to') : '2100-01-01';
  2001. $params = [
  2002. 'q' => '%' . $q . '%',
  2003. 'from' => $from,
  2004. 'to' => $to
  2005. ];
  2006. $hcpPro = $request->input('hcp') ? Pro::where('uid', $request->input('hcp'))->first() : null;
  2007. if($hcpPro) {
  2008. $params['hcp'] = $hcpPro->id;
  2009. }
  2010. $claims = DB::select(DB::raw("
  2011. SELECT claim.uid AS uid,
  2012. DATE(claim.created_at) AS created,
  2013. claim.status,
  2014. client.uid AS client_uid,
  2015. client.cell_number AS client_phone,
  2016. client.phone_home AS client_phone_home,
  2017. (client.name_last || ' ' || client.name_first) AS client ,
  2018. client.chart_number AS client_chart_number,
  2019. cp.id AS claim_pro_id,
  2020. (cp.name_last || ' ' || cp.name_first) AS claim_pro,
  2021. sp.id AS status_pro_id,
  2022. (sp.name_last || ' ' || sp.name_first) AS status_pro,
  2023. note.uid AS note_uid,
  2024. note.method,
  2025. note.new_or_fu_or_na,
  2026. care_month.uid AS care_month_uid,
  2027. care_month.start_date as care_month_start__date,
  2028. -- claim.status_updated_at,
  2029. (DATE(claim.status_updated_at) || ' ' ||
  2030. LPAD(EXTRACT(hour FROM claim.status_updated_at)::text, 2, '0') || ':' ||
  2031. LPAD(EXTRACT(minute FROM claim.status_updated_at)::text, 2, '0')) AS status_updated_at,
  2032. (SELECT string_agg(claim_line.cpt, ', ') FROM claim_line where claim_id = claim.id) AS cpts,
  2033. (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,
  2034. ROUND(claim.expected_total, 3) as expected_total
  2035. FROM claim
  2036. join client on claim.client_id = client.id
  2037. join pro cp on claim.pro_id = cp.id
  2038. left join note on claim.note_id = note.id
  2039. left join care_month on claim.care_month_id = care_month.id
  2040. left join app_session on claim.status_updated_by_session_id = app_session.id
  2041. left join pro sp on app_session.pro_id = sp.id
  2042. --WHERE claim.status IS NULL OR claim.status = 'NEW'
  2043. WHERE (claim.status is NULL OR claim.status NOT IN ('CANCELLED', 'ABANDONED'" . ($request->input('show-submitted') ? "" : ", 'SUBMITTED'") . "))
  2044. -- AND claim.current_version_id IS NOT NULL
  2045. AND (client.name_first ILIKE :q OR
  2046. client.name_last ILIKE :q OR
  2047. client.chart_number ILIKE :q OR
  2048. client.mcn ILIKE :q)
  2049. AND (claim.created_at >= :from AND claim.created_at <= :to)
  2050. " . ($hcpPro ? "AND claim.pro_id = :hcp" : '') . "
  2051. AND claim.id IN (SELECT mb_claim.claim_id FROM mb_claim)
  2052. ORDER BY claim.created_at DESC
  2053. --OFFSET 0 LIMIT 15
  2054. "), $params);
  2055. if($request->input('json')) {
  2056. return json_encode($claims);
  2057. }
  2058. return view('app.practice-management.process-claims', compact('claims', 'status'));
  2059. }
  2060. public function rmLaunchAndClean(Request $request) {
  2061. $keyNumbers = [];
  2062. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_40'] = CareMonth::where('is_bill_closed', false)
  2063. ->whereNotNull('company_pro_id')
  2064. ->whereNotNull('company_pro_payer_id')
  2065. ->whereNotNull('company_location_id')
  2066. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2067. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  2068. ->where('rm_total_time_in_seconds', '>=', 4200) // at 4200 (70 minutes, it becomes eligible for plus40)
  2069. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2070. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2071. ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS TRUE OR has_mcp_rm_interacted_by_note IS TRUE )')
  2072. ->count();
  2073. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_40_ifHadInteraction'] = CareMonth::where('is_bill_closed', false)
  2074. ->whereNotNull('company_pro_id')
  2075. ->whereNotNull('company_pro_payer_id')
  2076. ->whereNotNull('company_location_id')
  2077. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2078. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  2079. ->where('rm_total_time_in_seconds', '>=', 4200) // at 4200 (70 minutes, it becomes eligible for plus40)
  2080. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2081. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2082. ->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 )')
  2083. ->count();
  2084. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_20'] = CareMonth::where('is_bill_closed', false)
  2085. ->whereNotNull('company_pro_id')
  2086. ->whereNotNull('company_pro_payer_id')
  2087. ->whereNotNull('company_location_id')
  2088. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2089. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  2090. ->where('rm_total_time_in_seconds', '<', 4200)
  2091. ->where('rm_total_time_in_seconds', '>=', 3000) // at 3000 (50 minutes, it becomes eligible for plus20)
  2092. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2093. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2094. ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS TRUE OR has_mcp_rm_interacted_by_note IS TRUE)')
  2095. ->count();
  2096. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_20_ifHadInteraction'] = CareMonth::where('is_bill_closed', false)
  2097. ->whereNotNull('company_pro_id')
  2098. ->whereNotNull('company_pro_payer_id')
  2099. ->whereNotNull('company_location_id')
  2100. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2101. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  2102. ->where('rm_total_time_in_seconds', '<', 4200)
  2103. ->where('rm_total_time_in_seconds', '>=', 3000) // at 3000 (50 minutes, it becomes eligible for plus20)
  2104. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2105. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2106. ->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 )')
  2107. ->count();
  2108. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP'] = CareMonth::where('is_bill_closed', false)
  2109. ->whereNotNull('company_pro_id')
  2110. ->whereNotNull('company_pro_payer_id')
  2111. ->whereNotNull('company_location_id')
  2112. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2113. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  2114. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  2115. ->whereRaw('(rm_total_time_in_seconds < 3000 OR (rm_total_time_in_seconds >= 3000 AND is_rm_interaction_waived IS TRUE))')
  2116. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2117. ->count();
  2118. $keyNumbers['careMonthsEligibleForBillGeneration_RMB'] = CareMonth::where('is_bill_closed', false)
  2119. ->whereNotNull('company_pro_id')
  2120. ->whereNotNull('company_pro_payer_id')
  2121. ->whereNotNull('company_location_id')
  2122. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  2123. ->whereRaw('is_rm_time_waived IS TRUE')
  2124. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2125. ->count();
  2126. $keyNumbers['careMonthsWith16OrMoreMeasurementDays'] = CareMonth::where('is_bill_closed', false)
  2127. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  2128. ->count();
  2129. $careMonthsWith16PlusMeasurements = CareMonth::where('is_bill_closed', false)
  2130. ->where('number_of_days_with_remote_measurements', '>=', 16 )->get();
  2131. return view('app.practice-management.rm-launch-and-clean', compact('keyNumbers', 'careMonthsWith16PlusMeasurements'));
  2132. }
  2133. public function processNotes(Request $request) {
  2134. $mode = $request->input('mode') ? $request->input('mode') : '1';
  2135. if(($mode < 1 || $mode > 5) && $mode != 8) $mode = 1;
  2136. DB::enableQueryLog(); // Enable query log
  2137. $test = Note::where('is_cancelled', false)
  2138. ->where('is_signed_by_hcp', true)
  2139. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  2140. ->whereNull('current_note_pickup_for_processing_id')
  2141. ->where('is_billing_marked_done', true)
  2142. ->where('is_bill_closed', true)
  2143. ->where('is_claim_closed', true)
  2144. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  2145. ->count();
  2146. // var_dump($test);
  2147. // dd(DB::getQueryLog()); // Show results of log
  2148. // exit;
  2149. $counts = [
  2150. "picked" => Note::where('is_cancelled', false)
  2151. ->whereNotNull('current_note_pickup_for_processing_id')
  2152. ->count(),
  2153. "bad" => Note::where('is_cancelled', false)
  2154. ->whereRaw("((detail_json)::json->>'isBad' = 'true')")
  2155. ->count(),
  2156. // not yet signed
  2157. "mode-1" => Note::where('is_cancelled', false)
  2158. ->where('is_signed_by_hcp', false)
  2159. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2160. // ->whereNull('current_note_pickup_for_processing_id')
  2161. ->count(),
  2162. // billing not marked done
  2163. "mode-2" => Note::where('is_cancelled', false)
  2164. ->where('is_signed_by_hcp', true)
  2165. //->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2166. // ->whereNull('current_note_pickup_for_processing_id')
  2167. ->where('is_billing_marked_done', false)
  2168. ->count(),
  2169. // billing not closed
  2170. "mode-3" => Note::where('is_cancelled', false)
  2171. ->where('is_signed_by_hcp', true)
  2172. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2173. // ->whereNull('current_note_pickup_for_processing_id')
  2174. ->where('is_billing_marked_done', true)
  2175. ->where('is_bill_closed', false)
  2176. ->count(),
  2177. // claiming not closed
  2178. "mode-4" => Note::where('is_cancelled', false)
  2179. ->where('is_signed_by_hcp', true)
  2180. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2181. // ->whereNull('current_note_pickup_for_processing_id')
  2182. ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true' OR ((detail_json)::json->>'isGood')::text IS NULL)")
  2183. ->where('is_billing_marked_done', true)
  2184. ->where('is_bill_closed', true)
  2185. ->where('is_claim_closed', false)
  2186. ->count(),
  2187. // has unsubmitted claims
  2188. "mode-5" => Note::where('is_cancelled', false)
  2189. /*->where('is_signed_by_hcp', true)
  2190. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2191. ->whereNull('current_note_pickup_for_processing_id')
  2192. ->where('is_billing_marked_done', true)
  2193. ->where('is_bill_closed', true)
  2194. ->where('is_claim_closed', true)
  2195. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0")
  2196. */
  2197. ->where('is_signed_by_hcp', true)
  2198. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2199. // ->whereNull('current_note_pickup_for_processing_id')
  2200. ->where('is_billing_marked_done', true)
  2201. ->where('is_bill_closed', true)
  2202. // ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true')")
  2203. ->where('is_claim_closed', true)
  2204. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0)")
  2205. ->count(),
  2206. // has unsubmitted claims MARKED GOOD!
  2207. "mode-8" => Note::where('is_cancelled', false)
  2208. ->where('is_signed_by_hcp', true)
  2209. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  2210. ->whereNull('current_note_pickup_for_processing_id')
  2211. ->where('is_billing_marked_done', true)
  2212. ->where('is_bill_closed', true)
  2213. ->where('is_claim_closed', false)
  2214. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  2215. ->count(),
  2216. // all good
  2217. "mode-6" => Note::where('is_cancelled', false)
  2218. ->where('is_signed_by_hcp', true)
  2219. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2220. // ->whereNull('current_note_pickup_for_processing_id')
  2221. ->where('is_billing_marked_done', true)
  2222. ->where('is_bill_closed', true)
  2223. ->where('is_claim_closed', true)
  2224. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id) > 0)")
  2225. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  2226. ->count(),
  2227. "mode-7" => Note::where('is_cancelled', false)
  2228. ->whereRaw("(detail_json)::json->>'isBad' = 'true'")
  2229. ->count(),
  2230. ];
  2231. return view('app.practice-management.process-notes', compact('mode', 'counts'));
  2232. }
  2233. public function notesProcessingCenter(Request $request) {
  2234. $notes = Note::where('is_cancelled', false);
  2235. // filters
  2236. $proUid = $request->input('proUid');
  2237. if($proUid) {
  2238. $fPro = Pro::where('uid', $proUid)->first();
  2239. if($fPro) {
  2240. $notes = $notes->where('hcp_pro_id', $fPro->id);
  2241. }
  2242. }
  2243. $proSigned = $request->input('proSigned');
  2244. switch($proSigned) {
  2245. case 'yes': $notes = $notes->where('is_signed_by_hcp', true); break;
  2246. case 'no': $notes = $notes->where('is_signed_by_hcp', '!=', true); break;
  2247. }
  2248. $billingMarkedDone = $request->input('billingMarkedDone');
  2249. switch($billingMarkedDone) {
  2250. case 'yes': $notes = $notes->where('is_billing_marked_done', true); break;
  2251. case 'no': $notes = $notes->where('is_billing_marked_done', '!=', true); break;
  2252. }
  2253. $billingClosed = $request->input('billingClosed');
  2254. switch($billingClosed) {
  2255. case 'yes': $notes = $notes->where('is_bill_closed', true); break;
  2256. case 'no': $notes = $notes->where('is_bill_closed', '!=', true); break;
  2257. }
  2258. $claimingClosed = $request->input('claimingClosed');
  2259. switch($claimingClosed) {
  2260. case 'yes': $notes = $notes->where('is_claim_closed', true); break;
  2261. case 'no': $notes = $notes->where('is_claim_closed', '!=', true); break;
  2262. }
  2263. $allClaimsSubmitted = $request->input('allClaimsSubmitted');
  2264. if($allClaimsSubmitted) {
  2265. // TODO
  2266. }
  2267. $goodBad = $request->input('goodBad');
  2268. switch($goodBad) {
  2269. case 'good': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' = 'false'"); break;
  2270. case 'bad': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' = 'true'"); break;
  2271. case 'unclassified': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' is null"); break;
  2272. }
  2273. $startDate = $request->input('startDate');
  2274. if($startDate) {
  2275. $notes = $notes->where('effective_dateest', '>=', $startDate);
  2276. }
  2277. $endDate = $request->input('endDate');
  2278. if($endDate) {
  2279. $notes = $notes->where('effective_dateest', '<=', $endDate);
  2280. }
  2281. $mcPartB = $request->input('mcPartB');
  2282. if($mcPartB) {
  2283. // TODO
  2284. }
  2285. $notes = $notes->orderBy('effective_dateest')->paginate(10);
  2286. return view('app.practice-management.notes-processing-center', compact('notes'));
  2287. }
  2288. public function getNextNote(Request $request, $mode)
  2289. {
  2290. $note = null;
  2291. switch (+$mode) {
  2292. case 1:
  2293. $note = Note::where('is_cancelled', false)
  2294. ->where('is_signed_by_hcp', false)
  2295. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2296. ->whereNull('current_note_pickup_for_processing_id')
  2297. ->orderBy('effective_dateest', 'DESC')
  2298. ->first();
  2299. break;
  2300. case 2:
  2301. $note = Note::where('is_cancelled', false)
  2302. ->where('is_signed_by_hcp', true)
  2303. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2304. ->whereNull('current_note_pickup_for_processing_id')
  2305. ->where('is_billing_marked_done', false)
  2306. ->orderBy('effective_dateest', 'DESC')
  2307. ->first();
  2308. break;
  2309. case 3:
  2310. $note = Note::where('is_cancelled', false)
  2311. ->where('is_signed_by_hcp', true)
  2312. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2313. ->whereNull('current_note_pickup_for_processing_id')
  2314. ->where('is_billing_marked_done', true)
  2315. ->where('is_bill_closed', false)
  2316. ->orderBy('effective_dateest', 'DESC')
  2317. ->first();
  2318. break;
  2319. case 4: // claiming not closed
  2320. DB::enableQueryLog(); // Enable query log
  2321. $note = Note::where('is_cancelled', false)
  2322. ->where('is_signed_by_hcp', true)
  2323. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2324. ->whereNull('current_note_pickup_for_processing_id')
  2325. ->where('is_billing_marked_done', true)
  2326. ->where('is_bill_closed', true)
  2327. ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true' OR ((detail_json)::json->>'isGood')::text IS NULL)")
  2328. ->where('is_claim_closed', false)
  2329. ->orderBy('effective_dateest', 'DESC')
  2330. ->first();
  2331. // DB::enableQueryLog(); // Enable query log
  2332. // Your Eloquent query executed by using get()
  2333. // dd(DB::getQueryLog()); // Show results of log
  2334. break;
  2335. case 5:
  2336. $note = Note::where('is_cancelled', false)
  2337. ->where('is_signed_by_hcp', true)
  2338. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2339. ->whereNull('current_note_pickup_for_processing_id')
  2340. ->where('is_billing_marked_done', true)
  2341. ->where('is_bill_closed', true)
  2342. ->where('is_claim_closed', true)
  2343. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0")
  2344. ->orderBy('effective_dateest', 'DESC')
  2345. ->first();
  2346. break;
  2347. case 8:
  2348. $note = Note::where('is_cancelled', false)
  2349. ->where('is_signed_by_hcp', true)
  2350. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  2351. ->whereNull('current_note_pickup_for_processing_id')
  2352. ->where('is_billing_marked_done', true)
  2353. ->where('is_bill_closed', true)
  2354. ->where('is_claim_closed', false)
  2355. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  2356. ->orderBy('effective_dateest', 'DESC')
  2357. ->first();
  2358. break;
  2359. }
  2360. if($note) {
  2361. $note->client_uid = $note->client->uid;
  2362. }
  2363. return json_encode($note);
  2364. }
  2365. public function pickedNotes(Request $request) {
  2366. $counts = [
  2367. "unpicked" => Note::where('is_cancelled', false)
  2368. ->whereNull('current_note_pickup_for_processing_id')
  2369. ->count(),
  2370. ];
  2371. $notes = Note::where('is_cancelled', false)
  2372. ->whereNotNull('current_note_pickup_for_processing_id')
  2373. ->orderBy('effective_dateest', 'ASC')
  2374. ->paginate();
  2375. return view('app.practice-management.picked-notes', compact('counts', 'notes'));
  2376. }
  2377. public function badNotes(Request $request) {
  2378. $counts = [
  2379. "unpicked" => Note::where('is_cancelled', false)
  2380. ->whereNull('current_note_pickup_for_processing_id')
  2381. ->count(),
  2382. ];
  2383. $notes = Note::where('is_cancelled', false)
  2384. ->whereRaw("(detail_json)::json->>'isBad' = 'true'")
  2385. ->orderBy('effective_dateest', 'ASC')
  2386. ->paginate();
  2387. return view('app.practice-management.bad-notes', compact('counts', 'notes'));
  2388. }
  2389. public function doneNotes(Request $request) {
  2390. $counts = [
  2391. "unpicked" => Note::where('is_cancelled', false)
  2392. ->whereNull('current_note_pickup_for_processing_id')
  2393. ->count(),
  2394. ];
  2395. $notes = Note::where('is_cancelled', false)
  2396. ->where('is_signed_by_hcp', true)
  2397. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  2398. ->whereNull('current_note_pickup_for_processing_id')
  2399. ->where('is_billing_marked_done', true)
  2400. ->where('is_bill_closed', true)
  2401. ->where('is_claim_closed', true)
  2402. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id) > 0")
  2403. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0")
  2404. ->orderBy('effective_dateest', 'ASC')
  2405. ->paginate();
  2406. return view('app.practice-management.done-notes', compact('counts', 'notes'));
  2407. }
  2408. public function currentMbClaim(Request $request, $claimUid) {
  2409. $claim = Claim::where('uid', $claimUid)->first();
  2410. return json_encode(MBClaim::where('claim_version_id', $claim->currentVersion->id)->where('status', '!=', 'CANCELLED')->first());
  2411. }
  2412. public function currentClaimLines(Request $request, $claimUid) {
  2413. $claim = Claim::where('uid', $claimUid)->first();
  2414. if($request->input('json')) {
  2415. foreach ($claim->lines as $line) {
  2416. $line->expected_total = round($line->expected_total, 3);
  2417. $x = $line->claimLineIcds;
  2418. }
  2419. return json_encode($claim->lines);
  2420. }
  2421. return view('app.practice-management._claim-lines', compact('claim'));
  2422. }
  2423. public function packsMultiPrint(Request $request) {
  2424. $packs = Pack
  2425. ::select('pack.*')
  2426. ->leftJoin('shipment', function($join) {
  2427. $join->on('pack.shipment_id', '=', 'shipment.id');
  2428. })
  2429. ->whereNotIn('shipment.status', ['CANCELLED', 'DISPATCHED'])
  2430. ->where(function ($query) {
  2431. $query->where('pack.status', '<>', 'DELETED')->orWhereNull('pack.status'); // weird, but just the <> isn't working!
  2432. })
  2433. ->whereNotNull('pack.label_system_file_id')
  2434. ->orderBy('pack.created_at', 'ASC')
  2435. ->get();
  2436. return view('app.practice-management.packs-multi-print', compact('packs'));
  2437. }
  2438. public function packsMultiPDF(Request $request, $ids) {
  2439. $ids = array_map(function ($_x) {
  2440. return intval($_x);
  2441. }, explode("|", $ids));
  2442. $packs = Pack::whereIn('id', $ids)->get();
  2443. }
  2444. public function handouts(Request $request) {
  2445. $handouts = Handout::orderBy('display_name')->get();
  2446. return view('app.practice-management.handouts', compact('handouts'));
  2447. }
  2448. private function callJava($request, $endPoint, $data)
  2449. {
  2450. $url = config('stag.backendUrl') . $endPoint;
  2451. $response = Http::asForm()
  2452. ->withHeaders([
  2453. 'sessionKey' => $request->cookie('sessionKey')
  2454. ])
  2455. ->post($url, $data)
  2456. ->body();
  2457. dd($response);
  2458. return $response;
  2459. }
  2460. public function genericBills(Request $request)
  2461. {
  2462. return view('app.practice-management.generic-bills');
  2463. }
  2464. public function billsUnderProcessing(Request $request)
  2465. {
  2466. $bills = Bill::where('is_cancelled', false)
  2467. ->where(function ($query) { // mcp of any client program and program OB pending
  2468. $query
  2469. ->where(function ($_query) {
  2470. $_query->where('hcp_pro_id', $this->pro->id)
  2471. ->where('hcp_expected_payment_amount', '>', 0)
  2472. ->where('has_hcp_been_paid', false)
  2473. ->where('is_signed_by_hcp', true);
  2474. })
  2475. ->orWhere(function ($_query) {
  2476. $_query->where('cm_pro_id', $this->pro->id)
  2477. ->where('cm_expected_payment_amount', '>', 0)
  2478. ->where('has_cm_been_paid', false)
  2479. ->where('is_signed_by_cm', true);
  2480. })
  2481. ->orWhere(function ($_query) {
  2482. $_query->where('rme_pro_id', $this->pro->id)
  2483. ->where('rme_expected_payment_amount', '>', 0)
  2484. ->where('has_rme_been_paid', false)
  2485. ->where('is_signed_by_rme', true);
  2486. })
  2487. ->orWhere(function ($_query) {
  2488. $_query->where('rmm_pro_id', $this->pro->id)
  2489. ->where('rmm_expected_payment_amount', '>', 0)
  2490. ->where('has_rmm_been_paid', false)
  2491. ->where('is_signed_by_rmm', true);
  2492. })
  2493. ->orWhere(function ($_query) {
  2494. $_query->where('generic_pro_id', $this->pro->id)
  2495. ->where('generic_pro_expected_payment_amount', '>', 0)
  2496. ->where('has_generic_pro_been_paid', false)
  2497. ->where('is_signed_by_generic_pro', true);
  2498. });
  2499. })
  2500. ->orderBy('created_at', 'DESC')
  2501. ->paginate();
  2502. return view('app.practice-management.bills-under-processing', compact('bills'));
  2503. }
  2504. public function careMonthReport(Request $request) {
  2505. $m = $request->input('m');
  2506. $y = $request->input('y');
  2507. if(!$m || !$y) {
  2508. $date = date('Y-m-01');
  2509. }
  2510. else {
  2511. $date = date('Y-m-d', strtotime("$m/1/$y"));
  2512. }
  2513. $pro = $this->pro;
  2514. $records = DB::select("
  2515. SELECT cm.id as care_month_id,
  2516. cm.uid as care_month_uid,
  2517. c.id as client_id,
  2518. c.uid as client_uid,
  2519. cm.number_of_days_with_remote_measurements,
  2520. cm.rm_total_time_in_seconds_by_mcp,
  2521. cm.rm_total_time_in_seconds_by_rme_pro,
  2522. cm.rm_total_time_in_seconds_by_rmm_pro,
  2523. cm.mcp_pro_id,
  2524. cm.rme_pro_id,
  2525. cm.rmm_pro_id,
  2526. (c.name_first || ' ' || c.name_last) as client_name
  2527. FROM care_month cm
  2528. JOIN client c on cm.client_id = c.id
  2529. WHERE cm.start_date = :startDate
  2530. AND (cm.mcp_pro_id = :proID OR
  2531. cm.rme_pro_id = :proID OR
  2532. cm.rmm_pro_id = :proID)
  2533. ORDER BY c.name_last, c.name_first
  2534. ",
  2535. ['startDate' => $date, 'proID' => $pro->id]
  2536. );
  2537. return view('app.practice-management.care-month-report', compact('records', 'date'));
  2538. }
  2539. public function myTeams(Request $request) {
  2540. $pro = $this->pro;
  2541. // get all teams where the authed-pro is the assistant pro
  2542. $teams = ProTeam::where('assistant_pro_id', $pro->id)
  2543. ->where('is_active', true)
  2544. ->orderBy('slug')
  2545. ->get();
  2546. return view('app.practice-management.my-teams', compact('teams'));
  2547. }
  2548. public function patientsAccountsInvites(Request $request){
  2549. $filters = $request->all();
  2550. $accountInvites = AccountInvite::select('account_invite.*')
  2551. ->join('client', 'client.id', '=', 'account_invite.for_client_id');
  2552. if($this->performer->pro->pro_type !== 'ADMIN'){
  2553. $accountInvites = $accountInvites->where('client.mcp_pro_id', $this->performer->pro->id);
  2554. }
  2555. $this->filterMultiQuery($request, $accountInvites, 'account_invite.created_at', 'date_category', 'date_value_1', 'date_value_2');
  2556. $this->filterSimpleQuery($request, $accountInvites, 'account_invite.status', 'status');
  2557. $accountInvites = $accountInvites->orderBy('created_at', 'DESC')->paginate(20);
  2558. return view('app.practice-management.patients-accounts-invites', compact('accountInvites','filters'));
  2559. }
  2560. public function clientsBdtDevices(Request $request){
  2561. $filters = $request->all();
  2562. $devices = ClientBDTDevice::select(
  2563. 'client_bdt_device.*',
  2564. 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'))
  2565. // 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'))
  2566. ->join('client', 'client.id', '=', 'client_bdt_device.client_id');
  2567. if($this->performer->pro->pro_type !== 'ADMIN'){
  2568. $devices = $devices->where('client.mcp_pro_id', $this->performer->pro->id);
  2569. }
  2570. $this->filterMultiQuery($request, $devices, 'client_bdt_device.most_recent_measurement_at', 'date_category', 'date_value_1', 'date_value_2');
  2571. // $dateKeyName = $request->get('date_category');
  2572. // $date1 = $request->get('date_value_1');
  2573. // $date2 = $request->get('date_value_2');
  2574. // $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)";
  2575. // switch($dateKeyName) {
  2576. // case 'EXACTLY':
  2577. // if($date1) {
  2578. // $devices->whereRaw($dateColumnName." = '$date1'::DATE");
  2579. // }
  2580. // break;
  2581. // case 'LESS_THAN':
  2582. // if($date1) {
  2583. // $devices->whereRaw($dateColumnName. "< '$date1'::DATE" );
  2584. // }
  2585. // break;
  2586. // case 'GREATER_THAN':
  2587. // if($date1) {
  2588. // $devices->whereRaw($dateColumnName. "> '$date1'::DATE");
  2589. // }
  2590. // break;
  2591. // case 'BETWEEN':
  2592. // if($date1 && $date2) {
  2593. // $devices
  2594. // ->whereRaw($dateColumnName. ">= '$date1'::DATE")
  2595. // ->whereRaw($dateColumnName. "<= '$date2'::DATE");
  2596. // }
  2597. // break;
  2598. // case 'NOT_BETWEEN':
  2599. // if($date2 && $date1) {
  2600. // $devices
  2601. // ->where(function ($q) use ($request, $dateColumnName, $date1, $date2) {
  2602. // $q->whereRaw($dateColumnName. "< '$date1'::DATE")
  2603. // ->orWhereRaw($dateColumnName. "> '$date2'::DATE");
  2604. // });
  2605. // }
  2606. // break;
  2607. // }
  2608. $keyName = $request->get('measurement_count_category');
  2609. $value1 = $request->get('measurement_count_value_1');
  2610. $value2 = $request->get('measurement_count_value_2');
  2611. $columnName = "(SELECT COUNT(*) FROM bdt_measurement WHERE bdt_measurement.bdt_device_id = client_bdt_device.device_id AND is_cellular_zero IS FALSE)";
  2612. switch($keyName) {
  2613. case 'EXACTLY':
  2614. if($value1) {
  2615. $devices->whereRaw($columnName.'='.$value1);
  2616. }
  2617. break;
  2618. case 'LESS_THAN':
  2619. if($value1) {
  2620. $devices->whereRaw($columnName. '<' .$value1);
  2621. }
  2622. break;
  2623. case 'GREATER_THAN':
  2624. if($value1) {
  2625. $devices->whereRaw($columnName. '>'. $value1);
  2626. }
  2627. break;
  2628. case 'BETWEEN':
  2629. if($value1 && $value2) {
  2630. $devices
  2631. ->whereRaw($columnName. '>=' . $value1)
  2632. ->whereRaw($columnName. '<=' . $value1);
  2633. }
  2634. break;
  2635. case 'NOT_BETWEEN':
  2636. if($value1 && $value2) {
  2637. $devices
  2638. ->where(function ($q) use ($request, $columnName, $value1, $value2) {
  2639. $q->whereRaw($columnName. '<'. $value1)
  2640. ->orWhereRaw($columnName. '>'.$value2);
  2641. });
  2642. }
  2643. break;
  2644. }
  2645. $status = $request->get('status');
  2646. if($status){
  2647. if($status === 'ACTIVE') $devices = $devices->where('client_bdt_device.is_active', true);
  2648. if($status === 'DEACTIVATED') $devices = $devices->where('client_bdt_device.is_active', false);
  2649. }
  2650. $devices = $devices->orderBy('num_of_measurements', 'DESC')->paginate(20);
  2651. return view('app.practice-management.clients_bdt_devices', compact('devices','filters'));
  2652. }
  2653. public function memos(Request $request){
  2654. $filters = $request->all();
  2655. $memos = ClientMemo::select('client_memo.*')
  2656. ->join('client', 'client.id', '=', 'client_memo.client_id');
  2657. if($this->performer->pro->pro_type !== 'ADMIN'){
  2658. $memos = $memos->where('client.mcp_pro_id', $this->performer->pro->id);
  2659. }
  2660. $this->filterMultiQuery($request, $memos, 'client_memo.created_at', 'date_category', 'date_value_1', 'date_value_2');
  2661. $this->filterSimpleQuery($request, $memos, 'category', 'category');
  2662. $memos = $memos->orderBy('created_at', 'DESC')->paginate(20);
  2663. return view('app.practice-management.memos', compact('memos', 'filters'));
  2664. }
  2665. public function segmentTemplates(Request $request){
  2666. $segmentTemplates = SegmentTemplate::query();
  2667. $segmentTemplates = $segmentTemplates->orderBy('created_at', 'DESC');
  2668. $responseType = $request->get('response_type');
  2669. if($responseType && $responseType == 'json'){
  2670. $segmentTemplates = $segmentTemplates->where('is_active', true)->get();
  2671. return $this->pass($segmentTemplates);
  2672. }
  2673. $segmentTemplates = $segmentTemplates->paginate(30);
  2674. return view('app.practice-management.segment-templates.index', compact('segmentTemplates'));
  2675. }
  2676. public function visitTemplates(Request $request){
  2677. $visitTemplates = VisitTemplate::query();
  2678. $visitTemplates = $visitTemplates->orderBy('created_at', 'DESC');
  2679. $responseType = $request->get('response_type');
  2680. if($responseType && $responseType == 'json'){
  2681. $visitTemplates = $visitTemplates->where('is_active', true)->get();
  2682. return $this->pass($visitTemplates);
  2683. }
  2684. $visitTemplates = $visitTemplates->paginate(30);
  2685. return view('app.practice-management.visit-templates.index', compact('visitTemplates'));
  2686. }
  2687. public function visitTemplate(Request $request, VisitTemplate $visitTemplate){
  2688. $visitTemplateSegmentTemplates = VisitTemplateSegmentTemplate::query();
  2689. $visitTemplateSegmentTemplates = $visitTemplateSegmentTemplates->where('visit_template_id', $visitTemplate->id);
  2690. $visitTemplateSegmentTemplates = $visitTemplateSegmentTemplates->orderBy('position_index', 'ASC');
  2691. $visitTemplateSegmentTemplates = $visitTemplateSegmentTemplates->paginate(50);
  2692. return view('app.practice-management.visit-templates.visit-template-segment-templates.index', compact('visitTemplate','visitTemplateSegmentTemplates'));
  2693. }
  2694. public function visitTemplateAccess(Request $request, VisitTemplate $visitTemplate){
  2695. $visitTemplateAccesses = VisitTemplateAccess::where('visit_template_id', $visitTemplate->id)->paginate(50);
  2696. return view('app.practice-management.visit-templates.visit-template-accesses.index', compact('visitTemplate','visitTemplateAccesses'));
  2697. }
  2698. public function clientCcmRmStatus(Request $request){
  2699. $filters = $request->all();
  2700. $patients = Client::whereNull('shadow_pro_id');
  2701. $pro = $this->performer()->pro;
  2702. if($pro->pro_type !== 'ADMIN') {
  2703. $patients = $patients->where('mcp_pro_id', $this->performer()->pro->id);
  2704. }
  2705. // filters
  2706. /*
  2707. array:18 [▼
  2708. "age_category" => "LESS_THAN"
  2709. "age_value_1" => "34"
  2710. "age_value_2" => null
  2711. "sex" => "M"
  2712. "bmi_category" => "BETWEEN"
  2713. "bmi_value_1" => "20"
  2714. "bmi_value_2" => "25"
  2715. "last_visit_category" => "LESS_THAN"
  2716. "last_visit_value_1" => "2021-10-14"
  2717. "last_visit_value_2" => null
  2718. "next_appointment_category" => "LESS_THAN"
  2719. "next_appointment_value_1" => "2021-10-15"
  2720. "status" => "ACTIVE"
  2721. "last_weighed_in_category" => "EXACTLY"
  2722. "last_weighed_in_value_1" => "2021-10-07"
  2723. "last_bp_category" => "BETWEEN"
  2724. "last_bp_value_1" => "2021-10-01"
  2725. "last_bp_value_2" => "2021-10-31"
  2726. ]
  2727. */
  2728. $this->filterMultiQuery($request, $patients, 'age_in_years', 'age_category', 'age_value_1', 'age_value_2');
  2729. $this->filterSimpleQuery($request, $patients, 'sex', 'sex');
  2730. $this->filterMultiQuery($request, $patients, 'usual_bmi', 'bmi_category', 'bmi_value_1', 'bmi_value_2');
  2731. $this->filterMultiQuery($request, $patients, 'most_recent_weight_at', 'last_weighed_in_category', 'last_weighed_in_value_1', 'last_weighed_in_value_2');
  2732. $this->filterMultiQuery($request, $patients, 'most_recent_bp_at', 'last_bp_category', 'last_bp_value_1', 'last_bp_value_2');
  2733. switch($request->input('status')) {
  2734. case 'ACTIVE':
  2735. $patients->where('is_active', true)->where('has_mcp_done_onboarding_visit', true);
  2736. break;
  2737. case 'AWAITING_VISIT':
  2738. $patients->where('is_active', true)->where('has_mcp_done_onboarding_visit', false);
  2739. break;
  2740. case 'INACTIVE':
  2741. $patients->where('is_active', '<>', true);
  2742. break;
  2743. }
  2744. if($request->input('is_eligible_for_cm')){
  2745. $patients->where('is_eligible_for_cm', '=', $request->input('is_eligible_for_cm'));
  2746. }
  2747. if($request->input('is_enrolled_in_cm')){
  2748. $patients->where('is_enrolled_in_cm', '=', $request->input('is_enrolled_in_cm'));
  2749. }
  2750. if($request->input('has_cm_setup_been_performed')){
  2751. $patients->where('has_cm_setup_been_performed', '=', $request->input('has_cm_setup_been_performed')=='YES'? true : false);
  2752. }
  2753. if($request->input('is_eligible_for_rm')){
  2754. $patients->where('is_eligible_for_rm', '=', $request->input('is_eligible_for_rm'));
  2755. }
  2756. if($request->input('is_enrolled_in_rm')){
  2757. $patients->where('is_enrolled_in_rm', '=', $request->input('is_enrolled_in_rm'));
  2758. }
  2759. if($request->input('has_rm_setup_been_performed')){
  2760. $patients->where('has_rm_setup_been_performed', '=', $request->input('has_rm_setup_been_performed') =='YES'? true : false);
  2761. }
  2762. $patients = $patients->orderBy('created_at', 'DESC')->paginate(20);
  2763. return view('app.admin.client-ccm-rm-status', compact('patients', 'filters'));
  2764. }
  2765. public function rmActionReport(Request $request){
  2766. $filters = $request->all();
  2767. $careMonthStartDate = $request->get('care_month_start_date');
  2768. $careMonthYear = $request->get('care_month_year');
  2769. if(!$careMonthStartDate){
  2770. $careMonthStartDate = '2022-01-01';
  2771. }
  2772. if($careMonthYear){
  2773. $careMonthStartDate = $careMonthYear . "-01";
  2774. }
  2775. $lastDateOfMonth = new DateTime(date("Y-m-t", strtotime(get_current_date())));
  2776. $today = new DateTime(get_current_date());
  2777. $diff = $lastDateOfMonth->diff($today);
  2778. $daysBetweenNowAndEndmonth = $diff->days;
  2779. $minRequiredMeasurements = 16 - $daysBetweenNowAndEndmonth -1;
  2780. $numOfMeasurements = $request->get('num_of_measurements'); //16_or_more, 12_or_more
  2781. $hasRecentVisit = $request->get('has_recent_visit'); //yes no
  2782. $hasBeenSpokenToThisMonth = $request->get('has_been_spoken_to'); //yes no
  2783. $cmQuery = CareMonth::where('start_date', $careMonthStartDate);
  2784. //remove dummies
  2785. $cmQuery = $cmQuery->whereHas('client', function($clientQuery) {
  2786. return $clientQuery->where('client_engagement_status_category','<>', 'DUMMY')
  2787. ->orWhere('client_engagement_status_category', '=', null);
  2788. });
  2789. if($numOfMeasurements){
  2790. if($numOfMeasurements == '16_or_more'){
  2791. $cmQuery = $cmQuery->where('number_of_days_with_remote_measurements', '>=', 16);
  2792. }
  2793. if($numOfMeasurements == 'min_or_more'){
  2794. $cmQuery = $cmQuery->where('number_of_days_with_remote_measurements', '>=', $minRequiredMeasurements)
  2795. ->where('number_of_days_with_remote_measurements', '<', 16);
  2796. }
  2797. if($numOfMeasurements == 'less_than_min'){
  2798. $cmQuery = $cmQuery->where('number_of_days_with_remote_measurements', '<', $minRequiredMeasurements);
  2799. }
  2800. }
  2801. if($hasRecentVisit){
  2802. if($hasRecentVisit == 'YES'){
  2803. $cmQuery = $cmQuery->whereHas('client', function($clientQuery) {
  2804. return $clientQuery->whereRaw("most_recent_completed_mcp_note_date::DATE >= ((NOW() - interval '90 days')::DATE)");
  2805. });
  2806. }else{
  2807. $cmQuery = $cmQuery->whereHas('client', function($clientQuery) {
  2808. return $clientQuery->whereRaw("most_recent_completed_mcp_note_date::DATE < ((NOW() - interval '90 days')::DATE)");
  2809. });
  2810. }
  2811. }
  2812. if($hasBeenSpokenToThisMonth){
  2813. if($hasBeenSpokenToThisMonth == 'YES'){
  2814. $cmQuery = $cmQuery->where('has_anyone_interacted_with_client_about_rm_outside_note', '=', true);
  2815. }else{
  2816. $cmQuery = $cmQuery->where('has_anyone_interacted_with_client_about_rm_outside_note', '=', false);
  2817. }
  2818. }
  2819. $claimingClosed = $request->get('claiming_closed');
  2820. if($claimingClosed){
  2821. if($claimingClosed === 'YES') $cmQuery = $cmQuery->where('is_claim_closed', true);
  2822. if($claimingClosed === 'NO') $cmQuery = $cmQuery->where('is_claim_closed', false);
  2823. }
  2824. $cmQuery = $cmQuery->orderBy('start_date', 'DESC')->orderBy('client_id', 'ASC');
  2825. $rows =$cmQuery->paginate(15);
  2826. return view('app.practice-management.rm-action-report', compact('rows', 'filters', 'minRequiredMeasurements'));
  2827. }
  2828. public function myFlyers(Request $request){
  2829. $pro = $this->performer->pro;
  2830. $slug = $pro->slug ?? $pro->uid;
  2831. $url = config('app.stagfe6_url') . '/flyers/json-list?slug=' . $slug;
  2832. $arrContextOptions=array(
  2833. "ssl"=>array(
  2834. "verify_peer"=>false,
  2835. "verify_peer_name"=>false,
  2836. ),
  2837. );
  2838. $response = @file_get_contents($url, false, stream_context_create($arrContextOptions));
  2839. $response = @json_decode($response);
  2840. $flyerTemplates = [];
  2841. if(isset($response->data)){
  2842. $flyerTemplates = $response->data;
  2843. }
  2844. return view('app.my-flyers', compact('pro','flyerTemplates'));
  2845. }
  2846. }