• Lorant Dobrondi
  • NEWBIE
  • 0 Points
  • Member since 2019

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 10
    Questions
  • 4
    Replies

Hello!

I have a batch apex that is running through 5 CSV attachments, and creating records from the data that is in the files.

Each CSV file is for a different object, and sometimes there are lookup relationships between them (like Account < Contact).

How can I make sure that the CSV files are read & processed in the correct order?
I want the Accounts to be created first, and then the Contacts follow (because the Contacts are related to Accounts) and the rest of the CSV files should follow.

I tried putting the files in order, but this is not working out...
 

Here are some code examples:
 

global String getDocumentQuery() {
        return 'SELECT Id, Name, Body FROM Attachment WHERE ParentId =: JobId order by Name asc';
}
 
global void execute(Database.BatchableContext context, List<SObject> records) {
        //get Accounts
        Attachment accountsAttachment = getAttachmentByType('accounts', records);
        if (accountsAttachment != null) {
            List<List<String>> accountsCsvRecords = parseCSV.parseCSV(accountsAttachment.Body.toString(), true); 
            import (accountsCsvRecords, 'Account');
        }
        
        //get Contacts
        Attachment contactsAttachment = getAttachmentByType('contacts', records);
        if (contactsAttachment != null) {
            List<List<String>> contactsCsvRecords = parseCSV.parseCSV(contactsAttachment.Body.toString(), true); 
            import (contactsCsvRecords, 'Contact');
        }

}

You can see that my execute function gets a list of SObjects (which are the Attachments themselves), but the batchable nature of the class makes it asynchronous, and the import will finish at random times on each Attachment.

Any way to make this synchronous, and still be able to run thru a big list of objects without any SOQL error?
Hello,

I have some issues while reading a CSV attachment of an inbound email.

I want Salesforce to listen to an email address, and process all inbound emails coming to that email address.
We will send CSV files as attachments, and I want to load that data into Leads and custom objects, however I'm having difficulties reading the CSV file.
 
if(email.textAttachments != null) {
  for (Messaging.Inboundemail.TextAttachment tAttachment : email.textAttachments) {
    if (tAttachment.fileName == 'Leads-import.csv') {
      //process text attachment with CSV parser
      Blob csvBlob = Blob.valueOf(tAttachment.body);
      // Convert your csv file into a list of CSV fields
      List<List<String>> csvRecords = CSVReader.readIETFRFC4180CSVFile(csvBlob);
      import(csvRecords, 'Lead');
    }
  }
}

I implemented the above code in an Inbound Email Handler class, where nothing happens...The exact same code runs fine if I read the CSV file from a Salesforce Document/File.

I am using Marty Chang's CSV Reader implementation which can be found here: LINK (http://frombelvideres4thfloor.blogspot.com/2010/10/ietf-rfc-4180-compliant-csv-reader-for.html)

What can be the issue with the Email Handler?

Hello,

I have been tasked to create a batch apex loader which parses a CSV file from an email attachment.

I will use an email handler to get the email with the CSV file attached, and then I will try to load the attachment, and go through it, and create a new object for each line in it.

The CSV file will be sent from an outside source, and it can contain a lot of long text in some of the columns. Even line-breaks, and quotes can appear in some of the columns.

Is there a good, readily available CSV parser class/library in APEX, that I could use? One that handles all the cases, where there could be separators, quotes, end of lines INSIDE a value? Also, I would like to be able to handle all kinds of international & special characters.

I don't want to re-invent the wheel, and spend a lot of time on writing & testing the parser, if there's something already out there.

Thanks

Hello,

Our company has an email address where we receive a list of leads every week.
We're currently manually checking this email address, downloading the list of leads (it's a .csv file), and then using a batch loader to load the data into Salesforce.

Since this is sent to us in an automated way, we would also like to load this data into Salesforce, in a completely automated way.

Is there a way to fetch these incoming emails,  process their attachments, and load them directly into Salesforce, without the need of human interaction?

Alternatively: are there any usable tools out there, which could help with this?

Hello,

I have to send out a weekly report to my sales reps as an Excel file. I initially made a simple CSV file from a scheduled apex class, but I had to add some formatting, so I was forced to go with a Visualforce page instead.

I created the Visualforce page and its controller, and adding the following line to the first row of the Visualforce code enables me to download an .XLS file whenever I access the VF page:
contenttype="application/vnd.ms-excel#TestExport_{!TODAY()}.xls">

Now the hard part: how can I run this visualforce page every week, and email the Excel XLS file to my sales reps?
 
Hello,

I want to create a weekly report on the leads and their history, and I want to get it in a formatted Excel XLS document. I want this document to be sent to the right people via email (as an attachment)

I managed to achieve something similar to this, but only via a .CSV file, but now I want to be able to color the rows based on some criteria (like if a lead sits in a state for too long etc.)

I scheduled my batch apex class, to run every Friday, and send the email.

Can I achieve something similar to this? I've read a couple of answers that mentioned that I need VisualForce pages for this. How am I able to "schedule" those?

Hello!

I have a custom object, where our Sales Reps log their daily work, client visits, holidays etc. (basically it's a timesheet for their activities)

The custom object has an Account field, where they select the Account that the activity was related to. There's also a Country field. I would like this Country field to be pre-populated with the selected accounts country.
So when they create the record, and set the Account, I want the Country field to update as well, by taking the Country field of the selected Account.

Can this be achieved without a screen refresh? I don't want to have validation rules or workflows here, since I would like this to happen seamlessly.
It's basically an AID for the Sales Reps, it helps them create the new records, HOWEVER the field can be manually changed, if an activity was in a different country.

Hello,

I've made an Apex class that runs through the current weeks active leads and creates an Excel (.csv) report on the lead data + history data (looking for the dates when the status of the lead has changed from one to the next).

The code works nicely, but now when I got into the test coverage part, I was quickly surprised to see that the LeadHistory object is not working in the test classes.

The test coverage starts to be red on the following line, and I actually think that it goes into the catch(Exception) part.
 
list<LeadHistory> leadHistory = [SELECT LeadId, CreatedDate, Field, toLabel(OldValue), toLabel(NewValue) FROM LeadHistory WHERE LeadId =: l.Id AND Field = 'Status' order by CreatedDate asc];

My test class looks like this:
@isTest

public class CreateAutomaticLeadReportTest {
    static testMethod void testMethod1() {

        //create test leads
        Lead l = new Lead();
        l.LastName = 'Test John';
        l.Company = 'Testing Company';
        l.Email = 'test@email.com';
        l.Date__c = Date.newInstance(2019, 3, 1);
        l.Country__c = 'Germany';
        INSERT l;
        
        Leadhistory lh = new Leadhistory(Field='Status', LeadId=l.id);
        INSERT lh;

        Test.startTest();
            CreateAutomaticLeadReport CALR = new CreateAutomaticLeadReport();
            Database.QueryLocator ql = CALR.start(null);
            List<Lead> listOfLeads = [SELECT Id FROM Lead];
            CALR.execute(null, listOfLeads);
            CALR.Finish(null);
        Test.stopTest();
        
    }
}

I tried adding the (SeeAllData=true) annotation to my test class, but it didn't help. (Then I removed the test data insertion)​​​​​​​

Hi!
I have a Master-Detail relationship between my custom object and the Opportunity built-in object.

I would like to be able to create a record of my custom object from the Opportunity record via a visualforce page, but i'm not sure how to achieve this.
If I use the standardController as Opportunity, the visualforce page shows up in the page layout builder, but obviously, the code is not working.

Here's the visualforce page:

<apex:page standardController="CFA__c">
    <apex:sectionHeader title="CFA Edit" subtitle="{!CFA__c.Name}"/>
    <apex:form id="CFA_Edit_Form">
        <apex:pageBlock title="CFA Edit" mode="edit">

            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}"/>
                <apex:commandButton value="Save & New" action="{!save}" />
                <apex:commandButton value="Cancel" action="{!cancel}"/>
            </apex:pageBlockButtons>


            <apex:pageBlockSection title="Information" columns="2">
                <apex:inputField value="{!CFA__c.Name}" required="true"/>
                <apex:inputField value="{!CFA__c.Type__c}" required="true">
                    <apex:actionSupport event="onchange" reRender="CFA_Edit_Form" />
                </apex:inputField>
                
                <apex:inputField value="{!CFA__c.AE__c}" rendered="{!CFA__c.Type__c == 'Joint Visit'}" />
                <apex:inputField value="{!CFA__c.AE_Description__c}" rendered="{!CFA__c.Type__c == 'Joint Visit'}" />
            </apex:pageBlockSection>

        </apex:pageBlock>
    </apex:form>
</apex:page>
 

Any way this is achievable with Visualforce?

Hello,

I have this custom object that describes a Client Visit, and it's related to an opportunity (there's a Master-Detail Relationship on this custom object to the Opportunity object).

I want to be able to create a "Client Visit" related record from the Opportunity page layout, and I understand that to achieve this, I will have to create a Visualforce page.

I also need to do it in Visualforce, because I have the following requirement: if the user selects "Group Visit" from the type picklist, then 2 new fields should pop up on the view, where the user could select an additional User, who was there at the client visit. (I can see that this is not doable with simple record pages, or even flows.)

Now my question is the following: How should my page tags look like in order to be able to
1. Be able to select the Visualforce page from the Page Layout editor on the Opportunity object (which means that I would have to have the Opportunity as the standardController...??)
2. Create a "Client Visit" record

Hello,

Our company has an email address where we receive a list of leads every week.
We're currently manually checking this email address, downloading the list of leads (it's a .csv file), and then using a batch loader to load the data into Salesforce.

Since this is sent to us in an automated way, we would also like to load this data into Salesforce, in a completely automated way.

Is there a way to fetch these incoming emails,  process their attachments, and load them directly into Salesforce, without the need of human interaction?

Alternatively: are there any usable tools out there, which could help with this?

Hello,

I have to send out a weekly report to my sales reps as an Excel file. I initially made a simple CSV file from a scheduled apex class, but I had to add some formatting, so I was forced to go with a Visualforce page instead.

I created the Visualforce page and its controller, and adding the following line to the first row of the Visualforce code enables me to download an .XLS file whenever I access the VF page:
contenttype="application/vnd.ms-excel#TestExport_{!TODAY()}.xls">

Now the hard part: how can I run this visualforce page every week, and email the Excel XLS file to my sales reps?
 

Hi!
I have a Master-Detail relationship between my custom object and the Opportunity built-in object.

I would like to be able to create a record of my custom object from the Opportunity record via a visualforce page, but i'm not sure how to achieve this.
If I use the standardController as Opportunity, the visualforce page shows up in the page layout builder, but obviously, the code is not working.

Here's the visualforce page:

<apex:page standardController="CFA__c">
    <apex:sectionHeader title="CFA Edit" subtitle="{!CFA__c.Name}"/>
    <apex:form id="CFA_Edit_Form">
        <apex:pageBlock title="CFA Edit" mode="edit">

            <apex:pageBlockButtons >
                <apex:commandButton value="Save" action="{!save}"/>
                <apex:commandButton value="Save & New" action="{!save}" />
                <apex:commandButton value="Cancel" action="{!cancel}"/>
            </apex:pageBlockButtons>


            <apex:pageBlockSection title="Information" columns="2">
                <apex:inputField value="{!CFA__c.Name}" required="true"/>
                <apex:inputField value="{!CFA__c.Type__c}" required="true">
                    <apex:actionSupport event="onchange" reRender="CFA_Edit_Form" />
                </apex:inputField>
                
                <apex:inputField value="{!CFA__c.AE__c}" rendered="{!CFA__c.Type__c == 'Joint Visit'}" />
                <apex:inputField value="{!CFA__c.AE_Description__c}" rendered="{!CFA__c.Type__c == 'Joint Visit'}" />
            </apex:pageBlockSection>

        </apex:pageBlock>
    </apex:form>
</apex:page>
 

Any way this is achievable with Visualforce?

Desperately needing some help here! 

I have a batch class that sends an email to a lead owner based on the Status not changing during a specified timeframe. I manually tested it (without the time query filter) and the code was doing what it needs to do. I've now written the test code only to find the Leadhistory query returns an null record set. I can see the Leads have an ID and I perform some status updates on the test method to generate the LeadHistory records so im clueless as to why it is not returning any records.

test method:
@isTest
private class LeadStatusBatchTest {
	
	@isTest static void test_method_one() {
		// First Load some Leads from resource file
		List<sObject> leads = Test.loadData(Lead.sObjectType, 'Default_Lead_Test_Data');
		system.debug('### [LeadStatusBatchTest] leads (loaded test data): '+ leads);

		//set a datetime to 4 weeks ago to update createdDate
		Datetime weeksAgo_4 = Datetime.now().addDays(-28);
		
		for(Lead ld: (List<Lead>)leads) {
			//update the status and save to DB
			ld.Status = 'Open';
			Test.setCreatedDate(ld.Id, weeksAgo_4.addDays(-7));
		} 
		
		update leads; //to generate a leadHistory entry for Open status
		system.debug('### [LeadStatusBatchTest] Updated CreatedDate on Leads: '+ [Select id, CreatedDate From Lead where Id = :leads]);

		//validate update worked
		for(lead ld: [select id, status, createdDate From Lead where id in : leads]){
			system.assertEquals('Open', ld.Status);
			system.assertEquals(weeksAgo_4.addDays(-7), ld.CreatedDate);
		}

		//get the leadhistory records and update their createddate to same as lead created date
		for(LeadHistory lh: [select id, oldvalue, newvalue from LeadHistory where LeadId =: leads]){
			Test.setCreatedDate(lh.id, weeksAgo_4.addDays(-7));
		}
		system.debug('### [LeadStatusBatchTest] LeadHistory testdata: '+ [select id, oldvalue, newvalue from LeadHistory where LeadId =: leads]);

		//update Status to Contacted
		for(lead ld: (List<Lead>)leads){
			ld.Status = 'Contacted';
		}
		update leads;
		
		//get LeadHistory for Lead and update the CreatedDate
		for(LeadHistory lh: [select id, oldvalue, newvalue from LeadHistory where LeadId =: leads]){
			if(lh.newvalue == 'Contacted')
				Test.setCreatedDate(lh.id, weeksAgo_4);
		}
		system.debug('### [LeadStatusBatchTest] leadHistory Contacted status: '+ [select id, oldvalue, newvalue from LeadHistory where LeadId =: leads]);

		//validate LeadHistory CreatedDate
		for(LeadHistory lh: [select id, CreatedDate from LeadHistory where LeadId =: leads]){
			system.assertEquals(weeksAgo_4, lh.CreatedDate);
		}

		test.startTest();
			//run batch class
			LeadStatusBatch db = new LeadStatusBatch();
			database.executeBatch(db);
		test.stopTest();
		system.debug('### [LeadStatusBatchTest] Stopped Test. ');
		
		//make validations if execution was successful


	}
	
	
}

When I run the test the test method debugs return a null data set on the LeadHistory query that is supposed to set the CreatedDate. All queries before that work just fine.

Is it that you cant query hte LeadHistory table on a testmethods? (doesnt seem right)
Or that changes to the lead are not tracked in LeadHistory?

Any help here would be much appreciated!