PracticeManagementController.php 129 KB

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