PracticeManagementController.php 142 KB

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