PracticeManagementController.php 117 KB

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