PracticeManagementController.php 109 KB

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