PracticeManagementController.php 116 KB

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