PracticeManagementController.php 129 KB

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