PracticeManagementController.php 128 KB

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