PracticeManagementController.php 120 KB

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