PracticeManagementController.php 130 KB

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