Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*****************************************************************************
- * bg_POPSAVisitReportEmailService
- *
- * Handler class for the POPSA/Visit Report email service
- *
- * Author:
- * Date: 30/01/2018
- * Changes:
- *****************************************************************************/
- global class bg_POPSAVisitReportEmailService implements Messaging.InboundEmailHandler
- {
- //Initiialize these to the account/contact given in the email body. These will then be used to query the database.
- // The boolean accountInEmailBody etc. will be used to generate soql queries... ie if(accountInEmailBody)... create soql query
- // else don't create soqlquery.
- @TestVisible boolean isPopsa = false;
- @TestVisible boolean isMeetingNote = false;
- @TestVisible boolean isCall = false;
- Visit_Report__c popsaVisitReport;
- Meeting_Note__c meetingNote;
- Meeting_Note__c meetingCall;
- String accountName;
- String accountUniqueId;
- boolean accountInEmailBody = false;
- String contactName;
- boolean contactInEmailBody = false;
- String opportunityName;
- boolean opportunityNameInEmailBody = false;
- String campaignName;
- boolean campaignInEmailBody = false;
- String priceReview;
- @TestVisible boolean priceReviewInEmailBody = false;
- String description = '';
- User owner;
- boolean ownerGiven = false;
- String ownerName;
- global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope envelope)
- {
- //retrieve the email body, title and address
- String emailBody = email.plainTextBody;
- String title = email.subject.split('-')[1].trim();
- String emailAddress = email.fromAddress;
- //Separate the email body from the signature.
- if (email.plainTextBody.containsIgnoreCase(Label.Signature))
- {
- Integer index = emailbody.indexOfIgnoreCase(Label.Signature);
- emailBody = emailBody.left(index);
- }
- // Determine the type based on the context of the email
- if (email.subject.containsIgnoreCase(Label.Popsa))
- {
- isPopsa = true;
- popsaVisitReport = new Visit_Report__c();
- popsaVisitReport.put('RecordTypeID', Schema.Sobjecttype.Visit_Report__c.getRecordTypeInfosByName().get(Label.Popsa).getRecordTypeId());
- createPOPSAMeetingNoteOrCall(popsaVisitReport, title, emailAddress, emailBody, isPopsa, isMeetingNote, isCall, email);
- }
- else if (email.subject.containsIgnoreCase(Label.Meeting_Note))
- {
- isMeetingNote = true;
- meetingNote = new Meeting_Note__c();
- meetingNote.put('RecordTypeId', Schema.SObjectType.Meeting_Note__c.getRecordTypeInfosByName().get(Label.Meeting_Note).getRecordTypeId());
- createPOPSAMeetingNoteOrCall(meetingNote, title, emailAddress, emailBody, isPopsa, isMeetingNote, isCall, email);
- }
- else if (email.subject.containsIgnoreCase(Label.Call))
- {
- isCall = true;
- meetingCall = new Meeting_Note__c();
- meetingCall.put('RecordTypeId', Schema.SObjectType.Meeting_Note__c.getRecordTypeInfosByName().get(Label.Meeting_Note).getRecordTypeId());
- createPOPSAMeetingNoteOrCall(meetingCall, title, emailAddress, emailBody, isPopsa, isMeetingNote, isCall, email);
- }
- // Return service result
- Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
- result.success = true;
- return result;
- }
- //This method will be called in each of the else if statements for POPSA, Meeting Note or Call and
- // create the appropriate object and assign the email contents to the correct fields.
- public void createPOPSAMeetingNoteOrCall(sObject obj, String title, String emailAddress, String emailBody, boolean popsa, boolean meetingNote, boolean call, Messaging.inboundEmail inboundEmail)
- {
- obj.put('Name', title);
- obj.put('Created_by_Email__c', true);
- obj.put('Original_Email_Sender__c', emailAddress);
- // Populate a map of the custom settings fields.
- Map<String, POPSA_Field_Mappings__c> fieldMappings = POPSA_Field_Mappings__c.getall();
- Set<String> customSettingsKeys = fieldMappings.keySet();
- // Create a new String list of the field set fields
- List<String> fieldSetFieldStrings = new list<String>();
- //Split the email body into individual lines.
- List<String> emailBodyLines = emailBody.split('\n');
- List<String> errorList = new List<String>();
- //iterate over the whole email body
- for(String line : emailBodyLines)
- {
- //potentialFieldName is what is to the left of the colon e.g account, contact etc.
- // specific record is what is to the right of the colon e.g. Craig Test Account
- String potentialFieldName = line.split(':')[0].toUpperCase();
- String specificRecord = '';
- // Check that what is written to the left of the colon is a field in the custom settings map.
- if(fieldMappings.containsKey(potentialFieldName))
- {
- //if the types of the fied map are lookups and not cheeckboxes, dates etc.
- if(!fieldMappings.get(potentialFieldName).Field_Type__c.equalsIgnoreCase('String')
- && !fieldMappings.get(potentialFieldName).Field_Type__c.equalsIgnoreCase('DateTime')
- && !fieldMappings.get(potentialFieldName).Field_Type__c.equalsIgnoreCase('Date')
- && !fieldMappings.get(potentialFieldName).Field_Type__c.equalsIgnoreCase('Boolean'))
- {
- if(potentialFieldName.equalsIgnoreCase('Account'))
- {
- if(line.split(':').size() >= 1)
- {
- specificRecord = line.remove(line.left(line.indexOf(':') + 1));
- // gets the bit between Account: and @Test.com
- accountName = specificRecord.split('@')[0].trim();
- //adds underscores
- accountUniqueId = accountName.replaceAll('(\\s+)', '_');
- //adds what is right of the @ to the account name.
- //The account name should now read craig@test.com for example.
- accountUniqueId += line.substring(line.indexOf('@'));
- accountInEmailBody = true;
- }
- }
- else if(potentialFieldName.equalsIgnoreCase('Contact'))
- {
- if(line.split(':').size() >= 1)
- {
- specificRecord = line.remove(line.left(line.indexOf(':') + 1));
- contactName = specificRecord.trim();
- contactInEmailBody = true;
- }
- }
- else if(potentialFieldName.equalsIgnoreCase('Opportunity'))
- {
- if(line.split(':').size() >= 1)
- {
- specificRecord = line.remove(line.left(line.indexOf(':') + 1));
- opportunityName = specificRecord.trim();
- opportunityNameInEmailBody = true;
- }
- }
- else if(potentialFieldName.equalsIgnoreCase('Campaign'))
- {
- if(line.split(':').size() >= 1)
- {
- specificRecord = line.remove(line.left(line.indexOf(':') + 1));
- campaignName = specificRecord.trim();
- campaignInEmailBody = true;
- }
- }
- else if(potentialFieldName.equalsIgnoreCase('Price_Review'))
- {
- if(line.split(':').size() >= 1)
- {
- specificRecord = line.remove(line.left(line.indexOf(':') + 1));
- priceReview = specificRecord.trim();
- priceReviewInEmailBody = true;
- }
- }
- }
- //Could add extra logic if the user enters the time as well... but that might affect the functionality if time isn't given.
- if(fieldMappings.get(potentialFieldName).Field_Type__c.equalsIgnoreCase('Owner'))
- {
- ownerGiven = true;
- specificRecord = line.split(':')[1];
- ownerName = specificRecord.trim();
- }
- if(fieldMappings.get(potentialFieldName).Field_Type__c.equalsIgnoreCase('Date'))
- {
- try
- {
- specificRecord = line.split(':')[1];
- List<String> splitDateStrings = specificRecord.split('/');
- String day = splitDateStrings[0].trim();
- String month = splitDateStrings[1].trim();
- String year = splitDateStrings[2].trim();
- boolean dayNumeric = day.isNumeric();
- boolean monthNumeric = month.isNumeric();
- boolean yearNumeric = year.isNumeric();
- if((day.length() == 2) && (month.length() == 2) && (year.length() == 4) && dayNumeric && monthNumeric && yearNumeric)
- {
- if(popsa)
- {
- DateTime startDateTime = DateTime.newInstance(Integer.valueOf(year), Integer.valueOf(month), Integer.valueOf(day), 12, 0, 0);
- DateTime endDateTime = DateTime.newInstance(Integer.valueOf(year), Integer.valueOf(month), Integer.valueOf(day), 12, 30, 0);
- obj.put('Event_Start__c', startDateTime);
- obj.put('Event_End__c', endDateTime);
- }
- else
- {
- Date meetingDate = Date.newInstance(Integer.valueOf(year), Integer.valueOf(month), Integer.valueOf(day));
- obj.put('Meeting_Date__c', meetingDate);
- }
- }
- else
- {
- // date has not been given in the correct format
- }
- }
- catch(ListException e)
- {
- }
- }
- }
- else
- {
- description += line + '\n';
- }
- }
- //if the owner is given, query the db for email and name that match. if 1 is returned then assign that user as the owner
- //This will only work if the person who sends the email is trying to make themselves the owner. Unless they send from
- // a common address.
- if(ownerGiven)
- {
- List<User> userList = [select id, name from User where email = :emailAddress AND name = :ownerName AND IsActive = true];
- if(userList.size() == 1)
- {
- owner = userList.get(0);
- obj.put('ownerId', owner.id);
- }
- }
- else
- {
- List<User> userList = [select id, name from User where email = :emailAddress AND IsActive = true];
- if(userList.size() != 0)
- {
- owner = [select Id, Name from User where email = :emailAddress AND isActive = true LIMIT 1];
- obj.put('ownerId', owner.Id);
- }
- else
- {
- owner = [select Id, Name FROM USer where email ='shell.sfdc@brightgen.com' and IsActive = true LIMIT 1];
- obj.put('ownerId', owner.Id);
- }
- }
- if(accountInEmailBody)
- {
- //Query the database for the given account and look to see if one account is returned.
- List<Account> accountList = [SELECT Id FROM Account WHERE Unique_Identifier__c = :accountUniqueId AND Active__c = true];
- if(accountList.size() == 1)
- {
- Id accountId = accountList.get(0).Id;
- if(popsa)
- {
- obj.put('Account_Name__c', accountId);
- }
- else
- {
- obj.put('Account__c', accountId);
- }
- }
- else
- {
- errorList.add('Account');
- }
- }
- //If the email sender has put a contact in the email body, query the database to find the contact
- //if there is only one with that name,add it to the popsa.
- if(contactInEmailBody)
- {
- List<Contact> contactList = [SELECT Id FROM Contact WHERE Name = :contactName AND Active__c = true];
- if(contactList.size() == 1)
- {
- Id contactId = contactList.get(0).Id;
- if(popsa)
- {
- obj.put('Contact_Name__c', contactId);
- }
- else
- {
- obj.put('Contact__c', contactId);
- }
- }
- else
- {
- errorList.add('Contact');
- }
- }
- if(opportunityNameInEmailBody)
- {
- List<Opportunity> opportunityList = [SELECT Id FROM Opportunity WHERE Name = :opportunityName];
- if(opportunityList.size() == 1)
- {
- Id opportunityId = opportunityList.get(0).Id;
- if(popsa)
- {
- obj.put('Opportunity_Name__c', opportunityId);
- }
- else
- {
- obj.put('Opportunity__c', opportunityId);
- }
- }
- else
- {
- errorList.add('Opportunity');
- }
- }
- if(campaignInEmailBody)
- {
- List<Campaign> campaignList = [SELECT Id FROM Campaign WHERE Name = :campaignName];
- if(campaignList.size() == 1)
- {
- Id campaignId = campaignList.get(0).Id;
- obj.put('Campaign__c', campaignId);
- }
- else
- {
- errorList.add('Campaign');
- }
- }
- if(priceReviewInEmailBody)
- {
- if(popsa)
- {
- List<Price_Review__c> priceReviewList = [SELECT Id FROM Price_Review__c WHERE Name = :priceReview];
- if(priceReviewList.size() == 1)
- {
- Id priceReviewId = priceReviewList.get(0).Id;
- obj.put('Price_Review__c', priceReviewId);
- obj.put('Customer_Type__c', 'Price Review');
- }
- else
- {
- errorList.add('Price_Review');
- }
- }
- }
- if(popsa)
- {
- obj.put(Label.POPSA_c, description);
- }
- else
- {
- obj.put(Label.Meeting_Note_c, description);
- }
- insert obj;
- if (inboundEmail.binaryAttachments != null && inboundEmail.binaryAttachments.size() > 0)
- {
- for (integer i = 0 ; i < inboundEmail.binaryAttachments.size() ; i++) {
- Attachment attachment = new Attachment();
- attachment.ParentId = popsaVisitReport.Id;
- attachment.Name = inboundEmail.binaryAttachments[i].filename;
- attachment.Body = inboundEmail.binaryAttachments[i].body;
- insert attachment;
- }
- }
- if (!errorList.isEmpty())
- {
- Task reminderTask = new Task(
- OwnerID = owner.Id,
- Status = Label.Open,
- Priority = Label.High
- );
- if (popsa)
- {
- reminderTask.Subject = Label.Popsa_Reminder;
- }
- else if (meetingNote)
- {
- reminderTask.Subject = Label.Meeting_Note_Reminder;
- }
- else if (call)
- {
- reminderTask.Subject = Label.Logged_Call_Reminder;
- }
- if ([select Id from User where email = :emailAddress].size() != 0)
- {
- reminderTask.OwnerId = [select Id, Name from User where email = :emailAddress and IsActive = true LIMIT 1].Id;
- }
- else
- {
- reminderTask.ownerID = [select Id, Name FROM USer where email ='shell.sfdc@brightgen.com' and IsActive = true LIMIT 1].Id;
- }
- string returnEmailBody = owner != null ? Label.Dear + ' ' + owner.Name + ',\n' : Label.Dear + ' User,';
- string errorFieldString = '';
- for (String line : errorList)
- {
- if (line.contains('Account'))
- {
- returnEmailBody += Label.Unable_to_Identify + '\n' + URL.getSalesforceBaseURL().toExternalForm() + '/' + obj.Id +'\n\n';
- }
- else
- {
- errorFieldString += line + ', ';
- }
- }
- errorFieldString = errorFieldString.trim().removeEnd(',') + ' ';
- String correctedLabel = Label.Unable_to_Identify_Other.replace('$Field', errorFieldString);
- returnEmailBody += correctedLabel + '\n' + URL.getSalesforceBaseURL().toExternalForm() + '/' + obj.Id + ' \n\n' + Label.Many_Thanks;
- reminderTask.Description = returnEmailBody;
- insert reminderTask;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement