PracticeManagementController.php 121 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764
  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.cell_number,
  908. client.is_assigned_cellular_bp_device,
  909. client.is_assigned_cellular_weight_scale_device,
  910. care_month.uid as care_month_uid,
  911. care_month.id as care_month_id,
  912. care_month.start_date,
  913. care_month.rm_total_time_in_seconds_by_mcp,
  914. care_month.rm_total_time_in_seconds_by_rmm_pro,
  915. care_month.number_of_days_with_remote_measurements,
  916. care_month.has_mcp_interacted_with_client_about_rm,
  917. care_month.rm_num_measurements_not_stamped_by_mcp,
  918. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  919. care_month.rm_num_measurements_not_stamped_by_rmm,
  920. care_month.rm_num_measurements_not_stamped_by_rme,
  921. care_month.mcp_pro_id as care_month_mcp_pro_id,
  922. care_month.rmm_pro_id as care_month_rmm_pro_id,
  923. client.mcp_pro_id,
  924. client.default_na_pro_id,
  925. client.rmm_pro_id,
  926. client.rme_pro_id,
  927. client.cell_number,
  928. client.most_recent_cellular_bp_dbp_mm_hg,
  929. client.most_recent_cellular_bp_sbp_mm_hg,
  930. client.most_recent_cellular_bp_measurement_at,
  931. client.most_recent_cellular_weight_value,
  932. client.most_recent_cellular_weight_measurement_at
  933. FROM care_month join client on care_month.client_id = client.id
  934. WHERE
  935. (care_month.mcp_pro_id = {$performer->pro->id} OR care_month.rmm_pro_id = {$performer->pro->id})
  936. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  937. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  938. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '') . "
  939. $orderBy
  940. ";
  941. $patients = DB::select($query);
  942. $timestamp = strtotime(date('Y-m-d'));
  943. $daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
  944. return view('app.practice-management.remote-monitoring', compact('patients', 'daysRemaining', 'careMonthStart'));
  945. }
  946. public function rpm_work_matrix(Request $request) {
  947. // get the patient having most recent unstamped measurement
  948. $performer = $this->performer();
  949. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  950. $careMonthStart = date($ym . '-01');
  951. $patient = null;
  952. $careMonth = null;
  953. if($request->input('patientUid') && $request->input('careMonthUid')) {
  954. $patient = Client::where('uid', $request->input('patientUid'))->first();
  955. $careMonth = CareMonth::where('uid', $request->input('careMonthUid'))->first();
  956. }
  957. if(!$patient && !$careMonth) {
  958. $query = "
  959. SELECT client.name_first, client.name_last,
  960. (client.name_first || ' ' || client.name_last) as client_name,
  961. client.uid as client_uid,
  962. client.dob,
  963. client.is_enrolled_in_rm,
  964. client.most_recent_completed_mcp_note_date,
  965. care_month.uid as care_month_uid,
  966. care_month.id as care_month_id,
  967. care_month.start_date,
  968. care_month.rm_total_time_in_seconds_by_mcp,
  969. care_month.number_of_days_with_remote_measurements,
  970. care_month.rm_num_measurements_not_stamped_by_mcp,
  971. care_month.rm_num_measurements_not_stamped_by_rmm,
  972. client.mcp_pro_id,
  973. client.default_na_pro_id,
  974. client.rmm_pro_id,
  975. client.rme_pro_id,
  976. client.cell_number,
  977. client.most_recent_cellular_bp_dbp_mm_hg,
  978. client.most_recent_cellular_bp_sbp_mm_hg,
  979. client.most_recent_cellular_bp_measurement_at,
  980. client.most_recent_cellular_weight_value,
  981. client.most_recent_cellular_weight_measurement_at,
  982. GREATEST(client.most_recent_cellular_bp_measurement_at, client.most_recent_cellular_weight_measurement_at) as latest_measurement_at
  983. FROM care_month join client on care_month.client_id = client.id
  984. WHERE
  985. (
  986. (care_month.mcp_pro_id = {$performer->pro->id} AND care_month.rm_num_measurements_not_stamped_by_mcp > 0) OR
  987. (care_month.rmm_pro_id = {$performer->pro->id} AND care_month.rm_num_measurements_not_stamped_by_rmm > 0)
  988. )
  989. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  990. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  991. ORDER BY latest_measurement_at DESC
  992. LIMIT 1
  993. ";
  994. $patients = DB::select($query);
  995. if (count($patients)) {
  996. $patient = Client::where('uid', $patients[0]->client_uid)->first();
  997. $careMonth = CareMonth::where('uid', $patients[0]->care_month_uid)->first();
  998. }
  999. }
  1000. return view('app.practice-management.rpm_work_matrix', compact('patient', 'careMonth'));
  1001. }
  1002. public function remoteMonitoringCount(Request $request) {
  1003. $performer = $this->performer();
  1004. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1005. $careMonthStart = date($ym . '-01');
  1006. $rc = $request->input('rc') ?: 1;
  1007. $rc2 = $request->input('rc2') ?: 2;
  1008. $conditions = $this->rpmConditions($performer, $rc, $rc2);
  1009. $count = DB::select(
  1010. DB::raw(
  1011. "
  1012. SELECT count(*)
  1013. FROM care_month join client on care_month.client_id = client.id
  1014. WHERE
  1015. client.mcp_pro_id = {$performer->pro->id}
  1016. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1017. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1018. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '')
  1019. )
  1020. );
  1021. return $count[0]->count;
  1022. }
  1023. public function remoteMonitoringAdmin(Request $request) {
  1024. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1025. $careMonthStart = date($ym . '-01');
  1026. $rc = $request->input('rc') ?: 1;
  1027. $rc2 = $request->input('rc2') ?: 2;
  1028. $conditions = $this->rpmConditionsAdmin($this->performer(), $rc, $rc2);
  1029. $patients = DB::select(
  1030. DB::raw(
  1031. "
  1032. SELECT client.name_first,
  1033. client.name_last,
  1034. client.uid as client_uid,
  1035. client.dob,
  1036. client.is_enrolled_in_rm,
  1037. client.most_recent_completed_mcp_note_date,
  1038. care_month.uid as care_month_uid,
  1039. care_month.id as care_month_id,
  1040. care_month.start_date,
  1041. care_month.rm_total_time_in_seconds_by_mcp,
  1042. care_month.number_of_days_with_remote_measurements,
  1043. care_month.has_anyone_interacted_with_client_about_rm_outside_note,
  1044. care_month.rm_num_measurements_not_stamped_by_mcp,
  1045. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  1046. care_month.rm_num_measurements_not_stamped_by_rmm,
  1047. care_month.rm_num_measurements_not_stamped_by_rme,
  1048. client.mcp_pro_id,
  1049. client.default_na_pro_id,
  1050. client.rmm_pro_id,
  1051. client.rme_pro_id,
  1052. client.cell_number,
  1053. client.most_recent_cellular_bp_dbp_mm_hg,
  1054. client.most_recent_cellular_bp_sbp_mm_hg,
  1055. client.most_recent_cellular_bp_measurement_at,
  1056. client.most_recent_cellular_weight_value,
  1057. client.most_recent_cellular_weight_measurement_at
  1058. FROM care_month join client on care_month.client_id = client.id
  1059. WHERE
  1060. client.shadow_pro_id is null AND client.is_enrolled_in_rm = 'YES'
  1061. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1062. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1063. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '') . "
  1064. ORDER BY care_month.number_of_days_with_remote_measurements DESC NULLS LAST, client.name_first, client.name_last
  1065. "
  1066. )
  1067. );
  1068. $timestamp = strtotime(date('Y-m-d'));
  1069. $daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
  1070. return view('app.practice-management.remote-monitoring-admin', compact('patients', 'daysRemaining', 'careMonthStart'));
  1071. }
  1072. public function remoteMonitoringAdminCount(Request $request) {
  1073. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  1074. $careMonthStart = date($ym . '-01');
  1075. $rc = $request->input('rc') ?: 1;
  1076. $rc2 = $request->input('rc2') ?: 2;
  1077. $conditions = $this->rpmConditionsAdmin($this->performer(), $rc, $rc2);
  1078. $count = DB::select(
  1079. DB::raw(
  1080. "
  1081. SELECT count(*)
  1082. FROM care_month join client on care_month.client_id = client.id
  1083. WHERE
  1084. client.shadow_pro_id is null AND client.is_enrolled_in_rm = 'YES'
  1085. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  1086. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  1087. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '')
  1088. )
  1089. );
  1090. return $count[0]->count;
  1091. }
  1092. private function rpmConditions($performer, $rc, $rc2) {
  1093. $conditions = [];
  1094. $c_isMCP = "client.mcp_pro_id = {$performer->pro->id}";
  1095. $c_enrolledInRPM = "client.is_enrolled_in_rm = 'YES'";
  1096. $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";
  1097. $c_lastVisitBefore90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) > 90";
  1098. $c_lastVisitWithin90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) <= 90";
  1099. $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)";
  1100. $c_spokenToThisMonth = "care_month.has_anyone_interacted_with_client_about_rm_outside_note = TRUE";
  1101. $c_hasUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp > 0";
  1102. $c_hasNoUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp = 0";
  1103. $c_lt16MeasurementDays = "care_month.number_of_days_with_remote_measurements < 16";
  1104. $c_gte16MeasurementDays = "care_month.number_of_days_with_remote_measurements >= 16";
  1105. $c_subscribedToSMS = "client.send_sms_on_bdt_measurement = TRUE";
  1106. $c_deviceUsed = "(client.most_recent_cellular_bp_measurement_at IS NOT NULL OR most_recent_cellular_weight_measurement_at IS NOT NULL)";
  1107. $c_lt20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp < 1200";
  1108. $c_gte20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp >= 1200";
  1109. switch ($rc) {
  1110. case 1:
  1111. $conditions = [$c_isMCP];
  1112. break;
  1113. case 2:
  1114. $conditions = [$c_isMCP, $c_enrolledInRPM];
  1115. break;
  1116. case 3:
  1117. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice];
  1118. break;
  1119. case 4:
  1120. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, ($rc2 == 1 ? $c_lastVisitBefore90Days : $c_lastVisitWithin90Days)];
  1121. break;
  1122. case 5:
  1123. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, ($rc2 == 1 ? $c_notSpokenToThisMonth : $c_spokenToThisMonth)];
  1124. break;
  1125. case 6:
  1126. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_hasUnstamped : $c_hasNoUnstamped)];
  1127. break;
  1128. case 7:
  1129. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_lt16MeasurementDays : $c_gte16MeasurementDays)];
  1130. break;
  1131. case 10:
  1132. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, $c_gte16MeasurementDays, ($rc2 == 1 ? $c_lt20BillingMinutes : $c_gte20BillingMinutes)];
  1133. break;
  1134. case 8:
  1135. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_subscribedToSMS];
  1136. break;
  1137. case 9:
  1138. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_deviceUsed];
  1139. break;
  1140. }
  1141. return $conditions;
  1142. }
  1143. private function rpmConditionsAdmin($performer, $rc, $rc2) {
  1144. $conditions = [];
  1145. $c_enrolledInRPM = "client.is_enrolled_in_rm = 'YES'";
  1146. $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";
  1147. $c_lastVisitBefore90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) > 90";
  1148. $c_lastVisitWithin90Days = "DATE_PART('day', care_month.start_date::timestamp - client.most_recent_completed_mcp_note_date::timestamp) <= 90";
  1149. $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)";
  1150. $c_spokenToThisMonth = "care_month.has_anyone_interacted_with_client_about_rm_outside_note = TRUE";
  1151. $c_hasUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp > 0";
  1152. $c_hasNoUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp = 0";
  1153. $c_lt16MeasurementDays = "care_month.number_of_days_with_remote_measurements < 16";
  1154. $c_gte16MeasurementDays = "care_month.number_of_days_with_remote_measurements >= 16";
  1155. $c_subscribedToSMS = "client.send_sms_on_bdt_measurement = TRUE";
  1156. $c_deviceUsed = "(client.most_recent_cellular_bp_measurement_at IS NOT NULL OR most_recent_cellular_weight_measurement_at IS NOT NULL)";
  1157. $c_lt20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp < 1200";
  1158. $c_gte20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp >= 1200";
  1159. switch ($rc) {
  1160. case 2:
  1161. $conditions = [$c_enrolledInRPM];
  1162. break;
  1163. case 3:
  1164. $conditions = [$c_enrolledInRPM, $c_hasDevice];
  1165. break;
  1166. case 4:
  1167. $conditions = [$c_enrolledInRPM, $c_hasDevice, ($rc2 == 1 ? $c_lastVisitBefore90Days : $c_lastVisitWithin90Days)];
  1168. break;
  1169. case 5:
  1170. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, ($rc2 == 1 ? $c_notSpokenToThisMonth : $c_spokenToThisMonth)];
  1171. break;
  1172. case 6:
  1173. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_hasUnstamped : $c_hasNoUnstamped)];
  1174. break;
  1175. case 7:
  1176. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_lt16MeasurementDays : $c_gte16MeasurementDays)];
  1177. break;
  1178. case 10:
  1179. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, $c_gte16MeasurementDays, ($rc2 == 1 ? $c_lt20BillingMinutes : $c_gte20BillingMinutes)];
  1180. break;
  1181. case 8:
  1182. $conditions = [$c_enrolledInRPM, $c_subscribedToSMS];
  1183. break;
  1184. case 9:
  1185. $conditions = [$c_enrolledInRPM, $c_deviceUsed];
  1186. break;
  1187. }
  1188. return $conditions;
  1189. }
  1190. public function remoteMonitoringMeasurements(Request $request, CareMonth $careMonth) {
  1191. $performer = $this->performer();
  1192. $measurements = DB::select(
  1193. DB::raw(
  1194. "
  1195. SELECT measurement.label,
  1196. measurement.ts,
  1197. measurement.effective_date,
  1198. measurement.sbp_mm_hg,
  1199. measurement.dbp_mm_hg,
  1200. measurement.value_pulse,
  1201. measurement.value_irregular,
  1202. measurement.numeric_value,
  1203. measurement.value,
  1204. measurement.uid,
  1205. client.name_first,
  1206. client.name_last,
  1207. client.mcp_pro_id,
  1208. client.default_na_pro_id,
  1209. client.rmm_pro_id,
  1210. client.rme_pro_id
  1211. FROM measurement RIGHT JOIN client on measurement.client_id = client.id
  1212. WHERE
  1213. client.id = {$careMonth->client_id}
  1214. AND measurement.label IS NOT NULL
  1215. AND measurement.label NOT IN ('SBP', 'DBP')
  1216. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  1217. AND measurement.is_removed IS FALSE
  1218. AND measurement.client_bdt_measurement_id IS NOT NULL
  1219. AND measurement.care_month_id = {$careMonth->id}
  1220. AND (
  1221. (client.mcp_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_mcp IS FALSE)
  1222. OR (client.rmm_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_rmm IS FALSE)
  1223. OR (client.rme_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_rme IS FALSE)
  1224. OR (client.default_na_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_non_hcp IS FALSE)
  1225. )
  1226. ORDER BY ts DESC
  1227. "
  1228. )
  1229. );
  1230. return view('app.practice-management.remote-monitoring-measurements', compact('careMonth', 'measurements'));
  1231. }
  1232. public function billMatrix(Request $request)
  1233. {
  1234. $bClients = [];
  1235. $bHCPPros = [];
  1236. $bNAPros = [];
  1237. $filters = [];
  1238. $filters['client'] = $request->input('client');
  1239. $filters['service'] = $request->input('service');
  1240. $filters['hcp'] = $request->input('hcp');
  1241. $filters['hcp_paid'] = $request->input('hcp_paid');
  1242. $filters['expected_op'] = $request->input('expected_op');
  1243. $filters['expected_value'] = $request->input('expected_value');
  1244. $filters['paid_op'] = $request->input('paid_op');
  1245. $filters['paid_value'] = $request->input('paid_value');
  1246. $filters['bal_post_date_op'] = $request->input('bal_post_date_op');
  1247. $filters['bal_post_date_value'] = $request->input('bal_post_date_value');
  1248. $filters['hcp_sign'] = $request->input('hcp_sign');
  1249. $filters['verified'] = $request->input('verified');
  1250. $filters['cancelled'] = $request->input('cancelled');
  1251. $bills = Bill::orderBy('effective_date')->paginate();
  1252. return view('app.practice-management.bill-matrix', compact('bills', 'bClients', 'bHCPPros', 'filters'));
  1253. }
  1254. public function medicarePartBClaims(Request $request)
  1255. {
  1256. $medicarePartBOnly = $request->get("medicare_part_b");
  1257. $allClaims = Claim::where('was_submitted', false)->orWhere('was_submitted', null)->orderBy('created_at', 'desc')->get();
  1258. //Only medicare claims
  1259. $claims = [];
  1260. foreach ($allClaims as $claim) {
  1261. if ($claim->client != null && $claim->client->getPrimaryCoverageStatus() == 'YES' && !$claim->edi) {
  1262. $claims[] = $claim;
  1263. }
  1264. }
  1265. $claimEDIs = ClaimEDI::all();
  1266. return view('app.practice-management.medicare-partb-claims', compact('claims', 'claimEDIs'));
  1267. }
  1268. // Generate PDF
  1269. public function downloadClaims()
  1270. {
  1271. $claims = Claim::where('was_submitted', false)->orWhere('was_submitted', null)->orderBy('created_at', 'desc')->limit(100)->get();
  1272. view()->share('claims', $claims);
  1273. $pdf = PDF::loadView('app.practice-management.claims-pdf', $claims);
  1274. return $pdf->download('pdf_file.pdf');
  1275. }
  1276. public function tickets(Request $request, $proUid = null)
  1277. {
  1278. $tickets = Ticket::orderBy('created_at', 'desc')->paginate();
  1279. return view('app.practice-management.tickets', compact('tickets'));
  1280. }
  1281. public function supplyOrders(Request $request)
  1282. {
  1283. // counts
  1284. $counts = $this->getSupplyOrderCounts();
  1285. // so clients
  1286. $soClientIDs = DB::table('supply_order')->select('client_id')->distinct()->get()->toArray();
  1287. $soClientIDs = array_map(function ($_x) {
  1288. return $_x->client_id;
  1289. }, $soClientIDs);
  1290. $soClients = Client::whereIn('id', $soClientIDs)->get();
  1291. // so products
  1292. $soProductIDs = DB::table('supply_order')->select('product_id')->distinct()->get()->toArray();
  1293. $soProductIDs = array_map(function ($_x) {
  1294. return $_x->product_id;
  1295. }, $soProductIDs);
  1296. $soProducts = Product::whereIn('id', $soProductIDs)->get();
  1297. $filters = [];
  1298. $filters['client'] = $request->input('client');
  1299. $filters['product'] = $request->input('product');
  1300. $filters['reason'] = $request->input('reason');
  1301. $filters['cu_memo'] = $request->input('cu_memo');
  1302. $filters['pro_sign'] = $request->input('pro_sign');
  1303. $filters['client_sign'] = $request->input('client_sign');
  1304. $filters['shipment'] = $request->input('shipment');
  1305. $filters['lot_number'] = $request->input('lot_number');
  1306. $filters['imei'] = $request->input('imei');
  1307. $filters['cancelled'] = $request->input('cancelled');
  1308. $supplyOrders = SupplyOrder::where('id', '>', 0);
  1309. // apply filters
  1310. if ($filters['client']) $supplyOrders->where('client_id', $filters['client']);
  1311. if ($filters['product']) $supplyOrders->where('product_id', $filters['product']);
  1312. if ($filters['reason']) $supplyOrders->where('reason', 'ILIKE', '%' . $filters['reason'] . '%');
  1313. if ($filters['cu_memo']) $supplyOrders->where('cu_memo', 'ILIKE', '%' . $filters['cu_memo'] . '%');
  1314. if ($filters['pro_sign']) $supplyOrders->where('is_signed_by_pro', ($filters['pro_sign'] === 'signed'));
  1315. if ($filters['client_sign']) {
  1316. if ($filters['client_sign'] === 'signed')
  1317. $supplyOrders->where('is_signed_by_client', true);
  1318. elseif ($filters['client_sign'] === 'waived')
  1319. $supplyOrders->where('is_client_signature_waived', true);
  1320. else
  1321. $supplyOrders->where('is_client_signature_waived', false)->where('is_signed_by_client', false);
  1322. }
  1323. if ($filters['shipment']) {
  1324. if ($filters['shipment'] === 'not_cleared_for_shipment')
  1325. $supplyOrders->whereNull('shipment_id')->where('is_cleared_for_shipment', false);
  1326. elseif ($filters['shipment'] === 'cleared_for_shipment')
  1327. $supplyOrders->whereNull('shipment_id')->where('is_cleared_for_shipment', true);
  1328. else
  1329. $supplyOrders
  1330. ->whereNotNull('shipment_id')
  1331. ->whereRaw('(SELECT status FROM shipment WHERE id = shipment_id LIMIT 1) = ?', [$filters['shipment']]);
  1332. }
  1333. if ($filters['lot_number']) $supplyOrders->where('lot_number', 'ILIKE', '%' . $filters['lot_number'] . '%');
  1334. if ($filters['imei']) $supplyOrders->where('imei', 'ILIKE', '%' . $filters['imei'] . '%');
  1335. if ($filters['cancelled']) $supplyOrders->where('is_cancelled', ($filters['cancelled'] === 'cancelled'));
  1336. $supplyOrders = $supplyOrders->orderBy('created_at', 'desc')->paginate();
  1337. return view('app.practice-management.supply-orders',
  1338. compact('supplyOrders', 'filters',
  1339. 'soClients', 'soProducts', 'counts'
  1340. )
  1341. );
  1342. }
  1343. public function shipments(Request $request, $filter = null)
  1344. {
  1345. // counts
  1346. $counts = $this->getShipmentCounts();
  1347. // so clients
  1348. $shClientIDs = DB::table('shipment')->select('client_id')->distinct()->get()->toArray();
  1349. $shClientIDs = array_map(function ($_x) {
  1350. return $_x->client_id;
  1351. }, $shClientIDs);
  1352. $shClients = Client::whereIn('id', $shClientIDs)->get();
  1353. $shipments = Shipment::where('id', '>', 0);
  1354. $filters = [];
  1355. $filters['client'] = $request->input('client');
  1356. $filters['courier'] = $request->input('courier');
  1357. $filters['tracking_num'] = $request->input('tracking_num');
  1358. $filters['label'] = $request->input('label');
  1359. $filters['status'] = $request->input('status');
  1360. $filters['cancelled'] = $request->input('cancelled');
  1361. if ($filters['client']) $shipments->where('client_id', $filters['client']);
  1362. if ($filters['courier']) $shipments->where('courier', 'ILIKE', '%' . $filters['courier'] . '%');
  1363. if ($filters['tracking_num']) $shipments->where('tracking_number', 'ILIKE', '%' . $filters['tracking_num'] . '%');
  1364. if ($filters['label']) {
  1365. if ($filters['label'] === 'yes')
  1366. $shipments->whereNotNull('label_system_file_id');
  1367. else
  1368. $shipments->whereNull('label_system_file_id');
  1369. }
  1370. if ($filters['status']) $shipments->where('status', $filters['status']);
  1371. if ($filters['cancelled']) $shipments->where('is_cancelled', ($filters['cancelled'] === 'cancelled'));
  1372. $shipments = $shipments->orderBy('created_at', 'desc')->paginate();
  1373. return view('app.practice-management.shipments', compact('shipments', 'filters', 'shClients', 'counts'));
  1374. }
  1375. public function cellularMeasurements(Request $request)
  1376. {
  1377. $measurements = Measurement::orderBy('ts', 'desc')->whereNotNull('ts')->paginate();
  1378. return view('app.practice-management.cellular-measurements', compact('measurements'));
  1379. }
  1380. // v2 supply-orders & shipments management (wh)
  1381. public function supplyOrdersReadyToShip(Request $request)
  1382. {
  1383. $counts = $this->getSupplyOrderCounts();
  1384. $supplyOrders = SupplyOrder
  1385. ::where('is_cleared_for_shipment', true)
  1386. ->where('is_cancelled', false)
  1387. ->whereNull('shipment_id')
  1388. ->join('client', 'client.id', '=', 'supply_order.client_id')
  1389. ->orderBy('client.name_last', 'ASC')
  1390. ->orderBy('client.name_first', 'ASC')
  1391. ->orderBy('supply_order.client_id', 'ASC')
  1392. ->orderBy('supply_order.mailing_address_full', 'ASC')
  1393. ->orderBy('supply_order.created_at', 'ASC')
  1394. ->select('supply_order.*')
  1395. ->paginate();
  1396. return view('app.practice-management.supply-orders-ready-to-ship', compact('supplyOrders', 'counts'));
  1397. }
  1398. public function supplyOrdersShipmentUnderway(Request $request)
  1399. {
  1400. $counts = $this->getSupplyOrderCounts();
  1401. $supplyOrders = SupplyOrder
  1402. ::where('is_cancelled', false)
  1403. ->whereNotNull('shipment_id')
  1404. ->orderBy('client_id', 'ASC')
  1405. ->orderBy('mailing_address_full', 'ASC')
  1406. ->orderBy('created_at', 'ASC')
  1407. ->paginate();
  1408. return view('app.practice-management.supply-orders-shipment-underway', compact('supplyOrders', 'counts'));
  1409. }
  1410. public function supplyOrdersHanging(Request $request)
  1411. {
  1412. $counts = $this->getSupplyOrderCounts();
  1413. $supplyOrders = SupplyOrder
  1414. ::select('supply_order.*')
  1415. ->leftJoin('shipment', function($join) {
  1416. $join->on('supply_order.shipment_id', '=', 'shipment.id');
  1417. })
  1418. ->where('shipment.status', 'CANCELLED')
  1419. ->where('supply_order.is_cancelled', false)
  1420. ->orderBy('supply_order.client_id', 'ASC')
  1421. ->orderBy('supply_order.mailing_address_full', 'ASC')
  1422. ->orderBy('supply_order.created_at', 'ASC')
  1423. ->paginate();
  1424. return view('app.practice-management.supply-orders-hanging', compact('supplyOrders', 'counts'));
  1425. }
  1426. public function supplyOrdersCancelledButUnacknowledged(Request $request)
  1427. {
  1428. $supplyOrders = SupplyOrder::where('signed_by_pro_id', $this->performer()->pro->id)
  1429. ->where('is_cancelled', true)
  1430. ->where('is_cancellation_acknowledged', false)
  1431. ->orderBy('created_at', 'desc')
  1432. ->paginate();
  1433. return view('app.practice-management.supply-orders-cancelled-but-unacknowledged', compact('supplyOrders'));
  1434. }
  1435. public function supplyOrdersUnsigned(Request $request)
  1436. {
  1437. $supplyOrders = SupplyOrder
  1438. ::where('is_cancelled', false)
  1439. ->where('is_signed_by_pro', false)
  1440. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$this->performer()->pro->id])
  1441. ->orderBy('created_at', 'desc')
  1442. ->paginate();
  1443. return view('app.practice-management.supply-orders-unsigned', compact('supplyOrders'));
  1444. }
  1445. private function getSupplyOrderCounts()
  1446. {
  1447. return [
  1448. "supplyOrders" => SupplyOrder::count(),
  1449. "supplyOrdersReadyToShip" => SupplyOrder
  1450. ::where('is_cleared_for_shipment', true)
  1451. ->where('is_cancelled', false)
  1452. ->whereNull('shipment_id')->count(),
  1453. "supplyOrdersShipmentUnderway" => SupplyOrder
  1454. ::where('is_cancelled', false)
  1455. ->whereNotNull('shipment_id')->count(),
  1456. "supplyOrdersHanging" => SupplyOrder
  1457. ::leftJoin('shipment', function($join) {
  1458. $join->on('supply_order.shipment_id', '=', 'shipment.id');
  1459. })
  1460. ->where('shipment.status', 'CANCELLED')
  1461. ->where('supply_order.is_cancelled', false)
  1462. ->count(),
  1463. ];
  1464. }
  1465. public function shipmentsReadyToPrint(Request $request)
  1466. {
  1467. $counts = $this->getShipmentCounts();
  1468. $shipments = Shipment
  1469. ::where('is_cancelled', false)
  1470. ->where('status', 'CREATED')
  1471. ->orderBy('created_at', 'ASC')
  1472. ->paginate();
  1473. return view('app.practice-management.shipments-ready-to-print', compact('shipments', 'counts'));
  1474. }
  1475. public function shipmentsShipmentUnderway(Request $request)
  1476. {
  1477. $counts = $this->getShipmentCounts();
  1478. $shipments = Shipment
  1479. ::where('is_cancelled', false)
  1480. ->where('status', 'PRINTED')
  1481. ->orderBy('created_at', 'ASC')
  1482. ->paginate();
  1483. return view('app.practice-management.shipments-waiting-for-picker', compact('shipments', 'counts'));
  1484. }
  1485. private function getShipmentCounts()
  1486. {
  1487. return [
  1488. "shipments" => Shipment::count(),
  1489. "shipmentsReadyToPrint" => Shipment
  1490. ::where('is_cancelled', false)
  1491. ->where('status', 'CREATED')
  1492. ->count(),
  1493. "shipmentsWaitingForPicker" => Shipment
  1494. ::where('is_cancelled', false)
  1495. ->where('status', 'PRINTED')
  1496. ->count()
  1497. ];
  1498. }
  1499. public function shipment(Request $request, Shipment $shipment)
  1500. {
  1501. return view('app.practice-management.shipment', compact('shipment'));
  1502. }
  1503. public function shipmentsMultiPrint(Request $request, $ids)
  1504. {
  1505. $ids = array_map(function ($_x) {
  1506. return intval($_x);
  1507. }, explode("|", $ids));
  1508. $shipments = Shipment::whereIn('id', $ids)->get();
  1509. return view('app.practice-management.shipments-multi-print', compact('shipments'));
  1510. }
  1511. public function patientClaimSummary(Request $request, $proUid = null)
  1512. {
  1513. $notesTotal = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE"))[0]->count;
  1514. $notesTotalWithBillingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE AND is_bill_closed IS TRUE"))[0]->count;
  1515. $notesTotalWithClaimingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE AND is_claim_closed IS TRUE"))[0]->count;
  1516. $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;
  1517. $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;
  1518. $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;
  1519. $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;
  1520. $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;
  1521. $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;
  1522. $performerPro = $this->performer->pro;
  1523. $allPros = [];
  1524. if ($performerPro->pro_type == 'ADMIN') {
  1525. $allPros = Pro::all();
  1526. } else {
  1527. $allPros = [$performerPro];
  1528. }
  1529. //Patient | MCP | # Notes Total | # Notes without Billing Closed | # Notes without Claiming Closed
  1530. $patientsQuery = Client::where('is_dummy', '=', false)
  1531. ->whereNull('shadow_pro_id')
  1532. ->select('id', 'uid', 'name_first', 'name_last', 'mcp_pro_id', 'is_part_b_primary', 'medicare_advantage_plan',
  1533. DB::raw("(SELECT name_first||' '||name_last FROM pro where pro.id = client.mcp_pro_id) as mcp"),
  1534. DB::raw("(SELECT uid FROM pro where pro.id = mcp_pro_id) as mcp_pro_uid"),
  1535. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id) as notes_total"),
  1536. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id AND is_bill_closed IS NOT true) as notes_without_billing_closed"),
  1537. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id AND is_claim_closed IS NOT true) as notes_without_claiming_closed")
  1538. )->orderBy('is_part_b_primary', 'asc')->orderBy('notes_without_claiming_closed', 'desc');
  1539. if ($proUid) {
  1540. $mcpPro = Pro::where('uid', $proUid)->first();
  1541. if ($mcpPro) {
  1542. $patientsQuery->where('client.mcp_pro_id', '=', $mcpPro->id);
  1543. }
  1544. }
  1545. $patientsQuery->whereRaw('(SELECT COUNT(*) FROM note where note.client_id = client.id) > 0');
  1546. $patientsQuery->orderBy('notes_total', 'DESC');
  1547. $patients = $patientsQuery->paginate(50);
  1548. $data = [
  1549. 'patients' => $patients,
  1550. 'proUid' => $proUid,
  1551. 'allPros' => $allPros,
  1552. 'notesTotal' => $notesTotal,
  1553. 'notesTotalWithBillingClosed' => $notesTotalWithBillingClosed,
  1554. 'notesTotalWithClaimingClosed' => $notesTotalWithClaimingClosed,
  1555. 'notes3rdPartyTotal' => $notes3rdPartyTotal,
  1556. 'notes3rdPartyTotalWithBillingClosed' => $notes3rdPartyTotalWithBillingClosed,
  1557. 'notes3rdPartyTotalWithClaimingClosed' => $notes3rdPartyTotalWithClaimingClosed,
  1558. 'patientsTotal' => $patientsTotal,
  1559. 'patientsTotalWithBillingClosed' => $patientsTotalWithBillingClosed,
  1560. 'patientsTotalWithClaimingClosed' => $patientsTotalWithClaimingClosed
  1561. ];
  1562. return view('app.practice-management.patient-claim-summary', $data);
  1563. }
  1564. public function claims(Request $request){
  1565. $status = $request->get('status');
  1566. $claims = [];
  1567. if(!$status){
  1568. $claims = Claim::orderBy('created_at', 'DESC')->paginate();
  1569. }else{
  1570. $claims = Claim::where('status', $status)->orderBy('created_at', 'DESC')->paginate();
  1571. }
  1572. return view('app.practice-management.claims', compact('claims', 'status'));
  1573. }
  1574. public function processClaims(Request $request) {
  1575. $status = '';
  1576. $q = $request->input('q') ? $request->input('q') : '';
  1577. $from = $request->input('from') ? $request->input('from') : '1900-01-01';
  1578. $to = $request->input('to') ? $request->input('to') : '2100-01-01';
  1579. $params = [
  1580. 'q' => '%' . $q . '%',
  1581. 'from' => $from,
  1582. 'to' => $to
  1583. ];
  1584. $hcpPro = $request->input('hcp') ? Pro::where('uid', $request->input('hcp'))->first() : null;
  1585. if($hcpPro) {
  1586. $params['hcp'] = $hcpPro->id;
  1587. }
  1588. $claims = DB::select(DB::raw("
  1589. SELECT claim.uid AS uid,
  1590. DATE(claim.created_at) AS created,
  1591. claim.status,
  1592. client.uid AS client_uid,
  1593. client.cell_number AS client_phone,
  1594. client.phone_home AS client_phone_home,
  1595. (client.name_last || ' ' || client.name_first) AS client ,
  1596. client.chart_number AS client_chart_number,
  1597. cp.id AS claim_pro_id,
  1598. (cp.name_last || ' ' || cp.name_first) AS claim_pro,
  1599. sp.id AS status_pro_id,
  1600. (sp.name_last || ' ' || sp.name_first) AS status_pro,
  1601. note.uid AS note_uid,
  1602. note.method,
  1603. note.new_or_fu_or_na,
  1604. care_month.uid AS care_month_uid,
  1605. -- claim.status_updated_at,
  1606. (DATE(claim.status_updated_at) || ' ' ||
  1607. LPAD(EXTRACT(hour FROM claim.status_updated_at)::text, 2, '0') || ':' ||
  1608. LPAD(EXTRACT(minute FROM claim.status_updated_at)::text, 2, '0')) AS status_updated_at,
  1609. (SELECT string_agg(claim_line.cpt, ', ') FROM claim_line where claim_id = claim.id) AS cpts,
  1610. (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,
  1611. ROUND(claim.expected_total, 3) as expected_total
  1612. FROM claim
  1613. join client on claim.client_id = client.id
  1614. join pro cp on claim.pro_id = cp.id
  1615. left join note on claim.note_id = note.id
  1616. left join care_month on claim.care_month_id = care_month.id
  1617. left join app_session on claim.status_updated_by_session_id = app_session.id
  1618. left join pro sp on app_session.pro_id = sp.id
  1619. --WHERE claim.status IS NULL OR claim.status = 'NEW'
  1620. WHERE (claim.status is NULL OR claim.status NOT IN ('CANCELLED', 'ABANDONED'" . ($request->input('show-submitted') ? "" : ", 'SUBMITTED'") . "))
  1621. -- AND claim.current_version_id IS NOT NULL
  1622. AND (client.name_first ILIKE :q OR
  1623. client.name_last ILIKE :q OR
  1624. client.chart_number ILIKE :q OR
  1625. client.mcn ILIKE :q)
  1626. AND (claim.created_at >= :from AND claim.created_at <= :to)
  1627. " . ($hcpPro ? "AND claim.pro_id = :hcp" : '') . "
  1628. AND claim.id IN (SELECT mb_claim.claim_id FROM mb_claim)
  1629. ORDER BY claim.created_at DESC
  1630. --OFFSET 0 LIMIT 15
  1631. "), $params);
  1632. if($request->input('json')) {
  1633. return json_encode($claims);
  1634. }
  1635. return view('app.practice-management.process-claims', compact('claims', 'status'));
  1636. }
  1637. public function rmLaunchAndClean(Request $request) {
  1638. $keyNumbers = [];
  1639. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_40'] = CareMonth::where('is_bill_closed', false)
  1640. ->whereNotNull('company_pro_id')
  1641. ->whereNotNull('company_pro_payer_id')
  1642. ->whereNotNull('company_location_id')
  1643. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  1644. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  1645. ->where('rm_total_time_in_seconds', '>=', 4200) // at 4200 (70 minutes, it becomes eligible for plus40)
  1646. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  1647. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  1648. ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS TRUE OR has_mcp_rm_interacted_by_note IS TRUE )')
  1649. ->count();
  1650. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_40_ifHadInteraction'] = CareMonth::where('is_bill_closed', false)
  1651. ->whereNotNull('company_pro_id')
  1652. ->whereNotNull('company_pro_payer_id')
  1653. ->whereNotNull('company_location_id')
  1654. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  1655. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  1656. ->where('rm_total_time_in_seconds', '>=', 4200) // at 4200 (70 minutes, it becomes eligible for plus40)
  1657. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  1658. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  1659. ->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 )')
  1660. ->count();
  1661. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_20'] = CareMonth::where('is_bill_closed', false)
  1662. ->whereNotNull('company_pro_id')
  1663. ->whereNotNull('company_pro_payer_id')
  1664. ->whereNotNull('company_location_id')
  1665. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  1666. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  1667. ->where('rm_total_time_in_seconds', '<', 4200)
  1668. ->where('rm_total_time_in_seconds', '>=', 3000) // at 3000 (50 minutes, it becomes eligible for plus20)
  1669. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  1670. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  1671. ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS TRUE OR has_mcp_rm_interacted_by_note IS TRUE)')
  1672. ->count();
  1673. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_20_ifHadInteraction'] = CareMonth::where('is_bill_closed', false)
  1674. ->whereNotNull('company_pro_id')
  1675. ->whereNotNull('company_pro_payer_id')
  1676. ->whereNotNull('company_location_id')
  1677. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  1678. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  1679. ->where('rm_total_time_in_seconds', '<', 4200)
  1680. ->where('rm_total_time_in_seconds', '>=', 3000) // at 3000 (50 minutes, it becomes eligible for plus20)
  1681. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  1682. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  1683. ->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 )')
  1684. ->count();
  1685. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP'] = CareMonth::where('is_bill_closed', false)
  1686. ->whereNotNull('company_pro_id')
  1687. ->whereNotNull('company_pro_payer_id')
  1688. ->whereNotNull('company_location_id')
  1689. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  1690. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  1691. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  1692. ->whereRaw('(rm_total_time_in_seconds < 3000 OR (rm_total_time_in_seconds >= 3000 AND is_rm_interaction_waived IS TRUE))')
  1693. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  1694. ->count();
  1695. $keyNumbers['careMonthsEligibleForBillGeneration_RMB'] = CareMonth::where('is_bill_closed', false)
  1696. ->whereNotNull('company_pro_id')
  1697. ->whereNotNull('company_pro_payer_id')
  1698. ->whereNotNull('company_location_id')
  1699. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  1700. ->whereRaw('is_rm_time_waived IS TRUE')
  1701. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  1702. ->count();
  1703. $keyNumbers['careMonthsWith16OrMoreMeasurementDays'] = CareMonth::where('is_bill_closed', false)
  1704. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  1705. ->count();
  1706. $careMonthsWith16PlusMeasurements = CareMonth::where('is_bill_closed', false)
  1707. ->where('number_of_days_with_remote_measurements', '>=', 16 )->get();
  1708. return view('app.practice-management.rm-launch-and-clean', compact('keyNumbers', 'careMonthsWith16PlusMeasurements'));
  1709. }
  1710. public function processNotes(Request $request) {
  1711. $mode = $request->input('mode') ? $request->input('mode') : '1';
  1712. if(($mode < 1 || $mode > 5) && $mode != 8) $mode = 1;
  1713. DB::enableQueryLog(); // Enable query log
  1714. $test = Note::where('is_cancelled', false)
  1715. ->where('is_signed_by_hcp', true)
  1716. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  1717. ->whereNull('current_note_pickup_for_processing_id')
  1718. ->where('is_billing_marked_done', true)
  1719. ->where('is_bill_closed', true)
  1720. ->where('is_claim_closed', true)
  1721. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  1722. ->count();
  1723. // var_dump($test);
  1724. // dd(DB::getQueryLog()); // Show results of log
  1725. // exit;
  1726. $counts = [
  1727. "picked" => Note::where('is_cancelled', false)
  1728. ->whereNotNull('current_note_pickup_for_processing_id')
  1729. ->count(),
  1730. "bad" => Note::where('is_cancelled', false)
  1731. ->whereRaw("((detail_json)::json->>'isBad' = 'true')")
  1732. ->count(),
  1733. // not yet signed
  1734. "mode-1" => Note::where('is_cancelled', false)
  1735. ->where('is_signed_by_hcp', false)
  1736. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1737. // ->whereNull('current_note_pickup_for_processing_id')
  1738. ->count(),
  1739. // billing not marked done
  1740. "mode-2" => Note::where('is_cancelled', false)
  1741. ->where('is_signed_by_hcp', true)
  1742. //->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1743. // ->whereNull('current_note_pickup_for_processing_id')
  1744. ->where('is_billing_marked_done', false)
  1745. ->count(),
  1746. // billing not closed
  1747. "mode-3" => Note::where('is_cancelled', false)
  1748. ->where('is_signed_by_hcp', true)
  1749. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1750. // ->whereNull('current_note_pickup_for_processing_id')
  1751. ->where('is_billing_marked_done', true)
  1752. ->where('is_bill_closed', false)
  1753. ->count(),
  1754. // claiming not closed
  1755. "mode-4" => Note::where('is_cancelled', false)
  1756. ->where('is_signed_by_hcp', true)
  1757. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1758. // ->whereNull('current_note_pickup_for_processing_id')
  1759. ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true' OR ((detail_json)::json->>'isGood')::text IS NULL)")
  1760. ->where('is_billing_marked_done', true)
  1761. ->where('is_bill_closed', true)
  1762. ->where('is_claim_closed', false)
  1763. ->count(),
  1764. // has unsubmitted claims
  1765. "mode-5" => Note::where('is_cancelled', false)
  1766. /*->where('is_signed_by_hcp', true)
  1767. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1768. ->whereNull('current_note_pickup_for_processing_id')
  1769. ->where('is_billing_marked_done', true)
  1770. ->where('is_bill_closed', true)
  1771. ->where('is_claim_closed', true)
  1772. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0")
  1773. */
  1774. ->where('is_signed_by_hcp', true)
  1775. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1776. // ->whereNull('current_note_pickup_for_processing_id')
  1777. ->where('is_billing_marked_done', true)
  1778. ->where('is_bill_closed', true)
  1779. // ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true')")
  1780. ->where('is_claim_closed', true)
  1781. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0)")
  1782. ->count(),
  1783. // has unsubmitted claims MARKED GOOD!
  1784. "mode-8" => Note::where('is_cancelled', false)
  1785. ->where('is_signed_by_hcp', true)
  1786. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  1787. ->whereNull('current_note_pickup_for_processing_id')
  1788. ->where('is_billing_marked_done', true)
  1789. ->where('is_bill_closed', true)
  1790. ->where('is_claim_closed', false)
  1791. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  1792. ->count(),
  1793. // all good
  1794. "mode-6" => Note::where('is_cancelled', false)
  1795. ->where('is_signed_by_hcp', true)
  1796. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1797. // ->whereNull('current_note_pickup_for_processing_id')
  1798. ->where('is_billing_marked_done', true)
  1799. ->where('is_bill_closed', true)
  1800. ->where('is_claim_closed', true)
  1801. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id) > 0)")
  1802. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  1803. ->count(),
  1804. "mode-7" => Note::where('is_cancelled', false)
  1805. ->whereRaw("(detail_json)::json->>'isBad' = 'true'")
  1806. ->count(),
  1807. ];
  1808. return view('app.practice-management.process-notes', compact('mode', 'counts'));
  1809. }
  1810. public function notesProcessingCenter(Request $request) {
  1811. $notes = Note::where('is_cancelled', false);
  1812. // filters
  1813. $proUid = $request->input('proUid');
  1814. if($proUid) {
  1815. $fPro = Pro::where('uid', $proUid)->first();
  1816. if($fPro) {
  1817. $notes = $notes->where('hcp_pro_id', $fPro->id);
  1818. }
  1819. }
  1820. $proSigned = $request->input('proSigned');
  1821. switch($proSigned) {
  1822. case 'yes': $notes = $notes->where('is_signed_by_hcp', true); break;
  1823. case 'no': $notes = $notes->where('is_signed_by_hcp', '!=', true); break;
  1824. }
  1825. $billingMarkedDone = $request->input('billingMarkedDone');
  1826. switch($billingMarkedDone) {
  1827. case 'yes': $notes = $notes->where('is_billing_marked_done', true); break;
  1828. case 'no': $notes = $notes->where('is_billing_marked_done', '!=', true); break;
  1829. }
  1830. $billingClosed = $request->input('billingClosed');
  1831. switch($billingClosed) {
  1832. case 'yes': $notes = $notes->where('is_bill_closed', true); break;
  1833. case 'no': $notes = $notes->where('is_bill_closed', '!=', true); break;
  1834. }
  1835. $claimingClosed = $request->input('claimingClosed');
  1836. switch($claimingClosed) {
  1837. case 'yes': $notes = $notes->where('is_claim_closed', true); break;
  1838. case 'no': $notes = $notes->where('is_claim_closed', '!=', true); break;
  1839. }
  1840. $allClaimsSubmitted = $request->input('allClaimsSubmitted');
  1841. if($allClaimsSubmitted) {
  1842. // TODO
  1843. }
  1844. $goodBad = $request->input('goodBad');
  1845. switch($goodBad) {
  1846. case 'good': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' = 'false'"); break;
  1847. case 'bad': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' = 'true'"); break;
  1848. case 'unclassified': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' is null"); break;
  1849. }
  1850. $startDate = $request->input('startDate');
  1851. if($startDate) {
  1852. $notes = $notes->where('effective_dateest', '>=', $startDate);
  1853. }
  1854. $endDate = $request->input('endDate');
  1855. if($endDate) {
  1856. $notes = $notes->where('effective_dateest', '<=', $endDate);
  1857. }
  1858. $mcPartB = $request->input('mcPartB');
  1859. if($mcPartB) {
  1860. // TODO
  1861. }
  1862. $notes = $notes->orderBy('effective_dateest')->paginate(10);
  1863. return view('app.practice-management.notes-processing-center', compact('notes'));
  1864. }
  1865. public function getNextNote(Request $request, $mode)
  1866. {
  1867. $note = null;
  1868. switch (+$mode) {
  1869. case 1:
  1870. $note = Note::where('is_cancelled', false)
  1871. ->where('is_signed_by_hcp', false)
  1872. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1873. ->whereNull('current_note_pickup_for_processing_id')
  1874. ->orderBy('effective_dateest', 'DESC')
  1875. ->first();
  1876. break;
  1877. case 2:
  1878. $note = Note::where('is_cancelled', false)
  1879. ->where('is_signed_by_hcp', true)
  1880. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1881. ->whereNull('current_note_pickup_for_processing_id')
  1882. ->where('is_billing_marked_done', false)
  1883. ->orderBy('effective_dateest', 'DESC')
  1884. ->first();
  1885. break;
  1886. case 3:
  1887. $note = 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', false)
  1893. ->orderBy('effective_dateest', 'DESC')
  1894. ->first();
  1895. break;
  1896. case 4: // claiming not closed
  1897. DB::enableQueryLog(); // Enable query log
  1898. $note = Note::where('is_cancelled', false)
  1899. ->where('is_signed_by_hcp', true)
  1900. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1901. ->whereNull('current_note_pickup_for_processing_id')
  1902. ->where('is_billing_marked_done', true)
  1903. ->where('is_bill_closed', true)
  1904. ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true' OR ((detail_json)::json->>'isGood')::text IS NULL)")
  1905. ->where('is_claim_closed', false)
  1906. ->orderBy('effective_dateest', 'DESC')
  1907. ->first();
  1908. // DB::enableQueryLog(); // Enable query log
  1909. // Your Eloquent query executed by using get()
  1910. // dd(DB::getQueryLog()); // Show results of log
  1911. break;
  1912. case 5:
  1913. $note = Note::where('is_cancelled', false)
  1914. ->where('is_signed_by_hcp', true)
  1915. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1916. ->whereNull('current_note_pickup_for_processing_id')
  1917. ->where('is_billing_marked_done', true)
  1918. ->where('is_bill_closed', true)
  1919. ->where('is_claim_closed', true)
  1920. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0")
  1921. ->orderBy('effective_dateest', 'DESC')
  1922. ->first();
  1923. break;
  1924. case 8:
  1925. $note = Note::where('is_cancelled', false)
  1926. ->where('is_signed_by_hcp', true)
  1927. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  1928. ->whereNull('current_note_pickup_for_processing_id')
  1929. ->where('is_billing_marked_done', true)
  1930. ->where('is_bill_closed', true)
  1931. ->where('is_claim_closed', false)
  1932. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  1933. ->orderBy('effective_dateest', 'DESC')
  1934. ->first();
  1935. break;
  1936. }
  1937. if($note) {
  1938. $note->client_uid = $note->client->uid;
  1939. }
  1940. return json_encode($note);
  1941. }
  1942. public function pickedNotes(Request $request) {
  1943. $counts = [
  1944. "unpicked" => Note::where('is_cancelled', false)
  1945. ->whereNull('current_note_pickup_for_processing_id')
  1946. ->count(),
  1947. ];
  1948. $notes = Note::where('is_cancelled', false)
  1949. ->whereNotNull('current_note_pickup_for_processing_id')
  1950. ->orderBy('effective_dateest', 'ASC')
  1951. ->paginate();
  1952. return view('app.practice-management.picked-notes', compact('counts', 'notes'));
  1953. }
  1954. public function badNotes(Request $request) {
  1955. $counts = [
  1956. "unpicked" => Note::where('is_cancelled', false)
  1957. ->whereNull('current_note_pickup_for_processing_id')
  1958. ->count(),
  1959. ];
  1960. $notes = Note::where('is_cancelled', false)
  1961. ->whereRaw("(detail_json)::json->>'isBad' = 'true'")
  1962. ->orderBy('effective_dateest', 'ASC')
  1963. ->paginate();
  1964. return view('app.practice-management.bad-notes', compact('counts', 'notes'));
  1965. }
  1966. public function doneNotes(Request $request) {
  1967. $counts = [
  1968. "unpicked" => Note::where('is_cancelled', false)
  1969. ->whereNull('current_note_pickup_for_processing_id')
  1970. ->count(),
  1971. ];
  1972. $notes = Note::where('is_cancelled', false)
  1973. ->where('is_signed_by_hcp', true)
  1974. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1975. ->whereNull('current_note_pickup_for_processing_id')
  1976. ->where('is_billing_marked_done', true)
  1977. ->where('is_bill_closed', true)
  1978. ->where('is_claim_closed', true)
  1979. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id) > 0")
  1980. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0")
  1981. ->orderBy('effective_dateest', 'ASC')
  1982. ->paginate();
  1983. return view('app.practice-management.done-notes', compact('counts', 'notes'));
  1984. }
  1985. public function currentMbClaim(Request $request, $claimUid) {
  1986. $claim = Claim::where('uid', $claimUid)->first();
  1987. return json_encode(MBClaim::where('claim_version_id', $claim->currentVersion->id)->where('status', '!=', 'CANCELLED')->first());
  1988. }
  1989. public function currentClaimLines(Request $request, $claimUid) {
  1990. $claim = Claim::where('uid', $claimUid)->first();
  1991. if($request->input('json')) {
  1992. foreach ($claim->lines as $line) {
  1993. $line->expected_total = round($line->expected_total, 3);
  1994. $x = $line->claimLineIcds;
  1995. }
  1996. return json_encode($claim->lines);
  1997. }
  1998. return view('app.practice-management._claim-lines', compact('claim'));
  1999. }
  2000. public function packsMultiPrint(Request $request) {
  2001. $packs = Pack
  2002. ::select('pack.*')
  2003. ->leftJoin('shipment', function($join) {
  2004. $join->on('pack.shipment_id', '=', 'shipment.id');
  2005. })
  2006. ->whereNotIn('shipment.status', ['CANCELLED', 'DISPATCHED'])
  2007. ->where(function ($query) {
  2008. $query->where('pack.status', '<>', 'DELETED')->orWhereNull('pack.status'); // weird, but just the <> isn't working!
  2009. })
  2010. ->whereNotNull('pack.label_system_file_id')
  2011. ->orderBy('pack.created_at', 'ASC')
  2012. ->get();
  2013. return view('app.practice-management.packs-multi-print', compact('packs'));
  2014. }
  2015. public function packsMultiPDF(Request $request, $ids) {
  2016. $ids = array_map(function ($_x) {
  2017. return intval($_x);
  2018. }, explode("|", $ids));
  2019. $packs = Pack::whereIn('id', $ids)->get();
  2020. }
  2021. public function handouts(Request $request) {
  2022. $handouts = Handout::orderBy('display_name')->get();
  2023. return view('app.practice-management.handouts', compact('handouts'));
  2024. }
  2025. private function callJava($request, $endPoint, $data)
  2026. {
  2027. $url = config('stag.backendUrl') . $endPoint;
  2028. $response = Http::asForm()
  2029. ->withHeaders([
  2030. 'sessionKey' => $request->cookie('sessionKey')
  2031. ])
  2032. ->post($url, $data)
  2033. ->body();
  2034. dd($response);
  2035. return $response;
  2036. }
  2037. public function genericBills(Request $request)
  2038. {
  2039. return view('app.practice-management.generic-bills');
  2040. }
  2041. public function billsUnderProcessing(Request $request)
  2042. {
  2043. $bills = Bill::where('is_cancelled', false)
  2044. ->where(function ($query) { // mcp of any client program and program OB pending
  2045. $query
  2046. ->where(function ($_query) {
  2047. $_query->where('hcp_pro_id', $this->pro->id)
  2048. ->where('hcp_expected_payment_amount', '>', 0)
  2049. ->where('has_hcp_been_paid', false)
  2050. ->where('is_signed_by_hcp', true);
  2051. })
  2052. ->orWhere(function ($_query) {
  2053. $_query->where('cm_pro_id', $this->pro->id)
  2054. ->where('cm_expected_payment_amount', '>', 0)
  2055. ->where('has_cm_been_paid', false)
  2056. ->where('is_signed_by_cm', true);
  2057. })
  2058. ->orWhere(function ($_query) {
  2059. $_query->where('rme_pro_id', $this->pro->id)
  2060. ->where('rme_expected_payment_amount', '>', 0)
  2061. ->where('has_rme_been_paid', false)
  2062. ->where('is_signed_by_rme', true);
  2063. })
  2064. ->orWhere(function ($_query) {
  2065. $_query->where('rmm_pro_id', $this->pro->id)
  2066. ->where('rmm_expected_payment_amount', '>', 0)
  2067. ->where('has_rmm_been_paid', false)
  2068. ->where('is_signed_by_rmm', true);
  2069. })
  2070. ->orWhere(function ($_query) {
  2071. $_query->where('generic_pro_id', $this->pro->id)
  2072. ->where('generic_pro_expected_payment_amount', '>', 0)
  2073. ->where('has_generic_pro_been_paid', false)
  2074. ->where('is_signed_by_generic_pro', true);
  2075. });
  2076. })
  2077. ->orderBy('created_at', 'DESC')
  2078. ->paginate();
  2079. return view('app.practice-management.bills-under-processing', compact('bills'));
  2080. }
  2081. public function careMonthReport(Request $request) {
  2082. $m = $request->input('m');
  2083. $y = $request->input('y');
  2084. if(!$m || !$y) {
  2085. $date = date('Y-m-01');
  2086. }
  2087. else {
  2088. $date = date('Y-m-d', strtotime("$m/1/$y"));
  2089. }
  2090. $pro = $this->pro;
  2091. $records = DB::select("
  2092. SELECT cm.id as care_month_id,
  2093. cm.uid as care_month_uid,
  2094. c.id as client_id,
  2095. c.uid as client_uid,
  2096. cm.number_of_days_with_remote_measurements,
  2097. cm.rm_total_time_in_seconds_by_mcp,
  2098. cm.rm_total_time_in_seconds_by_rme_pro,
  2099. cm.rm_total_time_in_seconds_by_rmm_pro,
  2100. cm.mcp_pro_id,
  2101. cm.rme_pro_id,
  2102. cm.rmm_pro_id,
  2103. (c.name_first || ' ' || c.name_last) as client_name
  2104. FROM care_month cm
  2105. JOIN client c on cm.client_id = c.id
  2106. WHERE cm.start_date = :startDate
  2107. AND (cm.mcp_pro_id = :proID OR
  2108. cm.rme_pro_id = :proID OR
  2109. cm.rmm_pro_id = :proID)
  2110. ORDER BY c.name_last, c.name_first
  2111. ",
  2112. ['startDate' => $date, 'proID' => $pro->id]
  2113. );
  2114. return view('app.practice-management.care-month-report', compact('records', 'date'));
  2115. }
  2116. public function myTeams(Request $request) {
  2117. $pro = $this->pro;
  2118. // get all teams where the authed-pro is the assistant pro
  2119. $teams = ProTeam::where('assistant_pro_id', $pro->id)
  2120. ->where('is_active', true)
  2121. ->orderBy('slug')
  2122. ->get();
  2123. return view('app.practice-management.my-teams', compact('teams'));
  2124. }
  2125. public function patientsAccountsInvites(Request $request){
  2126. $filters = $request->all();
  2127. $accountInvites = AccountInvite::select('account_invite.*')
  2128. ->join('client', 'client.id', '=', 'account_invite.for_client_id');
  2129. if($this->performer->pro->pro_type !== 'ADMIN'){
  2130. $accountInvites = $accountInvites->where('client.mcp_pro_id', $this->performer->pro->id);
  2131. }
  2132. $this->filterMultiQuery($request, $accountInvites, 'account_invite.created_at', 'date_category', 'date_value_1', 'date_value_2');
  2133. $this->filterSimpleQuery($request, $accountInvites, 'account_invite.status', 'status');
  2134. $accountInvites = $accountInvites->orderBy('created_at', 'DESC')->paginate(20);
  2135. return view('app.practice-management.patients-accounts-invites', compact('accountInvites','filters'));
  2136. }
  2137. public function clientsBdtDevices(Request $request){
  2138. $filters = $request->all();
  2139. $devices = ClientBDTDevice::select(
  2140. 'client_bdt_device.*',
  2141. 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'))
  2142. // 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'))
  2143. ->join('client', 'client.id', '=', 'client_bdt_device.client_id');
  2144. if($this->performer->pro->pro_type !== 'ADMIN'){
  2145. $devices = $devices->where('client.mcp_pro_id', $this->performer->pro->id);
  2146. }
  2147. $this->filterMultiQuery($request, $devices, 'client_bdt_device.most_recent_measurement_at', 'date_category', 'date_value_1', 'date_value_2');
  2148. // $dateKeyName = $request->get('date_category');
  2149. // $date1 = $request->get('date_value_1');
  2150. // $date2 = $request->get('date_value_2');
  2151. // $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)";
  2152. // switch($dateKeyName) {
  2153. // case 'EXACTLY':
  2154. // if($date1) {
  2155. // $devices->whereRaw($dateColumnName." = '$date1'::DATE");
  2156. // }
  2157. // break;
  2158. // case 'LESS_THAN':
  2159. // if($date1) {
  2160. // $devices->whereRaw($dateColumnName. "< '$date1'::DATE" );
  2161. // }
  2162. // break;
  2163. // case 'GREATER_THAN':
  2164. // if($date1) {
  2165. // $devices->whereRaw($dateColumnName. "> '$date1'::DATE");
  2166. // }
  2167. // break;
  2168. // case 'BETWEEN':
  2169. // if($date1 && $date2) {
  2170. // $devices
  2171. // ->whereRaw($dateColumnName. ">= '$date1'::DATE")
  2172. // ->whereRaw($dateColumnName. "<= '$date2'::DATE");
  2173. // }
  2174. // break;
  2175. // case 'NOT_BETWEEN':
  2176. // if($date2 && $date1) {
  2177. // $devices
  2178. // ->where(function ($q) use ($request, $dateColumnName, $date1, $date2) {
  2179. // $q->whereRaw($dateColumnName. "< '$date1'::DATE")
  2180. // ->orWhereRaw($dateColumnName. "> '$date2'::DATE");
  2181. // });
  2182. // }
  2183. // break;
  2184. // }
  2185. $keyName = $request->get('measurement_count_category');
  2186. $value1 = $request->get('measurement_count_value_1');
  2187. $value2 = $request->get('measurement_count_value_2');
  2188. $columnName = "(SELECT COUNT(*) FROM bdt_measurement WHERE bdt_measurement.bdt_device_id = client_bdt_device.device_id AND is_cellular_zero IS FALSE)";
  2189. switch($keyName) {
  2190. case 'EXACTLY':
  2191. if($value1) {
  2192. $devices->whereRaw($columnName.'='.$value1);
  2193. }
  2194. break;
  2195. case 'LESS_THAN':
  2196. if($value1) {
  2197. $devices->whereRaw($columnName. '<' .$value1);
  2198. }
  2199. break;
  2200. case 'GREATER_THAN':
  2201. if($value1) {
  2202. $devices->whereRaw($columnName. '>'. $value1);
  2203. }
  2204. break;
  2205. case 'BETWEEN':
  2206. if($value1 && $value2) {
  2207. $devices
  2208. ->whereRaw($columnName. '>=' . $value1)
  2209. ->whereRaw($columnName. '<=' . $value1);
  2210. }
  2211. break;
  2212. case 'NOT_BETWEEN':
  2213. if($value1 && $value2) {
  2214. $devices
  2215. ->where(function ($q) use ($request, $columnName, $value1, $value2) {
  2216. $q->whereRaw($columnName. '<'. $value1)
  2217. ->orWhereRaw($columnName. '>'.$value2);
  2218. });
  2219. }
  2220. break;
  2221. }
  2222. $status = $request->get('status');
  2223. if($status){
  2224. if($status === 'ACTIVE') $devices = $devices->where('client_bdt_device.is_active', true);
  2225. if($status === 'DEACTIVATED') $devices = $devices->where('client_bdt_device.is_active', false);
  2226. }
  2227. $devices = $devices->orderBy('num_of_measurements', 'DESC')->paginate(20);
  2228. return view('app.practice-management.clients_bdt_devices', compact('devices','filters'));
  2229. }
  2230. public function memos(Request $request){
  2231. $filters = $request->all();
  2232. $memos = ClientMemo::select('client_memo.*')
  2233. ->join('client', 'client.id', '=', 'client_memo.client_id');
  2234. if($this->performer->pro->pro_type !== 'ADMIN'){
  2235. $memos = $memos->where('client.mcp_pro_id', $this->performer->pro->id);
  2236. }
  2237. $this->filterMultiQuery($request, $memos, 'client_memo.created_at', 'date_category', 'date_value_1', 'date_value_2');
  2238. $this->filterSimpleQuery($request, $memos, 'category', 'category');
  2239. $memos = $memos->orderBy('created_at', 'DESC')->paginate(20);
  2240. return view('app.practice-management.memos', compact('memos', 'filters'));
  2241. }
  2242. public function segmentTemplates(Request $request){
  2243. $segmentTemplates = SegmentTemplate::query();
  2244. $segmentTemplates = $segmentTemplates->orderBy('created_at', 'DESC');
  2245. $responseType = $request->get('response_type');
  2246. if($responseType && $responseType == 'json'){
  2247. $segmentTemplates = $segmentTemplates->where('is_active', true)->get();
  2248. return $this->pass($segmentTemplates);
  2249. }
  2250. $segmentTemplates = $segmentTemplates->paginate(30);
  2251. return view('app.practice-management.segment-templates.index', compact('segmentTemplates'));
  2252. }
  2253. public function visitTemplates(Request $request){
  2254. $visitTemplates = VisitTemplate::query();
  2255. $visitTemplates = $visitTemplates->orderBy('created_at', 'DESC');
  2256. $responseType = $request->get('response_type');
  2257. if($responseType && $responseType == 'json'){
  2258. $visitTemplates = $visitTemplates->where('is_active', true)->get();
  2259. return $this->pass($visitTemplates);
  2260. }
  2261. $visitTemplates = $visitTemplates->paginate(30);
  2262. return view('app.practice-management.visit-templates.index', compact('visitTemplates'));
  2263. }
  2264. public function visitTemplate(Request $request, VisitTemplate $visitTemplate){
  2265. $visitTemplateSegmentTemplates = VisitTemplateSegmentTemplate::query();
  2266. $visitTemplateSegmentTemplates = $visitTemplateSegmentTemplates->where('visit_template_id', $visitTemplate->id);
  2267. $visitTemplateSegmentTemplates = $visitTemplateSegmentTemplates->orderBy('position_index', 'ASC');
  2268. $visitTemplateSegmentTemplates = $visitTemplateSegmentTemplates->paginate(50);
  2269. return view('app.practice-management.visit-templates.visit-template-segment-templates.index', compact('visitTemplate','visitTemplateSegmentTemplates'));
  2270. }
  2271. public function visitTemplateAccess(Request $request, VisitTemplate $visitTemplate){
  2272. $visitTemplateAccesses = VisitTemplateAccess::where('visit_template_id', $visitTemplate->id)->paginate(50);
  2273. return view('app.practice-management.visit-templates.visit-template-accesses.index', compact('visitTemplate','visitTemplateAccesses'));
  2274. }
  2275. public function clientCcmRmStatus(Request $request){
  2276. $filters = $request->all();
  2277. $patients = Client::whereNull('shadow_pro_id');
  2278. $pro = $this->performer()->pro;
  2279. if($pro->pro_type !== 'ADMIN') {
  2280. $patients = $patients->where('mcp_pro_id', $this->performer()->pro->id);
  2281. }
  2282. // filters
  2283. /*
  2284. array:18 [▼
  2285. "age_category" => "LESS_THAN"
  2286. "age_value_1" => "34"
  2287. "age_value_2" => null
  2288. "sex" => "M"
  2289. "bmi_category" => "BETWEEN"
  2290. "bmi_value_1" => "20"
  2291. "bmi_value_2" => "25"
  2292. "last_visit_category" => "LESS_THAN"
  2293. "last_visit_value_1" => "2021-10-14"
  2294. "last_visit_value_2" => null
  2295. "next_appointment_category" => "LESS_THAN"
  2296. "next_appointment_value_1" => "2021-10-15"
  2297. "status" => "ACTIVE"
  2298. "last_weighed_in_category" => "EXACTLY"
  2299. "last_weighed_in_value_1" => "2021-10-07"
  2300. "last_bp_category" => "BETWEEN"
  2301. "last_bp_value_1" => "2021-10-01"
  2302. "last_bp_value_2" => "2021-10-31"
  2303. ]
  2304. */
  2305. $this->filterMultiQuery($request, $patients, 'age_in_years', 'age_category', 'age_value_1', 'age_value_2');
  2306. $this->filterSimpleQuery($request, $patients, 'sex', 'sex');
  2307. $this->filterMultiQuery($request, $patients, 'usual_bmi', 'bmi_category', 'bmi_value_1', 'bmi_value_2');
  2308. $this->filterMultiQuery($request, $patients, 'most_recent_weight_at', 'last_weighed_in_category', 'last_weighed_in_value_1', 'last_weighed_in_value_2');
  2309. $this->filterMultiQuery($request, $patients, 'most_recent_bp_at', 'last_bp_category', 'last_bp_value_1', 'last_bp_value_2');
  2310. switch($request->input('status')) {
  2311. case 'ACTIVE':
  2312. $patients->where('is_active', true)->where('has_mcp_done_onboarding_visit', true);
  2313. break;
  2314. case 'AWAITING_VISIT':
  2315. $patients->where('is_active', true)->where('has_mcp_done_onboarding_visit', false);
  2316. break;
  2317. case 'INACTIVE':
  2318. $patients->where('is_active', '<>', true);
  2319. break;
  2320. }
  2321. if($request->input('is_eligible_for_cm')){
  2322. $patients->where('is_eligible_for_cm', '=', $request->input('is_eligible_for_cm'));
  2323. }
  2324. if($request->input('is_enrolled_in_cm')){
  2325. $patients->where('is_enrolled_in_cm', '=', $request->input('is_enrolled_in_cm'));
  2326. }
  2327. if($request->input('has_cm_setup_been_performed')){
  2328. $patients->where('has_cm_setup_been_performed', '=', $request->input('has_cm_setup_been_performed')=='YES'? true : false);
  2329. }
  2330. if($request->input('is_eligible_for_rm')){
  2331. $patients->where('is_eligible_for_rm', '=', $request->input('is_eligible_for_rm'));
  2332. }
  2333. if($request->input('is_enrolled_in_rm')){
  2334. $patients->where('is_enrolled_in_rm', '=', $request->input('is_enrolled_in_rm'));
  2335. }
  2336. if($request->input('has_rm_setup_been_performed')){
  2337. $patients->where('has_rm_setup_been_performed', '=', $request->input('has_rm_setup_been_performed') =='YES'? true : false);
  2338. }
  2339. $patients = $patients->orderBy('created_at', 'DESC')->paginate(20);
  2340. return view('app.admin.client-ccm-rm-status', compact('patients', 'filters'));
  2341. }
  2342. public function rmActionReport(Request $request){
  2343. $filters = $request->all();
  2344. $careMonthStartDate = $request->get('care_month_start_date');
  2345. if(!$careMonthStartDate){
  2346. $careMonthStartDate = '2022-01-01';
  2347. }
  2348. $lastDateOfMonth = new DateTime(date("Y-m-t", strtotime(get_current_date())));
  2349. $today = new DateTime(get_current_date());
  2350. $diff = $lastDateOfMonth->diff($today);
  2351. $daysBetweenNowAndEndmonth = $diff->days;
  2352. $minRequiredMeasurements = 16 - $daysBetweenNowAndEndmonth -1;
  2353. $numOfMeasurements = $request->get('num_of_measurements'); //16_or_more, 12_or_more
  2354. $hasRecentVisit = $request->get('has_recent_visit'); //yes no
  2355. $hasBeenSpokenToThisMonth = $request->get('has_been_spoken_to'); //yes no
  2356. $cmQuery = CareMonth::where('start_date', $careMonthStartDate);
  2357. //remove dummies
  2358. $cmQuery = $cmQuery->whereHas('client', function($clientQuery) {
  2359. return $clientQuery->where('client_engagement_status_category','<>', 'DUMMY')
  2360. ->orWhere('client_engagement_status_category', '=', null);
  2361. });
  2362. if($numOfMeasurements){
  2363. if($numOfMeasurements == '16_or_more'){
  2364. $cmQuery = $cmQuery->where('number_of_days_with_remote_measurements', '>=', 16);
  2365. }
  2366. if($numOfMeasurements == 'min_or_more'){
  2367. $cmQuery = $cmQuery->where('number_of_days_with_remote_measurements', '>=', $minRequiredMeasurements)
  2368. ->where('number_of_days_with_remote_measurements', '<', 16);
  2369. }
  2370. if($numOfMeasurements == 'less_than_min'){
  2371. $cmQuery = $cmQuery->where('number_of_days_with_remote_measurements', '<', $minRequiredMeasurements);
  2372. }
  2373. }
  2374. if($hasRecentVisit){
  2375. if($hasRecentVisit == 'YES'){
  2376. $cmQuery = $cmQuery->whereHas('client', function($clientQuery) {
  2377. return $clientQuery->whereRaw("most_recent_completed_mcp_note_date::DATE >= ((NOW() - interval '90 days')::DATE)");
  2378. });
  2379. }else{
  2380. $cmQuery = $cmQuery->whereHas('client', function($clientQuery) {
  2381. return $clientQuery->whereRaw("most_recent_completed_mcp_note_date::DATE < ((NOW() - interval '90 days')::DATE)");
  2382. });
  2383. }
  2384. }
  2385. if($hasBeenSpokenToThisMonth){
  2386. if($hasBeenSpokenToThisMonth == 'YES'){
  2387. $cmQuery = $cmQuery->where('has_anyone_interacted_with_client_about_rm_outside_note', '=', true);
  2388. }else{
  2389. $cmQuery = $cmQuery->where('has_anyone_interacted_with_client_about_rm_outside_note', '=', false);
  2390. }
  2391. }
  2392. $rows = $cmQuery->paginate(50);
  2393. return view('app.practice-management.rm-action-report', compact('rows', 'filters', 'minRequiredMeasurements'));
  2394. }
  2395. }