• Guru 91
  • NEWBIE
  • 99 Points
  • Member since 2017
  • SFDC Consultant
  • Race2cloud

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 30
    Questions
  • 30
    Replies
Hi,
I want to create delivery record on 1st of each month.
How we can do that?


Thanks
Guru
Hi,
Can please help me with surveys in sfdc.I want to send survey form to Lead after contact with him or after given demo automatically.
I want to get reponse store in lead.


Thanks&Regards
Guru 
Hi,
My below code is giving only the immediate parent ID of an account but I need to fetch multi level parents means his parent then his parent then his parent till the parentid for an account in heirarchy is null. Please help me out. And then I need to update all parent Account.

set<id> ParentIds = new set<id>(); 
For(Account acc: Trigger.New){
                    if(acc.ParentId!=null){
                   ParentIds.add(acc.ParentId);
              }
}

 
Hi Everyone,
Basically what I need is to override the default behavior of SFDC with regards to setting the Primary Campaign Source in Opportunities. The default behavior is it takes the last campaign associated with a contact and make it the Primary Campaign Source in the Opportunity. WE DO NOT WANT THAT. What we want is the FIRST RESPONDED Campaign of the contact to be the Primary Campaign Source.
I written code above only takes the first associated campaign, we need to updated with first responded campaign.

Here is my code:

trigger SetPrimaryCampaignSource on Opportunity (before insert) {
    Set<Id> contIds = new Set<Id>();
   for (Opportunity opp : Trigger.new) {
        contIds.add(opp.Sourced_by__c);
    }
 
    contIds.remove(null);
 
    if (!contIds.isEmpty()) {
        Map<Id, CampaignMember> campaignMap = new Map<Id, CampaignMember>();
 
        for (CampaignMember cm : [
            select ContactId,
                CampaignId,
                Status
            from CampaignMember
            where ContactId in :contIds
            order by CreatedDate asc
            nulls last
        ]) {
            campaignMap.put(cm.ContactId, cm);
        }
 
        for (Opportunity opp : Trigger.new) {
            if (campaignMap.containsKey(opp.Sourced_by__c)) {
                opp.CampaignId = campaignMap.get(opp.Sourced_by__c).CampaignId;
            }
        }
    }
}


Thanks
Hi,
Help me with test class

public with sharing class CDP_Deal_BookmarkAfterUpdateHandler extends TriggerHandlerBase{
    Map<Id, CDP_Deal_Bookmark__c> qualifiedBookmarks;

    public override void qualifyStartingRecords(List<sObject> newList, List<sObject> oldList, Map<ID, sObject> newMap, Map<ID, sObject> oldMap) {
        // everything qualifies for the CDPService.createFieldTrackingFeeds method
        CDPService.createFieldTrackingFeeds(newMap, oldMap, 'Deal__c', true);
    }

    public override void start() {

    }

    public override void finish(boolean fromStart){}
}
  • September 13, 2018
  • Like
  • 0
Help me with test class,

Class Name:

public without sharing class UtilityClassWithoutSharing {
static final String ERROR_MSG = 'The Opportunity you have chosen does not meet all Opportunity Validation rules.  Please update the opportunity and then re-assocaite it with the Deal.';
  
  //Method used in Deal Trigger.
  public static void updateOpp(map<id,id> oppIdDealIdMap, List<Deal__c> newDeals){
    
    list<Opportunity> opps = [select id,Deal__c from Opportunity where id in:oppIdDealIdMap.keySet()];
    list<Opportunity> oppsToUpdate = new list<Opportunity>();
    
    if(opps!=null && opps.size()>0){
      for(Opportunity opp:opps){
        if(opp.Deal__c != oppIdDealIdMap.get(opp.id)){
          opp.Deal__c = oppIdDealIdMap.get(opp.id);
          oppsToUpdate.add(opp);
        }
      }
    }
    
  
    if(oppsToUpdate!=null && oppsToUpdate.size()>0){
      Database.SaveResult[] results = Database.update(oppsToUpdate,false);
      System.debug('MPK: '+results);
      Map<Id,String> mapErrors = new Map<Id,String>();
      for(Integer index = 0 ; index < results.size(); index++){
          Database.SaveResult result = results.get(index);
          Opportunity oppty = oppsToUpdate.get(index);
          if(!result.isSuccess() && String.valueOf(result.getErrors()[0].getStatusCode()).contains('FIELD_CUSTOM_VALIDATION_EXCEPTION')){
              mapErrors.put(oppty.Deal__c,ERROR_MSG);
          }
      }
      for(Deal__c deal  : newDeals){
          if(mapErrors.containsKey(deal.id)){
              deal.addError(mapErrors.get(deal.id));
          }
      }
    }
  }
  
  //Method used in Deal Trigger.
  public static void updateOppToRemoveDealId(list<id> oppIdDealIdMap){
    
    list<Opportunity> opps = [select id,Deal__c from Opportunity where Deal__c in:oppIdDealIdMap];
    list<Opportunity> oppsToUpdate = new list<Opportunity>();
    
    if(opps!=null && opps.size()>0){
      for(Opportunity opp:opps){
          opp.Deal__c = null;
          oppsToUpdate.add(opp);
        
      }
    }
    
    if(oppsToUpdate!=null && oppsToUpdate.size()>0){
      update oppsToUpdate;
    }
  }
}
  • September 12, 2018
  • Like
  • 0
Hi,

Can you please help me with test  class
Class:
global class CDPWeeklyDigestBatchScheduler implements Schedulable {

    global void execute(SchedulableContext sc) {
        String query = 'SELECT Id, Deal_Id__c, Deal_Name__c, Deal_Stage__c, Type__c, Region_Type__c, Market__c, Deal_Owner__c, Latest_Change__c, Deal_Lost_Reason__c, Number_Of_Updates__c FROM CDP_Notification__c WHERE LastModifiedDate = LAST_N_DAYS:7 ';
        List<SObject> records = Database.query(query);    
        NotificationHelper.getNotificationHelperInstance().notifyUsersAboutWeeklyDigest(records);
    }








 
  • September 11, 2018
  • Like
  • 0
Hi,
Can you please help me with test class


Class:

global with sharing class BatchToEndCarouselAnnouncementsScheduler extends BatchScheduler implements Schedulable
{
    global BatchToEndCarouselAnnouncementsScheduler()
    {
        super(10 /*minutes between attempts */, 'End Carousel Announcements');
    }
    
    global void execute(SchedulableContext sc)
    {
        schedule(new BatchToEndCarouselAnnouncements());
    }
}


Extended Class:

public with sharing abstract class BatchScheduler implements Schedulable
{
    @TestVisible static final Integer MAX_CONCURRENT_BATCH = 5;
    @TestVisible Integer minutesBeforeReschedule;
    @TestVisible String title;
    public BatchScheduler( Integer minutes, String title )
    {
        this.minutesBeforeReschedule = minutes;
        this.title = title;
    } 
    public void schedule( IBatchHelper helper, Integer batchSize )
    {
        Integer currentlyRunningBatches = [SELECT count() FROM AsyncApexJob WHERE JobType='BatchApex'
                                           AND (Status = 'Processing' OR Status = 'Preparing')];
        if( currentlyRunningBatches < MAX_CONCURRENT_BATCH )
        {
            BatchHandler batch = new BatchHandler( helper );
            Database.executeBatch( batch, batchSize );
        }
        else
        {
            scheduleRetry();
        }
    }

    public void schedule( IBatchHelper helper )
    {
        schedule( helper, 200 );
    }

    @TestVisible void scheduleRetry() 
    { 
        Datetime rescheduleDateTime = Datetime.now().addMinutes(minutesBeforeReschedule); 
        String timeForScheduler = rescheduleDateTime.format('s m H d M \'?\' yyyy'); 
        System.schedule(title + ' ' + timeForScheduler, timeForScheduler, this); 
    } 
}
  • September 11, 2018
  • Like
  • 0
Hi,
Please help me with test class


public with sharing class Tenant_ImprovementAfterUpdateHandler  extends TriggerHandlerBase {
    Set<Id> selectedUnitIds = new Set<Id>();
    Set<Id> opportunityIds = new Set<Id>();
    List<Opportunity> opportunityToUpdate = new List<Opportunity>();

    public override void qualifyStartingRecords(List<sObject> newList, List<sObject> oldList, Map<ID, sObject> newMap, Map<ID, sObject> oldMap) {
        for(String tiId : newMap.keySet()) {
            if(newMap.get(tiId).get('Standard_Ti__c') != oldMap.get(tiId).get('Standard_Ti__c')
                || newMap.get(tiId).get('Total_ASTI__c') != oldMap.get(tiId).get('Total_ASTI__c')
                    || newMap.get(tiId).get('Shell_Ti__c') != oldMap.get(tiId).get('Shell_Ti__c')
                        || newMap.get(tiId).get('Make_Ready_Costs__c') != oldMap.get(tiId).get('Make_Ready_Costs__c'))  {
                selectedUnitIds.add((Id)newMap.get(tiId).get('Selected_Unit__c'));
            }
            for(Lease_Analysis_Selected_Unit__c selectedUnit : [SELECT Id, Name, Scenario__c, Scenario__r.Lease_Analysis__c, Scenario__r.Lease_Analysis__r.Opportunity__c FROM Lease_Analysis_Selected_Unit__c WHERE Id =: selectedUnitIds AND Scenario__r.IsPrimary__c = true]) {
                opportunityIds.add(selectedUnit.Scenario__r.Lease_Analysis__r.Opportunity__c);
            }
        }
    }

    public override void start() {
        if(null != opportunityIds && opportunityIds.size() > 0) {
            for(Opportunity opp : [SELECT Id, Name, Forecast_Matrix_Date__c FROM Opportunity WHERE Id =: opportunityIds]) {
                Opportunity opportunity = new Opportunity(Id = opp.Id);
                Boolean needToUpdate = false;
                if(opp.Forecast_Matrix_Date__c == null || opp.Forecast_Matrix_Date__c < System.today()) {
                    needToUpdate = true;
                    opportunity.Forecast_Matrix_Date__c = System.today();
                }
                if(needToUpdate) {
                    opportunityToUpdate.add(opportunity);
                }
            }
        }
    }

    public override void finish(boolean fromStart){
        if(opportunityToUpdate.size() > 0) {
            update opportunityToUpdate;
        }
    }
}

​Thanks
  • September 08, 2018
  • Like
  • 0
Hi,
need test class help

global class CDPForecastExtractBatch implements Database.Batchable<sObject> {
    
    String query;
    Forecast_Scenario__c forecastScenario;
    
    global CDPForecastExtractBatch(Forecast_Scenario__c scenario) {
        forecastScenario = scenario;
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC) {
        query = 'SELECT Id, Deal__c, Deal__r.Parent_Deal_Id__c, Deal__r.Stage__c, Deal__r.IsPlaceholder_Deal__c, Deal__r.IsInfrastructure_Deal__c, Deal__r.RecordType.Name, Deal__r.Is_Cloned_Deal__c, Deal__r.Is_Closed_Deal__c, Deal__r.Forecast_Scenario__c, ';
        query += '(SELECT Id, CDP_Asset__c, Customer__c, Customer__r.Name,Customer__r.Account_Subtype__c FROM CDP_Asset_Customer_Accounts__r) , ';
        query += '(SELECT Id, Development_Deal_Id__c, Land_Name__c, CDP_Asset__c, Land_Area__c, Land_Area_UOM__c, Land_Source__c, Land_Code__c FROM CDP_Land_Strategy__r) '; 
        query += 'FROM CDP_Asset__c WHERE (NOT Deal__r.Stage__c like \'%Lost%\')  AND (Deal__r.Is_Cloned_Deal__c = true OR (Deal__r.Stage__c like \'%Won%\') ) ';
        query += 'AND Deal__r.Hold__c = false AND (Deal__r.IsNamedDeal__c = true OR Deal__r.IsPlaceholder_Deal__c = true OR Deal__r.IsInfrastructure_Deal__c = true OR (Deal__r.Stage__c like \'%Won%\') ) ';
           query += 'AND Deal__r.RecordType.Name NOT IN ('+ '\'Value-Add\'' +')';
        return Database.getQueryLocator(query);
    }

       global void execute(Database.BatchableContext BC, List<sObject> scope) {
        CDPForecastExtractHandler.getChildRecords(scope, forecastScenario);
    }
    
    global void finish(Database.BatchableContext BC) {
        
    }
    
}
  • September 08, 2018
  • Like
  • 0
Hi,
Require test class help

public with sharing class CompetitorStructure extends Hierarchy
{   
    /**
    * Return ObjectStructureMap to page
    * @return competitorNodes
    */
    public List<CompetitorHierarchyNode> getObjectStructure()
    {
        if ( currentId == null ) {
            currentId = System.currentPageReference().getParameters().get( 'id' );
        }
        
        System.assertNotEquals( currentId, null, 'sObject ID must be provided' );
        return formatObjectStructure( CurrentId );
    }

    /**
    * Query competitor from top down to build the CompetitorHierarchyNode
    * @param currentId
    * @return competitorNodes
    */
    public List<CompetitorHierarchyNode> formatObjectStructure( String currentId )
    {
        List<CompetitorHierarchyNode> competitorNodes = new List<CompetitorHierarchyNode>();
        return (List<CompetitorHierarchyNode>) generateHierarchy(competitorNodes);
    }

    protected override HierarchyNode getAllNodes()
    {
        idToNode.clear();
        List<Competitor__c> competitors = new List<Competitor__c>();
        List<Id> currentParents         = new List<Id>();
        HierarchyNode topNode           = null;

        Integer level                   = 0;
        Boolean noChildren              = false;
        
        //Find highest level obejct in the structure
        currentParents.add( GetTopElement( currentId ) );

        //Loop though all children
        while ( !noChildren ){

            if( level == 0 ){
                //Change below     
                competitors = [ SELECT Parent_Competitor__c, OwnerId, Name, Industry__c FROM Competitor__c WHERE Id IN :currentParents ORDER BY Name ];
            } 
            else {
                //Change below      
                competitors = [ SELECT Parent_Competitor__c, OwnerId, Name, Industry__c FROM Competitor__c WHERE Parent_Competitor__c IN :currentParents ORDER BY Name ];
            }

            if( competitors.size() == 0 )
            {
                noChildren = true;
            }
            else
            {
                currentParents.clear();
                for (Competitor__c competitor : competitors)
                {
                    //Change below
                    HierarchyNode parentNode = idToNode.get(competitor.Parent_Competitor__c);
                    CompetitorHierarchyNode node = new CompetitorHierarchyNode(false, competitor);
                    idToNode.put(competitor.Id, node);
                    currentParents.add( competitor.id );

                    if (parentNode != null)
                        node.setParent(parentNode);
                    else
                        topNode = node;
                }
                
                maxLevel.add( level );
                level++;
            }
        }

        return topNode;
    }
    
    /**
    * Find the tom most element in Heirarchy  
    * @return objId
    */
    public String GetTopElement( String objId ){
        
        Boolean top = false;
        while ( !top ) {
            //Change below
            Competitor__c competitor = [ Select competitor.Id, competitor.Parent_Competitor__c From Competitor__c competitor where competitor.Id =: objId limit 1 ];
            
            if ( competitor.Parent_Competitor__c != null ) {
                objId = competitor.Parent_Competitor__c;
            }
            else {
                top = true;
            }
        }
        return objId ;
    }

    public with sharing class CompetitorHierarchyNode extends HierarchyNode
    {
        public Competitor__c competitor;
        public Competitor__c getCompetitor() { return competitor; }
        public void setCompetitor( Competitor__c competitor ) { this.competitor = competitor; }

        public CompetitorHierarchyNode( Boolean currentNode, Competitor__c competitor)
        {
            super(currentNode);
            this.competitor = competitor;
        }
    }
}
  • September 05, 2018
  • Like
  • 0
Can anyone help with test class


public with sharing class AccountStructure extends Hierarchy
{
    /**
    * Return ObjectStructureMap to page
    * @return asm
    */
    public List<AccountHierarchyNode> getObjectStructure()
    {
        if ( currentId == null ) {
            currentId = System.currentPageReference().getParameters().get( 'id' );
        }
        
        System.assertNotEquals( currentId, null, 'sObject ID must be provided' );
        return formatObjectStructure( CurrentId );
    }

    /**
    * Query Account from top down to build the AccountHierarchyNode
    * @param currentId
    * @return asm
    */
    public List<AccountHierarchyNode> formatObjectStructure( String currentId )
    {
        List<AccountHierarchyNode> accountNodes = new List<AccountHierarchyNode>();
        return (List<AccountHierarchyNode>) generateHierarchy(accountNodes);
    }

    protected override HierarchyNode getAllNodes()
    {
        idToNode.clear();
        List<Account> accounts = new List<Account>();
        List<Id> currentParents         = new List<Id>();
        HierarchyNode topNode           = null;

        Integer level                   = 0;
        Boolean noChildren              = false;
        
        //Find highest level obejct in the structure
        currentParents.add( GetTopElement( currentId ) );

        //Loop though all children
        while ( !noChildren ){

            if( level == 0 ){
                //Change below     
                accounts = [SELECT Type, Site, ParentId, OwnerId, Name, Industry FROM Account WHERE Id IN :currentParents ORDER BY Name];
            } 
            else {
                //Change below      
                accounts = [SELECT Type, Site, ParentId, OwnerId, Name, Industry FROM Account WHERE ParentID IN :currentParents ORDER BY Name];
            }

            if( accounts.size() == 0 )
            {
                noChildren = true;
            }
            else
            {
                currentParents.clear();
                for (Account account : accounts)
                {
                    //Change below
                    HierarchyNode parentNode = idToNode.get(account.ParentId);
                    AccountHierarchyNode node = new AccountHierarchyNode(false, account);
                    idToNode.put(account.Id, node);
                    currentParents.add( account.id );

                    if (parentNode != null)
                        node.setParent(parentNode);
                    else
                        topNode = node;
                }
                
                maxLevel.add( level );
                level++;
            }
        }

        return topNode;
    }
    
    /**
    * Find the tom most element in Heirarchy  
    * @return objId
    */
    public String GetTopElement( String objId ){
        
        Boolean top = false;
        while ( !top ) {
            //Change below
            Account a = [ Select a.Id, a.ParentId From Account a where a.Id =: objId limit 1 ];
            
            if ( a.ParentID != null ) {
                objId = a.ParentID;
            }
            else {
                top = true;
            }
        }
        return objId ;
    }

    public with sharing class AccountHierarchyNode extends HierarchyNode
    {
        public Account account;
        public Account getAccount() { return account; }
        public void setAccount( Account a ) { this.account = a; }

        public AccountHierarchyNode(Boolean currentNode, Account account)
        {
            super(currentNode);
            this.account = account;
        }
    }
}
  • September 03, 2018
  • Like
  • 0
Hi
needed help in Code coverage

trigger UnitTrigger on Unit__c (before insert, before update) {

    if(trigger.isBefore){
    
    Map<String, Id> unitRecTypeMap = new Map<String, Id>();
    for(RecordType r: [Select Id, Name From RecordType Where sObjectType = 'Unit__c'])
        unitRecTypeMap.put(r.Name,r.Id);
    
    if(trigger.isInsert){
        for(Unit__c u: trigger.new){
            // flipping Unit to Retired if its inserted with 0 area
            if(u.Area_SF__c == 0)
            {u.Available__c = false; u.RecordTypeId = unitRecTypeMap.get('Retired'); }
            // initializing unit as unavailable if its Raw Land or Sold
            else if(u.Lifecycle__c == 'Sold')    
            u.Available__c = false;
            // initializing the unit availability to true when its first inserted with non-zero (includes null) area
            else
            u.Available__c = true;
        }
    }
    
    set<Id> unitIdSet = new set<Id>();
    
    if(trigger.isUpdate){
        for(Unit__c u: trigger.new){
            
            // updating sold units as unavailable
            if (u.Lifecycle__c == 'Sold')
                {u.Available__c = false; u.IsAvailabilityUpdatedByUser__c = false;}
            
            // Active --> Retired
            if(u.Area_SF__c == 0)
                {u.Available__c = false; u.IsAvailabilityUpdatedByUser__c = false; u.RecordTypeId = unitRecTypeMap.get('Retired'); }
            
            // Retired --> Active (very unlikely that this code will be executed)
            if(u.Area_SF__c != 0 && trigger.oldMap.get(u.Id).Area_SF__c == 0){ 
                u.RecordTypeId = unitRecTypeMap.get('Active'); 
                if(u.Lifecycle__c != 'Sold')
                    unitIdSet.add(u.Id);
            }
        }
        
        //Informatica, SSIS and other Sys Admins will skip this
            Id SysAdminId = Label.System_Administrator;
            if(LeaseUnitRelationManagement.exitUnitTrigger == false && UserInfo.getProfileId() != SysAdminId){
                for(Unit__c u: trigger.new){
                    if(u.Available__c != trigger.oldMap.get(u.Id).Available__c && u.IsAvailabilityUpdatedByUser__c == false){
                        u.IsAvailabilityUpdatedByUser__c = true;
                    }  
                }
            }
        
    }
    
        // unitIdSet - units that need to be re-evaluated for Availability (very unlikely that this code will be executed)
        if(unitIdSet.size()>0 && unitIdSet != null){ 
            UnitTriggerManagement.reEvaluateUnitsforAvailability(unitIdSet);    
        }
        
  } // end of isBefore

}
  • September 03, 2018
  • Like
  • 0
global class ApprovalDelegationsBatchable implements Database.Batchable<sObject> {
    
    String query;
    Map<String, String> emailTemplateMap;

    global ApprovalDelegationsBatchable() {
        query = 'Select Id, Name,'+
        ' Status__c,'+
        ' Primary_Delegate__c,'+
        ' Secondary_Delegate__c,'+
        ' User__r.Out_Of_Office__c,'+
        ' User__r.Secondary_Delegated_Approver_Id__c,'+
        ' User__r.DelegatedApproverId,'+
        ' Notified_Date__c,'+
        ' Lease_Approval__r.Comments__c,'+
        ' Lease_Approval__c,'+
        ' Lease_Approval__r.Scenario__r.Lease_Analysis__r.Assumption_Comparison__c, '+
        ' Lease_Approval__r.Scenario__r.Lease_Analysis__r.Opportunity__r.Name, '+
        ' Lease_Approval__r.Scenario__r.Lease_Analysis__r.Opportunity__r.ownerId, '+
        ' Lease_Approval__r.Scenario__r.Lease_Analysis__r.Opportunity__r.Account.Account_Subtype__c,'+
        ' Lease_Approval__r.Scenario__r.Lease_Analysis__r.Opportunity__c,'+
        ' Lease_Approval__r.Scenario__c';
        for(String s : Schema.SObjectType.Scenario__c.fields.getMap().keySet()){
            query+=',Lease_Approval__r.Scenario__r.'+s;
        }

       
        query+=' From Lease_Approval_Role__c Where Status__c = \'Awaiting Response\'';
        emailTemplateMap = LeaseApprovalHelper.getLeaseApprovalTemplates();
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC) {

        return Database.getQueryLocator(query);
    }

       global void execute(Database.BatchableContext BC, List<sObject> scope) {
           List<Lease_Approval_Role__c> larList = new List<Lease_Approval_Role__c>();
           List<Messaging.SingleEmailMessage> emailsToSend = new List<Messaging.SingleEmailMessage>();
           Set<Id> opps = new Set<Id>();
           Set<Id> delegateIds = new Set<Id>();
           Set<Id> dealMakerIds = new Set<Id>();
           Map<Id, String> scenarioToUnitInfoMap = new Map<Id, String>();
           //Map<Id, Opportunity> oppMap = new Map<Id, Opportunity>([Select Id, Name, AccountId, Account.Account_Subtype__c From Opportunity Where Id in ]);
           for(sobject s : scope){
            Lease_Approval_Role__c lar = (Lease_Approval_Role__c)s;
            dealMakerIds.add(lar.Lease_Approval__r.Scenario__r.Lease_Analysis__r.Opportunity__r.OwnerId);
            scenarioToUnitInfoMap.put(lar.Lease_Approval__r.Scenario__c, null);
            if(lar.User__r.DelegatedApproverId != null && LeaseApprovalHelper.getDiffBusinessDays(lar.Notified_Date__c, System.today())>=4){  
                opps.add(lar.Lease_Approval__r.Scenario__r.Lease_Analysis__r.Opportunity__c);
                delegateIds.add(lar.User__r.DelegatedApproverId);
                if(lar.User__r.Secondary_Delegated_Approver_Id__c != null) delegateIds.add(lar.User__r.Secondary_Delegated_Approver_Id__c);
            }    
           }
           Set<Id> combinedUnits = new Set<Id>();
        for(Lease_Analysis_Selected_Unit__c su : [Select Id, Scenario__c, Unit__c,Unit__r.Unit__r.Property__c, Unit__r.Unit__r.Property_Address__c, Unit__r.Unit__r.Property_Code__c, Unit__r.Unit__r.Name, Unit__r.Unit__r.Property__r.Name from Lease_Analysis_Selected_Unit__c where Scenario__c IN : scenarioToUnitInfoMap.keySet() order by Scenario__c]){
               if(su.Unit__c==null){
                   combinedUnits.add(su.Id);
               }
               else{
                   String unitTable;
                   if(scenarioToUnitInfoMap.containsKey(su.Scenario__c) && scenarioToUnitInfoMap.get(su.Scenario__c)!=null){
                       unitTable = scenarioToUnitInfoMap.get(su.Scenario__c);
                       if(unitTable.contains(su.Unit__r.Unit__r.Property__r.Name)){
                           unitTable += '<tr><td>'+su.Unit__r.Unit__r.Name+' - ' + su.Unit__r.Unit__r.Property_Code__c + '</td></tr>';
                       }
                       else{
                           unitTable += '<br/><table>    <tr><td>'+su.Unit__r.Unit__r.Property__r.Name+'</td></tr>'+
                                               '<tr><td>'+su.Unit__r.Unit__r.Property_Address__c+'</td></tr>'+
                                               '<tr><td>'+su.Unit__r.Unit__r.Name+' - ' + su.Unit__r.Unit__r.Property_Code__c + '</td></tr>';
                       }
                       scenarioToUnitInfoMap.put(su.Scenario__c, unitTable);
                   }
                   else{
                       unitTable = '<table>    <tr><td>'+su.Unit__r.Unit__r.Property__r.Name+'</td></tr>'+
                                               '<tr><td>'+su.Unit__r.Unit__r.Property_Address__c+'</td></tr>'+
                                               '<tr><td>'+su.Unit__r.Unit__r.Name+' - ' + su.Unit__r.Unit__r.Property_Code__c + '</td></tr>';
                       scenarioToUnitInfoMap.put(su.Scenario__c, unitTable);
                                               
                   }
                   
               }
           } 
           for(Combined_Unit__c su : [Select Id, Unit_Opportunity__r.Unit__r.Property_Code__c, Selected_Unit__r.Scenario__c, Unit_Opportunity__r.Unit__r.Name, Unit_Opportunity__r.Unit__r.Property__r.Name, Unit_Opportunity__r.Unit__r.Property_Address__c from Combined_Unit__c where Selected_Unit__c IN : combinedUnits]){
               String unitTable;
            if(scenarioToUnitInfoMap.containsKey(su.Selected_Unit__r.Scenario__c) && scenarioToUnitInfoMap.get(su.Selected_Unit__r.Scenario__c)!=null){
                unitTable = scenarioToUnitInfoMap.get(su.Selected_Unit__r.Scenario__c);
                if(unitTable.contains(su.Unit_Opportunity__r.Unit__r.Property__r.Name)){
                    unitTable += '<tr><td>'+su.Unit_Opportunity__r.Unit__r.Name+' - ' + su.Unit_Opportunity__r.Unit__r.Property_Code__c + '</td></tr>';
                }
                else{
                    unitTable += '<br/><table>    <tr><td>'+su.Unit_Opportunity__r.Unit__r.Property__r.Name+'</td></tr>'+
                                        '<tr><td>'+su.Unit_Opportunity__r.Unit__r.Property_Address__c+'</td></tr>'+
                                        '<tr><td>'+su.Unit_Opportunity__r.Unit__r.Name+' - ' + su.Unit_Opportunity__r.Unit__r.Property_Code__c + '</td></tr>';
                }
                scenarioToUnitInfoMap.put(su.Selected_Unit__r.Scenario__c, unitTable);
            }
            else{
                unitTable = '<table>    <tr><td>'+su.Unit_Opportunity__r.Unit__r.Property__r.Name+'</td></tr>'+
                                        '<tr><td>'+su.Unit_Opportunity__r.Unit__r.Property_Address__c+'</td></tr>'+
                                        '<tr><td>'+su.Unit_Opportunity__r.Unit__r.Name+' - ' + su.Unit_Opportunity__r.Unit__r.Property_Code__c + '</td></tr>';
                scenarioToUnitInfoMap.put(su.Selected_Unit__r.Scenario__c, unitTable);
                                        
            }
            
        }
        for(String s : scenarioToUnitInfoMap.values()){
            s+='</table>';
        }
           Map<Id, Opportunity> oppMap = new Map<Id, Opportunity>([Select Id, Name, AccountId, Account.Account_Subtype__c From Opportunity Where Id in :opps]);
           Map<Id, Opportunity> larToOppMap = new Map<Id, Opportunity>();
           System.debug(delegateIds);
           Map<Id, User> delegates = new Map<Id, User>([Select Id, Name, Email From User where Id IN :delegateIds]);
           Map<Id, User> dealMakerMap = new Map<Id, User>([Select Id, Name From User where Id IN :dealMakerIds]);
        for(sobject s : scope){
            Lease_Approval_Role__c lar = (Lease_Approval_Role__c)s;
            larToOppMap.put(lar.Id, oppMap.get(lar.Lease_Approval__r.Scenario__r.Lease_Analysis__r.Opportunity__c));
            System.debug('DAYS: '+LeaseApprovalHelper.getDiffBusinessDays(lar.Notified_Date__c, System.today()));
            if(lar.User__r.DelegatedApproverId != null && LeaseApprovalHelper.getDiffBusinessDays(lar.Notified_Date__c, System.today())>=4){  //Nothing to do if no delegates for user or if notified less than 4 business days ago
                
                if(lar.User__r.Out_Of_Office__c){ 
                    if(lar.User__r.Secondary_Delegated_Approver_Id__c != null){
                        if(lar.Secondary_Delegate__c == null){
                            lar.Secondary_Delegate__c = lar.User__r.Secondary_Delegated_Approver_Id__c;
                            larList.add(lar);
                        }
                        //send email
                        Messaging.SingleEmailMessage mail = LeaseApprovalHelper.createApprovalActionNeededEmail(emailTemplateMap.get('Approver_Action_Needed'), 
                                                            //delegates.get(lar.User__r.Secondary_Delegated_Approver_Id__c).Name,
                                                            dealMakerMap.get(lar.Lease_Approval__r.Scenario__r.Lease_Analysis__r.Opportunity__r.ownerId).Name,
                                                            delegates.get(lar.User__r.Secondary_Delegated_Approver_Id__c).Email, 
                                                            larToOppMap.get(lar.Id), 
                                                            lar.Lease_Approval__r,
                                                            lar.Id,
                                                            scenarioToUnitInfoMap.get(lar.Lease_Approval__r.Scenario__c));
                        mail.setSubject('Secondary Delegate Action Required(Primary Waited 4 days.');
                        emailsToSend.add(mail);
                    }
                }else{
                    //if more than 8, send to secondary, else send to primary
                    if(LeaseApprovalHelper.getDiffBusinessDays(lar.Notified_Date__c, System.today())>8 && lar.User__r.Secondary_Delegated_Approver_Id__c != null){
                        //email to secondary, add secondary to lar
                        lar.Secondary_Delegate__c = lar.User__r.Secondary_Delegated_Approver_Id__c;
                        larList.add(lar);
                        Messaging.SingleEmailMessage mail = LeaseApprovalHelper.createApprovalActionNeededEmail(emailTemplateMap.get('Approver_Action_Needed'), 
                                                            dealMakerMap.get(lar.Lease_Approval__r.Scenario__r.Lease_Analysis__r.Opportunity__r.ownerId).Name,
                                                            delegates.get(lar.User__r.Secondary_Delegated_Approver_Id__c).Email, 
                                                            larToOppMap.get(lar.Id), 
                                                            lar.Lease_Approval__r,
                                                            lar.Id,
                                                            scenarioToUnitInfoMap.get(lar.Lease_Approval__r.Scenario__c));
                        mail.setSubject('Secondary Delegate Action Required(Primary Waited 4 days.');
                        emailsToSend.add(mail);
                    }else{
                        //email to primary, add primary to lar
                        lar.Primary_Delegate__c = lar.User__r.DelegatedApproverId;
                        larList.add(lar);
                        Messaging.SingleEmailMessage mail = LeaseApprovalHelper.createApprovalActionNeededEmail(emailTemplateMap.get('Approver_Action_Needed'), 
                                                            dealMakerMap.get(lar.Lease_Approval__r.Scenario__r.Lease_Analysis__r.Opportunity__r.ownerId).Name,
                                                            delegates.get(lar.User__r.DelegatedApproverId).Email, 
                                                            larToOppMap.get(lar.Id), 
                                                            lar.Lease_Approval__r,
                                                            lar.Id,
                                                            scenarioToUnitInfoMap.get(lar.Lease_Approval__r.Scenario__c));
                        mail.setSubject('Primary Delegate Action Required(Main Approver Waited 4 days.');
                        emailsToSend.add(mail);
                    }
                }
            }
        }
        if(larList.size()>0){
            update larList;
        }
        if(emailsToSend.size()>0){
            Messaging.sendEmail(emailsToSend);
        }
    }
    
    global void finish(Database.BatchableContext BC) {
        
    }
    
}




global class ApprovalDelegationsSchedulable implements Schedulable {
    global void execute(SchedulableContext sc) {
        ApprovalDelegationsBatchable b = new ApprovalDelegationsBatchable();
        database.executebatch(b);
    }
}

Thanks
  • September 03, 2018
  • Like
  • 0
Hi Everyone,
can you please help me with test class
public class AccntExtension {
    public List<AccHierarchy> accountList{get;set;}
    public String chumma{get;set;}
    public Map<id,Account> accMap{get;set;}
    public AccHierarchy hier;
    public AccntExtension(ApexPages.StandardController c){
    accMap= new Map<id,Account>([SELECT (SELECT Name,Market__r.Name,Type,StageName FROM Opportunities) from Account]);
        accountList = new List<AccHierarchy>();
        List<AccHierarchy> chilList = null;
        for(Account acc : accMap.values()){
            if(acc.ParentId == null){
                hier = new AccHierarchy();
                hier.setAccount(acc);
                accMap.remove(acc.id);
                //accountList=
                accountList.add(hier);
                chilList = getChildAccount(acc.id);
                hier.setChildVal(chilList);
                
            }
        }
        system.debug('FinalList'+accountList);
    }
    private List<AccHierarchy> getChildAccount(Id parentId){
        List<AccHierarchy> accList = new List<AccHierarchy>();
        for(Account acc : accMap.values()){
            if(parentId == acc.ParentId){
                accMap.remove(acc.id);
                AccHierarchy hierChd = new AccHierarchy();
                hierChd.setAccount(acc);
                
                accList.add(hierChd);
                List<AccHierarchy> chilList = null;
                chilList = getChildAccount(acc.id);
                hierChd.setChildVal(chilList);
            }
        }
        system.debug('Loop top '+accList);
        return accList;
    }
    
}
  • September 01, 2018
  • Like
  • 0
Hi Everyone,
can you please help me with test class


public without sharing class AccountHelperUtility {
  
   //update account area fields 
    public static void insertUpdateAccountAreaFields(List<Account> AccountList, Map<ID,sObject> AccountMapOld) { 
    for(Account account:AccountList) {
        Account accountOld = AccountMapOld == null ? null : (Account)AccountMapOld.get(account.id);
      populateValuesBeforeInsertUpdate(account, accountOld, 'Planned_Retention_Tsubo__c', 'Planned_Retention_SF__c', 'Planned_Retention_SM__c');
      populateValuesBeforeInsertUpdate(account, accountOld, 'Customer_Total_Footprint_Wallet_Tsubo__c', 'Customer_Total_Footprint_Wallet_SF__c', 'Customer_Total_Footprint_Wallet_SM__c');
    }   
    }
    
    static void populateValuesBeforeInsertUpdate(Account account, Account accountOld, String Tsubo, String SF, String SM) {
        Boolean isUpdate = accountOld == null ? false : true;
      if(account.get(SF) != null && String.valueOf(account.get(SF))!= '' && (!isUpdate || Integer.valueOf(account.get(SF)) != Integer.valueOf(accountOld.get(SF))) ){
        account.put(Tsubo , UOMCalculation.getTsuboFromSf((decimal)account.get(SF)));
        account.put(SM , UOMCalculation.getM2FromSf((decimal)account.get(SF)));
      }else if(account.get(SM) != null && String.valueOf(account.get(SM))!= '' && (!isUpdate || Integer.valueOf(account.get(SM)) != Integer.valueOf(accountOld.get(SM))) ){
          Decimal sqFt = UOMCalculation.getSfFromM2((decimal)account.get(SM));
        account.put(Tsubo , UOMCalculation.getTsuboFromSf(sqFt));
        account.put(SF , sqFt);
      }else if(account.get(Tsubo) != null && String.valueOf(account.get(Tsubo))!= '' && (!isUpdate || Integer.valueOf(account.get(Tsubo)) != Integer.valueOf(accountOld.get(Tsubo))) ) {
          Decimal sqFt = UOMCalculation.getSfFromTsubo((decimal)account.get(Tsubo));
      account.put(SM , UOMCalculation.getM2FromSf(sqFt));
      account.put(SF , sqFt);
      }
    }
    
     //Added for T-131999
    public static void removeTeamMembers(Map<Id,Account> accountNewMap, Map<Id,Account> accountOldMap){
      map<Id,Id> accIdToGCSOfficerMap = new map<Id,Id>();
      list<AccountTeamMember> teamMembersToBeDeleted = new list<AccountTeamMember>();
      for(Account acc : accountNewMap.values()){
        if((acc.GCS_Account_Officer__c != null && 
          acc.GCS_Account_Officer__c != accountOldMap.get(acc.Id).GCS_Account_Officer__c)){
            accIdToGCSOfficerMap.put(acc.Id,acc.GCS_Account_Officer__c);
        }
      }
      if(accIdToGCSOfficerMap.size() > 0 ){
        for(AccountTeamMember accTeamMember : [Select Id,UserId,AccountId from AccountTeamMember where AccountId IN : 
          accIdToGCSOfficerMap.keySet()]){
            if(accTeamMember.AccountId != null && accIdToGCSOfficerMap.containsKey(accTeamMember.AccountId) &&
              accTeamMember.UserId != null && accIdToGCSOfficerMap.get(accTeamMember.AccountId) == accTeamMember.UserId){
                teamMembersToBeDeleted.add(accTeamMember);
              }
        }
      }
      if(teamMembersToBeDeleted.size() > 0){
        delete teamMembersToBeDeleted;
      }
    }
}
  • September 01, 2018
  • Like
  • 0

Hi everyone,
I have written a SQQL query. It is returning records but in some columns, it is showing  [Object Object] .  

Can anyone help me with this query


select Customer__r.Name,CDP_Asset__r.Deal__r.Name, CDP_Asset__r.Market__r.Name, CDP_Asset__r.Deal__r.Type__c,CDP_Asset__r.Deal__r.Stage__c from CDP_Asset_Customer_Account__c where Customer__r.Id IN ('0010B00001kPbx9QAC', '0010B00001nIOI0QAO', '0010B00001qTAG1QAO', '001U000000Ooi35IAB', '001U000000Ooj29IAB', '001U000000oSCeVIAW', '001U000001Tg4OAIAZ', '001U000001XqBrFIAV', '001U000001frl9cIAA')

Result:
User-added image







 
Hi, 
Please help me with test class


public   class OV_Bean implements Comparable {
  
    public String objId;
    public Long score;   
    
    public OV_Bean(String n, Long p) {     
        this.objId = n;
        this.score = p;
    }
    public  Integer compareTo(Object compareTo) {
        OV_Bean compareToEmp = (OV_Bean)compareTo;
        if (score > compareToEmp.score) return -1;
        if (score < compareToEmp.score) return 1;
        return 0;        
    }
}

Thanks
Hi ,
How to get test coverage for this class.

global abstract class PageControllerBase {

    public Boolean showHeader {get; set;}
    
    public PageControllerBase() {
        showHeader = true;
        String headerParameter = ApexPages.currentPage().getParameters().get('showHeader');
        if ('false' == headerParameter || 'no' == headerParameter) {
            showHeader = false;
        }
        String userAgent = ApexPages.currentPage().getHeaders().get('USER-AGENT');
        if (null != userAgent && (userAgent.contains('iPhone') || userAgent.contains('iPad'))) {
            showHeader = false;
        } 
    }
}


Thanks
Hi All,
I am wring test class and i got only 25% code coverage and unable to achive test coverage for two methods


 private static String  appendWhere(String query,String whereCon ){
          if(whereCon!=''){
             String Id = whereCon.Split('\'')[1];
             String str= whereCon;
             integer tot= str.countMatches(' AND ');
             system.debug('----------Test-------'+tot); 
             String acctIds =OV_BAUtility.getAcctIds(Id);
             if(tot==2){
             String andClause = (whereCon.contains('AND')?' AND '+whereCon.Split('AND')[1]+' AND '+whereCon.Split('AND')[2]:'');
             query=query +' where '+whereCon.Split('=')[0]+' IN '+ acctIds +andClause;   
             }else{
             String andClause = (whereCon.contains('AND')?' AND '+whereCon.Split('AND')[1]:'');
             query=query +' where '+whereCon.Split('=')[0]+' IN '+ acctIds +andClause;
             }
           
         }
         return query;
     }
    public static void setTotal(List<sobject> sObjectsList,String totalFields,lightningTableWrapper wrp){
        List<String> total =totalFields.split(',');
        system.debug('-----------------------------------------------tttttt-------------='+totalFields+'=----------'+sObjectsList+'total.size()---'+total.size());
        Map<String,Decimal > totalmap= new Map<String,Decimal >();
        if(total.size() > 1){
            for(sObject obj :sObjectsList){
                for(String t:total){
                    t=t.trim();
                    if(totalmap.containsKey(t)){
                        totalmap.put(t,totalmap.get(t)+(Decimal )obj.get(t));
                    }else{
                        totalmap.put(t,(Decimal )obj.get(t));
                    }
                }
            }
        }
        wrp.totalFields=totalmap;
    }

Thanks
Hello Everyone,
I created Onclick java script button in quote to update quote version.
{!REQUIRESCRIPT("/soap/ajax/31.0/connection.js")} 

//declare the varaiable that will hold all the information 
var newRecords = []; 

var opp = new sforce.SObject("Quote"); 
opp.Id = '{!Quote.Id}'; 
opp.CBG_Check_to_Quote_Version__c = '1';
opp.CBG_Check_to_Version__c = '1';

if (confirm("Do you want to revise Quote?") == true)
 {
opp.CBG_Check_to_Quote_Version__c = '1';   
 txt = "You pressed OK!";
 
}

else 
{
opp.CBG_Check_to_Quote_Version__c = '0';
opp.CBG_Quote_Version__c = "  ";
txt = "You pressed Cancel!";



result = sforce.connection.update([opp]); 
window.location.reload(); 
opp.CBG_Check_to_Quote_Version__c = '0'; 
newRecords.push(opp); 
result = sforce.connection.update([opp]); 
window.location.reload();


This button is only visible if opportunity Brand = textile(Opportunity field).
so i created two separate record types with deferent page layout.
Now i created workflow to change record type.
Up to now working  well like whenever opportunity Brand = Phoenix and when i create New quote. I am able to see button in Quote detail page.
  User-added image            User-added image                               
Now if change opportunity Brannd = non Phoenix and if i update existing quote. I should not see the button button over there but button is there.---It is not working.

User-added image
User-added image

Please help me how to do it.
since we cant use screen to show an error message in auto launched flow so I want another solution so that I can show the message on the screen on which you are creating record.
comment If you want further clarification

Thanks in advance 
I forgot the password of pst. Sometime before I created pst password for protect my pst folder. How to unlock my pst password
Hi,
I want to create delivery record on 1st of each month.
How we can do that?


Thanks
Guru
Hi,
Can please help me with surveys in sfdc.I want to send survey form to Lead after contact with him or after given demo automatically.
I want to get reponse store in lead.


Thanks&Regards
Guru 
Hi Everyone,
Basically what I need is to override the default behavior of SFDC with regards to setting the Primary Campaign Source in Opportunities. The default behavior is it takes the last campaign associated with a contact and make it the Primary Campaign Source in the Opportunity. WE DO NOT WANT THAT. What we want is the FIRST RESPONDED Campaign of the contact to be the Primary Campaign Source.
I written code above only takes the first associated campaign, we need to updated with first responded campaign.

Here is my code:

trigger SetPrimaryCampaignSource on Opportunity (before insert) {
    Set<Id> contIds = new Set<Id>();
   for (Opportunity opp : Trigger.new) {
        contIds.add(opp.Sourced_by__c);
    }
 
    contIds.remove(null);
 
    if (!contIds.isEmpty()) {
        Map<Id, CampaignMember> campaignMap = new Map<Id, CampaignMember>();
 
        for (CampaignMember cm : [
            select ContactId,
                CampaignId,
                Status
            from CampaignMember
            where ContactId in :contIds
            order by CreatedDate asc
            nulls last
        ]) {
            campaignMap.put(cm.ContactId, cm);
        }
 
        for (Opportunity opp : Trigger.new) {
            if (campaignMap.containsKey(opp.Sourced_by__c)) {
                opp.CampaignId = campaignMap.get(opp.Sourced_by__c).CampaignId;
            }
        }
    }
}


Thanks
Hi,
Help me with test class

public with sharing class CDP_Deal_BookmarkAfterUpdateHandler extends TriggerHandlerBase{
    Map<Id, CDP_Deal_Bookmark__c> qualifiedBookmarks;

    public override void qualifyStartingRecords(List<sObject> newList, List<sObject> oldList, Map<ID, sObject> newMap, Map<ID, sObject> oldMap) {
        // everything qualifies for the CDPService.createFieldTrackingFeeds method
        CDPService.createFieldTrackingFeeds(newMap, oldMap, 'Deal__c', true);
    }

    public override void start() {

    }

    public override void finish(boolean fromStart){}
}
  • September 13, 2018
  • Like
  • 0
Hi,

Can you please help me with test  class
Class:
global class CDPWeeklyDigestBatchScheduler implements Schedulable {

    global void execute(SchedulableContext sc) {
        String query = 'SELECT Id, Deal_Id__c, Deal_Name__c, Deal_Stage__c, Type__c, Region_Type__c, Market__c, Deal_Owner__c, Latest_Change__c, Deal_Lost_Reason__c, Number_Of_Updates__c FROM CDP_Notification__c WHERE LastModifiedDate = LAST_N_DAYS:7 ';
        List<SObject> records = Database.query(query);    
        NotificationHelper.getNotificationHelperInstance().notifyUsersAboutWeeklyDigest(records);
    }








 
  • September 11, 2018
  • Like
  • 0
Hi,
Can you please help me with test class


Class:

global with sharing class BatchToEndCarouselAnnouncementsScheduler extends BatchScheduler implements Schedulable
{
    global BatchToEndCarouselAnnouncementsScheduler()
    {
        super(10 /*minutes between attempts */, 'End Carousel Announcements');
    }
    
    global void execute(SchedulableContext sc)
    {
        schedule(new BatchToEndCarouselAnnouncements());
    }
}


Extended Class:

public with sharing abstract class BatchScheduler implements Schedulable
{
    @TestVisible static final Integer MAX_CONCURRENT_BATCH = 5;
    @TestVisible Integer minutesBeforeReschedule;
    @TestVisible String title;
    public BatchScheduler( Integer minutes, String title )
    {
        this.minutesBeforeReschedule = minutes;
        this.title = title;
    } 
    public void schedule( IBatchHelper helper, Integer batchSize )
    {
        Integer currentlyRunningBatches = [SELECT count() FROM AsyncApexJob WHERE JobType='BatchApex'
                                           AND (Status = 'Processing' OR Status = 'Preparing')];
        if( currentlyRunningBatches < MAX_CONCURRENT_BATCH )
        {
            BatchHandler batch = new BatchHandler( helper );
            Database.executeBatch( batch, batchSize );
        }
        else
        {
            scheduleRetry();
        }
    }

    public void schedule( IBatchHelper helper )
    {
        schedule( helper, 200 );
    }

    @TestVisible void scheduleRetry() 
    { 
        Datetime rescheduleDateTime = Datetime.now().addMinutes(minutesBeforeReschedule); 
        String timeForScheduler = rescheduleDateTime.format('s m H d M \'?\' yyyy'); 
        System.schedule(title + ' ' + timeForScheduler, timeForScheduler, this); 
    } 
}
  • September 11, 2018
  • Like
  • 0
Hi,
Please help me with test class


public with sharing class Tenant_ImprovementAfterUpdateHandler  extends TriggerHandlerBase {
    Set<Id> selectedUnitIds = new Set<Id>();
    Set<Id> opportunityIds = new Set<Id>();
    List<Opportunity> opportunityToUpdate = new List<Opportunity>();

    public override void qualifyStartingRecords(List<sObject> newList, List<sObject> oldList, Map<ID, sObject> newMap, Map<ID, sObject> oldMap) {
        for(String tiId : newMap.keySet()) {
            if(newMap.get(tiId).get('Standard_Ti__c') != oldMap.get(tiId).get('Standard_Ti__c')
                || newMap.get(tiId).get('Total_ASTI__c') != oldMap.get(tiId).get('Total_ASTI__c')
                    || newMap.get(tiId).get('Shell_Ti__c') != oldMap.get(tiId).get('Shell_Ti__c')
                        || newMap.get(tiId).get('Make_Ready_Costs__c') != oldMap.get(tiId).get('Make_Ready_Costs__c'))  {
                selectedUnitIds.add((Id)newMap.get(tiId).get('Selected_Unit__c'));
            }
            for(Lease_Analysis_Selected_Unit__c selectedUnit : [SELECT Id, Name, Scenario__c, Scenario__r.Lease_Analysis__c, Scenario__r.Lease_Analysis__r.Opportunity__c FROM Lease_Analysis_Selected_Unit__c WHERE Id =: selectedUnitIds AND Scenario__r.IsPrimary__c = true]) {
                opportunityIds.add(selectedUnit.Scenario__r.Lease_Analysis__r.Opportunity__c);
            }
        }
    }

    public override void start() {
        if(null != opportunityIds && opportunityIds.size() > 0) {
            for(Opportunity opp : [SELECT Id, Name, Forecast_Matrix_Date__c FROM Opportunity WHERE Id =: opportunityIds]) {
                Opportunity opportunity = new Opportunity(Id = opp.Id);
                Boolean needToUpdate = false;
                if(opp.Forecast_Matrix_Date__c == null || opp.Forecast_Matrix_Date__c < System.today()) {
                    needToUpdate = true;
                    opportunity.Forecast_Matrix_Date__c = System.today();
                }
                if(needToUpdate) {
                    opportunityToUpdate.add(opportunity);
                }
            }
        }
    }

    public override void finish(boolean fromStart){
        if(opportunityToUpdate.size() > 0) {
            update opportunityToUpdate;
        }
    }
}

​Thanks
  • September 08, 2018
  • Like
  • 0
Can anyone help with test class


public with sharing class AccountStructure extends Hierarchy
{
    /**
    * Return ObjectStructureMap to page
    * @return asm
    */
    public List<AccountHierarchyNode> getObjectStructure()
    {
        if ( currentId == null ) {
            currentId = System.currentPageReference().getParameters().get( 'id' );
        }
        
        System.assertNotEquals( currentId, null, 'sObject ID must be provided' );
        return formatObjectStructure( CurrentId );
    }

    /**
    * Query Account from top down to build the AccountHierarchyNode
    * @param currentId
    * @return asm
    */
    public List<AccountHierarchyNode> formatObjectStructure( String currentId )
    {
        List<AccountHierarchyNode> accountNodes = new List<AccountHierarchyNode>();
        return (List<AccountHierarchyNode>) generateHierarchy(accountNodes);
    }

    protected override HierarchyNode getAllNodes()
    {
        idToNode.clear();
        List<Account> accounts = new List<Account>();
        List<Id> currentParents         = new List<Id>();
        HierarchyNode topNode           = null;

        Integer level                   = 0;
        Boolean noChildren              = false;
        
        //Find highest level obejct in the structure
        currentParents.add( GetTopElement( currentId ) );

        //Loop though all children
        while ( !noChildren ){

            if( level == 0 ){
                //Change below     
                accounts = [SELECT Type, Site, ParentId, OwnerId, Name, Industry FROM Account WHERE Id IN :currentParents ORDER BY Name];
            } 
            else {
                //Change below      
                accounts = [SELECT Type, Site, ParentId, OwnerId, Name, Industry FROM Account WHERE ParentID IN :currentParents ORDER BY Name];
            }

            if( accounts.size() == 0 )
            {
                noChildren = true;
            }
            else
            {
                currentParents.clear();
                for (Account account : accounts)
                {
                    //Change below
                    HierarchyNode parentNode = idToNode.get(account.ParentId);
                    AccountHierarchyNode node = new AccountHierarchyNode(false, account);
                    idToNode.put(account.Id, node);
                    currentParents.add( account.id );

                    if (parentNode != null)
                        node.setParent(parentNode);
                    else
                        topNode = node;
                }
                
                maxLevel.add( level );
                level++;
            }
        }

        return topNode;
    }
    
    /**
    * Find the tom most element in Heirarchy  
    * @return objId
    */
    public String GetTopElement( String objId ){
        
        Boolean top = false;
        while ( !top ) {
            //Change below
            Account a = [ Select a.Id, a.ParentId From Account a where a.Id =: objId limit 1 ];
            
            if ( a.ParentID != null ) {
                objId = a.ParentID;
            }
            else {
                top = true;
            }
        }
        return objId ;
    }

    public with sharing class AccountHierarchyNode extends HierarchyNode
    {
        public Account account;
        public Account getAccount() { return account; }
        public void setAccount( Account a ) { this.account = a; }

        public AccountHierarchyNode(Boolean currentNode, Account account)
        {
            super(currentNode);
            this.account = account;
        }
    }
}
  • September 03, 2018
  • Like
  • 0
Hi Everyone,
can you please help me with test class
public class AccntExtension {
    public List<AccHierarchy> accountList{get;set;}
    public String chumma{get;set;}
    public Map<id,Account> accMap{get;set;}
    public AccHierarchy hier;
    public AccntExtension(ApexPages.StandardController c){
    accMap= new Map<id,Account>([SELECT (SELECT Name,Market__r.Name,Type,StageName FROM Opportunities) from Account]);
        accountList = new List<AccHierarchy>();
        List<AccHierarchy> chilList = null;
        for(Account acc : accMap.values()){
            if(acc.ParentId == null){
                hier = new AccHierarchy();
                hier.setAccount(acc);
                accMap.remove(acc.id);
                //accountList=
                accountList.add(hier);
                chilList = getChildAccount(acc.id);
                hier.setChildVal(chilList);
                
            }
        }
        system.debug('FinalList'+accountList);
    }
    private List<AccHierarchy> getChildAccount(Id parentId){
        List<AccHierarchy> accList = new List<AccHierarchy>();
        for(Account acc : accMap.values()){
            if(parentId == acc.ParentId){
                accMap.remove(acc.id);
                AccHierarchy hierChd = new AccHierarchy();
                hierChd.setAccount(acc);
                
                accList.add(hierChd);
                List<AccHierarchy> chilList = null;
                chilList = getChildAccount(acc.id);
                hierChd.setChildVal(chilList);
            }
        }
        system.debug('Loop top '+accList);
        return accList;
    }
    
}
  • September 01, 2018
  • Like
  • 0
Hi Everyone,
can you please help me with test class


public without sharing class AccountHelperUtility {
  
   //update account area fields 
    public static void insertUpdateAccountAreaFields(List<Account> AccountList, Map<ID,sObject> AccountMapOld) { 
    for(Account account:AccountList) {
        Account accountOld = AccountMapOld == null ? null : (Account)AccountMapOld.get(account.id);
      populateValuesBeforeInsertUpdate(account, accountOld, 'Planned_Retention_Tsubo__c', 'Planned_Retention_SF__c', 'Planned_Retention_SM__c');
      populateValuesBeforeInsertUpdate(account, accountOld, 'Customer_Total_Footprint_Wallet_Tsubo__c', 'Customer_Total_Footprint_Wallet_SF__c', 'Customer_Total_Footprint_Wallet_SM__c');
    }   
    }
    
    static void populateValuesBeforeInsertUpdate(Account account, Account accountOld, String Tsubo, String SF, String SM) {
        Boolean isUpdate = accountOld == null ? false : true;
      if(account.get(SF) != null && String.valueOf(account.get(SF))!= '' && (!isUpdate || Integer.valueOf(account.get(SF)) != Integer.valueOf(accountOld.get(SF))) ){
        account.put(Tsubo , UOMCalculation.getTsuboFromSf((decimal)account.get(SF)));
        account.put(SM , UOMCalculation.getM2FromSf((decimal)account.get(SF)));
      }else if(account.get(SM) != null && String.valueOf(account.get(SM))!= '' && (!isUpdate || Integer.valueOf(account.get(SM)) != Integer.valueOf(accountOld.get(SM))) ){
          Decimal sqFt = UOMCalculation.getSfFromM2((decimal)account.get(SM));
        account.put(Tsubo , UOMCalculation.getTsuboFromSf(sqFt));
        account.put(SF , sqFt);
      }else if(account.get(Tsubo) != null && String.valueOf(account.get(Tsubo))!= '' && (!isUpdate || Integer.valueOf(account.get(Tsubo)) != Integer.valueOf(accountOld.get(Tsubo))) ) {
          Decimal sqFt = UOMCalculation.getSfFromTsubo((decimal)account.get(Tsubo));
      account.put(SM , UOMCalculation.getM2FromSf(sqFt));
      account.put(SF , sqFt);
      }
    }
    
     //Added for T-131999
    public static void removeTeamMembers(Map<Id,Account> accountNewMap, Map<Id,Account> accountOldMap){
      map<Id,Id> accIdToGCSOfficerMap = new map<Id,Id>();
      list<AccountTeamMember> teamMembersToBeDeleted = new list<AccountTeamMember>();
      for(Account acc : accountNewMap.values()){
        if((acc.GCS_Account_Officer__c != null && 
          acc.GCS_Account_Officer__c != accountOldMap.get(acc.Id).GCS_Account_Officer__c)){
            accIdToGCSOfficerMap.put(acc.Id,acc.GCS_Account_Officer__c);
        }
      }
      if(accIdToGCSOfficerMap.size() > 0 ){
        for(AccountTeamMember accTeamMember : [Select Id,UserId,AccountId from AccountTeamMember where AccountId IN : 
          accIdToGCSOfficerMap.keySet()]){
            if(accTeamMember.AccountId != null && accIdToGCSOfficerMap.containsKey(accTeamMember.AccountId) &&
              accTeamMember.UserId != null && accIdToGCSOfficerMap.get(accTeamMember.AccountId) == accTeamMember.UserId){
                teamMembersToBeDeleted.add(accTeamMember);
              }
        }
      }
      if(teamMembersToBeDeleted.size() > 0){
        delete teamMembersToBeDeleted;
      }
    }
}
  • September 01, 2018
  • Like
  • 0

Hi everyone,
I have written a SQQL query. It is returning records but in some columns, it is showing  [Object Object] .  

Can anyone help me with this query


select Customer__r.Name,CDP_Asset__r.Deal__r.Name, CDP_Asset__r.Market__r.Name, CDP_Asset__r.Deal__r.Type__c,CDP_Asset__r.Deal__r.Stage__c from CDP_Asset_Customer_Account__c where Customer__r.Id IN ('0010B00001kPbx9QAC', '0010B00001nIOI0QAO', '0010B00001qTAG1QAO', '001U000000Ooi35IAB', '001U000000Ooj29IAB', '001U000000oSCeVIAW', '001U000001Tg4OAIAZ', '001U000001XqBrFIAV', '001U000001frl9cIAA')

Result:
User-added image