PracticeManagementController.php 126 KB

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