Advertisement
Guest User

Untitled

a guest
Oct 16th, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.79 KB | None | 0 0
  1. /*****************************************************************************
  2. * bg_POPSAVisitReportEmailService
  3. *
  4. * Handler class for the POPSA/Visit Report email service
  5. *
  6. * Author:
  7. * Date: 30/01/2018
  8. * Changes:
  9. *****************************************************************************/
  10.  
  11. global class bg_POPSAVisitReportEmailService implements Messaging.InboundEmailHandler
  12. {
  13.  
  14. //Initiialize these to the account/contact given in the email body. These will then be used to query the database.
  15. // The boolean accountInEmailBody etc. will be used to generate soql queries... ie if(accountInEmailBody)... create soql query
  16. // else don't create soqlquery.
  17.  
  18. @TestVisible boolean isPopsa = false;
  19. @TestVisible boolean isMeetingNote = false;
  20. @TestVisible boolean isCall = false;
  21. Visit_Report__c popsaVisitReport;
  22. Meeting_Note__c meetingNote;
  23. Meeting_Note__c meetingCall;
  24. String accountName;
  25. String accountUniqueId;
  26. boolean accountInEmailBody = false;
  27. String contactName;
  28. boolean contactInEmailBody = false;
  29. String opportunityName;
  30. boolean opportunityNameInEmailBody = false;
  31. String campaignName;
  32. boolean campaignInEmailBody = false;
  33. String priceReview;
  34. @TestVisible boolean priceReviewInEmailBody = false;
  35. String description = '';
  36. User owner;
  37. boolean ownerGiven = false;
  38. String ownerName;
  39.  
  40. global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope envelope)
  41. {
  42. //retrieve the email body, title and address
  43. String emailBody = email.plainTextBody;
  44. String title = email.subject.split('-')[1].trim();
  45. String emailAddress = email.fromAddress;
  46.  
  47. //Separate the email body from the signature.
  48. if (email.plainTextBody.containsIgnoreCase(Label.Signature))
  49. {
  50. Integer index = emailbody.indexOfIgnoreCase(Label.Signature);
  51. emailBody = emailBody.left(index);
  52. }
  53.  
  54. // Determine the type based on the context of the email
  55. if (email.subject.containsIgnoreCase(Label.Popsa))
  56. {
  57. isPopsa = true;
  58. popsaVisitReport = new Visit_Report__c();
  59. popsaVisitReport.put('RecordTypeID', Schema.Sobjecttype.Visit_Report__c.getRecordTypeInfosByName().get(Label.Popsa).getRecordTypeId());
  60. createPOPSAMeetingNoteOrCall(popsaVisitReport, title, emailAddress, emailBody, isPopsa, isMeetingNote, isCall, email);
  61.  
  62. }
  63. else if (email.subject.containsIgnoreCase(Label.Meeting_Note))
  64. {
  65. isMeetingNote = true;
  66. meetingNote = new Meeting_Note__c();
  67. meetingNote.put('RecordTypeId', Schema.SObjectType.Meeting_Note__c.getRecordTypeInfosByName().get(Label.Meeting_Note).getRecordTypeId());
  68. createPOPSAMeetingNoteOrCall(meetingNote, title, emailAddress, emailBody, isPopsa, isMeetingNote, isCall, email);
  69.  
  70. }
  71. else if (email.subject.containsIgnoreCase(Label.Call))
  72. {
  73. isCall = true;
  74. meetingCall = new Meeting_Note__c();
  75. meetingCall.put('RecordTypeId', Schema.SObjectType.Meeting_Note__c.getRecordTypeInfosByName().get(Label.Meeting_Note).getRecordTypeId());
  76. createPOPSAMeetingNoteOrCall(meetingCall, title, emailAddress, emailBody, isPopsa, isMeetingNote, isCall, email);
  77. }
  78.  
  79. // Return service result
  80. Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
  81. result.success = true;
  82. return result;
  83. }
  84.  
  85. //This method will be called in each of the else if statements for POPSA, Meeting Note or Call and
  86. // create the appropriate object and assign the email contents to the correct fields.
  87. public void createPOPSAMeetingNoteOrCall(sObject obj, String title, String emailAddress, String emailBody, boolean popsa, boolean meetingNote, boolean call, Messaging.inboundEmail inboundEmail)
  88. {
  89. obj.put('Name', title);
  90. obj.put('Created_by_Email__c', true);
  91. obj.put('Original_Email_Sender__c', emailAddress);
  92.  
  93. // Populate a map of the custom settings fields.
  94. Map<String, POPSA_Field_Mappings__c> fieldMappings = POPSA_Field_Mappings__c.getall();
  95.  
  96. Set<String> customSettingsKeys = fieldMappings.keySet();
  97.  
  98. // Create a new String list of the field set fields
  99. List<String> fieldSetFieldStrings = new list<String>();
  100.  
  101. //Split the email body into individual lines.
  102. List<String> emailBodyLines = emailBody.split('\n');
  103.  
  104. List<String> errorList = new List<String>();
  105.  
  106. //iterate over the whole email body
  107.  
  108. for(String line : emailBodyLines)
  109. {
  110. //potentialFieldName is what is to the left of the colon e.g account, contact etc.
  111. // specific record is what is to the right of the colon e.g. Craig Test Account
  112.  
  113. String potentialFieldName = line.split(':')[0].toUpperCase();
  114. String specificRecord = '';
  115.  
  116. // Check that what is written to the left of the colon is a field in the custom settings map.
  117. if(fieldMappings.containsKey(potentialFieldName))
  118. {
  119. //if the types of the fied map are lookups and not cheeckboxes, dates etc.
  120.  
  121. if(!fieldMappings.get(potentialFieldName).Field_Type__c.equalsIgnoreCase('String')
  122. && !fieldMappings.get(potentialFieldName).Field_Type__c.equalsIgnoreCase('DateTime')
  123. && !fieldMappings.get(potentialFieldName).Field_Type__c.equalsIgnoreCase('Date')
  124. && !fieldMappings.get(potentialFieldName).Field_Type__c.equalsIgnoreCase('Boolean'))
  125. {
  126.  
  127. if(potentialFieldName.equalsIgnoreCase('Account'))
  128. {
  129. if(line.split(':').size() >= 1)
  130. {
  131. specificRecord = line.remove(line.left(line.indexOf(':') + 1));
  132. // gets the bit between Account: and @Test.com
  133. accountName = specificRecord.split('@')[0].trim();
  134. //adds underscores
  135. accountUniqueId = accountName.replaceAll('(\\s+)', '_');
  136.  
  137. //adds what is right of the @ to the account name.
  138. //The account name should now read craig@test.com for example.
  139. accountUniqueId += line.substring(line.indexOf('@'));
  140. accountInEmailBody = true;
  141. }
  142.  
  143. }
  144. else if(potentialFieldName.equalsIgnoreCase('Contact'))
  145. {
  146.  
  147. if(line.split(':').size() >= 1)
  148. {
  149. specificRecord = line.remove(line.left(line.indexOf(':') + 1));
  150. contactName = specificRecord.trim();
  151. contactInEmailBody = true;
  152. }
  153. }
  154. else if(potentialFieldName.equalsIgnoreCase('Opportunity'))
  155. {
  156. if(line.split(':').size() >= 1)
  157. {
  158. specificRecord = line.remove(line.left(line.indexOf(':') + 1));
  159. opportunityName = specificRecord.trim();
  160. opportunityNameInEmailBody = true;
  161. }
  162.  
  163. }
  164. else if(potentialFieldName.equalsIgnoreCase('Campaign'))
  165. {
  166. if(line.split(':').size() >= 1)
  167. {
  168. specificRecord = line.remove(line.left(line.indexOf(':') + 1));
  169. campaignName = specificRecord.trim();
  170. campaignInEmailBody = true;
  171. }
  172.  
  173. }
  174. else if(potentialFieldName.equalsIgnoreCase('Price_Review'))
  175. {
  176. if(line.split(':').size() >= 1)
  177. {
  178. specificRecord = line.remove(line.left(line.indexOf(':') + 1));
  179. priceReview = specificRecord.trim();
  180. priceReviewInEmailBody = true;
  181. }
  182.  
  183. }
  184. }
  185.  
  186. //Could add extra logic if the user enters the time as well... but that might affect the functionality if time isn't given.
  187.  
  188. if(fieldMappings.get(potentialFieldName).Field_Type__c.equalsIgnoreCase('Owner'))
  189. {
  190. ownerGiven = true;
  191. specificRecord = line.split(':')[1];
  192. ownerName = specificRecord.trim();
  193. }
  194.  
  195. if(fieldMappings.get(potentialFieldName).Field_Type__c.equalsIgnoreCase('Date'))
  196. {
  197. try
  198. {
  199. specificRecord = line.split(':')[1];
  200. List<String> splitDateStrings = specificRecord.split('/');
  201. String day = splitDateStrings[0].trim();
  202. String month = splitDateStrings[1].trim();
  203. String year = splitDateStrings[2].trim();
  204.  
  205. boolean dayNumeric = day.isNumeric();
  206. boolean monthNumeric = month.isNumeric();
  207. boolean yearNumeric = year.isNumeric();
  208.  
  209. if((day.length() == 2) && (month.length() == 2) && (year.length() == 4) && dayNumeric && monthNumeric && yearNumeric)
  210. {
  211. if(popsa)
  212. {
  213. DateTime startDateTime = DateTime.newInstance(Integer.valueOf(year), Integer.valueOf(month), Integer.valueOf(day), 12, 0, 0);
  214. DateTime endDateTime = DateTime.newInstance(Integer.valueOf(year), Integer.valueOf(month), Integer.valueOf(day), 12, 30, 0);
  215. obj.put('Event_Start__c', startDateTime);
  216. obj.put('Event_End__c', endDateTime);
  217. }
  218. else
  219. {
  220. Date meetingDate = Date.newInstance(Integer.valueOf(year), Integer.valueOf(month), Integer.valueOf(day));
  221. obj.put('Meeting_Date__c', meetingDate);
  222. }
  223.  
  224. }
  225. else
  226. {
  227. // date has not been given in the correct format
  228. }
  229. }
  230. catch(ListException e)
  231. {
  232.  
  233. }
  234.  
  235.  
  236. }
  237.  
  238. }
  239. else
  240. {
  241. description += line + '\n';
  242. }
  243.  
  244. }
  245.  
  246. //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
  247. //This will only work if the person who sends the email is trying to make themselves the owner. Unless they send from
  248. // a common address.
  249.  
  250.  
  251. if(ownerGiven)
  252. {
  253. List<User> userList = [select id, name from User where email = :emailAddress AND name = :ownerName AND IsActive = true];
  254.  
  255. if(userList.size() == 1)
  256. {
  257.  
  258. owner = userList.get(0);
  259. obj.put('ownerId', owner.id);
  260. }
  261. }
  262. else
  263. {
  264. List<User> userList = [select id, name from User where email = :emailAddress AND IsActive = true];
  265. if(userList.size() != 0)
  266. {
  267. owner = [select Id, Name from User where email = :emailAddress AND isActive = true LIMIT 1];
  268. obj.put('ownerId', owner.Id);
  269. }
  270. else
  271. {
  272. owner = [select Id, Name FROM USer where email ='shell.sfdc@brightgen.com' and IsActive = true LIMIT 1];
  273. obj.put('ownerId', owner.Id);
  274. }
  275. }
  276.  
  277. if(accountInEmailBody)
  278. {
  279. //Query the database for the given account and look to see if one account is returned.
  280. List<Account> accountList = [SELECT Id FROM Account WHERE Unique_Identifier__c = :accountUniqueId AND Active__c = true];
  281.  
  282. if(accountList.size() == 1)
  283. {
  284.  
  285. Id accountId = accountList.get(0).Id;
  286.  
  287. if(popsa)
  288. {
  289. obj.put('Account_Name__c', accountId);
  290. }
  291. else
  292. {
  293. obj.put('Account__c', accountId);
  294. }
  295.  
  296. }
  297. else
  298. {
  299. errorList.add('Account');
  300. }
  301.  
  302. }
  303.  
  304. //If the email sender has put a contact in the email body, query the database to find the contact
  305. //if there is only one with that name,add it to the popsa.
  306. if(contactInEmailBody)
  307. {
  308. List<Contact> contactList = [SELECT Id FROM Contact WHERE Name = :contactName AND Active__c = true];
  309. if(contactList.size() == 1)
  310. {
  311.  
  312. Id contactId = contactList.get(0).Id;
  313.  
  314. if(popsa)
  315. {
  316. obj.put('Contact_Name__c', contactId);
  317. }
  318. else
  319. {
  320. obj.put('Contact__c', contactId);
  321. }
  322.  
  323. }
  324. else
  325. {
  326. errorList.add('Contact');
  327. }
  328.  
  329. }
  330. if(opportunityNameInEmailBody)
  331. {
  332. List<Opportunity> opportunityList = [SELECT Id FROM Opportunity WHERE Name = :opportunityName];
  333. if(opportunityList.size() == 1)
  334. {
  335.  
  336. Id opportunityId = opportunityList.get(0).Id;
  337. if(popsa)
  338. {
  339. obj.put('Opportunity_Name__c', opportunityId);
  340. }
  341. else
  342. {
  343. obj.put('Opportunity__c', opportunityId);
  344. }
  345. }
  346. else
  347. {
  348. errorList.add('Opportunity');
  349. }
  350. }
  351. if(campaignInEmailBody)
  352. {
  353. List<Campaign> campaignList = [SELECT Id FROM Campaign WHERE Name = :campaignName];
  354. if(campaignList.size() == 1)
  355. {
  356. Id campaignId = campaignList.get(0).Id;
  357. obj.put('Campaign__c', campaignId);
  358. }
  359. else
  360. {
  361. errorList.add('Campaign');
  362. }
  363.  
  364. }
  365. if(priceReviewInEmailBody)
  366. {
  367. if(popsa)
  368. {
  369. List<Price_Review__c> priceReviewList = [SELECT Id FROM Price_Review__c WHERE Name = :priceReview];
  370. if(priceReviewList.size() == 1)
  371. {
  372. Id priceReviewId = priceReviewList.get(0).Id;
  373. obj.put('Price_Review__c', priceReviewId);
  374. obj.put('Customer_Type__c', 'Price Review');
  375. }
  376. else
  377. {
  378. errorList.add('Price_Review');
  379. }
  380. }
  381. }
  382.  
  383. if(popsa)
  384. {
  385. obj.put(Label.POPSA_c, description);
  386. }
  387. else
  388. {
  389. obj.put(Label.Meeting_Note_c, description);
  390. }
  391. insert obj;
  392.  
  393. if (inboundEmail.binaryAttachments != null && inboundEmail.binaryAttachments.size() > 0)
  394. {
  395. for (integer i = 0 ; i < inboundEmail.binaryAttachments.size() ; i++) {
  396. Attachment attachment = new Attachment();
  397. attachment.ParentId = popsaVisitReport.Id;
  398. attachment.Name = inboundEmail.binaryAttachments[i].filename;
  399. attachment.Body = inboundEmail.binaryAttachments[i].body;
  400. insert attachment;
  401. }
  402. }
  403.  
  404. if (!errorList.isEmpty())
  405. {
  406. Task reminderTask = new Task(
  407. OwnerID = owner.Id,
  408. Status = Label.Open,
  409. Priority = Label.High
  410. );
  411.  
  412. if (popsa)
  413. {
  414. reminderTask.Subject = Label.Popsa_Reminder;
  415. }
  416. else if (meetingNote)
  417. {
  418. reminderTask.Subject = Label.Meeting_Note_Reminder;
  419. }
  420. else if (call)
  421. {
  422. reminderTask.Subject = Label.Logged_Call_Reminder;
  423. }
  424.  
  425. if ([select Id from User where email = :emailAddress].size() != 0)
  426. {
  427. reminderTask.OwnerId = [select Id, Name from User where email = :emailAddress and IsActive = true LIMIT 1].Id;
  428. }
  429. else
  430. {
  431. reminderTask.ownerID = [select Id, Name FROM USer where email ='shell.sfdc@brightgen.com' and IsActive = true LIMIT 1].Id;
  432. }
  433.  
  434. string returnEmailBody = owner != null ? Label.Dear + ' ' + owner.Name + ',\n' : Label.Dear + ' User,';
  435. string errorFieldString = '';
  436.  
  437. for (String line : errorList)
  438. {
  439. if (line.contains('Account'))
  440. {
  441. returnEmailBody += Label.Unable_to_Identify + '\n' + URL.getSalesforceBaseURL().toExternalForm() + '/' + obj.Id +'\n\n';
  442. }
  443. else
  444. {
  445. errorFieldString += line + ', ';
  446. }
  447. }
  448. errorFieldString = errorFieldString.trim().removeEnd(',') + ' ';
  449.  
  450. String correctedLabel = Label.Unable_to_Identify_Other.replace('$Field', errorFieldString);
  451. returnEmailBody += correctedLabel + '\n' + URL.getSalesforceBaseURL().toExternalForm() + '/' + obj.Id + ' \n\n' + Label.Many_Thanks;
  452.  
  453. reminderTask.Description = returnEmailBody;
  454. insert reminderTask;
  455. }
  456. }
  457. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement