Created
January 22, 2019 21:48
-
-
Save benjaminkreen/5a81f100953fe817099419ce1f82289f to your computer and use it in GitHub Desktop.
A discourse scheduled job to import plos salesforce users
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Jobs | |
class ::PlosSalesforceUserImporter < Jobs::Scheduled | |
every 2.hours # TODO: not sure if correct | |
CLIENT_KEYS = [:username, :password, :client_id, :client_secret, :host] | |
SETTING_PREFIX = 'plos_salesforce_user_importer_' | |
IMPORT_FIELDS = %w( | |
Id PersonEmail Salutation FirstName LastName Name | |
Affiliation__pc GUID_Acct__c ORCiD__c Iso_Country_Code__pc | |
Member_Status__c | |
) | |
EDITOR_FIELDS = { | |
'plosone' => 'Editor_Role__c', | |
'plosbiology' => 'Editor_Role_Biology__c', | |
'plosmedicine' => 'Editor_Role_Medicine__c', | |
'plosgenetics' => 'Editor_Role_Genetics__c', | |
'plospathogens' => 'Editor_Role_Pathogens__c', | |
'plosntds' => 'Editor_Role_NTDs__c', | |
'ploscompbiol' => 'Editor_Role_Comp_Bio__c' | |
} | |
def execute(args = nil) | |
# TODO: more robust error handling and notification | |
SiteSetting.plos_salesforce_user_importer_journals.split('|').each do |journal| | |
import_response = {} | |
accounts = client.query(accounts_query(EDITOR_FIELDS[journal])) | |
accounts.each do |account| | |
status = { salesforce: "No operation happened." } | |
user = User.find_or_initialize_by(email: account.PersonEmail).tap do |u| | |
u.name = "#{account.FirstName} #{account.LastName}" | |
u.title = account.Salutation | |
# TODO: support custom fields | |
u.save | |
end | |
if user.persisted? | |
status[:discourse] = "User created or updated" | |
account.Member_Status_Date__c = Date.today.to_s | |
status[:salesforce] = account.save ? "Member status date updated" : "Update failed" | |
else | |
status[:discourse] = user.errors.messages.to_s | |
end | |
import_response["#{account.Salutation} #{account.FirstName} #{account.LastName} - #{account.PersonEmail}"] = status | |
end | |
end | |
# TODO: send import_response to admin email address | |
end | |
private | |
def client | |
@client ||= Restforce.new(client_args) | |
end | |
def client_args | |
CLIENT_KEYS.each_with_object({}) { |key, obj| obj[key] = SiteSetting.send("#{SETTING_PREFIX}#{key}") } | |
end | |
def accounts_query(journal_field) | |
"select #{IMPORT_FIELDS.join(',')}, #{journal_field} from Account " + | |
"where Member_Status__c = 'Import' and #{journal_field} != NULL and " + | |
"CALENDAR_YEAR(LastModifiedDate) >= #{Date.today.year} and " + | |
"CALENDAR_MONTH(LastModifiedDate) >= #{Date.today.month - 1}" | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment