PracticeManagementController.php 99 KB

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