Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save RatanPaul/1ddd6c1098998b5b2a73ce3c213f9257 to your computer and use it in GitHub Desktop.
Save RatanPaul/1ddd6c1098998b5b2a73ce3c213f9257 to your computer and use it in GitHub Desktop.
global class AccountEmailService implements Messaging.InboundEmailHandler {
//describe call on Account object to fetch all fields and their Data type
public static Schema.DescribeSObjectResult objectDescribe = Account.getSObjectType().getDescribe();
public static Map<String, Schema.SObjectField> fields;
static{
fields = objectDescribe.fields.getMap();
}
global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) {
Messaging.InboundEmailResult result = new Messaging.InboundEmailresult();
List<String> recordDataLines = new List<String>();//store to CSV's each data lines
Map < String, Integer > fieldNumberMap = new Map < String, Integer >();//Store the Field API name and column no/position in CSV
List<String> lstFieldNames = new List<String>();//Store the Field API name
String fieldValue; //store field API Number
Integer fieldNumber;// store field column no/position in CSV
Map<String,List<String>> mapHeaderToFieldAPIName = new Map<String,List<String>>();// Store Metadata label and related field API Name
Map<String, String> fieldNameToFieldType = new Map<String, String>();
try{
//fetch metadata type
for(AccountFieldMapping__c fieldMapping: [SELECT Id, MasterLabel, Field_API_Name__c from AccountFieldMapping__c]){
if(fieldMapping.Field_API_Name__c.contains(',')){
List<String>lstfieldName = fieldMapping.Field_API_Name__c.split(',');
for(String fieldName : lstfieldName){
prepareFieldWithType(mapHeaderToFieldAPIName, fieldMapping, fieldNameToFieldType, fieldName);
}
}else{
prepareFieldWithType(mapHeaderToFieldAPIName, fieldMapping, fieldNameToFieldType, fieldMapping.Field_API_Name__c);
}
}
List<Document> lstDocument = new List<Document>();
Folder fd = [SELECT Id from Folder WHERE Name = 'My Folder Files'];
//get the CSV attachment from email and store in recordDataLines
for(Messaging.InboundEmail.BinaryAttachment att : email.binaryAttachments){
recordDataLines = att.body.toString().trim().split('\n');
Document d = new Document();
d.Name = att.fileName;
d.body=att.body;
d.folderid=fd.Id;
lstDocument.add(d);
}
insert lstDocument;
//get the first row for field headers and get the related field api name from metadata
List<String> csvFieldNames = recordDataLines[0].split(',');
for (Integer i = 0; i < csvFieldNames.size(); i++) {
String strFieldName = csvFieldNames[i].replaceAll('[^a-zA-Z0-9\\s+]', '').trim();//remove all special character
if(mapHeaderToFieldAPIName.containsKey(strFieldName)){
List<String> lstfieldName = mapHeaderToFieldAPIName.get(strFieldName);
for(String fieldName: lstfieldName){
fieldNumberMap.put(fieldName, i);
lstFieldNames.add(fieldName.trim());
}
}
}
List<Account> lstAccountInsert = new List<Account>();
List<String> lstWorkOrderNumber = new List<String>();
List<String> lstWorkEmail = new List<String>();
//get the data from 2nd row
for (Integer i = 1; i < recordDataLines.size(); i++) {
List<String> csvRecordData = recordDataLines[i].split(',');
Account objAcc = new Account();
//iterate over each field and based on their data type store in the Account fields
for (String fieldName: lstFieldNames) {
fieldNumber = fieldNumberMap.get(fieldName);
fieldMappingSTE( fieldNumber, csvRecordData[fieldNumber], fieldName, fieldNameToFieldType, objAcc );
}
//add into the list
lstAccountInsert.add(objAcc);
}
//insert the Account records
insert lstAccountInsert;
}
catch(Exception e){
System.debug('======exception========='+e.getMessage());
}
return result;
}
//based schema fetch the each field type so we can convert the data in correct datatype
public static void prepareFieldWithType(Map<String, List<String>> mapHeaderToFieldAPIName, AccountFieldMapping__c fieldMapping, Map<String, String> fieldNameToFieldType, String fieldName){
if(!mapHeaderToFieldAPIName.containsKey(fieldMapping.MasterLabel.trim())){
mapHeaderToFieldAPIName.put(fieldMapping.MasterLabel.trim(), new List<String>());
}
mapHeaderToFieldAPIName.get(fieldMapping.MasterLabel.trim()).add(fieldName.trim());
Schema.DescribeFieldResult fieldDescribe = fields.get(fieldName.trim()).getDescribe();
fieldNameToFieldType.put(fieldDescribe.getName(), String.valueOf(fieldDescribe.getType()));
}
//based on the field data type convert the data and save in Account
public static void fieldMappingSTE(Integer fieldNumber, String fieldValue, String fieldName, Map<String, String> fieldNameToFieldType, Account objAcc ){
if(fieldNameToFieldType.get(fieldName) == 'DATE'){
objAcc.put(fieldName.trim(), Date.parse(fieldValue));
}else if(fieldNameToFieldType.get(fieldName) == 'DOUBLE'){
objAcc.put(fieldName.trim(), Double.valueOf(fieldValue));
}else if(fieldNameToFieldType.get(fieldName) == 'TIME'){
Boolean isTimePM = fieldValue.contains('PM');
fieldValue = fieldValue.replace('PM', '').replace('AM','').trim();
String[] strTimeSplit = fieldValue.split(':');
Time timeChange = Time.newInstance( Integer.valueOf(strTimeSplit[0]) ,Integer.valueOf(strTimeSplit[1]),0,0);
if(isTimePM){
timechange.addHours(12);
}
objAcc.put(fieldName.trim(),timeChange);
}else {
objAcc.put(fieldName.trim(), String.valueOf(fieldValue).trim());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment