PracticeManagementController.php 105 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442
  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(*)
  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. public function remoteMonitoringAdmin(Request $request) {
  918. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  919. $careMonthStart = date($ym . '-01');
  920. $rc = $request->input('rc') ?: 1;
  921. $rc2 = $request->input('rc2') ?: 2;
  922. $conditions = $this->rpmConditionsAdmin($this->performer(), $rc, $rc2);
  923. $patients = DB::select(
  924. DB::raw(
  925. "
  926. SELECT client.name_first,
  927. client.name_last,
  928. client.uid as client_uid,
  929. client.dob,
  930. client.is_enrolled_in_rm,
  931. client.most_recent_completed_mcp_note_date,
  932. care_month.uid as care_month_uid,
  933. care_month.id as care_month_id,
  934. care_month.start_date,
  935. care_month.rm_total_time_in_seconds_by_mcp,
  936. care_month.number_of_days_with_remote_measurements,
  937. care_month.has_anyone_interacted_with_client_about_rm_outside_note,
  938. care_month.rm_num_measurements_not_stamped_by_mcp,
  939. care_month.rm_num_measurements_not_stamped_by_non_hcp,
  940. care_month.rm_num_measurements_not_stamped_by_rmm,
  941. care_month.rm_num_measurements_not_stamped_by_rme,
  942. client.mcp_pro_id,
  943. client.default_na_pro_id,
  944. client.rmm_pro_id,
  945. client.rme_pro_id,
  946. client.cell_number,
  947. client.most_recent_cellular_bp_dbp_mm_hg,
  948. client.most_recent_cellular_bp_sbp_mm_hg,
  949. client.most_recent_cellular_bp_measurement_at,
  950. client.most_recent_cellular_weight_value,
  951. client.most_recent_cellular_weight_measurement_at
  952. FROM care_month join client on care_month.client_id = client.id
  953. WHERE
  954. client.shadow_pro_id is null AND client.is_enrolled_in_rm = 'YES'
  955. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  956. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  957. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '') . "
  958. ORDER BY care_month.number_of_days_with_remote_measurements DESC NULLS LAST, client.name_first, client.name_last
  959. "
  960. )
  961. );
  962. $timestamp = strtotime(date('Y-m-d'));
  963. $daysRemaining = (int)date('t', $timestamp) - (int)date('j', $timestamp);
  964. return view('app.practice-management.remote-monitoring-admin', compact('patients', 'daysRemaining', 'careMonthStart'));
  965. }
  966. public function remoteMonitoringAdminCount(Request $request) {
  967. $ym = ($request->input('y') ?: 'Y') . '-' . ($request->input('m') ?: 'm');
  968. $careMonthStart = date($ym . '-01');
  969. $rc = $request->input('rc') ?: 1;
  970. $rc2 = $request->input('rc2') ?: 2;
  971. $conditions = $this->rpmConditionsAdmin($this->performer(), $rc, $rc2);
  972. $count = DB::select(
  973. DB::raw(
  974. "
  975. SELECT count(*)
  976. FROM care_month join client on care_month.client_id = client.id
  977. WHERE
  978. client.shadow_pro_id is null AND client.is_enrolled_in_rm = 'YES'
  979. AND EXTRACT(MONTH from care_month.start_date) = " . ($request->input('m') ?: 'EXTRACT(MONTH from now())') . "
  980. AND EXTRACT(YEAR from care_month.start_date) = " . ($request->input('y') ?: 'EXTRACT(YEAR from now())') . "
  981. " . (count($conditions) > 0 ? 'AND ' . implode(" AND ", $conditions) : '')
  982. )
  983. );
  984. return $count[0]->count;
  985. }
  986. private function rpmConditions($performer, $rc, $rc2) {
  987. $conditions = [];
  988. $c_isMCP = "client.mcp_pro_id = {$performer->pro->id}";
  989. $c_enrolledInRPM = "client.is_enrolled_in_rm = 'YES'";
  990. $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";
  991. $c_lastVisitBefore90Days = "DATE_PART('day', client.most_recent_completed_mcp_note_date::timestamp - care_month.start_date::timestamp) > 90";
  992. $c_lastVisitWithin90Days = "DATE_PART('day', client.most_recent_completed_mcp_note_date::timestamp - care_month.start_date::timestamp) <= 90";
  993. $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)";
  994. $c_spokenToThisMonth = "care_month.has_anyone_interacted_with_client_about_rm_outside_note = TRUE";
  995. $c_hasUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp > 0";
  996. $c_hasNoUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp = 0";
  997. $c_lt16MeasurementDays = "care_month.number_of_days_with_remote_measurements < 16";
  998. $c_gte16MeasurementDays = "care_month.number_of_days_with_remote_measurements >= 16";
  999. $c_subscribedToSMS = "client.send_sms_on_bdt_measurement = TRUE";
  1000. $c_deviceUsed = "(client.most_recent_cellular_bp_measurement_at IS NOT NULL OR most_recent_cellular_weight_measurement_at IS NOT NULL)";
  1001. $c_lt20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp < 1200";
  1002. $c_gte20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp >= 1200";
  1003. switch ($rc) {
  1004. case 1:
  1005. $conditions = [$c_isMCP];
  1006. break;
  1007. case 2:
  1008. $conditions = [$c_isMCP, $c_enrolledInRPM];
  1009. break;
  1010. case 3:
  1011. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice];
  1012. break;
  1013. case 4:
  1014. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, ($rc2 == 1 ? $c_lastVisitBefore90Days : $c_lastVisitWithin90Days)];
  1015. break;
  1016. case 5:
  1017. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, ($rc2 == 1 ? $c_notSpokenToThisMonth : $c_spokenToThisMonth)];
  1018. break;
  1019. case 6:
  1020. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_hasUnstamped : $c_hasNoUnstamped)];
  1021. break;
  1022. case 7:
  1023. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_lt16MeasurementDays : $c_gte16MeasurementDays)];
  1024. break;
  1025. case 10:
  1026. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, $c_gte16MeasurementDays, ($rc2 == 1 ? $c_lt20BillingMinutes : $c_gte20BillingMinutes)];
  1027. break;
  1028. case 8:
  1029. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_subscribedToSMS];
  1030. break;
  1031. case 9:
  1032. $conditions = [$c_isMCP, $c_enrolledInRPM, $c_deviceUsed];
  1033. break;
  1034. }
  1035. return $conditions;
  1036. }
  1037. private function rpmConditionsAdmin($performer, $rc, $rc2) {
  1038. $conditions = [];
  1039. $c_enrolledInRPM = "client.is_enrolled_in_rm = 'YES'";
  1040. $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";
  1041. $c_lastVisitBefore90Days = "DATE_PART('day', client.most_recent_completed_mcp_note_date::timestamp - care_month.start_date::timestamp) > 90";
  1042. $c_lastVisitWithin90Days = "DATE_PART('day', client.most_recent_completed_mcp_note_date::timestamp - care_month.start_date::timestamp) <= 90";
  1043. $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)";
  1044. $c_spokenToThisMonth = "care_month.has_anyone_interacted_with_client_about_rm_outside_note = TRUE";
  1045. $c_hasUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp > 0";
  1046. $c_hasNoUnstamped = "care_month.rm_num_measurements_not_stamped_by_mcp = 0";
  1047. $c_lt16MeasurementDays = "care_month.number_of_days_with_remote_measurements < 16";
  1048. $c_gte16MeasurementDays = "care_month.number_of_days_with_remote_measurements >= 16";
  1049. $c_subscribedToSMS = "client.send_sms_on_bdt_measurement = TRUE";
  1050. $c_deviceUsed = "(client.most_recent_cellular_bp_measurement_at IS NOT NULL OR most_recent_cellular_weight_measurement_at IS NOT NULL)";
  1051. $c_lt20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp < 1200";
  1052. $c_gte20BillingMinutes = "care_month.rm_total_time_in_seconds_by_mcp >= 1200";
  1053. switch ($rc) {
  1054. case 2:
  1055. $conditions = [$c_enrolledInRPM];
  1056. break;
  1057. case 3:
  1058. $conditions = [$c_enrolledInRPM, $c_hasDevice];
  1059. break;
  1060. case 4:
  1061. $conditions = [$c_enrolledInRPM, $c_hasDevice, ($rc2 == 1 ? $c_lastVisitBefore90Days : $c_lastVisitWithin90Days)];
  1062. break;
  1063. case 5:
  1064. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, ($rc2 == 1 ? $c_notSpokenToThisMonth : $c_spokenToThisMonth)];
  1065. break;
  1066. case 6:
  1067. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_hasUnstamped : $c_hasNoUnstamped)];
  1068. break;
  1069. case 7:
  1070. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, ($rc2 == 1 ? $c_lt16MeasurementDays : $c_gte16MeasurementDays)];
  1071. break;
  1072. case 10:
  1073. $conditions = [$c_enrolledInRPM, $c_hasDevice, $c_lastVisitWithin90Days, $c_spokenToThisMonth, $c_gte16MeasurementDays, ($rc2 == 1 ? $c_lt20BillingMinutes : $c_gte20BillingMinutes)];
  1074. break;
  1075. case 8:
  1076. $conditions = [$c_enrolledInRPM, $c_subscribedToSMS];
  1077. break;
  1078. case 9:
  1079. $conditions = [$c_enrolledInRPM, $c_deviceUsed];
  1080. break;
  1081. }
  1082. return $conditions;
  1083. }
  1084. public function remoteMonitoringMeasurements(Request $request, CareMonth $careMonth) {
  1085. $performer = $this->performer();
  1086. $measurements = DB::select(
  1087. DB::raw(
  1088. "
  1089. SELECT measurement.label,
  1090. measurement.ts,
  1091. measurement.effective_date,
  1092. measurement.sbp_mm_hg,
  1093. measurement.dbp_mm_hg,
  1094. measurement.value_pulse,
  1095. measurement.value_irregular,
  1096. measurement.numeric_value,
  1097. measurement.value,
  1098. measurement.uid,
  1099. client.name_first,
  1100. client.name_last,
  1101. client.mcp_pro_id,
  1102. client.default_na_pro_id,
  1103. client.rmm_pro_id,
  1104. client.rme_pro_id
  1105. FROM measurement RIGHT JOIN client on measurement.client_id = client.id
  1106. WHERE
  1107. client.id = {$careMonth->client_id}
  1108. AND measurement.label IS NOT NULL
  1109. AND measurement.label NOT IN ('SBP', 'DBP')
  1110. AND (measurement.is_cellular_zero = FALSE or measurement.is_cellular_zero IS NULL)
  1111. AND measurement.is_removed IS FALSE
  1112. AND measurement.client_bdt_measurement_id IS NOT NULL
  1113. AND measurement.care_month_id = {$careMonth->id}
  1114. AND (
  1115. (client.mcp_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_mcp IS FALSE)
  1116. OR (client.rmm_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_rmm IS FALSE)
  1117. OR (client.rme_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_rme IS FALSE)
  1118. OR (client.default_na_pro_id = {$performer->pro->id} AND measurement.has_been_stamped_by_non_hcp IS FALSE)
  1119. )
  1120. ORDER BY ts DESC
  1121. "
  1122. )
  1123. );
  1124. return view('app.practice-management.remote-monitoring-measurements', compact('careMonth', 'measurements'));
  1125. }
  1126. public function billMatrix(Request $request)
  1127. {
  1128. $bClients = [];
  1129. $bHCPPros = [];
  1130. $bNAPros = [];
  1131. $filters = [];
  1132. $filters['client'] = $request->input('client');
  1133. $filters['service'] = $request->input('service');
  1134. $filters['hcp'] = $request->input('hcp');
  1135. $filters['hcp_paid'] = $request->input('hcp_paid');
  1136. $filters['expected_op'] = $request->input('expected_op');
  1137. $filters['expected_value'] = $request->input('expected_value');
  1138. $filters['paid_op'] = $request->input('paid_op');
  1139. $filters['paid_value'] = $request->input('paid_value');
  1140. $filters['bal_post_date_op'] = $request->input('bal_post_date_op');
  1141. $filters['bal_post_date_value'] = $request->input('bal_post_date_value');
  1142. $filters['hcp_sign'] = $request->input('hcp_sign');
  1143. $filters['verified'] = $request->input('verified');
  1144. $filters['cancelled'] = $request->input('cancelled');
  1145. $bills = Bill::orderBy('effective_date')->paginate();
  1146. return view('app.practice-management.bill-matrix', compact('bills', 'bClients', 'bHCPPros', 'filters'));
  1147. }
  1148. public function medicarePartBClaims(Request $request)
  1149. {
  1150. $medicarePartBOnly = $request->get("medicare_part_b");
  1151. $allClaims = Claim::where('was_submitted', false)->orWhere('was_submitted', null)->orderBy('created_at', 'desc')->get();
  1152. //Only medicare claims
  1153. $claims = [];
  1154. foreach ($allClaims as $claim) {
  1155. if ($claim->client != null && $claim->client->getPrimaryCoverageStatus() == 'YES' && !$claim->edi) {
  1156. $claims[] = $claim;
  1157. }
  1158. }
  1159. $claimEDIs = ClaimEDI::all();
  1160. return view('app.practice-management.medicare-partb-claims', compact('claims', 'claimEDIs'));
  1161. }
  1162. // Generate PDF
  1163. public function downloadClaims()
  1164. {
  1165. $claims = Claim::where('was_submitted', false)->orWhere('was_submitted', null)->orderBy('created_at', 'desc')->limit(100)->get();
  1166. view()->share('claims', $claims);
  1167. $pdf = PDF::loadView('app.practice-management.claims-pdf', $claims);
  1168. return $pdf->download('pdf_file.pdf');
  1169. }
  1170. public function tickets(Request $request, $proUid = null)
  1171. {
  1172. $tickets = Ticket::orderBy('created_at', 'desc')->paginate();
  1173. return view('app.practice-management.tickets', compact('tickets'));
  1174. }
  1175. public function supplyOrders(Request $request)
  1176. {
  1177. // counts
  1178. $counts = $this->getSupplyOrderCounts();
  1179. // so clients
  1180. $soClientIDs = DB::table('supply_order')->select('client_id')->distinct()->get()->toArray();
  1181. $soClientIDs = array_map(function ($_x) {
  1182. return $_x->client_id;
  1183. }, $soClientIDs);
  1184. $soClients = Client::whereIn('id', $soClientIDs)->get();
  1185. // so products
  1186. $soProductIDs = DB::table('supply_order')->select('product_id')->distinct()->get()->toArray();
  1187. $soProductIDs = array_map(function ($_x) {
  1188. return $_x->product_id;
  1189. }, $soProductIDs);
  1190. $soProducts = Product::whereIn('id', $soProductIDs)->get();
  1191. $filters = [];
  1192. $filters['client'] = $request->input('client');
  1193. $filters['product'] = $request->input('product');
  1194. $filters['reason'] = $request->input('reason');
  1195. $filters['cu_memo'] = $request->input('cu_memo');
  1196. $filters['pro_sign'] = $request->input('pro_sign');
  1197. $filters['client_sign'] = $request->input('client_sign');
  1198. $filters['shipment'] = $request->input('shipment');
  1199. $filters['lot_number'] = $request->input('lot_number');
  1200. $filters['imei'] = $request->input('imei');
  1201. $filters['cancelled'] = $request->input('cancelled');
  1202. $supplyOrders = SupplyOrder::where('id', '>', 0);
  1203. // apply filters
  1204. if ($filters['client']) $supplyOrders->where('client_id', $filters['client']);
  1205. if ($filters['product']) $supplyOrders->where('product_id', $filters['product']);
  1206. if ($filters['reason']) $supplyOrders->where('reason', 'ILIKE', '%' . $filters['reason'] . '%');
  1207. if ($filters['cu_memo']) $supplyOrders->where('cu_memo', 'ILIKE', '%' . $filters['cu_memo'] . '%');
  1208. if ($filters['pro_sign']) $supplyOrders->where('is_signed_by_pro', ($filters['pro_sign'] === 'signed'));
  1209. if ($filters['client_sign']) {
  1210. if ($filters['client_sign'] === 'signed')
  1211. $supplyOrders->where('is_signed_by_client', true);
  1212. elseif ($filters['client_sign'] === 'waived')
  1213. $supplyOrders->where('is_client_signature_waived', true);
  1214. else
  1215. $supplyOrders->where('is_client_signature_waived', false)->where('is_signed_by_client', false);
  1216. }
  1217. if ($filters['shipment']) {
  1218. if ($filters['shipment'] === 'not_cleared_for_shipment')
  1219. $supplyOrders->whereNull('shipment_id')->where('is_cleared_for_shipment', false);
  1220. elseif ($filters['shipment'] === 'cleared_for_shipment')
  1221. $supplyOrders->whereNull('shipment_id')->where('is_cleared_for_shipment', true);
  1222. else
  1223. $supplyOrders
  1224. ->whereNotNull('shipment_id')
  1225. ->whereRaw('(SELECT status FROM shipment WHERE id = shipment_id LIMIT 1) = ?', [$filters['shipment']]);
  1226. }
  1227. if ($filters['lot_number']) $supplyOrders->where('lot_number', 'ILIKE', '%' . $filters['lot_number'] . '%');
  1228. if ($filters['imei']) $supplyOrders->where('imei', 'ILIKE', '%' . $filters['imei'] . '%');
  1229. if ($filters['cancelled']) $supplyOrders->where('is_cancelled', ($filters['cancelled'] === 'cancelled'));
  1230. $supplyOrders = $supplyOrders->orderBy('created_at', 'desc')->paginate();
  1231. return view('app.practice-management.supply-orders',
  1232. compact('supplyOrders', 'filters',
  1233. 'soClients', 'soProducts', 'counts'
  1234. )
  1235. );
  1236. }
  1237. public function shipments(Request $request, $filter = null)
  1238. {
  1239. // counts
  1240. $counts = $this->getShipmentCounts();
  1241. // so clients
  1242. $shClientIDs = DB::table('shipment')->select('client_id')->distinct()->get()->toArray();
  1243. $shClientIDs = array_map(function ($_x) {
  1244. return $_x->client_id;
  1245. }, $shClientIDs);
  1246. $shClients = Client::whereIn('id', $shClientIDs)->get();
  1247. $shipments = Shipment::where('id', '>', 0);
  1248. $filters = [];
  1249. $filters['client'] = $request->input('client');
  1250. $filters['courier'] = $request->input('courier');
  1251. $filters['tracking_num'] = $request->input('tracking_num');
  1252. $filters['label'] = $request->input('label');
  1253. $filters['status'] = $request->input('status');
  1254. $filters['cancelled'] = $request->input('cancelled');
  1255. if ($filters['client']) $shipments->where('client_id', $filters['client']);
  1256. if ($filters['courier']) $shipments->where('courier', 'ILIKE', '%' . $filters['courier'] . '%');
  1257. if ($filters['tracking_num']) $shipments->where('tracking_number', 'ILIKE', '%' . $filters['tracking_num'] . '%');
  1258. if ($filters['label']) {
  1259. if ($filters['label'] === 'yes')
  1260. $shipments->whereNotNull('label_system_file_id');
  1261. else
  1262. $shipments->whereNull('label_system_file_id');
  1263. }
  1264. if ($filters['status']) $shipments->where('status', $filters['status']);
  1265. if ($filters['cancelled']) $shipments->where('is_cancelled', ($filters['cancelled'] === 'cancelled'));
  1266. $shipments = $shipments->orderBy('created_at', 'desc')->paginate();
  1267. return view('app.practice-management.shipments', compact('shipments', 'filters', 'shClients', 'counts'));
  1268. }
  1269. public function cellularMeasurements(Request $request)
  1270. {
  1271. $measurements = Measurement::orderBy('ts', 'desc')->whereNotNull('ts')->paginate();
  1272. return view('app.practice-management.cellular-measurements', compact('measurements'));
  1273. }
  1274. // v2 supply-orders & shipments management (wh)
  1275. public function supplyOrdersReadyToShip(Request $request)
  1276. {
  1277. $counts = $this->getSupplyOrderCounts();
  1278. $supplyOrders = SupplyOrder
  1279. ::where('is_cleared_for_shipment', true)
  1280. ->where('is_cancelled', false)
  1281. ->whereNull('shipment_id')
  1282. ->join('client', 'client.id', '=', 'supply_order.client_id')
  1283. ->orderBy('client.name_last', 'ASC')
  1284. ->orderBy('client.name_first', 'ASC')
  1285. ->orderBy('supply_order.client_id', 'ASC')
  1286. ->orderBy('supply_order.mailing_address_full', 'ASC')
  1287. ->orderBy('supply_order.created_at', 'ASC')
  1288. ->select('supply_order.*')
  1289. ->paginate();
  1290. return view('app.practice-management.supply-orders-ready-to-ship', compact('supplyOrders', 'counts'));
  1291. }
  1292. public function supplyOrdersShipmentUnderway(Request $request)
  1293. {
  1294. $counts = $this->getSupplyOrderCounts();
  1295. $supplyOrders = SupplyOrder
  1296. ::where('is_cancelled', false)
  1297. ->whereNotNull('shipment_id')
  1298. ->orderBy('client_id', 'ASC')
  1299. ->orderBy('mailing_address_full', 'ASC')
  1300. ->orderBy('created_at', 'ASC')
  1301. ->paginate();
  1302. return view('app.practice-management.supply-orders-shipment-underway', compact('supplyOrders', 'counts'));
  1303. }
  1304. public function supplyOrdersHanging(Request $request)
  1305. {
  1306. $counts = $this->getSupplyOrderCounts();
  1307. $supplyOrders = SupplyOrder
  1308. ::select('supply_order.*')
  1309. ->leftJoin('shipment', function($join) {
  1310. $join->on('supply_order.shipment_id', '=', 'shipment.id');
  1311. })
  1312. ->where('shipment.status', 'CANCELLED')
  1313. ->where('supply_order.is_cancelled', false)
  1314. ->orderBy('supply_order.client_id', 'ASC')
  1315. ->orderBy('supply_order.mailing_address_full', 'ASC')
  1316. ->orderBy('supply_order.created_at', 'ASC')
  1317. ->paginate();
  1318. return view('app.practice-management.supply-orders-hanging', compact('supplyOrders', 'counts'));
  1319. }
  1320. public function supplyOrdersCancelledButUnacknowledged(Request $request)
  1321. {
  1322. $supplyOrders = SupplyOrder::where('signed_by_pro_id', $this->performer()->pro->id)
  1323. ->where('is_cancelled', true)
  1324. ->where('is_cancellation_acknowledged', false)
  1325. ->orderBy('created_at', 'desc')
  1326. ->paginate();
  1327. return view('app.practice-management.supply-orders-cancelled-but-unacknowledged', compact('supplyOrders'));
  1328. }
  1329. public function supplyOrdersUnsigned(Request $request)
  1330. {
  1331. $supplyOrders = SupplyOrder
  1332. ::where('is_cancelled', false)
  1333. ->where('is_signed_by_pro', false)
  1334. ->whereRaw('created_by_session_id IN (SELECT id FROM app_session WHERE pro_id = ?)', [$this->performer()->pro->id])
  1335. ->orderBy('created_at', 'desc')
  1336. ->paginate();
  1337. return view('app.practice-management.supply-orders-unsigned', compact('supplyOrders'));
  1338. }
  1339. private function getSupplyOrderCounts()
  1340. {
  1341. return [
  1342. "supplyOrders" => SupplyOrder::count(),
  1343. "supplyOrdersReadyToShip" => SupplyOrder
  1344. ::where('is_cleared_for_shipment', true)
  1345. ->where('is_cancelled', false)
  1346. ->whereNull('shipment_id')->count(),
  1347. "supplyOrdersShipmentUnderway" => SupplyOrder
  1348. ::where('is_cancelled', false)
  1349. ->whereNotNull('shipment_id')->count(),
  1350. "supplyOrdersHanging" => SupplyOrder
  1351. ::leftJoin('shipment', function($join) {
  1352. $join->on('supply_order.shipment_id', '=', 'shipment.id');
  1353. })
  1354. ->where('shipment.status', 'CANCELLED')
  1355. ->where('supply_order.is_cancelled', false)
  1356. ->count(),
  1357. ];
  1358. }
  1359. public function shipmentsReadyToPrint(Request $request)
  1360. {
  1361. $counts = $this->getShipmentCounts();
  1362. $shipments = Shipment
  1363. ::where('is_cancelled', false)
  1364. ->where('status', 'CREATED')
  1365. ->orderBy('created_at', 'ASC')
  1366. ->paginate();
  1367. return view('app.practice-management.shipments-ready-to-print', compact('shipments', 'counts'));
  1368. }
  1369. public function shipmentsShipmentUnderway(Request $request)
  1370. {
  1371. $counts = $this->getShipmentCounts();
  1372. $shipments = Shipment
  1373. ::where('is_cancelled', false)
  1374. ->where('status', 'PRINTED')
  1375. ->orderBy('created_at', 'ASC')
  1376. ->paginate();
  1377. return view('app.practice-management.shipments-waiting-for-picker', compact('shipments', 'counts'));
  1378. }
  1379. private function getShipmentCounts()
  1380. {
  1381. return [
  1382. "shipments" => Shipment::count(),
  1383. "shipmentsReadyToPrint" => Shipment
  1384. ::where('is_cancelled', false)
  1385. ->where('status', 'CREATED')
  1386. ->count(),
  1387. "shipmentsWaitingForPicker" => Shipment
  1388. ::where('is_cancelled', false)
  1389. ->where('status', 'PRINTED')
  1390. ->count()
  1391. ];
  1392. }
  1393. public function shipment(Request $request, Shipment $shipment)
  1394. {
  1395. return view('app.practice-management.shipment', compact('shipment'));
  1396. }
  1397. public function shipmentsMultiPrint(Request $request, $ids)
  1398. {
  1399. $ids = array_map(function ($_x) {
  1400. return intval($_x);
  1401. }, explode("|", $ids));
  1402. $shipments = Shipment::whereIn('id', $ids)->get();
  1403. return view('app.practice-management.shipments-multi-print', compact('shipments'));
  1404. }
  1405. public function patientClaimSummary(Request $request, $proUid = null)
  1406. {
  1407. $notesTotal = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE"))[0]->count;
  1408. $notesTotalWithBillingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE AND is_bill_closed IS TRUE"))[0]->count;
  1409. $notesTotalWithClaimingClosed = DB::select(DB::raw("SELECT COUNT(*) FROM note WHERE is_cancelled IS NOT TRUE AND is_claim_closed IS TRUE"))[0]->count;
  1410. $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;
  1411. $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;
  1412. $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;
  1413. $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;
  1414. $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;
  1415. $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;
  1416. $performerPro = $this->performer->pro;
  1417. $allPros = [];
  1418. if ($performerPro->pro_type == 'ADMIN') {
  1419. $allPros = Pro::all();
  1420. } else {
  1421. $allPros = [$performerPro];
  1422. }
  1423. //Patient | MCP | # Notes Total | # Notes without Billing Closed | # Notes without Claiming Closed
  1424. $patientsQuery = Client::where('is_dummy', '=', false)
  1425. ->whereNull('shadow_pro_id')
  1426. ->select('id', 'uid', 'name_first', 'name_last', 'mcp_pro_id', 'is_part_b_primary', 'medicare_advantage_plan',
  1427. DB::raw("(SELECT name_first||' '||name_last FROM pro where pro.id = client.mcp_pro_id) as mcp"),
  1428. DB::raw("(SELECT uid FROM pro where pro.id = mcp_pro_id) as mcp_pro_uid"),
  1429. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id) as notes_total"),
  1430. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id AND is_bill_closed IS NOT true) as notes_without_billing_closed"),
  1431. DB::raw("(SELECT COUNT(*) FROM note where note.client_id = client.id AND is_claim_closed IS NOT true) as notes_without_claiming_closed")
  1432. )->orderBy('is_part_b_primary', 'asc')->orderBy('notes_without_claiming_closed', 'desc');
  1433. if ($proUid) {
  1434. $mcpPro = Pro::where('uid', $proUid)->first();
  1435. if ($mcpPro) {
  1436. $patientsQuery->where('client.mcp_pro_id', '=', $mcpPro->id);
  1437. }
  1438. }
  1439. $patientsQuery->whereRaw('(SELECT COUNT(*) FROM note where note.client_id = client.id) > 0');
  1440. $patientsQuery->orderBy('notes_total', 'DESC');
  1441. $patients = $patientsQuery->paginate(50);
  1442. $data = [
  1443. 'patients' => $patients,
  1444. 'proUid' => $proUid,
  1445. 'allPros' => $allPros,
  1446. 'notesTotal' => $notesTotal,
  1447. 'notesTotalWithBillingClosed' => $notesTotalWithBillingClosed,
  1448. 'notesTotalWithClaimingClosed' => $notesTotalWithClaimingClosed,
  1449. 'notes3rdPartyTotal' => $notes3rdPartyTotal,
  1450. 'notes3rdPartyTotalWithBillingClosed' => $notes3rdPartyTotalWithBillingClosed,
  1451. 'notes3rdPartyTotalWithClaimingClosed' => $notes3rdPartyTotalWithClaimingClosed,
  1452. 'patientsTotal' => $patientsTotal,
  1453. 'patientsTotalWithBillingClosed' => $patientsTotalWithBillingClosed,
  1454. 'patientsTotalWithClaimingClosed' => $patientsTotalWithClaimingClosed
  1455. ];
  1456. return view('app.practice-management.patient-claim-summary', $data);
  1457. }
  1458. public function claims(Request $request){
  1459. $status = $request->get('status');
  1460. $claims = [];
  1461. if(!$status){
  1462. $claims = Claim::orderBy('created_at', 'DESC')->paginate();
  1463. }else{
  1464. $claims = Claim::where('status', $status)->orderBy('created_at', 'DESC')->paginate();
  1465. }
  1466. return view('app.practice-management.claims', compact('claims', 'status'));
  1467. }
  1468. public function processClaims(Request $request) {
  1469. $status = '';
  1470. $q = $request->input('q') ? $request->input('q') : '';
  1471. $from = $request->input('from') ? $request->input('from') : '1900-01-01';
  1472. $to = $request->input('to') ? $request->input('to') : '2100-01-01';
  1473. $params = [
  1474. 'q' => '%' . $q . '%',
  1475. 'from' => $from,
  1476. 'to' => $to
  1477. ];
  1478. $hcpPro = $request->input('hcp') ? Pro::where('uid', $request->input('hcp'))->first() : null;
  1479. if($hcpPro) {
  1480. $params['hcp'] = $hcpPro->id;
  1481. }
  1482. $claims = DB::select(DB::raw("
  1483. SELECT claim.uid AS uid,
  1484. DATE(claim.created_at) AS created,
  1485. claim.status,
  1486. client.uid AS client_uid,
  1487. client.cell_number AS client_phone,
  1488. (client.name_last || ' ' || client.name_first) AS client ,
  1489. client.chart_number AS client_chart_number,
  1490. cp.id AS claim_pro_id,
  1491. (cp.name_last || ' ' || cp.name_first) AS claim_pro,
  1492. sp.id AS status_pro_id,
  1493. (sp.name_last || ' ' || sp.name_first) AS status_pro,
  1494. note.uid AS note_uid,
  1495. note.method,
  1496. note.new_or_fu_or_na,
  1497. care_month.uid AS care_month_uid,
  1498. -- claim.status_updated_at,
  1499. (DATE(claim.status_updated_at) || ' ' ||
  1500. LPAD(EXTRACT(hour FROM claim.status_updated_at)::text, 2, '0') || ':' ||
  1501. LPAD(EXTRACT(minute FROM claim.status_updated_at)::text, 2, '0')) AS status_updated_at,
  1502. (SELECT string_agg(claim_line.cpt, ', ') FROM claim_line where claim_id = claim.id) AS cpts,
  1503. (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,
  1504. ROUND(claim.expected_total, 3) as expected_total
  1505. FROM claim
  1506. join client on claim.client_id = client.id
  1507. join pro cp on claim.pro_id = cp.id
  1508. left join note on claim.note_id = note.id
  1509. left join care_month on claim.care_month_id = care_month.id
  1510. left join app_session on claim.status_updated_by_session_id = app_session.id
  1511. left join pro sp on app_session.pro_id = sp.id
  1512. --WHERE claim.status IS NULL OR claim.status = 'NEW'
  1513. WHERE (claim.status is NULL OR claim.status NOT IN ('CANCELLED', 'ABANDONED'" . ($request->input('show-submitted') ? "" : ", 'SUBMITTED'") . "))
  1514. -- AND claim.current_version_id IS NOT NULL
  1515. AND (client.name_first ILIKE :q OR
  1516. client.name_last ILIKE :q OR
  1517. client.chart_number ILIKE :q OR
  1518. client.mcn ILIKE :q)
  1519. AND (claim.created_at >= :from AND claim.created_at <= :to)
  1520. " . ($hcpPro ? "AND claim.pro_id = :hcp" : '') . "
  1521. AND claim.id IN (SELECT mb_claim.claim_id FROM mb_claim)
  1522. ORDER BY claim.created_at DESC
  1523. --OFFSET 0 LIMIT 15
  1524. "), $params);
  1525. if($request->input('json')) {
  1526. return json_encode($claims);
  1527. }
  1528. return view('app.practice-management.process-claims', compact('claims', 'status'));
  1529. }
  1530. public function rmLaunchAndClean(Request $request) {
  1531. $keyNumbers = [];
  1532. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_40'] = CareMonth::where('is_bill_closed', false)
  1533. ->whereNotNull('company_pro_id')
  1534. ->whereNotNull('company_pro_payer_id')
  1535. ->whereNotNull('company_location_id')
  1536. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  1537. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  1538. ->where('rm_total_time_in_seconds', '>=', 4200) // at 4200 (70 minutes, it becomes eligible for plus40)
  1539. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  1540. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  1541. ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS TRUE OR has_mcp_rm_interacted_by_note IS TRUE )')
  1542. ->count();
  1543. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_40_ifHadInteraction'] = CareMonth::where('is_bill_closed', false)
  1544. ->whereNotNull('company_pro_id')
  1545. ->whereNotNull('company_pro_payer_id')
  1546. ->whereNotNull('company_location_id')
  1547. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  1548. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  1549. ->where('rm_total_time_in_seconds', '>=', 4200) // at 4200 (70 minutes, it becomes eligible for plus40)
  1550. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  1551. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  1552. ->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 )')
  1553. ->count();
  1554. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_20'] = CareMonth::where('is_bill_closed', false)
  1555. ->whereNotNull('company_pro_id')
  1556. ->whereNotNull('company_pro_payer_id')
  1557. ->whereNotNull('company_location_id')
  1558. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  1559. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  1560. ->where('rm_total_time_in_seconds', '<', 4200)
  1561. ->where('rm_total_time_in_seconds', '>=', 3000) // at 3000 (50 minutes, it becomes eligible for plus20)
  1562. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  1563. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  1564. ->whereRaw('(has_anyone_interacted_with_client_about_rm_outside_note IS TRUE OR has_mcp_rm_interacted_by_note IS TRUE)')
  1565. ->count();
  1566. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP_PLUS_20_ifHadInteraction'] = CareMonth::where('is_bill_closed', false)
  1567. ->whereNotNull('company_pro_id')
  1568. ->whereNotNull('company_pro_payer_id')
  1569. ->whereNotNull('company_location_id')
  1570. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  1571. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  1572. ->where('rm_total_time_in_seconds', '<', 4200)
  1573. ->where('rm_total_time_in_seconds', '>=', 3000) // at 3000 (50 minutes, it becomes eligible for plus20)
  1574. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  1575. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  1576. ->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 )')
  1577. ->count();
  1578. $keyNumbers['careMonthsEligibleForBillGeneration_RM30_HCP'] = CareMonth::where('is_bill_closed', false)
  1579. ->whereNotNull('company_pro_id')
  1580. ->whereNotNull('company_pro_payer_id')
  1581. ->whereNotNull('company_location_id')
  1582. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  1583. ->where('rm_total_time_in_seconds_by_mcp', '>=', 1800)
  1584. ->whereRaw('is_rm_time_waived IS NOT TRUE')
  1585. ->whereRaw('(rm_total_time_in_seconds < 3000 OR (rm_total_time_in_seconds >= 3000 AND is_rm_interaction_waived IS TRUE))')
  1586. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  1587. ->count();
  1588. $keyNumbers['careMonthsEligibleForBillGeneration_RMB'] = CareMonth::where('is_bill_closed', false)
  1589. ->whereNotNull('company_pro_id')
  1590. ->whereNotNull('company_pro_payer_id')
  1591. ->whereNotNull('company_location_id')
  1592. ->whereRaw('(SELECT count(id) FROM care_month_cm_rm_reason WHERE care_month_id = care_month.id) > 0')
  1593. ->whereRaw('is_rm_time_waived IS TRUE')
  1594. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  1595. ->count();
  1596. $keyNumbers['careMonthsWith16OrMoreMeasurementDays'] = CareMonth::where('is_bill_closed', false)
  1597. ->where('number_of_days_with_remote_measurements', '>=', 16 )
  1598. ->count();
  1599. $careMonthsWith16PlusMeasurements = CareMonth::where('is_bill_closed', false)
  1600. ->where('number_of_days_with_remote_measurements', '>=', 16 )->get();
  1601. return view('app.practice-management.rm-launch-and-clean', compact('keyNumbers', 'careMonthsWith16PlusMeasurements'));
  1602. }
  1603. public function processNotes(Request $request) {
  1604. $mode = $request->input('mode') ? $request->input('mode') : '1';
  1605. if(($mode < 1 || $mode > 5) && $mode != 8) $mode = 1;
  1606. DB::enableQueryLog(); // Enable query log
  1607. $test = Note::where('is_cancelled', false)
  1608. ->where('is_signed_by_hcp', true)
  1609. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  1610. ->whereNull('current_note_pickup_for_processing_id')
  1611. ->where('is_billing_marked_done', true)
  1612. ->where('is_bill_closed', true)
  1613. ->where('is_claim_closed', true)
  1614. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  1615. ->count();
  1616. // var_dump($test);
  1617. // dd(DB::getQueryLog()); // Show results of log
  1618. // exit;
  1619. $counts = [
  1620. "picked" => Note::where('is_cancelled', false)
  1621. ->whereNotNull('current_note_pickup_for_processing_id')
  1622. ->count(),
  1623. "bad" => Note::where('is_cancelled', false)
  1624. ->whereRaw("((detail_json)::json->>'isBad' = 'true')")
  1625. ->count(),
  1626. // not yet signed
  1627. "mode-1" => Note::where('is_cancelled', false)
  1628. ->where('is_signed_by_hcp', false)
  1629. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1630. // ->whereNull('current_note_pickup_for_processing_id')
  1631. ->count(),
  1632. // billing not marked done
  1633. "mode-2" => Note::where('is_cancelled', false)
  1634. ->where('is_signed_by_hcp', true)
  1635. //->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1636. // ->whereNull('current_note_pickup_for_processing_id')
  1637. ->where('is_billing_marked_done', false)
  1638. ->count(),
  1639. // billing not closed
  1640. "mode-3" => Note::where('is_cancelled', false)
  1641. ->where('is_signed_by_hcp', true)
  1642. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1643. // ->whereNull('current_note_pickup_for_processing_id')
  1644. ->where('is_billing_marked_done', true)
  1645. ->where('is_bill_closed', false)
  1646. ->count(),
  1647. // claiming not closed
  1648. "mode-4" => Note::where('is_cancelled', false)
  1649. ->where('is_signed_by_hcp', true)
  1650. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1651. // ->whereNull('current_note_pickup_for_processing_id')
  1652. ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true' OR ((detail_json)::json->>'isGood')::text IS NULL)")
  1653. ->where('is_billing_marked_done', true)
  1654. ->where('is_bill_closed', true)
  1655. ->where('is_claim_closed', false)
  1656. ->count(),
  1657. // has unsubmitted claims
  1658. "mode-5" => Note::where('is_cancelled', false)
  1659. /*->where('is_signed_by_hcp', true)
  1660. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1661. ->whereNull('current_note_pickup_for_processing_id')
  1662. ->where('is_billing_marked_done', true)
  1663. ->where('is_bill_closed', true)
  1664. ->where('is_claim_closed', true)
  1665. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0")
  1666. */
  1667. ->where('is_signed_by_hcp', true)
  1668. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1669. // ->whereNull('current_note_pickup_for_processing_id')
  1670. ->where('is_billing_marked_done', true)
  1671. ->where('is_bill_closed', true)
  1672. // ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true')")
  1673. ->where('is_claim_closed', true)
  1674. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0)")
  1675. ->count(),
  1676. // has unsubmitted claims MARKED GOOD!
  1677. "mode-8" => Note::where('is_cancelled', false)
  1678. ->where('is_signed_by_hcp', true)
  1679. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  1680. ->whereNull('current_note_pickup_for_processing_id')
  1681. ->where('is_billing_marked_done', true)
  1682. ->where('is_bill_closed', true)
  1683. ->where('is_claim_closed', false)
  1684. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  1685. ->count(),
  1686. // all good
  1687. "mode-6" => Note::where('is_cancelled', false)
  1688. ->where('is_signed_by_hcp', true)
  1689. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1690. // ->whereNull('current_note_pickup_for_processing_id')
  1691. ->where('is_billing_marked_done', true)
  1692. ->where('is_bill_closed', true)
  1693. ->where('is_claim_closed', true)
  1694. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id) > 0)")
  1695. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  1696. ->count(),
  1697. "mode-7" => Note::where('is_cancelled', false)
  1698. ->whereRaw("(detail_json)::json->>'isBad' = 'true'")
  1699. ->count(),
  1700. ];
  1701. return view('app.practice-management.process-notes', compact('mode', 'counts'));
  1702. }
  1703. public function notesProcessingCenter(Request $request) {
  1704. $notes = Note::where('is_cancelled', false);
  1705. // filters
  1706. $proUid = $request->input('proUid');
  1707. if($proUid) {
  1708. $fPro = Pro::where('uid', $proUid)->first();
  1709. if($fPro) {
  1710. $notes = $notes->where('hcp_pro_id', $fPro->id);
  1711. }
  1712. }
  1713. $proSigned = $request->input('proSigned');
  1714. switch($proSigned) {
  1715. case 'yes': $notes = $notes->where('is_signed_by_hcp', true); break;
  1716. case 'no': $notes = $notes->where('is_signed_by_hcp', '!=', true); break;
  1717. }
  1718. $billingMarkedDone = $request->input('billingMarkedDone');
  1719. switch($billingMarkedDone) {
  1720. case 'yes': $notes = $notes->where('is_billing_marked_done', true); break;
  1721. case 'no': $notes = $notes->where('is_billing_marked_done', '!=', true); break;
  1722. }
  1723. $billingClosed = $request->input('billingClosed');
  1724. switch($billingClosed) {
  1725. case 'yes': $notes = $notes->where('is_bill_closed', true); break;
  1726. case 'no': $notes = $notes->where('is_bill_closed', '!=', true); break;
  1727. }
  1728. $claimingClosed = $request->input('claimingClosed');
  1729. switch($claimingClosed) {
  1730. case 'yes': $notes = $notes->where('is_claim_closed', true); break;
  1731. case 'no': $notes = $notes->where('is_claim_closed', '!=', true); break;
  1732. }
  1733. $allClaimsSubmitted = $request->input('allClaimsSubmitted');
  1734. if($allClaimsSubmitted) {
  1735. // TODO
  1736. }
  1737. $goodBad = $request->input('goodBad');
  1738. switch($goodBad) {
  1739. case 'good': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' = 'false'"); break;
  1740. case 'bad': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' = 'true'"); break;
  1741. case 'unclassified': $notes = $notes->whereRaw("(detail_json)::json->>'isBad' is null"); break;
  1742. }
  1743. $startDate = $request->input('startDate');
  1744. if($startDate) {
  1745. $notes = $notes->where('effective_dateest', '>=', $startDate);
  1746. }
  1747. $endDate = $request->input('endDate');
  1748. if($endDate) {
  1749. $notes = $notes->where('effective_dateest', '<=', $endDate);
  1750. }
  1751. $mcPartB = $request->input('mcPartB');
  1752. if($mcPartB) {
  1753. // TODO
  1754. }
  1755. $notes = $notes->orderBy('effective_dateest')->paginate(10);
  1756. return view('app.practice-management.notes-processing-center', compact('notes'));
  1757. }
  1758. public function getNextNote(Request $request, $mode)
  1759. {
  1760. $note = null;
  1761. switch (+$mode) {
  1762. case 1:
  1763. $note = Note::where('is_cancelled', false)
  1764. ->where('is_signed_by_hcp', false)
  1765. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1766. ->whereNull('current_note_pickup_for_processing_id')
  1767. ->orderBy('effective_dateest', 'DESC')
  1768. ->first();
  1769. break;
  1770. case 2:
  1771. $note = Note::where('is_cancelled', false)
  1772. ->where('is_signed_by_hcp', true)
  1773. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1774. ->whereNull('current_note_pickup_for_processing_id')
  1775. ->where('is_billing_marked_done', false)
  1776. ->orderBy('effective_dateest', 'DESC')
  1777. ->first();
  1778. break;
  1779. case 3:
  1780. $note = Note::where('is_cancelled', false)
  1781. ->where('is_signed_by_hcp', true)
  1782. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1783. ->whereNull('current_note_pickup_for_processing_id')
  1784. ->where('is_billing_marked_done', true)
  1785. ->where('is_bill_closed', false)
  1786. ->orderBy('effective_dateest', 'DESC')
  1787. ->first();
  1788. break;
  1789. case 4: // claiming not closed
  1790. DB::enableQueryLog(); // Enable query log
  1791. $note = Note::where('is_cancelled', false)
  1792. ->where('is_signed_by_hcp', true)
  1793. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1794. ->whereNull('current_note_pickup_for_processing_id')
  1795. ->where('is_billing_marked_done', true)
  1796. ->where('is_bill_closed', true)
  1797. ->whereRaw("(((detail_json)::json->>'isGood')::text <> 'true' OR ((detail_json)::json->>'isGood')::text IS NULL)")
  1798. ->where('is_claim_closed', false)
  1799. ->orderBy('effective_dateest', 'DESC')
  1800. ->first();
  1801. // DB::enableQueryLog(); // Enable query log
  1802. // Your Eloquent query executed by using get()
  1803. // dd(DB::getQueryLog()); // Show results of log
  1804. break;
  1805. case 5:
  1806. $note = Note::where('is_cancelled', false)
  1807. ->where('is_signed_by_hcp', true)
  1808. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1809. ->whereNull('current_note_pickup_for_processing_id')
  1810. ->where('is_billing_marked_done', true)
  1811. ->where('is_bill_closed', true)
  1812. ->where('is_claim_closed', true)
  1813. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') > 0")
  1814. ->orderBy('effective_dateest', 'DESC')
  1815. ->first();
  1816. break;
  1817. case 8:
  1818. $note = Note::where('is_cancelled', false)
  1819. ->where('is_signed_by_hcp', true)
  1820. ->whereRaw("((detail_json)::json->>'isGood')::text = 'true'")
  1821. ->whereNull('current_note_pickup_for_processing_id')
  1822. ->where('is_billing_marked_done', true)
  1823. ->where('is_bill_closed', true)
  1824. ->where('is_claim_closed', false)
  1825. ->whereRaw("((SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0)")
  1826. ->orderBy('effective_dateest', 'DESC')
  1827. ->first();
  1828. break;
  1829. }
  1830. if($note) {
  1831. $note->client_uid = $note->client->uid;
  1832. }
  1833. return json_encode($note);
  1834. }
  1835. public function pickedNotes(Request $request) {
  1836. $counts = [
  1837. "unpicked" => Note::where('is_cancelled', false)
  1838. ->whereNull('current_note_pickup_for_processing_id')
  1839. ->count(),
  1840. ];
  1841. $notes = Note::where('is_cancelled', false)
  1842. ->whereNotNull('current_note_pickup_for_processing_id')
  1843. ->orderBy('effective_dateest', 'ASC')
  1844. ->paginate();
  1845. return view('app.practice-management.picked-notes', compact('counts', 'notes'));
  1846. }
  1847. public function badNotes(Request $request) {
  1848. $counts = [
  1849. "unpicked" => Note::where('is_cancelled', false)
  1850. ->whereNull('current_note_pickup_for_processing_id')
  1851. ->count(),
  1852. ];
  1853. $notes = Note::where('is_cancelled', false)
  1854. ->whereRaw("(detail_json)::json->>'isBad' = 'true'")
  1855. ->orderBy('effective_dateest', 'ASC')
  1856. ->paginate();
  1857. return view('app.practice-management.bad-notes', compact('counts', 'notes'));
  1858. }
  1859. public function doneNotes(Request $request) {
  1860. $counts = [
  1861. "unpicked" => Note::where('is_cancelled', false)
  1862. ->whereNull('current_note_pickup_for_processing_id')
  1863. ->count(),
  1864. ];
  1865. $notes = Note::where('is_cancelled', false)
  1866. ->where('is_signed_by_hcp', true)
  1867. ->whereRaw("((detail_json)::json->>'isBad' is null OR ((detail_json)::json->>'isBad')::text != 'true')")
  1868. ->whereNull('current_note_pickup_for_processing_id')
  1869. ->where('is_billing_marked_done', true)
  1870. ->where('is_bill_closed', true)
  1871. ->where('is_claim_closed', true)
  1872. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id) > 0")
  1873. ->whereRaw("(SELECT count(id) FROM claim WHERE note_id = note.id AND is_cancelled IS FALSE AND status != 'CANCELLED' AND status != 'SUBMITTED') = 0")
  1874. ->orderBy('effective_dateest', 'ASC')
  1875. ->paginate();
  1876. return view('app.practice-management.done-notes', compact('counts', 'notes'));
  1877. }
  1878. public function currentMbClaim(Request $request, $claimUid) {
  1879. $claim = Claim::where('uid', $claimUid)->first();
  1880. return json_encode(MBClaim::where('claim_version_id', $claim->currentVersion->id)->first());
  1881. }
  1882. public function currentClaimLines(Request $request, $claimUid) {
  1883. $claim = Claim::where('uid', $claimUid)->first();
  1884. if($request->input('json')) {
  1885. foreach ($claim->lines as $line) {
  1886. $line->expected_total = round($line->expected_total, 3);
  1887. $x = $line->claimLineIcds;
  1888. }
  1889. return json_encode($claim->lines);
  1890. }
  1891. return view('app.practice-management._claim-lines', compact('claim'));
  1892. }
  1893. public function packsMultiPrint(Request $request) {
  1894. $packs = Pack
  1895. ::select('pack.*')
  1896. ->leftJoin('shipment', function($join) {
  1897. $join->on('pack.shipment_id', '=', 'shipment.id');
  1898. })
  1899. ->whereNotIn('shipment.status', ['CANCELLED', 'DISPATCHED'])
  1900. ->where(function ($query) {
  1901. $query->where('pack.status', '<>', 'DELETED')->orWhereNull('pack.status'); // weird, but just the <> isn't working!
  1902. })
  1903. ->whereNotNull('pack.label_system_file_id')
  1904. ->orderBy('pack.created_at', 'ASC')
  1905. ->get();
  1906. return view('app.practice-management.packs-multi-print', compact('packs'));
  1907. }
  1908. public function packsMultiPDF(Request $request, $ids) {
  1909. $ids = array_map(function ($_x) {
  1910. return intval($_x);
  1911. }, explode("|", $ids));
  1912. $packs = Pack::whereIn('id', $ids)->get();
  1913. }
  1914. public function handouts(Request $request) {
  1915. $handouts = Handout::orderBy('display_name')->get();
  1916. return view('app.practice-management.handouts', compact('handouts'));
  1917. }
  1918. private function callJava($request, $endPoint, $data)
  1919. {
  1920. $url = config('stag.backendUrl') . $endPoint;
  1921. $response = Http::asForm()
  1922. ->withHeaders([
  1923. 'sessionKey' => $request->cookie('sessionKey')
  1924. ])
  1925. ->post($url, $data)
  1926. ->body();
  1927. dd($response);
  1928. return $response;
  1929. }
  1930. public function genericBills(Request $request)
  1931. {
  1932. return view('app.practice-management.generic-bills');
  1933. }
  1934. public function billsUnderProcessing(Request $request)
  1935. {
  1936. $bills = Bill::where('is_cancelled', false)
  1937. ->where(function ($query) { // mcp of any client program and program OB pending
  1938. $query
  1939. ->where(function ($_query) {
  1940. $_query->where('hcp_pro_id', $this->pro->id)
  1941. ->where('hcp_expected_payment_amount', '>', 0)
  1942. ->where('has_hcp_been_paid', false)
  1943. ->where('is_signed_by_hcp', true);
  1944. })
  1945. ->orWhere(function ($_query) {
  1946. $_query->where('cm_pro_id', $this->pro->id)
  1947. ->where('cm_expected_payment_amount', '>', 0)
  1948. ->where('has_cm_been_paid', false)
  1949. ->where('is_signed_by_cm', true);
  1950. })
  1951. ->orWhere(function ($_query) {
  1952. $_query->where('rme_pro_id', $this->pro->id)
  1953. ->where('rme_expected_payment_amount', '>', 0)
  1954. ->where('has_rme_been_paid', false)
  1955. ->where('is_signed_by_rme', true);
  1956. })
  1957. ->orWhere(function ($_query) {
  1958. $_query->where('rmm_pro_id', $this->pro->id)
  1959. ->where('rmm_expected_payment_amount', '>', 0)
  1960. ->where('has_rmm_been_paid', false)
  1961. ->where('is_signed_by_rmm', true);
  1962. })
  1963. ->orWhere(function ($_query) {
  1964. $_query->where('generic_pro_id', $this->pro->id)
  1965. ->where('generic_pro_expected_payment_amount', '>', 0)
  1966. ->where('has_generic_pro_been_paid', false)
  1967. ->where('is_signed_by_generic_pro', true);
  1968. });
  1969. })
  1970. ->orderBy('created_at', 'DESC')
  1971. ->paginate();
  1972. return view('app.practice-management.bills-under-processing', compact('bills'));
  1973. }
  1974. public function careMonthReport(Request $request) {
  1975. $m = $request->input('m');
  1976. $y = $request->input('y');
  1977. if(!$m || !$y) {
  1978. $date = date('Y-m-01');
  1979. }
  1980. else {
  1981. $date = date('Y-m-d', strtotime("$m/1/$y"));
  1982. }
  1983. $pro = $this->pro;
  1984. $records = DB::select("
  1985. SELECT cm.id as care_month_id,
  1986. cm.uid as care_month_uid,
  1987. c.id as client_id,
  1988. c.uid as client_uid,
  1989. cm.number_of_days_with_remote_measurements,
  1990. cm.rm_total_time_in_seconds_by_mcp,
  1991. cm.rm_total_time_in_seconds_by_rme_pro,
  1992. cm.rm_total_time_in_seconds_by_rmm_pro,
  1993. cm.mcp_pro_id,
  1994. cm.rme_pro_id,
  1995. cm.rmm_pro_id,
  1996. (c.name_first || ' ' || c.name_last) as client_name
  1997. FROM care_month cm
  1998. JOIN client c on cm.client_id = c.id
  1999. WHERE cm.start_date = :startDate
  2000. AND (cm.mcp_pro_id = :proID OR
  2001. cm.rme_pro_id = :proID OR
  2002. cm.rmm_pro_id = :proID)
  2003. ORDER BY c.name_last, c.name_first
  2004. ",
  2005. ['startDate' => $date, 'proID' => $pro->id]
  2006. );
  2007. return view('app.practice-management.care-month-report', compact('records', 'date'));
  2008. }
  2009. public function myTeams(Request $request) {
  2010. $pro = $this->pro;
  2011. // get all teams where the authed-pro is the assistant pro
  2012. $teams = ProTeam::where('assistant_pro_id', $pro->id)
  2013. ->where('is_active', true)
  2014. ->orderBy('slug')
  2015. ->get();
  2016. return view('app.practice-management.my-teams', compact('teams'));
  2017. }
  2018. public function patientsAccountsInvites(Request $request){
  2019. $filters = $request->all();
  2020. $accountInvites = AccountInvite::select('account_invite.*')
  2021. ->join('client', 'client.id', '=', 'account_invite.for_client_id');
  2022. if($this->performer->pro->pro_type !== 'ADMIN'){
  2023. $accountInvites = $accountInvites->where('client.mcp_pro_id', $this->performer->pro->id);
  2024. }
  2025. $this->filterMultiQuery($request, $accountInvites, 'account_invite.created_at', 'date_category', 'date_value_1', 'date_value_2');
  2026. $this->filterSimpleQuery($request, $accountInvites, 'account_invite.status', 'status');
  2027. $accountInvites = $accountInvites->orderBy('created_at', 'DESC')->paginate(20);
  2028. return view('app.practice-management.patients-accounts-invites', compact('accountInvites','filters'));
  2029. }
  2030. public function clientsBdtDevices(Request $request){
  2031. $filters = $request->all();
  2032. $devices = ClientBDTDevice::select('client_bdt_device.*')
  2033. ->join('client', 'client.id', '=', 'client_bdt_device.client_id');
  2034. if($this->performer->pro->pro_type !== 'ADMIN'){
  2035. $devices = $devices->where('client.mcp_pro_id', $this->performer->pro->id);
  2036. }
  2037. $this->filterMultiQuery($request, $devices, 'client_bdt_device.created_at', 'date_category', 'date_value_1', 'date_value_2');
  2038. $status = $request->get('status');
  2039. if($status){
  2040. if($status === 'ACTIVE') $devices = $devices->where('client_bdt_device.is_active', true);
  2041. if($status === 'DEACTIVATED') $devices = $devices->where('client_bdt_device.is_active', false);
  2042. }
  2043. $devices = $devices->orderBy('created_at', 'DESC')->paginate(20);
  2044. return view('app.practice-management.clients_bdt_devices', compact('devices','filters'));
  2045. }
  2046. public function memos(Request $request){
  2047. $filters = $request->all();
  2048. $memos = ClientMemo::select('client_memo.*')
  2049. ->join('client', 'client.id', '=', 'client_memo.client_id');
  2050. if($this->performer->pro->pro_type !== 'ADMIN'){
  2051. $memos = $memos->where('client.mcp_pro_id', $this->performer->pro->id);
  2052. }
  2053. $this->filterMultiQuery($request, $memos, 'client_memo.created_at', 'date_category', 'date_value_1', 'date_value_2');
  2054. $this->filterSimpleQuery($request, $memos, 'category', 'category');
  2055. $memos = $memos->orderBy('created_at', 'DESC')->paginate(20);
  2056. return view('app.practice-management.memos', compact('memos', 'filters'));
  2057. }
  2058. public function clientCcmRmStatus(Request $request){
  2059. $filters = $request->all();
  2060. $patients = Client::whereNull('shadow_pro_id');
  2061. // filters
  2062. /*
  2063. array:18 [▼
  2064. "age_category" => "LESS_THAN"
  2065. "age_value_1" => "34"
  2066. "age_value_2" => null
  2067. "sex" => "M"
  2068. "bmi_category" => "BETWEEN"
  2069. "bmi_value_1" => "20"
  2070. "bmi_value_2" => "25"
  2071. "last_visit_category" => "LESS_THAN"
  2072. "last_visit_value_1" => "2021-10-14"
  2073. "last_visit_value_2" => null
  2074. "next_appointment_category" => "LESS_THAN"
  2075. "next_appointment_value_1" => "2021-10-15"
  2076. "status" => "ACTIVE"
  2077. "last_weighed_in_category" => "EXACTLY"
  2078. "last_weighed_in_value_1" => "2021-10-07"
  2079. "last_bp_category" => "BETWEEN"
  2080. "last_bp_value_1" => "2021-10-01"
  2081. "last_bp_value_2" => "2021-10-31"
  2082. ]
  2083. */
  2084. $this->filterMultiQuery($request, $patients, 'age_in_years', 'age_category', 'age_value_1', 'age_value_2');
  2085. $this->filterSimpleQuery($request, $patients, 'sex', 'sex');
  2086. $this->filterMultiQuery($request, $patients, 'usual_bmi', 'bmi_category', 'bmi_value_1', 'bmi_value_2');
  2087. $this->filterMultiQuery($request, $patients, 'most_recent_weight_at', 'last_weighed_in_category', 'last_weighed_in_value_1', 'last_weighed_in_value_2');
  2088. $this->filterMultiQuery($request, $patients, 'most_recent_bp_at', 'last_bp_category', 'last_bp_value_1', 'last_bp_value_2');
  2089. switch($request->input('status')) {
  2090. case 'ACTIVE':
  2091. $patients->where('is_active', true)->where('has_mcp_done_onboarding_visit', true);
  2092. break;
  2093. case 'AWAITING_VISIT':
  2094. $patients->where('is_active', true)->where('has_mcp_done_onboarding_visit', false);
  2095. break;
  2096. case 'INACTIVE':
  2097. $patients->where('is_active', '<>', true);
  2098. break;
  2099. }
  2100. if($request->input('is_eligible_for_cm')){
  2101. $patients->where('is_eligible_for_cm', '=', $request->input('is_eligible_for_cm'));
  2102. }
  2103. if($request->input('is_enrolled_in_cm')){
  2104. $patients->where('is_enrolled_in_cm', '=', $request->input('is_enrolled_in_cm'));
  2105. }
  2106. if($request->input('has_cm_setup_been_performed')){
  2107. $patients->where('has_cm_setup_been_performed', '=', $request->input('has_cm_setup_been_performed')=='YES'? true : false);
  2108. }
  2109. if($request->input('is_eligible_for_rm')){
  2110. $patients->where('is_eligible_for_rm', '=', $request->input('is_eligible_for_rm'));
  2111. }
  2112. if($request->input('is_enrolled_in_rm')){
  2113. $patients->where('is_enrolled_in_rm', '=', $request->input('is_enrolled_in_rm'));
  2114. }
  2115. if($request->input('has_rm_setup_been_performed')){
  2116. $patients->where('has_rm_setup_been_performed', '=', $request->input('has_rm_setup_been_performed') =='YES'? true : false);
  2117. }
  2118. $patients = $patients->orderBy('created_at', 'DESC')->paginate(20);
  2119. return view('app.admin.client-ccm-rm-status', compact('patients', 'filters'));
  2120. }
  2121. }