PracticeManagementController.php 114 KB

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