PracticeManagementController.php 115 KB

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