• Ivan Winzer
  • NEWBIE
  • 130 Points
  • Member since 2014

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 38
    Questions
  • 72
    Replies
So we have a lead convert class that is now throwing a Cannot Insert Update error. It says that is is Unable to create/Update field: Name. Below is a part of the code that i believe is the issue but im not 100% sure on how to tweak it so that it doesnt try to place first and last name into the name field but doesnt break the code.
 
if(leadsToConvert.size()>0){
            List<Database.LeadConvertResult> results = Database.convertLead( leadsToConvert, false);
            List<Account> accountsToUpdate = new List<Account>();
            for(Database.LeadConvertResult result : results){
                lead l = leadIdMap.get(result.getLeadId());
                if(result.success && result.getAccountId()!=null){
                    String name = ((l.FirstName!=null)?l.FirstName+' '+l.LastName:l.LastName);
                    if(name!=null){
                        accountsToUpdate.add(new Account(Id=result.getAccountId(), name = name));
                    }
                }
                else{
                    for(Database.Error error : result.getErrors()){
                        l.addError(error.getMessage());
                    }
                }
            }

Any help or thoughts is grately appreciated. 

Ivan
So recently moved over to Person accounts in lightning and need to make an update to a class and trigger. however when i try to push the changes from sandbox to production i get a bunch of errors in regards to already established @istest and other classes in my production org and wondering if anyone can help. These are the errors im getting and the assocaited classes or test:

Run Failures:
  GuestAccountPopulateTest.PositiveTest System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_EXECUTE_FLOW_TRIGGER, We can't save this record because the “New Guest” process failed. Give your Salesforce admin these details. Probably Limit Exceeded or 0 recipients
: []
  Test_ContactWineClub.myUnitTest System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Account__c]: [Account__c]

  Test_PrimaryAddressValidationTriger.testCreateShipToAddress System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, mainShipToAddessTrigger: execution of BeforeInsert
caused by: System.QueryException: List has no rows for assignment to SObject

Trigger.mainShipToAddessTrigger: line 9, column 1: []
  Test_ShiptoAddressTrigger.testCreateShipToAddress System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, mainShipToAddessTrigger: execution of BeforeInsert
caused by: System.QueryException: List has no rows for assignment to SObject

Trigger.mainShipToAddessTrigger: line 9, column 1: []
  WineClubMembershipAccountPopulateTest.PositiveTest System.DmlException: Insert failed. First exception on row 0; first error: INVALID_FIELD_FOR_INSERT_UPDATE, Business Customer may not use Person Customer field  : WC Tenure: [WC Tenure]
 
@isTest
private class Test_ContactWineClub {

    static testMethod void myUnitTest() {

	date myDate = date.today();
	
        Account a = new Account(Name = 'Test MainContactTrigger', RecordTypeID = '0121W000000UgfA');
 //       a.RecordType = 'Household';
        insert a;
        
        Contact c = new Contact(AccountID = a.id, firstName = 'Test MainContactTrigger', lastName = 'Tester', email = 'testfake@gmail.com');
        insert c;
        
 //       System.debug('Contact record num: ' + [SELECT Id FROM Contact].size());
        
        Wineclub_Membership__c wc = new Wineclub_Membership__c( Contact__c = c.id, Active__c = true , Wine_Club_Code__c = 'Collection 2 Bottle', Start_Date__c = myDate);
        insert wc;
        
             
        c = [select AccountId, Account.Name from Contact where id = :c.id limit 1];
           System.assertEquals('Test MainContactTrigger', a.Name);
           System.assertEquals(1, [SELECT Id FROM Contact].size());
           System.assertEquals(a.id, c.AccountId);
     
     
    }
}
@isTest
private class Test_PrimaryAddressValidationTriger {

    @isTest
    public static void testCreateShipToAddress(){
        Account a = new Account(Name = 'Test PrimaryAddressValidation', RecordTypeID = '0121W000000UgfA');
        insert a;
        
        Contact c = new Contact(AccountID = a.ID, firstName = 'Test PrimaryAddressValidation', lastName = 'Tester', email = 'fakington@gmail.com');
        insert c;
        
        ShipTo_Address__c s1 = new ShipTo_Address__c( Contact__c = c.id,
           Address__c = '1919 Fakeone Way',
           City__c = 'Fakington',
           State__c = 'CA',
           Country__c = 'USA',
           ZIP__c = '00000',
           Primary_Billing_Address__c = true);
  
        insert s1;
   
    	ShipTo_Address__c s2 = new ShipTo_Address__c( Contact__c = c.id,
           Address__c = '1600 Alrington Way',
           City__c = 'Oakland',
           State__c = 'CA',
           Country__c = 'USA',
           ZIP__c = '00000',
           Default_Shipping_Address__c = true);        
   
   		insert s2;
   		
        c = [select AccountID,Account.Name from Contact where id = :c.id limit 1];
           System.assertEquals('Test PrimaryAddressValidation', c.Account.Name);
           System.assertEquals(a.id, c.AccountID);
    }

}
@isTest
public with sharing class Test_ShiptoAddressTrigger {
    @isTest
    public static void testCreateShipToAddress(){
        Account a = new Account(Name = 'Test MainShipToAddressTrigger', RecordTypeID = '01240000000UZ4V');
        insert a;
        
        Contact c = new Contact(AccountID = a.ID, firstName = 'Test MainShipToAddressTrigger', lastName = 'Tester', email = 'fakington@gmail.com');
        insert c;
        
        ShipTo_Address__c s1 = new ShipTo_Address__c( Contact__c = c.id,
           Address__c = '1919 Fakeone Way',
           City__c = 'Fakington',
           State__c = 'CA',
           Country__c = 'USA',
           ZIP__c = '00000',
           Primary_Billing_Address__c = true);
  
        insert s1;
   
    	ShipTo_Address__c s2 = new ShipTo_Address__c( Contact__c = c.id,
           Address__c = '1919 Fakeone Way',
           City__c = 'Fakington',
           State__c = 'CA',
           Country__c = 'USA',
           ZIP__c = '00000',
           Default_Shipping_Address__c = true);        
   
   		insert s2;
   		
        c = [select AccountId,Account.Name from Contact where id = :c.id limit 1];
           System.assertEquals('Test MainShipToAddressTrigger', c.Account.Name);
           System.assertEquals(a.id, c.AccountId);
    }
}
@isTest
public class WineClubMembershipAccountPopulateTest {

    @testSetup
    static void setup(){
        Account acc = new Account();
        acc.Name = 'Test1';
        insert acc;
        
        Contact con = new Contact();
        con.AccountId = acc.id;
        con.lastName = 'Test1';
        insert con;
        
        Wineclub_Membership__c wineClub = new Wineclub_Membership__C();
        wineClub.Account__c = acc.id;
        wineClub.Contact__c = con.id;
        insert wineClub;
    }
    
    @isTest
    static void PositiveTest() {
        Test.startTest();
        database.executeBatch(new WineClubMembershipAccountPopulate(), 200);
        Test.stopTest();
        
        Wineclub_Membership__c wineClub = [SELECT Id, account__c, contact__c FROM Wineclub_Membership__c Limit 1];
        System.assertNotEquals(null, wineClub.account__c);
    }
}

Any help is greatly appreciated as we are having integration issues with missing data and unable to update my main class and trigger since the above are causing me errors when trying to deploy to production


 
So we recently upgraded from magento 1 to magento 2 platfom. Before this we had a button created in SF that when pushed would open a magento session within the salesforce contact window (like a iframe within SF). Below is the link being used to open the session in M1:

https://www.waltwines.com/index.php/admin_HALLWINES_aHv0g/wineforce/view/model/customer/sfid/{!Contact.Case_Safe_ID__c}

This link would open the session for the contact in record in M1. Now that we are in the Magento 2 platform the URL has changed and not sure how to push the lookup the SF ID that is stored in Magento 2 to open the contact record:

https://www.waltwines.com/admin_HALLWINES_aHv0g/customer/index/index/key/contact_sf_id/{!Contact.Case_Safe_ID__c}

There are new proticals for pushing and sending data between the 2 systems but we figured that the link would still work with just some small modifications. But now even if i use the old link we either get a 403 forbidden page or a cant display depending on browser.

Not sure if anyone else has done this before with magento or with another platform and has any idea on how i can get this back working would be great. This was a huge help for our business and it being broken has doubled our times in working with customers records. Any thoughts, ideas or help is greatly appreciated.

Oh and side note we have one person when they select the button can get to the page still trying to figure that out. Does not open the customer record like before but does open a magento session. This is the url they have once they login:

https://na87.salesforce.com/servlet/servlet.Integration?scontrolCaching=1&lid=00b400000018RIt&eid=0034000001XN8nc&ic=1&linkToken=VmpFPSxNakF4T0MweE1pMHdNbFF4T0RvMU9Ub3lNeTQyTnpaYSxVUTVyTU16YnRrc1dyMnhfNF9lYmY5LFlXWmtNR0po


Ivan

 
So been working with my buddy Greg C and have code that sends data to third party system thru Json Post calls. When creating a new record in salesforce the class fires correctly and it passes over with no issue. Currently working on trigger to push address entries to push over as well. Now when i try to edit a contact record with no address related record the class fires off no issues but soon as you add a address record and try to edit a contacat i get the "System.JSONException: Can not write a field name, expecting a value" error message for the following line:

Class.MagentoUtility.getAddresses: line 78, column 1
Class.MagentoUtility.magentoPost: line 118, column 1

Here is the class that i am using and the trigger which im not sure how to get this to pass over without the message.

Class:
global class MagentoUtility {

    //This is a future method used to call the methods we need to get a token and then post to Magento.
    //Since this is executed using a trigger, callouts need to be future methods. As a result, our methods need to be static.
    @future(callout=true)
    public static void magentoIntegration(String contactData){

        String token = getToken();
        magentoPost(token, contactData);

   }
    public static String getToken() {

        //Retrieve Username from Magento Setting (custom metadata type)
        String magentoUsername = [SELECT Value__c FROM Magento_Setting__mdt WHERE DeveloperName = 'magentoUsername' LIMIT 1].Value__c;

        //Retrieve Password from Magento Setting (custom metadata type)
        String magentoPassword = [SELECT Value__c FROM Magento_Setting__mdt WHERE DeveloperName = 'magentoPassword' LIMIT 1].Value__c;

        //Retrieve Token Enpoint from Magento Setting (custom metadata type)
        String tokenEndpoint = [SELECT Value__c FROM Magento_Setting__mdt WHERE DeveloperName = 'tokenEndpoint' LIMIT 1].Value__c;

          //String UserName = 'username';

        /////Retrieve token/////
        HttpRequest req = new HttpRequest();
        req.setEndpoint(tokenEndpoint);
        req.setMethod('POST');

        JSONGenerator gen = JSON.createGenerator(true);
        gen.writeStartObject();
        gen.writeStringField('username', magentoUsername);
        gen.writeStringField('password',magentoPassword);
        gen.writeEndObject();
        String jsonA = gen.getAsString();
        System.debug('jsonMaterials'+jsonA);
        //Specify the required username and password to access the endpoint
           //String authBody = jsonA;
        //'{"username":"' + magentoUsername + '", "password" : "' + magentoPassword + '" }';
           //String parseJson = System.debug(Json.serialize(authBody));
        req.setBody(jsonA);
        req.setHeader('Content-Type', 'application/json; charset=UTF-8');

        Http http = new Http();
        HTTPResponse res = http.send(req);
        //JSONParser parser = JSON.createParser(res.getBody());
        System.debug('Response: ' + res.getBody());

        String authToken = res.getBody();
        authToken = authToken.replace('\\', '');
        authToken = authToken.replace('"', '');
        //String authToken = json.Replace("\", "");

        return authToken;
          //return authToken;
           //String parseJson = Json.serialize(authToken);
           //return parseJson;
    }

    public static Map<Id,String> getAddresses(List<Contact> contactList) {
        List<Contact> data = new List<Contact>();
        data = [Select Id,(Select Id, FirstName__c, LastName__c, Country__c, Zip__c, State__c, Phone_Number__c, Primary_Billing_Address__c, Default_Shipping_Address__c, Address__c, Address2__c, UUID__c  From R00N40000001gQKfEAM) From Contact c WHERE (c.Id IN (SELECT Contact__c FROM ShipTo_Address__c)) AND ( c.Id IN :contactList)];
        //data = [Select Id,(Select Id From ShipTo_Addresses__r) From Contact c WHERE (c.Id IN (SELECT Contact__c FROM ShipTo_Address__c)) AND ( c.Id IN :contactList)];
        
        Map<Id, String> contactAddressMap = new Map<Id, String>();

        for(Contact c : data){
            //Create JSON Generator for creating JSON Array for addresses
            JSONGenerator gen = JSON.createGenerator(true);

            for(ShipTo_Address__c cd : c.R00N40000001gQKfEAM){
            //for(ShipTo_Address__c cd : c.ShipTo_Addresses__r){
                //Build address data for each Contact passed by trigger
               //gen.writeStartObject();
               //gen.writeFieldName('addresses');
                gen.writeStartArray();
                if (cd.FirstName__c != Null){
                gen.writeStringField('firstname', cd.FirstName__c);
                } else {
                gen.writeStringField('firstname','');
                }
                gen.writeStringField('lastname', cd.LastName__c);
                gen.writeStringField('countryId', cd.Country__c);
                gen.writeStringField('postalcode', cd.ZIP__c);
                gen.writeStringField('state', cd.State__c);
                gen.writeStringField('telephone', cd.Phone_Number__c);
                gen.writeBooleanField('defaultBilling', cd.Primary_Billing_Address__c);
                gen.writeBooleanField('defaultShipping', cd.Default_Shipping_Address__c);
                if ( cd.Address2__c != null ){
                    gen.writeStringField('street', cd.Address__c + ' ' + cd.Address2__c);
                } else {
                    gen.writeStringField('street', cd.Address__c); 
                }
                //To avoid null pointer exception
                if( cd.UUID__c != null ) {
                    gen.writeStringField('uuid', cd.UUID__c); 
                }
                //gen.writeEndObject();
                gen.writeEndArray();
                gen.close();
            }

            //Add the child address to the map of the parent Contact ID and the address data
            contactAddressMap.put(c.Id, gen.getAsString());
        }
        return contactAddressMap;
    }

    public static void magentoPost(String token, String contactData) {
        //Retrieve Token Endpoint from Magento Setting (custom metadata type)
        String syncEndpoint = [SELECT Value__c FROM Magento_Setting__mdt WHERE DeveloperName = 'syncEndpoint' LIMIT 1].Value__c;

        //Deserialize the JSON string passed by the Contact trigger. We have to pass this as JSON because future methods don't support passing sObjects.
        List<Contact> contactList = (List<Contact>) Json.deserialize(contactData, List<Contact>.class);

        //Obtain the address data from child object
        Map<Id, String> addressMap = new Map<Id, String>();
        addressMap = getAddresses(contactList);

        //Loop through the new Contacts
        for( Contact c : contactList ) {
            HttpRequest req = new HttpRequest();
            req.setEndpoint(syncEndpoint);
            req.setMethod('POST');
            req.setHeader('Content-Type', 'application/json; charset=UTF-8');
            req.setHeader('Authorization', 'Bearer ' + token);

            JSONGenerator gen = JSON.createGenerator(true);

            //We need to create { "customer": {
            //writeStartObject() - Writes the starting marker of a JSON object ('{').
            gen.writeStartObject();
            gen.writeFieldName('customer');
            gen.writeStartObject();

            gen.writeStringField('firstname',c.FirstName);
            gen.writeStringField('lastname',c.LastName);
            gen.writeStringField('email',c.Email);
            gen.writeStringField('telephone',c.HomePhone);
            gen.writeStringField('contact_sf_id',c.Id);
            gen.writeDateTimeField('sfdc_updated_at',c.LastModifiedDate);
            if( c.Account.RMS_Account_Number__c != null ){
                gen.writeStringField('rms_account_no', c.Account.RMS_Account_Number__c);
            }
            gen.writeStringField('customer_group_code',c.Pricing_Profile__c);
            if( c.Revel_Id__c != null ) {
                gen.writeStringField('revel_id', c.Revel_Id__c);
            }
            //To avoid null pointer exception
            if( c.Magento_Associate_to_Website__c != null ) {
                gen.writeStringField('website_id', c.Magento_Associate_to_Website__c); 
            }
            //To avoid null pointer exception
            if( c.Store_ID__c != null ) {
                gen.writeStringField('store_id', c.Store_ID__c); 
            }
            //To avoid null pointer exception
            if( c.UUID__c != null ) {
                gen.writeStringField('uuid', c.UUID__c); 
            }

            //Addresses is a JSON array, so we use writeObjectField method based upon example in Salesforce documentation
            //Line 47 in their example code - https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_json_jsongenerator.htm
            if( addressMap.get(c.Id) != null ) {
                gen.writeObjectField('addresses', addressMap.get(c.Id));
            }

            //Expected JSON data ends in '} }' so we call "writeEndObject" twice
            gen.writeEndObject();
            gen.writeEndObject();

            String jsonStr = gen.getAsString();
            System.debug('JSON String: ' + jsonStr);

            req.setBody(jsonStr);

            System.debug('Req Body: ' + req.getBody());
            System.debug('Req Body as Blob: ' + req.getBodyAsBlob());

            Http http = new Http();
            HTTPResponse res = http.send(req);
            System.debug('Response Body: ' + res.getBody());
            System.debug('Response Body as Blob: ' + res.getBodyAsBlob());
        }
    }
}

Trigger:
trigger MainContactTrigger on Contact (before update, before insert, after update, after insert) {
    DuplicateEmailFilter def = new DuplicateEmailFilter();
    Map<id,Contact> oldMap = trigger.oldMap;
    CreateAccountFromContact accountCreation = New CreateAccountFromContact();
    
    if(oldMap == null){
        oldMap = new Map<Id,Contact>();
    }
    if(Trigger.isBefore){
    // 
    // For the before creation we check if the contact is getting created by a real user then we use 
    // the Duplicate Email Filter to generate an error preventing the contact from being created.
    
        if(!IntegrationUtils.isIntegrationUser()){
            def.processContacts(trigger.new, oldMap);
        }
        if( Trigger.isInsert && !IntegrationUtils.ignoreForAutoAccountUser() ) {
            accountCreation.ProcessBatchContactsWEmail(trigger.new,trigger.oldMap);
        }
        else if( Trigger.isInsert || Trigger.isUpdate ) {
            accountCreation.ProcessBatchContacts(trigger.new,trigger.oldMap);
        }
    }
    else if(Trigger.isAfter){
    //
    // This is the After trigger - we just need to check if the email address is already
    // in use in the duplicate email filter. 
    // if it is being created by the integration user then in the DEF we flag the contact as having 
    // a duplicate. Leaving it up to the Salesforce Admin to clean it up.
    //
        if(IntegrationUtils.isIntegrationUser()){
            def.processContacts(trigger.new, oldMap);
        }
        
        //Magento Integration
        if( Trigger.isInsert || Trigger.isUpdate  ){
            String jsonString = json.serialize(Trigger.NEW);
            MagentoUtility.magentoIntegration(jsonString);
        }
    }
}

Any input is greatly appreciated.

Ivan
So i have setup a oAuth connected app in my dev box and trying to follow all the steps, i even am working in POSTMAN and got it to connect using the key and tokens provided by magento but when i try to run it thru the debug in salesforce it says that "the nonce is already being used by the consumer with ID %1","paramerters":[114]

I already have triggers and classes in place for updating and creation of a customer but 1. cant figure out how to get my oauth to work in debug, and 2. where do i add this into my code to make the get / post calls to magneto. Hopefully someone has dont this before and can help me out.

This is the POSTMAN code i got to work how do i get it to work in salesforce:
POST /rest/V1/hall/salesforce/customer/sync HTTP/1.1
Host: hallwinesm2-uat.smarterspecies.com
Content-Type: application/json
Authorization: OAuth oauth_consumer_key="c3hhpk8hwwhj43cq1kmghueuurfyl5wu",oauth_token="i4xg6hropwhb6grq7xex7u0o22v79vst",oauth_signature_method="HMAC-SHA1",oauth_timestamp="1530801906",oauth_nonce="07QbX9VZBuH",oauth_version="1.0",oauth_signature="YVNZ4Sy0nreV0REXdM5gEK6XPlk%3D"
Cache-Control: no-cache
Postman-Token: 9d0ff9ce-c958-4152-beda-da435d19505d

{
    "customer": {
        "firstname": "Maciej", 
        "lastname": "Garycki", 
        "email": "mgarycki+sf5333@gorillagroup.com", 
        "telephone": "6924609876", 
        "contact_sf_id": "1234567890", 
        "sfdc_updated_at": "182736", 
        "rms_account_no": "12345", 
        "customer_group_code": "GENERAL", 
        "revel_id": "", 
        "website_id": "1", 
        "store_id": "1", 
        "uuid": "", 
        "addresses": []
    }
}

And this is my class that i need to get this added into:
 
public with sharing class DuplicateEmailFilter {


    public void createDefaultEmail(List<Contact> contacts){
        /*
        List<Contact> contactsToUpdate = new List<Contact>();
        for(Contact contact : contacts){
            if(contact.email==null){
                contactsToUpdate.add(new Contact(id=contact.id, email='RMS'+contact.Unique_Contact_Number__c+'@hallwines.noemail.com'));
            }
        }
        
        if(contactsToUpdate.size()>0){
            update contactsToUpdate;
        }
        */
    }
    
    public void processContacts(List<Contact> contacts, Map<Id,Contact> oldMap){
        List<Contact> dupes = new List<Contact>();
        Map<String, Contact> unique = new Map<String,Contact>();
        Set<Id> ids = new Set<Id>();
        
        List<Contact> contactsToUpdate = new List<Contact>();
        List<Task> tasksToCreate = new List<Task>();
        
        for(Contact contact : contacts){
            Contact old = oldMap.get(contact.id);
            if(old == null || old.email != contact.email){
                if(contact.email != null){
                    if(unique.containsKey(contact.email)){
                        dupes.add(contact);
                    }
                    else{
                        unique.put(contact.email,contact);
                    }
                    ids.add(contact.id);
                }
            }
        }
        
        Map<String, Contact> contactsByEmail = new Map<String, Contact>();
        
        for(Contact c : [select id,email,FirstName,LastName from Contact where Do_Not_Sync_with_Ecommerce__c = false and email in :unique.keySet() and id not in :ids]){
           contactsByEmail.put(c.Email, c);
        }  
        
        for(String e : unique.keySet()){
            Contact c = unique.get(e);
            Contact existing = contactsByEmail.get(c.email);
            if(existing!=null && existing.id != c.id){
                dupes.add(c);
            }
        }
        
        for(Contact c : dupes){
            Contact existing = contactsByEmail.get(c.email);
            if(existing == null){
               existing = unique.get(c.email);
            }
            if(IntegrationUtils.isIntegrationUser()){
                contactsToUpdate.add(new Contact(Id=c.id,Do_Not_Sync_With_Ecommerce__c = true));
                tasksToCreate.add(createTask(c, existing));
            }
            else{
                c.addError(getDuplicateMessage(existing));
            }
        }
        
        if(contactsToUpdate.size()>0){
            update contactsToUpdate;
        }
        if(tasksToCreate.size() > 0){
            insert tasksToCreate;
        }
    }
    
    private Task createTask(Contact c,Contact old){
        Task t = new Task(WhoId = c.id, Subject = 'Duplicate Contact',Description=getDuplicateMessage(old));
        return t;
    }
    
    public String getDuplicateMessage(Contact old){
        String link = '<a href="/'+ old.id +'">'+ old.FirstName+' '+old.LastName + '</a>';
        String message = 'Duplicate Contact '+link+' already exists with Email Address '+old.email;
        return message;
    }
    
    @IsTest
    public static void testNoEmail(){
        /*
        User u = new User(id = UserInfo.getUserId(), Integration_User__c = false);
        update u;
        
        Contact c = new Contact(LastName = 'Smith');
        insert c;
        c = [select id, Email, Unique_Contact_Number__c from Contact where id =: c.id];
        System.assertEquals('rms'+c.Unique_Contact_Number__c+'@hallwines.noemail.com',c.email);
        
        u.Integration_User__c = true;
        update u;
        
        c = new Contact(LastName = 'Smith');
        insert c;
        c = [select id, Email, Unique_Contact_Number__c from Contact where id =: c.id];
        System.assertEquals('rms'+c.Unique_Contact_Number__c+'@hallwines.noemail.com',c.email);
        */
    }
    
    
    
    @IsTest
    public static void testIntegrationDuplicateEmail(){
        User u = new User(id = UserInfo.getUserId(), Integration_User__c = true);
        update u;
        
        Contact c = new Contact(LastName = 'Smith',email='test@example.com');
        insert c;
        Contact c2 = new Contact(LastName = 'Smith',email='test@example.com');
        insert c2;
               
        
        c2 = [select id, Email, Do_Not_Sync_With_Ecommerce__c,(select id from Tasks) from Contact where id =: c2.id];
        System.assertEquals(true, c2.Do_Not_Sync_With_Ecommerce__c);
        System.assertEquals(1,c2.tasks.size());
    }
       
    
    @IsTest
    public static void testNotIntegrationDuplicateEmail(){
        User u = new User(id = UserInfo.getUserId(), Integration_User__c = false);
        update u;
        
        Contact c = new Contact(LastName = 'Smith',email='test@example.com');
        insert c;
        
        String msg = '';
        
        try{
            Contact c2 = new Contact(LastName = 'Smith',email='test@example.com');
            insert c2;
        }
        catch(Exception ex){
            msg = ex.getMessage();
        }
        System.assert(msg.contains('Duplicate Contact'));
    }
    
}

I really hope someone can help me out im in a time crunch to get this to work.

Ivan
 
So im in a pickle. The magento developer is asking for my contact/account creation trigger to call their API and below is what i need to add ino my trigger but not sure where and how to get it to fire the request. This what I have currently in my trigger:
 
trigger MainContactTrigger on Contact (before update, before insert, after update, after insert) {
    DuplicateEmailFilter def = new DuplicateEmailFilter();
    Map<id,Contact> oldMap = trigger.oldMap;
    CreateAccountFromContact accountCreation = New CreateAccountFromContact();
    
    if(oldMap == null){
        oldMap = new Map<Id,Contact>();
    }
    if(Trigger.isBefore){
    // 
    // For the before creation we check if the contact is getting created by a real user then we use 
    // the Duplicate Email Filter to generate an error preventing the contact from being created.
    //
        if(!IntegrationUtils.isIntegrationUser()){
            def.processContacts(trigger.new, oldMap);
        }
        if( Trigger.isInsert && !IntegrationUtils.ignoreForAutoAccountUser() ) {
            accountCreation.ProcessBatchContactsWEmail(trigger.new,trigger.oldMap);
        }
        else if( Trigger.isInsert || Trigger.isUpdate ) {
            accountCreation.ProcessBatchContacts(trigger.new,trigger.oldMap);
        }
    }
    else{
    //
    // This is the After trigger - we just need to check if the email address is already
    // in use in the duplicate email filter. 
    // if it is being created by the integration user then in the DEF we flag the contct as having 
    // a duplicate. Leaving it up to the Salesforce Admin to clean it up.
    //
        if(IntegrationUtils.isIntegrationUser()){
            def.processContacts(trigger.new, oldMap);
        }
    }
    
}

and this is what i need to add into it somewhere to make this call to magento:
 
Salesforce to Magento Customer update endpoint url:
https://hallwinesm2-uat.smarterspecies.com/rest/V1/hall/salesforce/customer/sync
Content-Type:application/json
POST:
{
    "customer": {
        "firstname": "Maciej", 
        "lastname": "Garycki", 
        "email": "mgarycki+sf5333@gorillagroup.com", 
        "telephone": "6924609876", 
        "contact_sf_id": "1234567890", 
        "sfdc_updated_at": "182736", 
        "rms_account_no": "12345", 
        "customer_group_code": "GENERAL", 
        "revel_id": "", 
        "website_id": "1", 
        "store_id": "1", 
        "uuid": "", 
        "addresses": []
    }
}

Can anyone help me..

Thanks,

Ivan
So i have a case field i am trying to create to push a certain shipping rate to the contact field. My formula filed Shipping Cost reads as:
CASE(Shipping_Cost_Key__c, 
"CO2", 20, 
"CO4", 22,
"CO6", 10, 
"FL2", 20, 
"FL4", 26,
"FL6", 10,  
"GA2", 26, 
"GA4", 33,
"GA6", 10,  
"KS2", 25, 
"KS4", 30,
"KS6", 10,  
"MO2", 28, 
"MO4", 31,
"MO6", 10,  
"NC2", 29, 
"NC4", 31,
"NC6", 10,  
"NE2", 28, 
"NE4", 31,
"NE6", 10,  
"NM2", 24, 
"NM4", 27,
"NM6", 10,  
"NV2", 24, 
"NV4", 26,
"NV6", 10,  
"SC2", 29, 
"SC4", 32,
"SC6", 10,  
"TN2", 29, 
"TN4", 32,
"TN6", 10, 
"TX2", 28, 
"TX4", 32, 
"TX6", 10, 
0)

and is field it is looking at is Shipping Cost Key:
 
if(Club_Bottle_Count_2__c >0, OtherState+TEXT(2), 
if(Club_Bottle_Count_4__c >0, OtherState+TEXT(4), 
OtherState+TEXT(6)))
I keep getting Error: Compiled formula is too big to execute (8,512 characters). Maximum size is 5,000 characters.

Can anyone help me figure out how to get this to work.

Ivan
 
So i have the following trigger that is suppose to create a new CC record in SF and if primary update the old card marked as primary and make it so only 1 primary card can exist at a time. Not sure if it broke or im missing something but now we can have more than 1 primary cc selected in the related list. Can anyone help me figure out what is wrong with the code:
 
Trigger to set the Primary wine club card on the contact record.
// Check if the flag is set on both inserts and updates, and if so
// set those fields on contact.
//
trigger CredCardTrigger on authnet_credit_card__c (After Insert, After Update) { 
    List<authnet_credit_card__c > slist = trigger.New; 
    List<authnet_credit_card__c> oldPrimaryList = new List<authnet_credit_card__c>(); 
    List<Contact> contactsToUpdate = new List<Contact>(); 

    for ( authnet_credit_card__c a : slist ) {  
        if ( a.isPrimaryWineClubCard__c == true) { 
            system.debug('Copying in primary Auth id '+a.Payment_Id__c); 
            Contact c = New Contact(Id = a.Contact__c); 

            if (c.authnet_profile_id__c != null) { 
                if (c.authnet_profile_id__c != a.Profile_Id__c) { 
                    authnet_credit_card__c oldPrimary = new authnet_credit_card__c(Profile_Id__c = c.authnet_profile_id__c); 
                    system.debug('Unchecking old authnet primary id '+a.Profile_Id__c); 
                    oldPrimary.IsPrimaryWineClubCard__c = false; 
                    oldPrimaryList.add(oldPrimary); 
                } 
            } 

            c.authnet_profile_id__c = a.Profile_Id__c; 
            c.authnet_default_payment_id__c = a.Payment_Id__c; 
            c.Authnet_Ex_Date__c = a.Expiration_Date__c;
            contactsToUpdate.add(c); 

        } 
    } 

   if (!oldPrimaryList.isEmpty()) { 
        update oldPrimaryList; 

    } 
    if (!contactsToUpdate.isEmpty()) { 
        update contactsToUpdate; 

    } 

}

Ivan
So i have test class that keeps failing when run in sandbox. The main error i am getting is:

Error MessageSystem.AssertException: Assertion Failed: Expected: , Actual: Collection
Stack TraceClass.Test_DataPushtoAccount.testDataPushtoAccount: line 19, column 1

Below is the code and im not sure why its saying its expecting a null i query it in my c = statement and the filed is set in hte creation of the customer. Can anyone let me know what im not seeing.
@isTest
public with sharing class Test_DataPushtoAccount {
	@isTest
    public static void testDataPushtoAccount(){
        Account a = new Account(Name = 'Test MainContactTrigger', RecordTypeID = '01240000000UZ4V');
 //       a.RecordType = 'Household';
        insert a;
        
        Contact c = new Contact(AccountID = a.id, firstName = 'Test MainContactTrigger', lastName = 'Tester', email = 'testfake@gmail.com', Pricing_Profile__c = 'Collection');
        insert c;
        
 //       System.debug('Contact record num: ' + [SELECT Id FROM Contact].size());
        
          
        c = [select AccountId, Account.Name, Pricing_Profile__c from Contact where id = :c.id limit 1];
           System.assertEquals('Test MainContactTrigger', a.Name);
           System.assertEquals(1, [SELECT Id FROM Contact].size());
           System.assertEquals(a.id, c.AccountId);
           System.assertEquals(a.Pricing_Profile__c, c.Pricing_Profile__c);
    }
    
}

 
So i have found a working solution thru the sucess community but still having a issue with the outcome. So below is what i have created in our org:

First- 
Create a formula field on the Opportunity
Name this something like "CloseDatewithAmount"
Formula field will be a number field with 2 decimals
Use the following formula:
VALUE(text(YEAR(CloseDate)) & 
  IF(LEN(text(MONTH(CloseDate))) = 1, "0" & TEXT(MONTH(CloseDate)),         TEXT(MONTH(CloseDate))) 
   & IF(LEN(text(DAY(CloseDate))) = 1, "0" & TEXT(DAY(CloseDate)), TEXT(DAY(CloseDate)))
      &  TEXT(Amount))

Second-
Create a Roll-up Summary field on the Account
Name this field something like "LastClosedWonFormula"
Summarized object = Opportunity
Choose Max as the rollup type
Field to aggregate = CloseDatewithAmount  (or whatever you named your Opportunity formula field)
Under filter criteria choose - Only records meeting certain criteria should be included in the calculation
For the criteria choose Won equals True

Third-
Create a formula field on the Account
Name this field something like "Last Closed Won Opportunity Amount"
Make the field a currency field with 2 decimals
The formula is : 
VALUE(TRIM(MID(TEXT(LastClosedWonFormula__c), 9, 25)))

So all of this has worked and on each opp i see the data. So where my issue is, that the roll up created to pull the most recent date and amount its pulling the largest amount which is not technically the last purchase. For example:

Customer Abby has a purchase on 10/31/2012 for $107 and another on 07/05/2013 for $50. So the data on each record reads as
2013070550
20121031107

Which it should but the problem is that the max rollup of the field created in the first section is pulling in 20121331107 since it is the highest amount in the list however it should be pulling in 2013070550 since 2013 is more than 2012.

So hopefully someone can help me figure out what is wrong with my rollup summary field or the fields in general to get it to pull by the year and not the enritre amount in regards to sorting the data to use.

All help is greatly appreciated :)

Ivan
 
Ok so i have a formula field that is pulling the address infromation from the contact into the field. What i am trying to do is that if my 3rd party shipping picklist value is null (meaning nothing choosen) then the text will show, but if a selction has been made that the formula field shows in text. Does anyone think this is possible.

This is what i have but not seeming to work
 
AND( ISPICKVAL(X3rd_Party_Shipper__c = "", "",
if(LEN(Contact__r.OtherStreet)>0, Contact__r.OtherStreet& " " , "" ) & BR() &
if(LEN(Contact__r.OtherCity)>0, Contact__r.OtherCity& ", " , "" )&
if(LEN(Contact__r.OtherState)>0, Contact__r.OtherState& " " , "" )&
if(LEN(Contact__r.OtherPostalCode)>0, Contact__r.OtherPostalCode,"") & BR() &
If(LEN(Contact__r.OtherCountry) >0, Contact__r.OtherCountry,"")))

 
So had this error sometime last year and now getting it again. For some reason today i started to get #Error# in my formula field that has the below code:

DATE(YEAR(TODAY())+
IF( DATE(1900, MONTH(TODAY()), MAX(1,DAY(TODAY()-1))) > DATE(1900, MONTH( Start_Date__c ), MAX(1,DAY( Start_Date__c )-1)),1,0) ,
MONTH(Start_Date__c), MAX(1,DAY(Start_Date__c)-1))+1

Not sure if this has to do with the leap year but for some reason it started erroring out again. Now the start date field is required to create the record so there are no blanks. Any have an idea on why this happened again and how i can get it to stop.

The main focus of this query is to show the customers next anniversary date from the time they started the membership.

Ivan
Ok so I am still learning coding and with so many code examples i think im getting confused so hopefully someone can help lead me in the right direction.

So company is trying to do a rewards type program. So for every opprotunity the contact has that has a revenue center of 'ECOM' within a time frame will count towards getting a reward when they have reached $600 then $2000. Now i dont have any lookups from the contact to opprotunity which has me lost. And id like to have this data rolled into a custom object Direct_Rewards__c so we can track when people join the program, drop out , then join again (i know very crazy)

So breakdown:

Have object Opprotunity that has purchases made by our customers and they have a feild called Revenue_Center__c which should equal 'ECOM'

Have object Direct_Rewards__c that has a Master Detail relationship with Contact. This object keeps track of the Start_Date__c, End_Date__c, Contact__c (Master Detail), Rewards_Points_Accumulated__c (number), and Active_Rewards_Member__c (checkbox) to insure its an active record.

Now what im looking to accomplish is Customer goes online and joins the club which creates a record. Then make a purchase online for $200. The opprotunity is added to SF and if the revenue center = 'ECOM' then the active Direct_Rewards__c record should pull that $200 total into the Rewards_Points_Accumulated__c field. Then if they come back agian and purchase the system will add the new purchase of $150 to the Rewards_Points_Accumulated__c field which would then have a total of $350.

Then once they hit $600 we give a reward and again at $2000 (which is the max and no more purchases should be added). Then come Jan 1st i will clear out the Rewards_Points_Accumulated__c field and only purcahses from that date will count towards the reward record.

Im probably asking for a lot but i hope someone can help me. Im trying different codes but trying to get the data from the Opp to pull into the direct reward record based on a contact is where i get stuck.

Your help is majorly appreciated.

Ivan
Ok so i have read other entries but nothing i take seems to be working so hopefully someone can look at my code and see what the issue is. Im getting these emails raipdly these days and even when going to clean up data im starting to see if on new records as well.

PrimaryAddressValidation: execution of BeforeUpdate

 

caused by: System.QueryException: Non-selective query against large object type (more than 100000 rows). Consider an indexed filter or contact salesforce.com about custom indexing.

Even if a field is indexed a filter might still not be selective when:

1. The filter value includes null (for instance binding with a list that contains null) 2. Data skew exists whereby the number of matching rows is very large (for instance, filtering for a particular foreign key value that occurs many times)

 

Trigger.PrimaryAddressValidation: line 55, column 1

and this is my code the error is coming in at the fist List select statment in each if statement below.
 
// section makes sure that only one checkbox is true within the related address list for the contact
      if(!contactIdsForShipping.isEmpty())
      {
          List<ShipTo_Address__c> toggleShippings = shipToExcluded.isEmpty()?
             [SELECT Id, Default_Shipping_Address__c FROM ShipTo_Address__c WHERE Contact__c IN :contactIdsForShipping AND Default_Shipping_Address__c=true]
             : [SELECT Id, Default_Shipping_Address__c FROM ShipTo_Address__c WHERE Contact__c IN :contactIdsForShipping AND Default_Shipping_Address__c=true AND Id NOT IN :shipToExcluded];

          for(ShipTo_Address__c a : toggleShippings)
          {
                  a.Default_Shipping_Address__c = false;
          }
          update toggleShippings;
      }

      if(!contactIdsForBilling.isEmpty())
          {
              List<ShipTo_Address__c> toggleBilling = billToExcluded.isEmpty()?
              [SELECT Id, Primary_Billing_Address__c FROM ShipTo_Address__c WHERE Contact__c IN :contactIdsForBilling AND Primary_Billing_Address__c=true]
              :[SELECT Id, Primary_Billing_Address__c FROM ShipTo_Address__c WHERE Contact__c IN :contactIdsForBilling AND Primary_Billing_Address__c=true AND Id NOT IN :billToExcluded];
              for(ShipTo_Address__c a : toggleBilling)
              {
                  a.Primary_Billing_Address__c = false;
              }
              update toggleBilling;
          }   

    }

 
So over the weekend im not sure what happend but for some reason i have a hand full of accounts that are duplicating on the second. I just did a mass delete of over 10k of the same account and just as soon as i refresh the report the name poped back up and i had another 119 of the same account but not tied to an contact. Here is a trigger an older developer wrote (before my time) and im wondering if something is triggering this to keep creating accounts even though they are not tied to any contacts. can anyone help this is casusing a huge problem as these duplicates are being pushed into other systems with our API calls and integrations.
 
trigger MainContactTrigger on Contact (before update, before insert, after update, after insert) {
    DuplicateEmailFilter def = new DuplicateEmailFilter();
    Map<id,Contact> oldMap = trigger.oldMap;
    CreateAccountFromContact accountCreation = New CreateAccountFromContact();
    
    if(oldMap == null){
        oldMap = new Map<Id,Contact>();
    }
    if(Trigger.isBefore){
    // 
    // For the before creation we check if the contact is getting created by a real user then we use 
    // the Duplicate Email Filter to generate an error preventing the contact from being created.
    //
        if(!IntegrationUtils.isIntegrationUser()){
            def.processContacts(trigger.new, oldMap);
        }
        if( Trigger.isInsert && !IntegrationUtils.ignoreForAutoAccountUser() ) {
            accountCreation.ProcessBatchContactsWEmail(trigger.new,trigger.oldMap);
        }
        else if( Trigger.isInsert || Trigger.isUpdate ) {
            accountCreation.ProcessBatchContacts(trigger.new,trigger.oldMap);
        }
    }
    else{
    //
    // This is the After trigger - we just need to check if the email address is already
    // in use in the duplicate email filter. 
    // if it is being created by the integration user then in the DEF we flag the contct as having 
    // a duplicate. Leaving it up to the Salesforce Admin to clean it up.
    //
        if(IntegrationUtils.isIntegrationUser()){
            def.processContacts(trigger.new, oldMap);
        }
    }
    
}

 
So not sure what happened but today my formula field start to show errors for all records. Below is the code which should just produce a date in teh future due to the sign up date of the record. But now all records show an error can anyone see why this is happening with the code below.
DATE(YEAR(TODAY())+ 
IF( DATE(1900, MONTH(TODAY()), MAX(1,DAY(TODAY()-1))) > DATE(1900, MONTH( Start_Date__c ), MAX(1,DAY( Start_Date__c )-1)),1,0) , 
MONTH(Start_Date__c), MAX(1,DAY(Start_Date__c)-1))+1

The formula is to show the next year of the sign up date.
Ok so this may sound crazy and may not be able to be done using formula's but hopefully it can.

So i have a field called wine credit avalible which will show user how much money the customer has left thru our buyin period (i.e. Started off with $750, then used $700, now has $50 left). So here is where it gets compliacated. Our buyin period stars on 5/1 each year so the current one would be from 5/1/15 to 5/1/16 where they are able to use the amount given. So what i need is this:

Customer buys in and received $750 for 5/1/15 to 5/1/16
Customer uses $700 during the buyin period and has $50 left at 5/1/16
Once the next buyin year starts from 5/1/16 to 5/1/17 customer should have total avalible of $800 ($750 start each year + remainder of $50)

Yes probably way to complicated for formula but thought id ask. I have the field for whats avalible to show correct but i cant figure out how to put the date range check in. See formula field below. The remainder IF is where i need to check the date and have it role over.
IF(TEXT(Is_a_HWG_Partner__c)= "Yes" && HWG_Wine_Credit_Remainder__c = 0,0, 
IF(TEXT(Is_a_HWG_Partner__c)= "Yes" && HWG_Wine_Credit_Remainder__c <= 25, HWG_Wine_Credit_Remainder__c + HWG_Wine_Credit__c, 
IF(TEXT(Is_a_HWG_Partner__c)= "No",0, 
HWG_Wine_Credit_Remainder__c)))

 
So i have a batch job that is scheduled to run at 5am and at 9am. I would like to change the scheduled job that runs at 9am to 5pm. Both jobs use the same class so not sure how to update it so i can reschedule the 9am batch run to 5pm. Any help is greatly appreciated. I can provide details if needed.

Ive read some post but still unclear if i can reschedule and if a new class needs to be written in order to do this.
So i was in need of scheduling a Apex job to run on scheduler. Few folks helped me out and i got the classes to work. But now im wondering if they are actually updating records. I ask becasue the class below is to update a checkbox on the object each time its run, but when i check my history i dont see any changes. And i should see it becaue once the class checks the box i have a work flow to uncheck it but im not seeing any of this in the history, yet the job keeps completing and saying it batched 61 batches. Is there a way i can see a log of whats being updated or does the code below not actually update anything?
global class WineClubCronJobBatch implements Database.Batchable<sObject> 
{ 
   global Database.QueryLocator start(Database.BatchableContext BC) 

  { 
    String query ='Select Id, Tenure_Cron_Job_Schedule__c From Wineclub_Membership__c Where Active__c=True'; 
      return Database.getQueryLocator(query); 
  } 

    global void execute(Database.BatchableContext BC, List<sObject> scope) 

   { 
       List<Wineclub_Membership__c> listToUpdate = new List<Wineclub_Membership__c>(); 
        for( Wineclub_Membership__c a: (List<Wineclub_Membership__c> ) scope) 
        {  
            if(a.Tenure_Cron_Job_Schedule__c = False ) 
            {    
                a.Tenure_Cron_Job_Schedule__c = True;  
                listToUpdate.add(a); 
            }    
        } 
        if(listToUpdate.size() > 0) 
       { 
            update(listToUpdate);  

       } 

   } 
   global void finish(Database.BatchableContext BC){ 
  } 

}

 
So with the help of a few forums i found out you can schedule classes. So i created one that will check a box on a custom object at 5am daily. But when i went to check this morning on the job it failed due to the error: Too many DML rows: 10001

Below is the code used, which probably needs to be bulk-i-fied but each way i try it errors out. Any help is greatly appreciated.
 
global class WineClubCronJob implements Schedulable{ 


    global void execute(SchedulableContext SC) { 
     List <Wineclub_Membership__c> acc = [Select Id, Tenure_Cron_Job_Schedule__c From Wineclub_Membership__c Where Active__c=True];
     
              

    for(Wineclub_Membership__c a: acc ){ 
        if(a.Tenure_Cron_Job_Schedule__c = False ) 
            a.Tenure_Cron_Job_Schedule__c = True; 
            

    } 


    update(acc); 


    }
}

 
Ok so i have read other entries but nothing i take seems to be working so hopefully someone can look at my code and see what the issue is. Im getting these emails raipdly these days and even when going to clean up data im starting to see if on new records as well.

PrimaryAddressValidation: execution of BeforeUpdate

 

caused by: System.QueryException: Non-selective query against large object type (more than 100000 rows). Consider an indexed filter or contact salesforce.com about custom indexing.

Even if a field is indexed a filter might still not be selective when:

1. The filter value includes null (for instance binding with a list that contains null) 2. Data skew exists whereby the number of matching rows is very large (for instance, filtering for a particular foreign key value that occurs many times)

 

Trigger.PrimaryAddressValidation: line 55, column 1

and this is my code the error is coming in at the fist List select statment in each if statement below.
 
// section makes sure that only one checkbox is true within the related address list for the contact
      if(!contactIdsForShipping.isEmpty())
      {
          List<ShipTo_Address__c> toggleShippings = shipToExcluded.isEmpty()?
             [SELECT Id, Default_Shipping_Address__c FROM ShipTo_Address__c WHERE Contact__c IN :contactIdsForShipping AND Default_Shipping_Address__c=true]
             : [SELECT Id, Default_Shipping_Address__c FROM ShipTo_Address__c WHERE Contact__c IN :contactIdsForShipping AND Default_Shipping_Address__c=true AND Id NOT IN :shipToExcluded];

          for(ShipTo_Address__c a : toggleShippings)
          {
                  a.Default_Shipping_Address__c = false;
          }
          update toggleShippings;
      }

      if(!contactIdsForBilling.isEmpty())
          {
              List<ShipTo_Address__c> toggleBilling = billToExcluded.isEmpty()?
              [SELECT Id, Primary_Billing_Address__c FROM ShipTo_Address__c WHERE Contact__c IN :contactIdsForBilling AND Primary_Billing_Address__c=true]
              :[SELECT Id, Primary_Billing_Address__c FROM ShipTo_Address__c WHERE Contact__c IN :contactIdsForBilling AND Primary_Billing_Address__c=true AND Id NOT IN :billToExcluded];
              for(ShipTo_Address__c a : toggleBilling)
              {
                  a.Primary_Billing_Address__c = false;
              }
              update toggleBilling;
          }   

    }

 
So recently moved over to Person accounts in lightning and need to make an update to a class and trigger. however when i try to push the changes from sandbox to production i get a bunch of errors in regards to already established @istest and other classes in my production org and wondering if anyone can help. These are the errors im getting and the assocaited classes or test:

Run Failures:
  GuestAccountPopulateTest.PositiveTest System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_EXECUTE_FLOW_TRIGGER, We can't save this record because the “New Guest” process failed. Give your Salesforce admin these details. Probably Limit Exceeded or 0 recipients
: []
  Test_ContactWineClub.myUnitTest System.DmlException: Insert failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Required fields are missing: [Account__c]: [Account__c]

  Test_PrimaryAddressValidationTriger.testCreateShipToAddress System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, mainShipToAddessTrigger: execution of BeforeInsert
caused by: System.QueryException: List has no rows for assignment to SObject

Trigger.mainShipToAddessTrigger: line 9, column 1: []
  Test_ShiptoAddressTrigger.testCreateShipToAddress System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, mainShipToAddessTrigger: execution of BeforeInsert
caused by: System.QueryException: List has no rows for assignment to SObject

Trigger.mainShipToAddessTrigger: line 9, column 1: []
  WineClubMembershipAccountPopulateTest.PositiveTest System.DmlException: Insert failed. First exception on row 0; first error: INVALID_FIELD_FOR_INSERT_UPDATE, Business Customer may not use Person Customer field  : WC Tenure: [WC Tenure]
 
@isTest
private class Test_ContactWineClub {

    static testMethod void myUnitTest() {

	date myDate = date.today();
	
        Account a = new Account(Name = 'Test MainContactTrigger', RecordTypeID = '0121W000000UgfA');
 //       a.RecordType = 'Household';
        insert a;
        
        Contact c = new Contact(AccountID = a.id, firstName = 'Test MainContactTrigger', lastName = 'Tester', email = 'testfake@gmail.com');
        insert c;
        
 //       System.debug('Contact record num: ' + [SELECT Id FROM Contact].size());
        
        Wineclub_Membership__c wc = new Wineclub_Membership__c( Contact__c = c.id, Active__c = true , Wine_Club_Code__c = 'Collection 2 Bottle', Start_Date__c = myDate);
        insert wc;
        
             
        c = [select AccountId, Account.Name from Contact where id = :c.id limit 1];
           System.assertEquals('Test MainContactTrigger', a.Name);
           System.assertEquals(1, [SELECT Id FROM Contact].size());
           System.assertEquals(a.id, c.AccountId);
     
     
    }
}
@isTest
private class Test_PrimaryAddressValidationTriger {

    @isTest
    public static void testCreateShipToAddress(){
        Account a = new Account(Name = 'Test PrimaryAddressValidation', RecordTypeID = '0121W000000UgfA');
        insert a;
        
        Contact c = new Contact(AccountID = a.ID, firstName = 'Test PrimaryAddressValidation', lastName = 'Tester', email = 'fakington@gmail.com');
        insert c;
        
        ShipTo_Address__c s1 = new ShipTo_Address__c( Contact__c = c.id,
           Address__c = '1919 Fakeone Way',
           City__c = 'Fakington',
           State__c = 'CA',
           Country__c = 'USA',
           ZIP__c = '00000',
           Primary_Billing_Address__c = true);
  
        insert s1;
   
    	ShipTo_Address__c s2 = new ShipTo_Address__c( Contact__c = c.id,
           Address__c = '1600 Alrington Way',
           City__c = 'Oakland',
           State__c = 'CA',
           Country__c = 'USA',
           ZIP__c = '00000',
           Default_Shipping_Address__c = true);        
   
   		insert s2;
   		
        c = [select AccountID,Account.Name from Contact where id = :c.id limit 1];
           System.assertEquals('Test PrimaryAddressValidation', c.Account.Name);
           System.assertEquals(a.id, c.AccountID);
    }

}
@isTest
public with sharing class Test_ShiptoAddressTrigger {
    @isTest
    public static void testCreateShipToAddress(){
        Account a = new Account(Name = 'Test MainShipToAddressTrigger', RecordTypeID = '01240000000UZ4V');
        insert a;
        
        Contact c = new Contact(AccountID = a.ID, firstName = 'Test MainShipToAddressTrigger', lastName = 'Tester', email = 'fakington@gmail.com');
        insert c;
        
        ShipTo_Address__c s1 = new ShipTo_Address__c( Contact__c = c.id,
           Address__c = '1919 Fakeone Way',
           City__c = 'Fakington',
           State__c = 'CA',
           Country__c = 'USA',
           ZIP__c = '00000',
           Primary_Billing_Address__c = true);
  
        insert s1;
   
    	ShipTo_Address__c s2 = new ShipTo_Address__c( Contact__c = c.id,
           Address__c = '1919 Fakeone Way',
           City__c = 'Fakington',
           State__c = 'CA',
           Country__c = 'USA',
           ZIP__c = '00000',
           Default_Shipping_Address__c = true);        
   
   		insert s2;
   		
        c = [select AccountId,Account.Name from Contact where id = :c.id limit 1];
           System.assertEquals('Test MainShipToAddressTrigger', c.Account.Name);
           System.assertEquals(a.id, c.AccountId);
    }
}
@isTest
public class WineClubMembershipAccountPopulateTest {

    @testSetup
    static void setup(){
        Account acc = new Account();
        acc.Name = 'Test1';
        insert acc;
        
        Contact con = new Contact();
        con.AccountId = acc.id;
        con.lastName = 'Test1';
        insert con;
        
        Wineclub_Membership__c wineClub = new Wineclub_Membership__C();
        wineClub.Account__c = acc.id;
        wineClub.Contact__c = con.id;
        insert wineClub;
    }
    
    @isTest
    static void PositiveTest() {
        Test.startTest();
        database.executeBatch(new WineClubMembershipAccountPopulate(), 200);
        Test.stopTest();
        
        Wineclub_Membership__c wineClub = [SELECT Id, account__c, contact__c FROM Wineclub_Membership__c Limit 1];
        System.assertNotEquals(null, wineClub.account__c);
    }
}

Any help is greatly appreciated as we are having integration issues with missing data and unable to update my main class and trigger since the above are causing me errors when trying to deploy to production


 
So im in a pickle. The magento developer is asking for my contact/account creation trigger to call their API and below is what i need to add ino my trigger but not sure where and how to get it to fire the request. This what I have currently in my trigger:
 
trigger MainContactTrigger on Contact (before update, before insert, after update, after insert) {
    DuplicateEmailFilter def = new DuplicateEmailFilter();
    Map<id,Contact> oldMap = trigger.oldMap;
    CreateAccountFromContact accountCreation = New CreateAccountFromContact();
    
    if(oldMap == null){
        oldMap = new Map<Id,Contact>();
    }
    if(Trigger.isBefore){
    // 
    // For the before creation we check if the contact is getting created by a real user then we use 
    // the Duplicate Email Filter to generate an error preventing the contact from being created.
    //
        if(!IntegrationUtils.isIntegrationUser()){
            def.processContacts(trigger.new, oldMap);
        }
        if( Trigger.isInsert && !IntegrationUtils.ignoreForAutoAccountUser() ) {
            accountCreation.ProcessBatchContactsWEmail(trigger.new,trigger.oldMap);
        }
        else if( Trigger.isInsert || Trigger.isUpdate ) {
            accountCreation.ProcessBatchContacts(trigger.new,trigger.oldMap);
        }
    }
    else{
    //
    // This is the After trigger - we just need to check if the email address is already
    // in use in the duplicate email filter. 
    // if it is being created by the integration user then in the DEF we flag the contct as having 
    // a duplicate. Leaving it up to the Salesforce Admin to clean it up.
    //
        if(IntegrationUtils.isIntegrationUser()){
            def.processContacts(trigger.new, oldMap);
        }
    }
    
}

and this is what i need to add into it somewhere to make this call to magento:
 
Salesforce to Magento Customer update endpoint url:
https://hallwinesm2-uat.smarterspecies.com/rest/V1/hall/salesforce/customer/sync
Content-Type:application/json
POST:
{
    "customer": {
        "firstname": "Maciej", 
        "lastname": "Garycki", 
        "email": "mgarycki+sf5333@gorillagroup.com", 
        "telephone": "6924609876", 
        "contact_sf_id": "1234567890", 
        "sfdc_updated_at": "182736", 
        "rms_account_no": "12345", 
        "customer_group_code": "GENERAL", 
        "revel_id": "", 
        "website_id": "1", 
        "store_id": "1", 
        "uuid": "", 
        "addresses": []
    }
}

Can anyone help me..

Thanks,

Ivan
So i have a case field i am trying to create to push a certain shipping rate to the contact field. My formula filed Shipping Cost reads as:
CASE(Shipping_Cost_Key__c, 
"CO2", 20, 
"CO4", 22,
"CO6", 10, 
"FL2", 20, 
"FL4", 26,
"FL6", 10,  
"GA2", 26, 
"GA4", 33,
"GA6", 10,  
"KS2", 25, 
"KS4", 30,
"KS6", 10,  
"MO2", 28, 
"MO4", 31,
"MO6", 10,  
"NC2", 29, 
"NC4", 31,
"NC6", 10,  
"NE2", 28, 
"NE4", 31,
"NE6", 10,  
"NM2", 24, 
"NM4", 27,
"NM6", 10,  
"NV2", 24, 
"NV4", 26,
"NV6", 10,  
"SC2", 29, 
"SC4", 32,
"SC6", 10,  
"TN2", 29, 
"TN4", 32,
"TN6", 10, 
"TX2", 28, 
"TX4", 32, 
"TX6", 10, 
0)

and is field it is looking at is Shipping Cost Key:
 
if(Club_Bottle_Count_2__c >0, OtherState+TEXT(2), 
if(Club_Bottle_Count_4__c >0, OtherState+TEXT(4), 
OtherState+TEXT(6)))
I keep getting Error: Compiled formula is too big to execute (8,512 characters). Maximum size is 5,000 characters.

Can anyone help me figure out how to get this to work.

Ivan
 
So i have test class that keeps failing when run in sandbox. The main error i am getting is:

Error MessageSystem.AssertException: Assertion Failed: Expected: , Actual: Collection
Stack TraceClass.Test_DataPushtoAccount.testDataPushtoAccount: line 19, column 1

Below is the code and im not sure why its saying its expecting a null i query it in my c = statement and the filed is set in hte creation of the customer. Can anyone let me know what im not seeing.
@isTest
public with sharing class Test_DataPushtoAccount {
	@isTest
    public static void testDataPushtoAccount(){
        Account a = new Account(Name = 'Test MainContactTrigger', RecordTypeID = '01240000000UZ4V');
 //       a.RecordType = 'Household';
        insert a;
        
        Contact c = new Contact(AccountID = a.id, firstName = 'Test MainContactTrigger', lastName = 'Tester', email = 'testfake@gmail.com', Pricing_Profile__c = 'Collection');
        insert c;
        
 //       System.debug('Contact record num: ' + [SELECT Id FROM Contact].size());
        
          
        c = [select AccountId, Account.Name, Pricing_Profile__c from Contact where id = :c.id limit 1];
           System.assertEquals('Test MainContactTrigger', a.Name);
           System.assertEquals(1, [SELECT Id FROM Contact].size());
           System.assertEquals(a.id, c.AccountId);
           System.assertEquals(a.Pricing_Profile__c, c.Pricing_Profile__c);
    }
    
}

 
Ok so i have a formula field that is pulling the address infromation from the contact into the field. What i am trying to do is that if my 3rd party shipping picklist value is null (meaning nothing choosen) then the text will show, but if a selction has been made that the formula field shows in text. Does anyone think this is possible.

This is what i have but not seeming to work
 
AND( ISPICKVAL(X3rd_Party_Shipper__c = "", "",
if(LEN(Contact__r.OtherStreet)>0, Contact__r.OtherStreet& " " , "" ) & BR() &
if(LEN(Contact__r.OtherCity)>0, Contact__r.OtherCity& ", " , "" )&
if(LEN(Contact__r.OtherState)>0, Contact__r.OtherState& " " , "" )&
if(LEN(Contact__r.OtherPostalCode)>0, Contact__r.OtherPostalCode,"") & BR() &
If(LEN(Contact__r.OtherCountry) >0, Contact__r.OtherCountry,"")))

 
Ok so I am still learning coding and with so many code examples i think im getting confused so hopefully someone can help lead me in the right direction.

So company is trying to do a rewards type program. So for every opprotunity the contact has that has a revenue center of 'ECOM' within a time frame will count towards getting a reward when they have reached $600 then $2000. Now i dont have any lookups from the contact to opprotunity which has me lost. And id like to have this data rolled into a custom object Direct_Rewards__c so we can track when people join the program, drop out , then join again (i know very crazy)

So breakdown:

Have object Opprotunity that has purchases made by our customers and they have a feild called Revenue_Center__c which should equal 'ECOM'

Have object Direct_Rewards__c that has a Master Detail relationship with Contact. This object keeps track of the Start_Date__c, End_Date__c, Contact__c (Master Detail), Rewards_Points_Accumulated__c (number), and Active_Rewards_Member__c (checkbox) to insure its an active record.

Now what im looking to accomplish is Customer goes online and joins the club which creates a record. Then make a purchase online for $200. The opprotunity is added to SF and if the revenue center = 'ECOM' then the active Direct_Rewards__c record should pull that $200 total into the Rewards_Points_Accumulated__c field. Then if they come back agian and purchase the system will add the new purchase of $150 to the Rewards_Points_Accumulated__c field which would then have a total of $350.

Then once they hit $600 we give a reward and again at $2000 (which is the max and no more purchases should be added). Then come Jan 1st i will clear out the Rewards_Points_Accumulated__c field and only purcahses from that date will count towards the reward record.

Im probably asking for a lot but i hope someone can help me. Im trying different codes but trying to get the data from the Opp to pull into the direct reward record based on a contact is where i get stuck.

Your help is majorly appreciated.

Ivan
Ok so i have read other entries but nothing i take seems to be working so hopefully someone can look at my code and see what the issue is. Im getting these emails raipdly these days and even when going to clean up data im starting to see if on new records as well.

PrimaryAddressValidation: execution of BeforeUpdate

 

caused by: System.QueryException: Non-selective query against large object type (more than 100000 rows). Consider an indexed filter or contact salesforce.com about custom indexing.

Even if a field is indexed a filter might still not be selective when:

1. The filter value includes null (for instance binding with a list that contains null) 2. Data skew exists whereby the number of matching rows is very large (for instance, filtering for a particular foreign key value that occurs many times)

 

Trigger.PrimaryAddressValidation: line 55, column 1

and this is my code the error is coming in at the fist List select statment in each if statement below.
 
// section makes sure that only one checkbox is true within the related address list for the contact
      if(!contactIdsForShipping.isEmpty())
      {
          List<ShipTo_Address__c> toggleShippings = shipToExcluded.isEmpty()?
             [SELECT Id, Default_Shipping_Address__c FROM ShipTo_Address__c WHERE Contact__c IN :contactIdsForShipping AND Default_Shipping_Address__c=true]
             : [SELECT Id, Default_Shipping_Address__c FROM ShipTo_Address__c WHERE Contact__c IN :contactIdsForShipping AND Default_Shipping_Address__c=true AND Id NOT IN :shipToExcluded];

          for(ShipTo_Address__c a : toggleShippings)
          {
                  a.Default_Shipping_Address__c = false;
          }
          update toggleShippings;
      }

      if(!contactIdsForBilling.isEmpty())
          {
              List<ShipTo_Address__c> toggleBilling = billToExcluded.isEmpty()?
              [SELECT Id, Primary_Billing_Address__c FROM ShipTo_Address__c WHERE Contact__c IN :contactIdsForBilling AND Primary_Billing_Address__c=true]
              :[SELECT Id, Primary_Billing_Address__c FROM ShipTo_Address__c WHERE Contact__c IN :contactIdsForBilling AND Primary_Billing_Address__c=true AND Id NOT IN :billToExcluded];
              for(ShipTo_Address__c a : toggleBilling)
              {
                  a.Primary_Billing_Address__c = false;
              }
              update toggleBilling;
          }   

    }

 
So over the weekend im not sure what happend but for some reason i have a hand full of accounts that are duplicating on the second. I just did a mass delete of over 10k of the same account and just as soon as i refresh the report the name poped back up and i had another 119 of the same account but not tied to an contact. Here is a trigger an older developer wrote (before my time) and im wondering if something is triggering this to keep creating accounts even though they are not tied to any contacts. can anyone help this is casusing a huge problem as these duplicates are being pushed into other systems with our API calls and integrations.
 
trigger MainContactTrigger on Contact (before update, before insert, after update, after insert) {
    DuplicateEmailFilter def = new DuplicateEmailFilter();
    Map<id,Contact> oldMap = trigger.oldMap;
    CreateAccountFromContact accountCreation = New CreateAccountFromContact();
    
    if(oldMap == null){
        oldMap = new Map<Id,Contact>();
    }
    if(Trigger.isBefore){
    // 
    // For the before creation we check if the contact is getting created by a real user then we use 
    // the Duplicate Email Filter to generate an error preventing the contact from being created.
    //
        if(!IntegrationUtils.isIntegrationUser()){
            def.processContacts(trigger.new, oldMap);
        }
        if( Trigger.isInsert && !IntegrationUtils.ignoreForAutoAccountUser() ) {
            accountCreation.ProcessBatchContactsWEmail(trigger.new,trigger.oldMap);
        }
        else if( Trigger.isInsert || Trigger.isUpdate ) {
            accountCreation.ProcessBatchContacts(trigger.new,trigger.oldMap);
        }
    }
    else{
    //
    // This is the After trigger - we just need to check if the email address is already
    // in use in the duplicate email filter. 
    // if it is being created by the integration user then in the DEF we flag the contct as having 
    // a duplicate. Leaving it up to the Salesforce Admin to clean it up.
    //
        if(IntegrationUtils.isIntegrationUser()){
            def.processContacts(trigger.new, oldMap);
        }
    }
    
}

 
So not sure what happened but today my formula field start to show errors for all records. Below is the code which should just produce a date in teh future due to the sign up date of the record. But now all records show an error can anyone see why this is happening with the code below.
DATE(YEAR(TODAY())+ 
IF( DATE(1900, MONTH(TODAY()), MAX(1,DAY(TODAY()-1))) > DATE(1900, MONTH( Start_Date__c ), MAX(1,DAY( Start_Date__c )-1)),1,0) , 
MONTH(Start_Date__c), MAX(1,DAY(Start_Date__c)-1))+1

The formula is to show the next year of the sign up date.
Ok so this may sound crazy and may not be able to be done using formula's but hopefully it can.

So i have a field called wine credit avalible which will show user how much money the customer has left thru our buyin period (i.e. Started off with $750, then used $700, now has $50 left). So here is where it gets compliacated. Our buyin period stars on 5/1 each year so the current one would be from 5/1/15 to 5/1/16 where they are able to use the amount given. So what i need is this:

Customer buys in and received $750 for 5/1/15 to 5/1/16
Customer uses $700 during the buyin period and has $50 left at 5/1/16
Once the next buyin year starts from 5/1/16 to 5/1/17 customer should have total avalible of $800 ($750 start each year + remainder of $50)

Yes probably way to complicated for formula but thought id ask. I have the field for whats avalible to show correct but i cant figure out how to put the date range check in. See formula field below. The remainder IF is where i need to check the date and have it role over.
IF(TEXT(Is_a_HWG_Partner__c)= "Yes" && HWG_Wine_Credit_Remainder__c = 0,0, 
IF(TEXT(Is_a_HWG_Partner__c)= "Yes" && HWG_Wine_Credit_Remainder__c <= 25, HWG_Wine_Credit_Remainder__c + HWG_Wine_Credit__c, 
IF(TEXT(Is_a_HWG_Partner__c)= "No",0, 
HWG_Wine_Credit_Remainder__c)))

 
So i have a batch job that is scheduled to run at 5am and at 9am. I would like to change the scheduled job that runs at 9am to 5pm. Both jobs use the same class so not sure how to update it so i can reschedule the 9am batch run to 5pm. Any help is greatly appreciated. I can provide details if needed.

Ive read some post but still unclear if i can reschedule and if a new class needs to be written in order to do this.
So i was in need of scheduling a Apex job to run on scheduler. Few folks helped me out and i got the classes to work. But now im wondering if they are actually updating records. I ask becasue the class below is to update a checkbox on the object each time its run, but when i check my history i dont see any changes. And i should see it becaue once the class checks the box i have a work flow to uncheck it but im not seeing any of this in the history, yet the job keeps completing and saying it batched 61 batches. Is there a way i can see a log of whats being updated or does the code below not actually update anything?
global class WineClubCronJobBatch implements Database.Batchable<sObject> 
{ 
   global Database.QueryLocator start(Database.BatchableContext BC) 

  { 
    String query ='Select Id, Tenure_Cron_Job_Schedule__c From Wineclub_Membership__c Where Active__c=True'; 
      return Database.getQueryLocator(query); 
  } 

    global void execute(Database.BatchableContext BC, List<sObject> scope) 

   { 
       List<Wineclub_Membership__c> listToUpdate = new List<Wineclub_Membership__c>(); 
        for( Wineclub_Membership__c a: (List<Wineclub_Membership__c> ) scope) 
        {  
            if(a.Tenure_Cron_Job_Schedule__c = False ) 
            {    
                a.Tenure_Cron_Job_Schedule__c = True;  
                listToUpdate.add(a); 
            }    
        } 
        if(listToUpdate.size() > 0) 
       { 
            update(listToUpdate);  

       } 

   } 
   global void finish(Database.BatchableContext BC){ 
  } 

}