PracticeManagementController.php 121 KB

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