PracticeManagementController.php 113 KB

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