PracticeManagementController.php 96 KB

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