2019-07-30 21:29:24 +00:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
2018-03-25 16:15:39 +00:00
|
|
|
# License: AGPL-3.0-or-later WITH Web-Template-Output-Additional-Permission-3.0-or-later
|
2018-03-25 17:30:42 +00:00
|
|
|
require 'qx'
|
|
|
|
|
|
|
|
module InsertEmailLists
|
|
|
|
def self.for_mailchimp(npo_id, tag_master_ids)
|
|
|
|
# Partial SQL expression for deleting deselected tags
|
|
|
|
delete_expr = Qx.delete_from(:email_lists).where(nonprofit_id: npo_id).returning('mailchimp_list_id')
|
|
|
|
|
|
|
|
if tag_master_ids.empty? # no tags were selected; remove all email lists
|
|
|
|
deleted = delete_expr.execute
|
|
|
|
else # Remove all email lists that exist in the db that are not included in tag_master_ids
|
2019-07-30 21:29:24 +00:00
|
|
|
deleted = delete_expr.where('tag_master_id NOT IN($ids)', ids: tag_master_ids).execute
|
2018-03-25 17:30:42 +00:00
|
|
|
end
|
2019-07-30 21:29:24 +00:00
|
|
|
mailchimp_lists_to_delete = deleted.map { |h| h['mailchimp_list_id'] }
|
2018-03-25 17:30:42 +00:00
|
|
|
result = Mailchimp.delete_mailchimp_lists(npo_id, mailchimp_lists_to_delete)
|
|
|
|
|
2019-07-30 21:29:24 +00:00
|
|
|
return { deleted: deleted, deleted_result: result } if tag_master_ids.empty?
|
2018-03-25 17:30:42 +00:00
|
|
|
|
2019-07-30 21:29:24 +00:00
|
|
|
existing = Qx.select('tag_master_id').from(:email_lists)
|
|
|
|
.where(nonprofit_id: npo_id)
|
|
|
|
.and_where('tag_master_id IN ($ids)', ids: tag_master_ids)
|
|
|
|
.execute
|
2018-03-25 17:30:42 +00:00
|
|
|
tag_master_ids -= existing
|
|
|
|
|
|
|
|
lists = Mailchimp.create_mailchimp_lists(npo_id, tag_master_ids)
|
2019-07-30 21:29:24 +00:00
|
|
|
if !lists || lists.none? || !lists.first[:name]
|
|
|
|
raise Exception, "Unable to create mailchimp lists. Response was: #{lists}"
|
2018-03-25 17:30:42 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
inserted_lists = Qx.insert_into(:email_lists)
|
2019-07-30 21:29:24 +00:00
|
|
|
.values(lists.map { |ls| { list_name: ls[:name], mailchimp_list_id: ls[:id], tag_master_id: ls[:tag_master_id] } })
|
|
|
|
.common_values(nonprofit_id: npo_id)
|
|
|
|
.ts
|
|
|
|
.returning('*')
|
|
|
|
.execute
|
2018-03-25 17:30:42 +00:00
|
|
|
|
2019-11-07 21:46:11 +00:00
|
|
|
EmailListCreateJob.perform_later(npo_id)
|
2018-03-25 17:30:42 +00:00
|
|
|
|
2019-07-30 21:29:24 +00:00
|
|
|
{ deleted: deleted, deleted_result: result, inserted_lists: inserted_lists, inserted_result: lists }
|
2018-03-25 17:30:42 +00:00
|
|
|
end
|
|
|
|
end
|