• PRAKASH JADA 13
  • NEWBIE
  • 465 Points
  • Member since 2019

  • Chatter
    Feed
  • 15
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 117
    Replies
Hi, I have a batch class which should send email to contact owner which includes contacts created from lead conversion. I was unable to use contact owner email in ToAddress field. Here is my batch class..

//Batch Class

global class EmailWithAttachment implements Database.Batchable <sObject>, Database.Stateful{
    public List<Contact> conList {get;set;}
    public String body{get;set;}
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id, FirstName, LastName, LeadSource, ConvertedDate isConverted FROM Lead';
        //system.debug('aaaaaaa'+query);
        return Database.getQueryLocator(query);
        
    }
    global void execute(Database.BatchableContext BC, Lead[] scope) {
        List<Contact> conList = new List<Contact>();
        for(Lead lead : scope) {
            conList = ([SELECT FirstName, LastName, Email, Phone
                        FROM Contact 
                        WHERE Id IN (SELECT ConvertedContactId FROM Lead)]);
        }
        system.debug('Contacts List'+conList);
        String.join(conList,',');
        messaging.SingleEmailMessage email = new messaging.SingleEmailMessage();
        body = 'Contact Details : ' +conList+ '';
        email.setPlainTextBody(body);
        email.setSubject('Contact Details from Converted Lead');
        email.setToAddresses(new string[]{'maddulasaivineeth@gmail.com'});
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
        //system.debug('Contacts'+conList);
    }
    global void Finish(Database.BatchableContext BC) {
        
    }

Can someone please help me write a test class for the same.

Thanks in Advance...
  • March 27, 2020
  • Like
  • 0
Hello,

I'm looking to build my automated tests from Amazon Workspace and connecting to my company's salesforce communities site but I'm not able to log in with Amazon Workspace.  I'm finding status "Restricted IP" from the Login History.  Found that I can add network access but still can't login and still seeing Restricted IP.  

Anyone having success with a similar scenario or situation like mine?

Thanks in advance for your help!
Tien
Hello -I have a soql query that searches for tasks created in the last 7 days that are related to leads created today.

sssTask = [SELECT Id, Owner.Name, WhoId FROM Task 
                       WHERE WhoId != null
                       AND qbdialer__Call_Date_Time__c = Last_N_Days:7
                       AND WhoId IN :leadIds
                       ORDER BY CreatedDate DESC];

A lead may have more than 1 task. I need to add only the most recently created task to a new list for each lead created today. 

List<Task> recentlyCreated = new List<Task>();

Any assistance would be greatly appreciated. 
Hey guys, I'm trying to get through this. I have this code:
 
trigger ContentVersionTitleUpdate on ContentVersion (before insert) {
      List<Id> saids = new List<Id>();
    Set<Id> cdids = new Set<Id>();
    for(ContentVersion a :Trigger.New) {
        if(a.ContentDocumentId != null){
            cdids.add(a.ContentDocumentId);
        }
        ContentDocument[] cd = [Select Id, ParentId From ContentDocument where Id in :cdids];
        if(cd[0] != null) {
            saids.add(cd[0].ParentId);
        }
        ServiceAppointment[] sa = [Select Id, FileTitle__c From ServiceAppointment where Id in :saids];
        for (ContentVersion b :Trigger.New){
            
        if(sa != null) {
            if(sa[0].FileTitle__c != 'DefaultValue') {
            b.Title = sa[0].FileTitle__c;
            }
            
        }
        }
        
       
    }

}

The problem is when I upload a file, it says this:
 
Trigger.ContentVersionTitleUpdate: line 9, column 1
19:08:54.0 (12583025)|FATAL_ERROR|System.ListException: List index out of bounds: 0

I think it means that the "a.ContentDocumentId" does not exist, so I can not use it. That is why cdaids is empty, hence the error.

The idea is that the trigger must get the ID of the related record of the file. Everything else is easy now. ContentVersion does not have a link to the related record, only ContentDocument has that (ParentId). Please give me an idea how to fix this?
Following the previous question: https://developer.salesforce.com/forums/ForumsMain?id=9062I000000XsipQAC

Hello,

I need to update a file title after it's upload.

That is an easy trigger, but here is the catch:

On object A is a text field. Each record of object A has some value in the text field. After I upload the file to the object A's record, I need to take the value in the text field of the record and set is as a title of the newly uploaded file.

Mr. PRAKASH JADA 13 helped me with the code:
 
Hi,


Trigger:
--------------------------
trigger AttcahmentTrigger on Attachment (before insert) {
    if(Trigger.isBefore) {
        if(Trigger.isInsert) {
            AttcahmentTriggerHandler.onBeforeInsert(Trigger.New);
        }
    }
}


Trigger Handler:
----------------------------------
/*
 * Author: Prakash
 * CreatedDate: Feb 14, 20202
*/
public with sharing class AttcahmentTriggerHandler {
    public static void onBeforeInsert(List<Attachment> attachments) {
        
        List<Id> accountIds = new List<Id>();
        
        //Loop to iterate over the list of attachments        
        for(Attachment att : attachments) {
            if(att.ParentId != null) {
                accountIds.add(att.ParentId); // Preparing the account Ids
            }
        }
        
        if(!accountIds.isEmpty()) {
            // Preparing the map that holds the account Name as a value and Id as a key
            Map<Id, Account> accountMap = new Map<Id,Account>([SELECT ID, Name FROM Account WHERE Id = :accountIds]);
            
            // Loop to iterate over the list of Attachments
            for(Attachment att : attachments) {
                att.Name = accountMap.get(att.ParentId).Name;
            }
            
        }
        
    }
}
But there is another catch to it - by object A I mean object SERVICE APPOINTMENT, which does not support the Attachment object.

Help me please!
 
I'm trying to return either a string of text or a date field to display on a visualforce page.  When i compile it i get the error above. If i take out RatingRelease = new Set<String>(); i get an error System.NullPointerException: Attempt to de-reference a null object.  I'm not sure if i have initialized RatingRelease properly. 
public String RatingRelease {get;set;}

//Returns the Rating Release date or the 'rating pending'
        RatingRelease = new Set<String>();

        IF (Today < currentQRpCase.Rating_Externally_Visible_Date__c){
            RatingRelease = 'Rating Pending';
        } else IF(Today > currentQRpCase.Rating_Externally_Visible_Date__c){
            RatingRelease = currentQRpCase.Rating_Externally_Visible_Date__c.format();
        } else {
            RatingRelease = '';
        }
Hello,

I need to update a file title after it's upload.

That is an easy trigger, but here is the catch:

On object A is a text field. Each record of object A has some value in the text field. After I upload the file to the object A's record, I need to take the value in the text field of the record and set is as a title of the newly uploaded file.

I don't know how to query for that. File is ContentDocument, but there has to be a different way. Thanks alot. Jan
Hi, We have a daily scheduled import (from a 3rd party app) of several records to a custom object. The import is set as an "upsert". I need to add a trigger that adds one more condition to decide whether to insert or update. Specifically, if a field called "discharge_date__c" is more than 5 days apart from the existing record, I want to INSERT the new record rather than UPDATING the previous one. The error I am receiving is " System.FinalException: Record is read-only". I need a way to bypass this error. Any suggestions are greatly appreciated.Here is my current Trigger and Class.:

TRIGGER:
trigger DischargeTrigger2 on Discharge__c (after update) {
     if(system.isFuture()) return;
    
//insert new Discharge record..  
      for (Discharge__c dis : trigger.new){
          if (dis.Discharge_Date__c != null && trigger.oldMap.get(dis.Id).Discharge_Date__c !=null){
    date oldDd = trigger.oldMap.get(dis.Id).Discharge_Date__c;
    date newDd = dis.Discharge_Date__c;
    Integer difDate = oldDd.daysBetween(newDd); 
    Integer diffDate = newDd.daysBetween(oldDd);
        if (difDate > 5 || diffDate > 5){
          Discharge2Class.generateNewDischarge(dis.id);
        }}
  }
    
//If Discharge Date is more than 5 days apart from existing record, leave existing record alone and create new record, with instance counter and link to existing record
for (Discharge__c dis : trigger.new){
    if (dis.Discharge_Date__c != null && trigger.oldMap.get(dis.Id).Discharge_Date__c !=null){
    date oldDd = trigger.oldMap.get(dis.Id).Discharge_Date__c;
    date newDd = dis.Discharge_Date__c;
    Integer difDate = oldDd.daysBetween(newDd); 
    Integer diffDate = newDd.daysBetween(oldDd);
        if (difDate > 5 || diffDate > 5){
            //Prevent changing existing record
            dis.Action_Code_ID__c = trigger.oldMap.get(dis.Id).Action_Code_ID__c;
            dis.Address__c = trigger.oldMap.get(dis.Id).Address__c;
            dis.City__c = trigger.oldMap.get(dis.Id).City__c;
            dis.Date_of_Birth__c = trigger.oldMap.get(dis.Id).Date_of_Birth__c;
            dis.Discharge_Date__c = trigger.oldMap.get(dis.Id).Discharge_Date__c;
            dis.name = trigger.oldMap.get(dis.Id).name;
            dis.State__c = trigger.oldMap.get(dis.Id).State__c;
            dis.Status_Code_ID__c = trigger.oldMap.get(dis.Id).Status_Code_ID__c;
            dis.Zip__c = trigger.oldMap.get(dis.Id).Zip__c;
            dis.Progress_Notes__c = trigger.oldMap.get(dis.Id).Progress_Notes__c;
        }
    }
}
}

CLASS:
public class Discharge2Class {
 @future(callout = true)
    public static void generateNewDischarge(id i){    
        
        Discharge__c disch = [select id,Action_Code_ID__c,Address__c,City__c,Date_of_Birth__c,
                              Discharge_Date__c, State__c,Status_Code_ID__c,Zip__c,Progress_Notes__c
                              from Discharge__c where id =: i];
       
        Discharge__c newDis = new Discharge__c();
            newdis.Action_Code_ID__c = disch.Action_Code_ID__c;
            newdis.Address__c = disch.Address__c;
            newdis.City__c = disch.City__c;
            newdis.Date_of_Birth__c = disch.Date_of_Birth__c;
            newdis.Discharge_Date__c = disch.Discharge_Date__c;
            newdis.Discharge_Location_Type__c =disch.Discharge_Location_Type__c;
            newdis.Discharge_Location__c =disch.Discharge_Location__c ;
            newdis.Facility_ID__c = disch.Facility_ID__c;
            newdis.Facility_Name__c = disch.Facility_Name__c;
            newdis.name = disch.name;
            newdis.State__c = disch.State__c;
            newdis.Status_Code_ID__c = disch.Status_Code_ID__c;
            newdis.Zip__c = disch.Zip__c;
            newdis.Progress_Notes__c = disch.Progress_Notes__c;
        insert newDis;
        
    }
}

Hi All,

I have a user request where the User would like a Path to a Windows Directory created from Salesforce data.

I originally tried using Apex, but APex did not like the Forward Slash. So I thought I would create Text Field on the Object with Forward Slash as the default value, but this was not allowed.

Any suggestions o should I just tell the user no. I hate saying no.

Goal is to create MyOpsPath = '\\MyFiles\MyFolder\';

I am adding "*/" at line 141 just above the last two brackets and I get this error: "Error: Compile Error: Expecting '}' but was: '*' at line 141 column 9"

Here's the code:

/*
*   Crane Barksdale Sandbox 
*   Created : 8-NOV-2012  
*   
*
*/
public with sharing class CallPlanner_detailcontroller 
{
 
 /*
    public string mutualpyramid{get;set;}
    public string customer{get;set;}
    public List<Event>lstEvent{get;set;}
    public boolean isEvent{get;set;}
    public final Call_Planner_2__c cplan;

    public CallPlanner_detailcontroller(ApexPages.StandardController ctlr)
    {
        
        mutualpyramid = '';
        customer= '';        
        customer = system.label.Customer_Needs; // image Link
        mutualpyramid = system.label.Mutual_Pyramid; // image Link
        isEvent = false;
        lstEvent = new List<Event>();
        
        try
        {
            //Get related events for this Call planner
            integer iCount = [  select count() 
                                from event 
                                where whatid = :ctlr.getId()
                             ];
    
    
    
            if (iCount != 0)
            {
                isEvent = true;
            }
            else 
            {
                this.cplan = (Call_Planner_2__c)ctlr.getRecord();
                if (cplan.event__c == '' || cplan.event__c == null) 
                {
                    isEvent = false;
                } 
                else 
                {
                    lstEvent = [    select id 
                                    from event 
                                    WHERE Id = :cplan.event__c
                                ];
                                
                    if (!lstEvent.isEmpty()) 
                    {
                        isEvent = true;
                    } 
                    else 
                    {
                        isEvent = false;
                    }
                }
            }
        }
        catch(Exception ex)
        {
            System.Debug(ex);
        }
    }

/**************************
Test Method
**************************/

static testMethod void myUnitTest1() {
        
        
        
        //creating Account
        Account objAcc = new Account();
        objAcc.Name='test';
        
        //objAcc.Market_Code__c='910-china';//commented for migration on 3rd may
        //objAcc.District__c='413-Nancy Rapp';//commented for migration on 3rd may
        insert objAcc;
        
        //Creating Contact
        Contact objcon= new Contact();
        objcon.AccountId = objAcc.id;
        objcon.LastName='test';
        objcon.FirstName='test';
        //objcon.Business_Phone_1__c='5555555555';
        insert objcon;
        
        //creating Opportunity
        Opportunity objopp= new Opportunity();
        objopp.AccountId =objAcc.id;
        objopp.Name = 'test';
        objopp.Type='simple';
        objopp.StageName='Universe';
        objopp.CloseDate=system.today();
        //objopp.Product__c = 'test';
        
        //objopp.Price_Target__c=578; //commented for migration frm sand to sand on 3rd may
        
        insert objopp;
        
        //creating Event 
        Event objevent = new Event();
        //objevent.AccountId =objAcc.Id;
        objevent.WhatId =objAcc.Id;
        objevent.Subject ='Email';
        objevent.StartDateTime=system.today();
        objevent.EndDateTime=system.today();
        insert objevent; 
        
        //creating Call_Planner
        Call_Planner_2__c objclp = new Call_Planner_2__c();
        objClp.Contact__c =objcon.Name;
        objClp.Call_Objective__c = 'test';
        objClp.Opportunity__c = objopp.id;
        insert objClp;
        ApexPages.StandardController c = new Apexpages.StandardController(objclp);
        CallPlanner_detailcontroller objdetail = new CallPlanner_detailcontroller(c);
        
        objClp.event__c = objevent.id;
        update objClp;
        c = new Apexpages.StandardController(objclp);
        objdetail = new CallPlanner_detailcontroller(c);
        
        objevent.whatid = objClp.id;
        update objevent;
        c = new Apexpages.StandardController(objclp);
        objdetail = new CallPlanner_detailcontroller(c);

        delete objevent;
        c = new Apexpages.StandardController(objclp);
        objdetail = new CallPlanner_detailcontroller(c);
        
        */
        
              }

}
Hello,

I have to transfer a field from Number to Text.

will thre by any loss of data ?

thank you for suggestion
  • February 11, 2020
  • Like
  • 0
Hey Guys

i have designed a trigger, when i create a lead it checks weather the custom field Company_Domain_Name__c already exists in the Existing accounts, if it exists,it will not create a lead, it creates contact which is associated to that existing accounts
How do i write test classes for this Trigger
 
trigger AutoConvertLeadAccount on Lead (after insert) {
    Set<String> LeadCompanyDomainNamec = new Set<String>();
    List<Lead> newLeads = new List<Lead>();
    
    // Get all the new leads
    for(Lead l : system.trigger.new){
        newLeads.add(l);
        LeadCompanyDomainNamec.add(l.Company_Domain_Name__c);
    }
    
    /* Make some maps of account and Company Domain */
    List<Account> AccountList = [select Id, Company_Domain_Name__c, OwnerId,Private__c from Account where Company_Domain_Name__c IN: LeadCompanyDomainNamec AND Private__c=true];
    system.debug('AccountList '+AccountList);
    Map<ID, String> peAccounts = new Map<ID, String>();
    Map<ID, ID> peAccountsOwner = new Map<ID, ID>();
    
    if(!AccountList.isEmpty()){
        // Generic map for preventing loss of ids
        for(Account a : AccountList){
            peAccounts.put(a.id, a.Company_Domain_Name__c);
            peAccountsOwner.put(a.id, a.OwnerId);
            system.debug('peAccounts '+peAccounts);
        }
        
        // We will need this to get the id from the email address
        Map<String, ID> peAccountsFlipped = new Map<String, ID>();
        for(ID i : peAccounts.keyset()){
            peAccountsFlipped.put(peAccounts.get(i), i);
            system.debug('peAccountsFlipped '+peAccountsFlipped);
        }
        
        /* System Conversion Requirements */
        leadStatus convertStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true LIMIT 1];
        List<Database.LeadConvert> leadConverts = new List<Database.LeadConvert>();
        Database.LeadConvert lc = new Database.LeadConvert();
        
        /* Configuring Payload */    
        for (Lead nl : newleads) {
            
            // Check to see if account already exists
            if(!peAccounts.isEmpty()){
                if(peAccountsFlipped.get(nl.Company_Domain_Name__c)!=null){
                    lc = new Database.LeadConvert();
                    lc.setLeadId(nl.id);
                    lc.setOverwriteLeadSource(false);
                    lc.setConvertedStatus(convertStatus.MasterLabel);
                    lc.setAccountId(peAccountsFlipped.get(nl.Company_Domain_Name__c));
                    lc.setOwnerId(peAccountsOwner.get(peAccountsFlipped.get(nl.Company_Domain_Name__c)));
                    lc.setDoNotCreateOpportunity(true);
                    system.debug('lc '+lc);
                    leadConverts.add(lc);
                }    
            } 
            
            system.debug(leadConverts);
        }
        
        // Fire Payload
        if(!leadConverts.isEmpty()){
            Database.LeadConvertResult[] lcr = Database.convertLead(leadConverts);
            System.debug(LoggingLevel.INFO, lcr);
        }
    }
}


 
Hello,

I have a usecase where, i get 4 characters of account name and i append a unique 10 digit number after.

i am wondering how can get the last number generated and increment it by one.

thank you for suggestion !
  • October 02, 2019
  • Like
  • 0
Hello, 

I am needing some assistnace writing a batched apex class that will update contacts meeting certin criteria, and update a picklist based on a date field. 

Example:

Get all contacts where record type id = XXXXXXX & Latest_Service_Date__c != (not equal) NULL

If Latest_Service_Date__c is ≥ Date(TODAY - 90) update Picklist_Field__c = TRUE

else If Latest_Service_Date__c is < Date(TODAY - 90) update Picklist_Field__c = FALSE


Date(TODAY - 90) meaning if the Latest_Service_Date__c is in the past 90 days. 

Would be glad to read through any articles or material, I just have not been successful in finding anything helpful thus far. 
I wrote a dedupe trigger that is supposed to check to see if the lead already exists in the system by email and contact. If the contact already exist then I want it to add the original lead to a lookup field. If it is not a duplicate then it would mark is_primary__c. I don't see it updating when I go and create a new lead manually. Is there something in my code that is causing it to not work? 
 
trigger findLeadDupes on Lead (before insert) {
  for (Lead myLead : Trigger.new) {
    if (myLead.Email != null) {
      List<Lead> dupes = [SELECT Id FROM Lead
                               WHERE Email = :myLead.Email AND Company = :myLead.Company];
      if (dupes.size() > 0) {
        myLead.Primary_Lead__c = dupes[0].Id;
      } else {
        myLead.Primary_Lead__c = null;
        myLead.Is_Primary__c = True;
      }                             
    }
  }
}

 
I have created one custom object using Lwc only I created a form. Now problem is that only I'd is getting printed.not the name. Can anybody help me . It's urgent
<template>
    <lightning-card title="Create Contact Record">
        <template if:true={conRecord}>
            <div class="slds-m-around--xx-large">
                <div class="container-fluid">
                    <div class="form-group">
                        <lightning-input label="Child Name" name="childName"  type="text"
                            value={conRecord.childName} onchange={handleChildNameChange}></lightning-input>
                    </div>
                </div>
                   
                <br />
                <lightning-button label="Submit" onclick={createRec} variant="brand"></lightning-button>
            </div>
        </template>
    </lightning-card>
</template>


js.
import {  LightningElement, track ,api } from 'lwc';
import {  ShowToastEvent } from 'lightning/platformShowToastEvent';
import insertDe from '@salesforce/apex/insertEvent.insertDe';
import Detail_OBJECT from '@salesforce/schema/Detail__c';
export default class insertEvent extends LightningElement {
   
   // @api childName;
    @track conRecord = Detail_OBJECT;
    handleChildNameChange(event) {
        this.conRecord.childName = event.target.value;
        window.console.log('child Name ==> ' + this.conRecord.childName);
     
    }

    createRec() {
        window.console.log('In createRec ===> ');
        insertDe({
            de: this.conRecord
            })
            .then(result => {
                // Clear the user enter values
                this.conRecord = {};
                window.console.log('result ===> ' + result);
                // Show success messsage
                this.dispatchEvent(new ShowToastEvent({
                    title: 'Success!!',
                    message: 'Contact Created Successfully!!',
                    variant: 'success'
                }), );
            })
            .catch(error => {
                this.error = error.message;
            });
    }
}


apex
public with sharing class insertEvent {
      @AuraEnabled
         public static void insertDe(Detail__c de) {

            try{  
               
                insert de;
                System.debug('Con '+de);
            }catch(Exception e){
                System.debug('--->'+e);
            }
            System.debug('Con '+de.Name);
            System.debug('Con '+de);
        }    
}

 
Hi
I have a requirement: My Salesforce org should send data to a web service whenever the status (field) of the tenant (object) changes from active to non-active.
The message that I post should contain the ID of the Tenant that not active anymore. I can't figure out how to add the ID of this tenant.

Please help me resolve this puzzle.


This is my code:
global class FOBCallouts1{
@Future (Callout=true)
public static void tenantUpdate(list<tenant__c> TenList, map <id,tenant__c> oldMap)
{ // list<tenant__c> TenList=new list<tenant__c>();
// map <id,tenant__c> oldMap=new map<id, tenant__c>(); for(tenant__c objten:TenList)
{ if(objten.status__c=='Non-active' && oldMap.get(objten.Id).status__c =='Active'){ Http http = new Http();
HttpRequest request = new HttpRequest(); request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
request.setMethod('POST');
Tenant__c tenant=[SELECT Id FROM Tenant__c]; 
String JsonString=JSON.serialize(objten.id);
String body = 'Please deactivate FOB for following tenants(ID)'; request.setBody(body+JsonString); System.debug(request.getBody()); } } } }
 
Hi, I have a batch class which should send email to contact owner which includes contacts created from lead conversion. I was unable to use contact owner email in ToAddress field. Here is my batch class..

//Batch Class

global class EmailWithAttachment implements Database.Batchable <sObject>, Database.Stateful{
    public List<Contact> conList {get;set;}
    public String body{get;set;}
    global Database.QueryLocator start(Database.BatchableContext BC) {
        String query = 'SELECT Id, FirstName, LastName, LeadSource, ConvertedDate isConverted FROM Lead';
        //system.debug('aaaaaaa'+query);
        return Database.getQueryLocator(query);
        
    }
    global void execute(Database.BatchableContext BC, Lead[] scope) {
        List<Contact> conList = new List<Contact>();
        for(Lead lead : scope) {
            conList = ([SELECT FirstName, LastName, Email, Phone
                        FROM Contact 
                        WHERE Id IN (SELECT ConvertedContactId FROM Lead)]);
        }
        system.debug('Contacts List'+conList);
        String.join(conList,',');
        messaging.SingleEmailMessage email = new messaging.SingleEmailMessage();
        body = 'Contact Details : ' +conList+ '';
        email.setPlainTextBody(body);
        email.setSubject('Contact Details from Converted Lead');
        email.setToAddresses(new string[]{'maddulasaivineeth@gmail.com'});
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
        //system.debug('Contacts'+conList);
    }
    global void Finish(Database.BatchableContext BC) {
        
    }

Can someone please help me write a test class for the same.

Thanks in Advance...
  • March 27, 2020
  • Like
  • 0
i have installed, JRE and installed the Eclipse , and to Configure the Eclipse to force.com , showing an error below while Installing a new software adding the url . showing cannot find it..

User-added image
thanks
karimulla
Hello,

I'm looking to build my automated tests from Amazon Workspace and connecting to my company's salesforce communities site but I'm not able to log in with Amazon Workspace.  I'm finding status "Restricted IP" from the Login History.  Found that I can add network access but still can't login and still seeing Restricted IP.  

Anyone having success with a similar scenario or situation like mine?

Thanks in advance for your help!
Tien
Hello -I have a soql query that searches for tasks created in the last 7 days that are related to leads created today.

sssTask = [SELECT Id, Owner.Name, WhoId FROM Task 
                       WHERE WhoId != null
                       AND qbdialer__Call_Date_Time__c = Last_N_Days:7
                       AND WhoId IN :leadIds
                       ORDER BY CreatedDate DESC];

A lead may have more than 1 task. I need to add only the most recently created task to a new list for each lead created today. 

List<Task> recentlyCreated = new List<Task>();

Any assistance would be greatly appreciated. 
Hi All,
          I have a test class but it's not covering the part in which I am showing the error message. Can anyone help me with the code coverage,
and let me know what am I missing in test class.
My helper class and Test class is given below :-

public  without sharing class OpportunityLineItemTriggerHelper {
    
    public static List<OpportunityLineItem> newOpportunityLineItem = new List<OpportunityLineItem>();
    public static List<OpportunityLineItem> oldOpportunityLineItem = new List<OpportunityLineItem>();
    public static Map<Id, OpportunityLineItem> newMapOpportunityLineItem = new Map<Id, OpportunityLineItem>();
    public static Map<Id, OpportunityLineItem> oldMapOpportunityLineItem = new Map<Id, OpportunityLineItem>(); 
     public static void validateServiceAgreementProduct(){
        
        Map<Id, Product2> mapProductIdToProduct = new Map<Id, Product2>(
                                                                        [ SELECT Id, Name, Family
                                                                           FROM Product2 
                                                                           WHERE Family LIKE 'SA - %'
                                                                           OR Family LIKE 'Service - %'
                                                                        ]
                                                                        );
        Set<Id> parentOppIds = new Set<Id>();
        Set<Id> serviceProductIds = new Set<Id>();
        List<OpportunityLineItem> serviceProductLines = new List<OpportunityLineItem>();
        for( OpportunityLineItem oppLine : newOpportunityLineItem ){
            if( mapProductIdToProduct.containsKey( oppLine.Product2Id ) ){
                parentOppIds.add( oppLine.opportunityId );
                serviceProductLines.add( oppLine );
                serviceProductIds.add( oppLine.Product2Id );
            }
        }
        
        Map<Id, Opportunity> oppMap = new Map<Id, Opportunity>( [ SELECT Id, Name, 
                                                                 ( SELECT Id, Name, Product2Id 
                                                                   FROM OpportunityLineItems 
                                                                   Where Product2Id not in :serviceProductIds
                                                                 )
                                                                 FROM Opportunity
                                                                 WHERE Id IN: parentOppIds ] 
                                                               );
                                                               
        Map<Id, Set<Id>> mapOppIdToHardwareProductIds = new Map<Id, Set<Id>>();
        for( Opportunity opp : oppMap.values() ) {
            Set<Id> setHarwareProductIds = new Set<Id>();
            for( OpportunityLineItem opli : opp.OpportunityLineItems ) {
                setHarwareProductIds.add( opli.Product2Id );
            }
            mapOppIdToHardwareProductIds.put( opp.Id, setHarwareProductIds );
        }
        
        Map<Id, Set<Id>> mapServicesProductIDToHardwareProductIds = new Map<Id, Set<Id>>();
        for( SA_Junction__c sJunction : [ SELECT Id, Hardware_Product__c, 
                                          Services_Product__c 
                                          FROM SA_Junction__c 
                                          Where Services_Product__c in :serviceProductIds
                                         ] 
                                         ){
            Set<Id> hardwareProductIds = mapServicesProductIDToHardwareProductIds.get( sJunction.Services_Product__c );
            hardwareProductIds = hardwareProductIds == null ? new Set<Id>() : hardwareProductIds;
            hardwareProductIds.add( sJunction.Hardware_Product__c );                             
            mapServicesProductIDToHardwareProductIds.put( sJunction.Services_Product__c, hardwareProductIds );                                        
        }
        
        for( OpportunityLineItem oppLine : serviceProductLines ){
            Set<Id> actualHardwareProductIdsOnOpp = mapOppIdToHardwareProductIds.get( oppLine.OpportunityId );
            Set<Id> expectedHardwareProductIds = mapServicesProductIDToHardwareProductIds.get( oppLine.Product2Id );
            if( expectedHardwareProductIds != null && expectedHardwareProductIds.size() > 0 
                && actualHardwareProductIdsOnOpp != null && actualHardwareProductIdsOnOpp.size() > 0 ) {
                Boolean hasExpectedHardware = false;
                for( Id hardwareProdId : actualHardwareProductIdsOnOpp ) {
                    if( expectedHardwareProductIds.contains( hardwareProdId )) {
                        hasExpectedHardware = true;
                        break;  
                    }
                }
                if( !hasExpectedHardware ) {  
                    oppLine.addError('You need to select the correct agreement based on hardware products.'); 
                }
            }
        }

    }
}
how to cover bold part?
Test class for trigger helper:-
@istest

private class Trigger_OpportunityLineItemTest {
static testmethod void validateServiceAgreementProductTest(){
        Account accTest = new Account( Name = 'Test Account' );
        insert accTest;
        
        Opportunity oppTest = new Opportunity( Name = 'Test Opportunity',
                                              StageName = 'Working',
                                              CloseDate = System.today(),
                                              AccountId = accTest.Id );
        insert oppTest;
        
        Product2 prod = new Product2( Name ='EV - PM1H0000BD',
                                     isActive = TRUE,
                                     Family = ' Printers' );
        insert prod;
        
        PricebookEntry pbe = new PricebookEntry( UnitPrice = 10,
                                                Product2Id = prod.Id,
                                                Pricebook2Id = Test.getStandardPricebookId(),
                                                isActive = TRUE, 
                                                UseStandardPrice = FALSE );
        insert pbe;
        
        
        Product2 prod1 = new Product2( Name ='Service Agreement - Full - Primacy Dual',
                                      isActive = TRUE,
                                      Family = ' SA - Hardware' );
        insert prod1;
        
        PricebookEntry pb = new PricebookEntry( UnitPrice = 20,
                                               Product2Id = prod1.Id,
                                               Pricebook2Id = Test.getStandardPricebookId(),
                                               isActive = TRUE, 
                                               UseStandardPrice = FALSE );
        insert pb;
        
        OpportunityLineItem oppLine = new OpportunityLineItem( OpportunityId = oppTest.Id,
                                                              Quantity = 2,
                                                              UnitPrice = 10,
                                                              Product2Id = prod.id,
                                                              PriceBookEntryId = pbe.Id
                                                             );
        insert oppLine;
        
        OpportunityLineItem oppLine1 = new OpportunityLineItem( OpportunityId = oppTest.Id,
                                                               Quantity = 2,
                                                               UnitPrice = 10,
                                                               Product2Id = prod1.id,
                                                               PriceBookEntryId = pb.Id
                                                              );
        insert oppLine1;
        
        OpportunityLineItem Oli = [select Name,Product2.Name
                                   from OpportunityLineItem 
                                   where OpportunityId =: oppTest.Id AND Product2Id =: prod.id ];
        System.assertEquals('EV - PM1H0000BD', Oli.Product2.Name );
    }
    
    static testmethod void validateServiceAgreementProductTestError(){
        Account accTest = new Account( Name = 'Test Account' );
        insert accTest;
        
        Opportunity oppTest = new Opportunity( Name = 'Test Opportunity',
                                              StageName = 'Working',
                                              CloseDate = System.today(),
                                              AccountId = accTest.Id );
        insert oppTest;
        
        Product2 prod = new Product2( Name ='EV - PM1H0000BD',
                                     isActive = TRUE,
                                     Family = 'Printers' );
        insert prod;
        
        PricebookEntry pbe = new PricebookEntry( UnitPrice = 10,
                                                Product2Id = prod.Id,
                                                Pricebook2Id = Test.getStandardPricebookId(),
                                                isActive = TRUE, 
                                                UseStandardPrice = FALSE );
        insert pbe;
        
        Product2 prod1 = new Product2( Name ='Service Agreement - Full - SD260',
                                      isActive = TRUE,
                                      Family = 'SA - Hardware' );
        insert prod1;
        
        PricebookEntry pb = new PricebookEntry( UnitPrice = 20,
                                               Product2Id = prod1.Id,
                                               Pricebook2Id = Test.getStandardPricebookId(),
                                               isActive = TRUE, 
                                               UseStandardPrice = FALSE );
        insert pb;
        
        SA_Junction__c SA = new SA_Junction__c();
        SA.Hardware_Product__c =  prod.id;
        SA.Services_Product__c =  prod1.id;
        insert SA;
        
        OpportunityLineItem oppLine = new OpportunityLineItem( OpportunityId = oppTest.Id,
                                                              Quantity = 2,
                                                              UnitPrice = 10,
                                                              Product2Id = prod.id,
                                                              PriceBookEntryId = pbe.Id
                                                             );
        insert oppLine;
        
        OpportunityLineItem oppLine1 = new OpportunityLineItem( OpportunityId = oppTest.Id,
                                                               Quantity = 2,
                                                               UnitPrice = 10,
                                                               Product2Id = prod1.id,
                                                               PriceBookEntryId = pbe.Id
                                                              );
         insert oppLine1;
        try{
             OpportunityLineItem Oli = [select Name,Product2.Name
                                   from OpportunityLineItem 
                                   where OpportunityId =: oppTest.Id AND Product2Id =: prod1.id ];
           System.assertEquals('Service Agreement - Full - SD260',oppLine1.Product2.Name);
             
        }
        catch(Exception e) {
            Boolean expectedExceptionThrown =  e.getMessage().contains('You need to select the correct agreement based on hardware products.') ? true : false;
            System.AssertEquals(expectedExceptionThrown, false);
            
        }
        
    }
}
Hello Gurus,

I faced the following exception when I am closing a case. The behaviour with the rest of the cases is normal. Something is missing with this, which I am not able to identify. FYR, I providing the code and the exception. Please help me understand.

Exception/Error:
Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger Email2CaseSharing caused an unexpected exception, contact your administrator: Email2CaseSharing: execution of BeforeUpdate caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.Email2CaseSharing: line 30, column 1




Code:
trigger Email2CaseSharing on Case (before insert, before update, after insert, after update) {
  
  Set<Id> contactIds = new Set<Id>();
    
    for(Case c : Trigger.new) {
        
        if(c.Origin != null && c.Origin == 'Email' && c.ContactId != null) {
            contactIds.add(c.ContactId);
        }
    }
    
    if(!contactIds.isEmpty()) {
      Map<String, String> contactEmails = new Map<String, String>();
      Map<String, User> emails = new Map<String, User>();
        for(Contact c : [SELECT Id, Email FROM Contact WHERE Id IN :contactIds]) {
            contactEmails.put(c.Id, c.Email);
            emails.put(c.Email, null);
        }
        for(User u : [SELECT Id, Email FROM User WHERE Email IN :emails.keySet()]) {
            emails.put(u.Email, u);
        }
        
        List<CaseShare> shares = new List<CaseShare>();
        
        for(Case c : Trigger.new) {
        
            if(c.Origin != null && c.Origin == 'Email' && c.ContactId != null) {
                
                Id uid = emails.get(contactEmails.get(c.ContactId)).Id;
                
                if(Trigger.isBefore) {
                  c.Submitter__c = uid;
                } else {
                  CaseShare cs = new CaseShare(
                    CaseId = c.Id,
                      UserOrGroupId = uid,
                      CaseAccessLevel = 'Read'
                  );
                  shares.add(cs);
                }
            }
        }
        
        try {
          if(!shares.isEmpty()) {
              insert shares;
          }
        } catch(Exception e) {
          System.debug(e.getStacktraceString());
        }
    }
}

 
Hi guys,

I have created a validation rule to make a date field mandatory on a custom Payment__c object when certain values in a picklist are selected. When I activate the rule, it causes issues on records which have a lookup field populated. Below is my trigger. Can anyone see where I am going wrong?

//Rolls up the related payment total amounts to parent payment record // 
trigger SumOfReplacedValue on Payment__c (after insert, after update, after delete, after undelete) {
Set<ID> setID = new Set<ID>();
    List<Payment__c> lstPay = new List<Payment__c>();
    
    if(trigger.isinsert || trigger.isundelete){
        for(Payment__c p : trigger.new){
            setID.add(p.Replaced_Payment__c);
        }
    }
    else if(trigger.isDelete){
        for(Payment__c p : trigger.old){
            setID.add(p.Replaced_Payment__c);
        }
    }
    
    else if(trigger.isUpdate){
         for(Payment__c p : trigger.new){
            if(p.Replaced_Payment__c != null){
                if(trigger.oldmap.get(p.id).Replaced_Payment__c != p.Replaced_Payment__c){
                    setID.add(p.Replaced_Payment__c);     
                }
            } 
            setID.add(trigger.oldmap.get(p.id).Replaced_Payment__c);
         }
    }
    if(setid.size() > 0){
        lstPay = [Select id,Replaced_With__c,(Select id,Payment_Amount__c from Replaced__r) from Payment__c where id IN : setID];
    }
    for(Payment__c pay : lstPay){
    Decimal val = 0;
        for(Payment__c rep : pay.Replaced__r){
            
            val += rep.Payment_Amount__c;
            
        }
        pay.Replaced_With__c  = val;
    }
    update lstPay;
}
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


 
Hello All,
I have two custom objects. project_c and week_c 
In Project_c.object  i have fileds start date and end date 
I want to create a trigger that will create records of weeks in week_c object based on start date and end date 
For example:
---------Project---------
start date : 10/02/2020
end date : 27/02/2020
----------week----------
week 9Feb
week 16Feb
week 23Feb
*PS (first day of the week will be sunday )

Thanks in Advance