PracticeManagementController.php 126 KB

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