PracticeManagementController.php 117 KB

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