PracticeManagementController.php 115 KB

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