PracticeManagementController.php 138 KB

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