Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a rake task to bulk invite users to an organization #578

Merged
merged 2 commits into from
Nov 20, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions lib/tasks/membership.rake
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
require "csv"

namespace :membership do
desc "Bulk invite members of an organization"
task :bulk_invite, %i[org_slug role filename sender_email] => [:destructive, :environment] do |_, args|
org_slug = args[:org_slug].to_s
org = Accounts::Organization.find_by slug: org_slug
abort "Org not found!" unless org

role = args[:role].to_s
abort "Invalid role" unless Accounts::Invite.roles.value?(role)

input_filename = args[:filename].to_s
abort "Provide a valid filename" if input_filename.blank?
abort "File does not exist" unless File.exist?(input_filename)

sender_email = args[:sender_email].to_s
abort "Sender email must be provided!" if sender_email.blank?
sender = org.users.find_by(email: sender_email)
abort "Sender not found!" if sender.blank?
abort "Sender does not have permissions to invite" unless sender.writer_for?(org)

csv_text = File.read(input_filename)
emails = CSV.parse(csv_text, headers: false)&.flatten

abort "No emails present in the file" if emails.empty?

existing_emails = org.invites.where(email: emails).pluck(:email)

new_emails = Set.new(emails) - Set.new(existing_emails)

new_emails.each do |email|
ActiveRecord::Base.transaction do
invite = Accounts::Invite.new({organization_id: org.id, role:, email:})
invite.sender = sender

if invite.save
if invite.recipient.present?
InvitationMailer.existing_user(invite).deliver
else
InvitationMailer.new_user(invite).deliver
end
else
puts "There was an error while saving the invite for #{email}!"
end
end
rescue Postmark::ApiInputError
puts "There was a delivery error while sending the invite for #{email}!"
end

puts "Invites successfully sent!"
end
end