PracticeManagementController.php 121 KB

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