PracticeManagementController.php 128 KB

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