PracticeManagementController.php 116 KB

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