diff --git a/app/controllers/organisations_controller.rb b/app/controllers/organisations_controller.rb index ff7d4db9a..cb600b004 100644 --- a/app/controllers/organisations_controller.rb +++ b/app/controllers/organisations_controller.rb @@ -29,13 +29,24 @@ class OrganisationsController < ApplicationController end def users - @pagy, @users = pagy(filtered_users(@organisation.users.sorted_by_organisation_and_role, search_term)) - @searched = search_term.presence - @total_count = @organisation.users.size - if current_user.support? - render "users", layout: "application" - else - render "users/index" + organisation_users = @organisation.users.sorted_by_organisation_and_role + unpaginated_filtered_users = filtered_collection(organisation_users, search_term) + + respond_to do |format| + format.html do + @pagy, @users = pagy(unpaginated_filtered_users) + @searched = search_term.presence + @total_count = @organisation.users.size + + if current_user.support? + render "users", layout: "application" + else + render "users/index" + end + end + format.csv do + send_data unpaginated_filtered_users.to_csv, filename: "users-#{@organisation.name}-#{Time.zone.now}.csv" + end end end diff --git a/app/views/users/_user_list.html.erb b/app/views/users/_user_list.html.erb index 7876d77dc..786e3c571 100644 --- a/app/views/users/_user_list.html.erb +++ b/app/views/users/_user_list.html.erb @@ -4,7 +4,7 @@ <%= render(SearchResultCaptionComponent.new(searched:, count: pagy.count, item_label:, total_count:, item: "users", path: request.path)) %> <% if current_user.support? %> <% query = searched.present? ? "?search=#{searched}" : nil %> - <%= govuk_link_to "Download (CSV)", "/users.csv#{query}", type: "text/csv" %> + <%= govuk_link_to "Download (CSV)", "#{request.path}.csv#{query}", type: "text/csv" %> <% end %> <% end %> <%= table.head do |head| %> diff --git a/spec/requests/organisations_controller_spec.rb b/spec/requests/organisations_controller_spec.rb index acc5c8da7..e17f140f5 100644 --- a/spec/requests/organisations_controller_spec.rb +++ b/spec/requests/organisations_controller_spec.rb @@ -1054,5 +1054,31 @@ RSpec.describe OrganisationsController, type: :request do end end end + + context "when they view the users tab" do + before do + get "/organisations/#{organisation.id}/users" + end + + it "has a CSV download button with the correct path" do + expect(page).to have_link("Download (CSV)", href: "/organisations/#{organisation.id}/users.csv") + end + + context "when you download the CSV" do + let(:headers) { { "Accept" => "text/csv" } } + let(:other_organisation) { FactoryBot.create(:organisation) } + + before do + FactoryBot.create_list(:user, 3, organisation:) + FactoryBot.create_list(:user, 2, organisation: other_organisation) + end + + it "only includes users from that organisation" do + get "/organisations/#{other_organisation.id}/users", headers:, params: {} + csv = CSV.parse(response.body) + expect(csv.count).to eq(3) + end + end + end end end