• Allen2
  • NEWBIE
  • 0 Points
  • Member since 2018

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 32
    Questions
  • 53
    Replies
I've written the below piece of code and called in after update context on lead but doesn't work. Can anyone help me to correct the code.
public class LeadHandler {
    public static void dedupeContactOnLeadConversion(List<Lead> newList,map<id, 
    Lead> oldLeadMap){
        List<String> email = new List<String>();
        List<String> firstName = new List<String>();
        List<String> lastName = new List<String>();
        
        for(Lead objLead: newList){
            if(!String.ISBLANK(objLead.Email) && objLead.IsConverted == false){
                email.add(objLead.Email);
            }
            if(!String.ISBLANK(objLead.FirstName) && objLead.IsConverted == false){
                firstName.add(objLead.FirstName);                
            }
            if(!String.ISBLANK(objLead.LastName) && objLead.IsConverted == false){
                lastName.add(objLead.LastName);   
            }
        }
        
        List<Contact> objContact = [Select Id, Email, FirstName, LastName from Contact where Email in: email OR FirstName in: firstName OR LastName in: lastName];
        
        for(Contact newContact: objContact){
            Database.LeadConvert lc = new Database.LeadConvert();
            lc.setContactId(newContact.Id);
            Database.LeadConvertResult listLeadConvertResult = Database.convertLead(lc, false);
        }
    }
}

I only want to write a trigger which will stop the creation of duplicate contact only when you're converting the lead.
Want to write a trigger on user, so for any user has einstein user package license, if any user of profile other than system admin and standard security is trying to update the user's profile should throw an error.

Also if the profile is changed to the new profile with prefix SM then also should throw the error.
public class errorMsgOnProfileUpdate {
    
    public static void errorMsgOnProfileChange (List<user> userList, Map<id,user> oldMap) {
        profile pf;
        userList = [Select Id, Profile.Name, ProfileId from User where  isActive = TRUE and Profile.UserLicense.LicenseDefinitionKey = 'SFDC' and Id in (SELECT UserID FROM UserPackageLicense WHERE (PackageLicenseId= '050800000004xiQ'))];
        pf = [Select Id, Name from Profile where Name = 'System administrator' or Name = 'Standard Security'];
        if(userList.size() > 0){
            for(User u: userList){
                if(trigger.isUpdate && u.Profile.Name != pf.Name && oldMap.get(u.id).ProfileId != u.ProfileId){
                    u.addError('Only system Administrator and security has access to edit profiles');
                }
            }  
        } 
    }
    
}
Please correct me as I'm gettin the exception error while updating the profile as below:

Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger UserTrigger caused an unexpected exception, contact your administrator: UserTrigger: execution of BeforeUpdate caused by: System.QueryException: Non-selective query against large object type (more than 200000 rows). Consider an indexed filter or contact salesforce.com about custom indexing. Even if a field is indexed a filter might still not be selective when: 1. The filter value includes null (for instance binding with a list that contains null) 2. Data skew exists whereby the number of matching rows is very large (for instance, filtering for a particular foreign key value that occurs many times): ()

 
I've written the below code to update the field on case object when we're getting email to case. But when I tried to write logic to fire case assignment rule based on whatever value we're having in emailMessae.toAddress, it's not working at all.
Public class emailMessageHelper {
    Public static void updateCase (list<EmailMessage> newEmailMessageList, map<Id, EmailMessage> oldMap){
        Set <Id> caseIdSet = new Set <Id>();
        list <Case> caseList = new List <Case>();
        Map<Id, Case> caseMap = new Map<Id, Case>();
        list<Case> newCaseList = new list<Case>();
        
        for (EmailMessage messageObj: newEmailMessageList)
        {
            caseIdSet.add(messageObj.ParentId);
        }
        
        if(caseIdSet.size()>0)
        {
            caseList=[Select Id, OwnerId, Owner.Email, Status, status_Alert__c from case where Id in :caseIdSet];
            for(case caseObj: caseList)
            {
                caseMap.put(caseObj.Id,caseObj);
            }
        }
        for (EmailMessage messageObj: newEmailMessageList){  

            Case caseObj = caseMap.get(messageObj.ParentId);
            caseObj.Source_Email__c = MessageObj.ToAddress;
            System.debug('messageObj.ToAddress abc '+messageObj.ToAddress);
            if(caseObj.status !='New' && caseObj.Status_Alert__c != 'New Email Received' && messageObj.incoming && messageObj.toAddress!= null ){
                caseobj.status_Alert__c = 'New Email received';                
               
                Database.DMLOptions dmlOpts = new Database.DMLOptions();
                dmlOpts.assignmentRuleHeader.useDefaultRule= true;
                caseobj.setOptions(dmlOpts); 
                
                newCaseList.add(caseObj);                
            }          
            else if(!messageObj.incoming){
                caseobj.status_Alert__c = '';
                newCaseList.add(caseObj);
            }
        }
        if(newCaseList.size() > 0){
            update newCaseList;
        }        
    }
}
I'm calling the method in After insert and After update context.
Can any one please help me out on this?
 
  • April 09, 2020
  • Like
  • 0
I've written the below code to update the field on case object when we're getting email to case. But when I tried to write logic to fire case assignment rule based on whatever value we're having in emailMessae.toAddress, it's not working at all.
Public class emailMessageHelper {
    Public static void updateCase (list<EmailMessage> newEmailMessageList, map<Id, EmailMessage> oldMap){
        Set <Id> caseIdSet = new Set <Id>();
        list <Case> caseList = new List <Case>();
        Map<Id, Case> caseMap = new Map<Id, Case>();
        list<Case> newCaseList = new list<Case>();
        
        for (EmailMessage messageObj: newEmailMessageList)
        {
            caseIdSet.add(messageObj.ParentId);
        }
        
        if(caseIdSet.size()>0)
        {
            caseList=[Select Id, OwnerId, Owner.Email, Status, status_Alert__c from case where Id in :caseIdSet];
            for(case caseObj: caseList)
            {
                caseMap.put(caseObj.Id,caseObj);
            }
        }
        for (EmailMessage messageObj: newEmailMessageList){  

            Case caseObj = caseMap.get(messageObj.ParentId);
            caseObj.Source_Email__c = MessageObj.ToAddress;
            System.debug('messageObj.ToAddress abc '+messageObj.ToAddress);
            if(caseObj.status !='New' && caseObj.Status_Alert__c != 'New Email Received' && messageObj.incoming && messageObj.toAddress!= null ){
                caseobj.status_Alert__c = 'New Email received';                
               
                Database.DMLOptions dmlOpts = new Database.DMLOptions();
                dmlOpts.assignmentRuleHeader.useDefaultRule= true;
                caseobj.setOptions(dmlOpts); 
                
                newCaseList.add(caseObj);                
            }          
            else if(!messageObj.incoming){
                caseobj.status_Alert__c = '';
                newCaseList.add(caseObj);
            }
        }
        if(newCaseList.size() > 0){
            update newCaseList;
        }        
    }
}

I'm calling the method in After insert and After update context.
Can any one please help me out on this?
 
  • April 08, 2020
  • Like
  • 0
I was having one custom button with JS code as below:
{!requireScript("/soap/ajax/30.0/connection.js")}
{!requireScript("/soap/ajax/30.0/apex.js")}

var opp = new sforce.SObject("Opportunity");
opp.id = "{!Opportunity.Id}";

try {

opp.isStatus = true;

var optresult = sforce.connection.update([opp]);
if(optresult[0].success=='false') {
alert(optresult[0].errors.message);
} else {

sforce.apex.execute('populateOpportunity', 'automatePopulatingOpp', {optyId:'{!Opportunity.Id}', action:'Default'});

alert('{!$Label.SuccessMsg}');
}
} catch(err) {
alert(err.message);
}
document.location = '/{!Opportunity.Id}';

I'm new to vf page implementation. I need to replace this JS with Vf page. I've written below vf page and custom controller.

VF Page
<apex:page standardController="Opportunity"  showHeader="false" extensions="oppController" >   
    <head>
        <style type='text/css'>
            .popupBackground{
            left: 20%;
            color:red;
            position: fixed;
            width: 450px;
            height: 100px;
            margin-left: -200px;
            top: 50px;
            }
            .popupBackground .close{
            position: absolute;
            background:#008CBA;
            color: white;
            bottom: 0;
            right: 10px;
            font-size: 10px;
            text-decoration: none;
            width:50px;
            }
        </style>
    </head>
    
    <apex:form rendered="{!showSuccessMsg}" id="opp">
        <apex:pageMessages id="errmsg"></apex:pageMessages> 
        <body onload="init();">
            <apex:outputPanel styleClass="popupBackground"  >
                <center>
                    <apex:outputText value="{!$Label.SuccessMsg}" escape="false"/>
                    <apex:commandButton value="OK" styleClass="close" onclick="parent.window.close();"/>
                </center>
            </apex:outputPanel>
        </body>
    </apex:form> 
</apex:page>

Custom Controller
public class oppController {
    public Id oppId;
    public Boolean showSuccessMsg{get;set;}
    public Boolean showErrorMsg{get;set;}
    
    public opptController(){
        showSuccessMsg = true;
        showErrorMsg = false;
        
        if(oppId != NULL){
            Opportunity opp = new Opportunity(Id = oppId);
            opp.isStatus = true;
            try{
                update opp;
                populateOpportunity.automatePopulatingOpp(oppId,'Default');
                showSuccessMsg = true;
                showErrorMsg = false;
                Error.LogSuccess(Label.SuccessMsg);
            }catch(Exception e){
                showSuccessMsg = false;
                showErrorMsg = true;
                Error.LogException(e);
            }
            showSuccessMsg = true;
            showErrorMsg = false;
            Error.LogSuccess(Label.SuccessMsg);
        }        
    }
}

Can anyone please help me out to correct this?
  • March 31, 2020
  • Like
  • 0
I've in build the lightning component and created a buttoon like below:
<div class="okButtonClass">
            <aura:if isTrue="{!!v.showSpinner}">
            <ui:button label="OK" press="{!c.okBtn}"/>
            </aura:if>
        </div>
Here is the controller.js file of lightnign component:
okBtn : function(component, event, helper) {
        // Close the action panel
        var dismissActionPanel = $A.get("e.force:closeQuickAction");
        dismissActionPanel.fire();
    }

Applied css as well but not able to change the background color and text color of button. Here us the css file:
 

.THIS .okButtonClass{
    position: relative;
    display: inline-block;
    float: right;
    background-color: #008CBA;
    color: white;
}

Created the lightning application:
 

<aura:application extends="ltng:outApp" access="GLOBAL" >
	<aura:dependency resource="c:OpportunityContainer"/>
</aura:application>
Below is my vf page:
<apex:page standardController="Opportunity"  showHeader="false">   
    <apex:includeLightning />
    <div id="lightning">
        <script>
        $Lightning.use("c:OppButtonApp", function(){
            $Lightning.createComponent("c:OpportunityContainer",{"recordId":"{!$CurrentPage.parameters.id}"},
                                       "lightning",function(cmp){
                                       });
        });
        </script>
    </div>
</apex:page>

I'm calling this vf page through one custom button and working fine.

But once we are clicking on the button created in lightning component through this vf page it's showing the below error:

This page has an error. You might just need to refresh it. Action failed: c:OpportunityContainer$controller$okBtn [Cannot read property 'fire' of undefined] Failing descriptor: {c:OpportunityContainer$controller$okBtn}

User-added image
Once we're clicking on this OK button on page it's throughing error. It's not able to find the controller.js.

Please anyone can help me to short out this error?
  • March 29, 2020
  • Like
  • 0
Scenario:
When the owner of an Account is changed, check to see the Division of the new owner of the Account. If it is "Regional Sales", perform the following changes 
Fo the Account, check the Open Opportunities that are owned by the previous owner of the Account, for each Open Opportunity set the owner to be the new owner of the Account 
For the Account, check each Contact that is owned by the previous owner of the Account and set the owner to be the new owner of the Account


Apex Class:
public class AccountHandler (){
    public static void updateOwner(List<Account> newAccountList, Map<Id, Account> oldMap){
        Set<Id> accountIds = new Set<Id>();
        List<opportunity> oppList = new List<opportunity>();
        List<contact> conList = new List<contact>();
        List<Account> AccountList = new List<Account>();
        
        User usr = [Select Id, Division from User where isActive = true and Division = 'Regional Sales'];
        
        for(Account acc : newAccountList) {
            if(trigger.IsUpdate && oldMap!=null && oldMap.get(acc.Id).OwnerId != acc.OwnerId && acc.OwnerId == usr.Id){
                accountIds.add(acc.Id);
            }                               
        }
        
        if(!accountIds.IsEmpty()){
            AccountList = [Select Id, OwnerId, Owner.Division from Account where Id =: accountIds];
            for(Account acc : AccountList){
                Opportunity opp = new Opportunity();
                opp.AccountId = acc.Id;
                opp.OwnerId = acc.OwnerId; 
                oppList.add(opp);
                
                Contact con = new Contact();
                con.AccountId = acc.Id;
                con.OwnerId = acc.OwnerId;
                conList.add(con);
            } 
        }
        if(oppList.size() > 0){
            update oppList;
        }
        if(conList.size() > 0){
            update conList;
        }
    }
}

Apex Trigger:
trigger AccountTrigger on Account (after insert, after update, before delete) {
    if(Trigger.isUpdate && Trigger.isAfter){
        AccountHandler.updateOwner(Trigger.New, Trigger.OldMap);
    }
}
  • December 21, 2019
  • Like
  • 0
BATCH CLASS

global class Chatterpostsbatch implements Database.batchable<sObject> {

global String queryOpps;

global Chatterpostsbatch(String query){
  queryOpps=query;
  system.debug(queryOpps);
}

global Database.QueryLocator start(Database.BatchableContext bc)
  {
    system.debug(queryOpps);
      return Database.getQueryLocator(queryOpps);
    }
    
    global void execute(Database.BatchableContext bc, List<SObject> lstOpps)
  {
    set<Id> setOppIds = new set<Id>();
    List<EntitySubscription> followers = new List<EntitySubscription> ();
    
    for(SObject o : lstopps)
    {
      setOppIds.add(o.Id);
    }
    if(!setOppIds.Isempty()){   
      System.debug(setOppIds);
        followers =  [select id from EntitySubscription
            where parentid in: setOppIds];
    }
        if(!followers.Isempty()){                    
        delete followers;
        }                  
  }
  
  global void finish(Database.BatchableContext bc)

  {
    //Mail notification...
    //empty;
  }
}

TEST CLASS

@isTest

private class TestClassChatterPosts {
    
    static testMethod void testChatterPostsScheduled() 
    {
        Test.StartTest();
        Chatterpostsschedule cp = new Chatterpostsschedule();
        datetime currentDateTime = datetime.now();
        String min = String.valueOf(math.mod((currentDateTime.minute() + 1),60));
        String schExp = '0 '+ min +' * * * ? ';
        system.schedule('ChatterPost - ' + system.now().format(), schExp, cp);     
        Test.StopTest();
    }
    
    static testMethod void testChatterPostsBatch() 
    {
        //String queryOpps = 'select Id from Opportunity where IsClosed=true and CloseDate <= LAST_N_DAYS:30 limit 1';
        CustomSettingCreation.SettingData();
        
        Account acc = new Account(Name = 'Test');
        insert acc;
        
        Opportunity opp = new Opportunity();        
        opp.name = 'Test';
        opp.AccountId = acc.id;
        insert opp;
        
        EntitySubscription ens = new EntitySubscription();
        insert ens;
        
        Test.StartTest();
        
        String opps = opp.name;
        Chatterpostsbatch   obj = new  Chatterpostsbatch('Test');
        Database.executeBatch(obj);
        
        Test.StopTest();
    }
}

The second method is failing at the place created the instance of the batch. The bold and underlined part unable to cover. Please someone help me to correct it....
  • September 03, 2019
  • Like
  • 0
APEX CLASS
trigger AvoidDuplicateUsageEntry on Amendment__c (before insert) 
{
    for (Amendment__c amendment: Trigger.new)
    {
        if (amendment.Override_Warning__c == false)
        {
            try
            {
              Amendment__c[] a = [SELECT a.CreatedById, a.CreatedDate, a.Amendment__c from Amendment__c a where a.Resp__c = :amendment.Resp__c and a.LSD__c = :amendment.LSD__c ORDER BY CreatedDate desc];
              if (a.size() > 0)
              {
                  User u = [SELECT u.Name from User u where id = :a[0].CreatedById];
                  String amendmentStr = String.escapeSingleauotes(a[0].Amendment__c);
                  amendmentStr = amendmentStr.replace('\"', '\\\"');
                  String userStr = String.escapeSingleauotes(u.Name);
                  userStr = userStr.replace('\"', '\\\"');
                  String dateStr = a[0].CreatedDate.format('MM/dd/yyyy hh:mm a');
                  String errorJSON = 'var errorJSON = {timesUsed: ' + a.size() + ', amendment: \"' + amendmentStr + '\", user: \"' + userStr + '\", time: \"' + dateStr + '\"};';  
                  amendment.Resp__c.addError(errorJSON);
              } // endif
            }
            catch (aueryException e)
            {
            }
        } // endif
    } // endfor

}

TEST CLASS
@isTest
public class test_Test {
    
    static testMethod void avoidDuplicateEntryTest() {
        
        Profile p = [select id from profile where name='System Administrator'];
        User u = new User(alias = 'standt', email = 'standarduser@testorg.com', emailencodingkey = 'UTF-8', lastname = 'Testing', languagelocalekey = 'en_US',
                          localesidkey = 'en_US', profileid = p.Id, timezonesidkey = 'America/Los_Angeles',
                          username = 'testclassuser@testorg.com');
        insert u;
        
        System.runAs(u){
            Test.startTest();
            Resp__c resp = new  Resp__c();
            resp.status__c = 'Draft';
            insert resp;
            
            LSD__c ref = new  LSD__c();
            ref.Due_Date__c = system.today();
            insert ref;
            
            list <Amendment__c> as = new list <Amendment__c>();
            Amendment__c amend = new Amendment__c();
            amend.Override_Warning__c = False;
            amend.LSD__c = ref.Id;
            amend.Resp__c = resp.Id; 
            amend.Amendment__c = 'TestText';
            amend.CreatedById = u.Id;
            as.add(amend);
            
            Amendment__c amend1 = new Amendment__c();
            amend1.Override_Warning__c = False;
            amend1.LSD__c = ref.Id;
            amend1.Resp__c = resp.Id; 
            amend1.Amendment__c = 'TestText1';
            amend1.CreatedById = u.Id;
            as.add(amend1);
            insert as;
            
            system.debug('size' + as.size());
            Test.stopTest();
        }      
    }          
}

I am not able to cover the bold & underlined part of my apex class. I am inserting the list in my test class but while debugging I m not getting any value in the list in my test class so unable to cover the rest of the part.

Could anyone can help me in this what is wrong I am doing here.. Please....
  • August 29, 2019
  • Like
  • 0
APEX CLASS
public with sharing class ccController {
    public String firstName {get; set;}
    public String lastName {get; set;}
    public String email {get; set;}
    public String password {get; set {password = value == null ? value : value.trim(); } }
    public String confirmPassword {get; set { confirmPassword = value == null ? value : value.trim(); } }
    public String communityNickname {get; set { communityNickname = value == null ? value : value.trim(); } }    
    public ccController() {}    
    private boolean isValidPassword() {
        return password == confirmPassword;
    }
    public PageReference registerUser() {    
           // it's okay if password is null - we'll send the user a random password in that case
        if (!isValidPassword()) {
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, Label.site.passwords_dont_match);
            ApexPages.addMessage(msg);
            return null;
        }    
        String profileId = null; // To be filled in by customer.
        String roleEnum = null; // To be filled in by customer.
        String accountId = ''; // To be filled in by customer.        
        String userName = email;
        User u = new User();
        u.Username = userName;
        u.Email = email;
        u.FirstName = firstName;
        u.LastName = lastName;
        u.CommunityNickname = communityNickname;
        u.ProfileId = profileId;        
        String userId = Site.createPortalUser(u, accountId, password);     
        if (userId != null) { 
            if (password != null && password.length() > 1) {
                return Site.login(userName, password, ApexPages.currentPage().getParameters().get('startURL'));
            }
            else {
                PageReference page = System.Page.ccPage;
                page.setRedirect(true);
                return page;

            }
        }
        return null;
    }
}

TEST CLASS

/**
* An apex page controller that supports self registration of users in communities that allow self registration
*/
@IsTest
public with sharing class ccControllerTEst {
    
    static testmethod void testCCController() {
        Account acc = new Account(Name = 'Test');
        insert acc;
        
        Profile p = [select id from profile where name='System Administrator'];
        User u = new User(alias = 'standt', email = 'standarduser@testorg.com', emailencodingkey = 'UTF-8', lastname = 'Testing', languagelocalekey = 'en_US',
                          localesidkey = 'en_US', profileid = p.Id, timezonesidkey = 'America/Los_Angeles',
                          username = 'testclassuser@testorg.com');
        insert u;
        
        ccController controller = new ccController();
        controller.firstName = 'FirstName';
        controller.lastName = 'LastName';
        controller.email = 'test@force.com';
        controller.communityNickname = 'test';
        // registerUser will always return null when the page isn't accessed as a guest user
        System.assert(controller.registerUser() == null); 
        
        controller.password = 'abcd1234';
        controller.confirmPassword = 'abcd123';
        System.assert(controller.registerUser() == null); 
        //String userId = Site.createPortalUser(u, acc.Id, controller.password);
        
    } 
}
  • August 06, 2019
  • Like
  • 0
Created two field (data type-picklist) on the opportunity and have to make the fields mandatory when advancing a F S opportunity beyond Stage 2.  Make mandatory for the profile F S S R and F S S M only. 

for this scenario have to create a validation rule. Please help me out for this..
 
and if the scenario will be changed to 

According to the above scenario 2 fields (data type-picklist) should be mandatory based on the user profile (F S S R or F S S M).  Instead we would like the validation rule to be if the Sales Occupy (a picklist field on opportunity) = Field Sales, then the 2 fields are mandatory. 
 
please help me to write the validation rule for both the scenarios...

Thank you!!
  • February 08, 2019
  • Like
  • 0
APEX TRIGGER
trigger Updatequickcontact on Case (after insert,after update) 
{
 if(IsUtil.adminByPass()) return;
// Bypass if dealer flag being updated
if(ClsStaticVariables.isUpdatingDealerFlag) return;
   {
    list<case> caslist1= new list<case>();
    list<id> casids= new list<id>();

    for(case cas :trigger.new)
    {
        if(Trigger.isInsert){
        if(cas.recordtypeid ==System.Label.RecordtypeId_of_NonserviceCase && 
        cas.Area__c == 'Billing'&&
         cas.SubArea__c == 'Credit Note')

           casids.add(cas.Id);
        }
         if(Trigger.isUpdate){
        if(cas.recordtypeid ==System.Label.RecordtypeId_of_NonserviceCase && 
        cas.Area__c == 'Billing' && (Trigger.oldMap.get(cas.id).Area__c  != 'Billing') &&
         cas.SubArea__c == 'Credit Note' && (Trigger.oldMap.get(cas.id).SubArea__c  != 'Credit Note'))

           casids.add(cas.Id);
        }
    }
     if(casids.size() > 0)
         caslist1=[select id,AccountId,Account.Billingcountry,ownerid from Case where id in: casids];
       
    List<Country_Mapping__c> couns = Country_Mapping__c.getall().values();
    List<task> tasklist = new List<task>();
    system.debug('ssssssss'+caslist1.size());
    String finalcoun;
    for(case cc : caslist1)
    {
        system.debug('bbbbbbbbbbbb'+cc.Account.Billingcountry);
        if(cc.Account.Billingcountry != null)
            finalcoun = (cc.Account.Billingcountry).toUppercase();
        for(Country_Mapping__c cs: couns)
        {
             system.debug('vvvvvv'+cs.PBCCC_Country__c);
             if(finalcoun != null)
             {
                if(finalcoun.contains(cs.PBCCC_Country__c))
                {
                    task kk =new task();
                    kk.whatid = cc.id;
                    kk.ownerid = cc.ownerid;
                    kk.Subject='Credit Note';
                    kk.RecordTypeid=System.Label.Task_Recordtpeid;
                    kk.Assign_To_Team__c = cs.PBCCC_Group_name__c;
                    kk.Assign_To_Team_check__c = false;
                    tasklist.add(kk);

                }
             }
        }
    }
    system.debug('vvvvvv'+tasklist.size());
    insert tasklist;
   }
}

TEST CLASS
@isTest
private class Updatequickcontact_Test{
  static testMethod void testUpdatequickcontact()
  {
    account a1 = new account(name='test account',Billingcountry = 'DENMARK');
    insert a1;

    contact con1 = new contact(accountid=a1.id,Phone='12345',lastname='test');
    insert con1;
    
    Id caseRecdTypeId = Schema.SObjectType.case.getRecordTypeInfosByName().get('Technical').getRecordTypeId();
    List<Country_Mapping__c> couns = Country_Mapping__c.getall().values();
    List<Case> caseList = new List<Case>();
        
        case c1 = new case(
        AccountId = a1.Id,
        ContactId = con1.id,
        status = 'new',
        //Area__c='Collections',
        Categories__c = 'Low/Medium Volume Mailing',
        Reasons__c = 'Error Codes',
        Sub_Reason__c = 'Bug Buddy',
        recordtypeid = caseRecdTypeId,
        //SubArea__c='Acceptance',
        Country__c = 'DENMARK');
    caseList.add(c1);
        
        case c2 = new case(
            AccountId = a1.Id,
            ContactId = con1.id,
            status = 'new',
            Area__c = 'Billing',
            Categories__c = 'Low/Medium Volume Mailing',
            Reasons__c = 'Error Codes',
            Sub_Reason__c = 'Bug Buddy',
            SubArea__c = 'Credit Note',
            RecordTypeId = caseRecdTypeId, 
            Country__c = 'DENMARK');
        caseList.add(c2);
    
        insert caseList;
    Test.startTest();
      task t1 = new task(Assign_To_Team__c = 'Group',
      Subject = 'meeting',
      Status = 'Not Started',
      Priority = 'Medium');
      insert t1;
      
      c1.recordtypeid = caseRecdTypeId;
      c1.Reasons__c = 'Error Codes';
      c1.Sub_Reason__c = 'Bug Buddy';
      update c1;
    Test.stopTest();
  }
}

bold, underlined part of trigger unable to cover... please help me..
  • January 01, 2019
  • Like
  • 0
We have two lookup field on user object manager and oManager... so the scenario is for the oManager != null, if  oManager is not changed and not equal to manager then it should update the manager field as whatever value we are enterling in the lookup field oManager
and 
if anytime updating the manager name then it should auto reflect to oManager also.......

please help me to write the trigger for this scenario...
I was always confused to write the trigger... but I think it should be before insert and before update....
 
  • December 07, 2018
  • Like
  • 0
APEX CLASS
public class Async_SFDCtoNextNotifyC {
    public class NotifyCRespFuture extends System.WebServiceCalloutFuture {
        public SFDCtoNextNotifyC.NotifyCResType getValue() {
            SFDCtoNextNotifyC.NotifyCResType response = (SFDCtoNextNotifyC.NotifyCResType)System.WebServiceCallout.endInvoke(this);
            return response;
        }
    }
    public class AsyncSOAPOverHTTPs_0 {
        public String endpoint_x = 'https://nextb-dev.abb.com:443/CommonInterface/Customer-2.0';
        public Map<String,String> inputHttpHeaders_x;
        public String clientCertName_x;
        public Integer timeout_x;
        private String[] ns_map_type_info = new String[]{'https://nextb.abb.com/CommonInterface/Customer-2.0', 'SFDCtoNextNotifyC'};
        public Async_SFDCtoNextNotifyC.NotifyCRespFuture beginNotifyC(System.Continuation continuation,SFDCtoNextNotifyC.NotifyCReqType[] notifyC) {
            SFDCtoNextNotifyC.NotifyCType request_x = new SFDCtoNextNotifyC.NotifyCType();
            request_x.notifyCustomer = notifyCustomer;
            return (Async_SFDCtoNextNotifyC.NotifyCRespFuture) System.WebServiceCallout.beginInvoke(
              this,
              request_x,
              Async_SFDCtoNextNotifyC.NotifyCRespFuture.class,
              continuation,
              new String[]{endpoint_x,
              'notifyCAction2_0',
              'https://nextb.abb.com/CommonInterface/Customer-2.0',
              'notifyCustomersRequest',
              'https://nextb.abb.com/CommonInterface/Customer-2.0',
              'notifyCustomersResponse',
              'SFDCtoNextNotifyC.NotifyCResType'}
            );
        }
    }
}

TEST CLASS
@isTest
public class Async_SFDCtoNextNotifyCTest {
    
    static testmethod void NotifyCus(){
        Test.setMock(WebServiceMock.class, new NotifyCMock());
        new Async_SFDCtoNextNotifyC.AsyncSOAPOverHTTPs_0();
        new Async_SFDCtoNextNotifyC.NotifyCRespFuture();
    }
}

MOCK CLASS
@isTest
global class NotifyCMock implements WebServiceMock {
    
    global void doInvoke(
           Object stub,
           Object request,
           Map<String, Object> response,
           String endpoint,
           String soapAction,
           String requestName,
           String responseNS,
           String responseName,
           String responseType) {
               
        Async_SFDCtoNextNotifyC.AsyncSOAPOverHTTPs_0 response_x = new Async_SFDCtoNextNotifyC.AsyncSOAPOverHTTPs_0();
        SFDCtoNextNotifyC.NotifyCResType response1 = new SFDCtoNextNotifyC.NotifyCResType();
        
        response.put('response_x', response_x);
           }
}
  • November 28, 2018
  • Like
  • 0
public class ProReqClass 
{
    public String checkPro(Opportunity[] old_oppValue,Opportunity[] new_oppValue)
    {
        String message='';
        List<OpportunityLineItem> oppProductList = new List<OpportunityLineItem>();
        Set<Id> priceBookEntryIds = new Set<Id>();
        Set<String> productName = new Set<String>();
        Set<String> stagNames = new Set<String>();
        stagNames.add('5. Prove');
        stagNames.add('6. Negotiate');
        stagNames.add('7. Contract');
        stagNames.add('8. Won');
        stagNames.add('4. Negotiate');
        stagNames.add('5. Closed Won');
        
        try
        {
            if(new_oppValue[0].RecordTypeId !=null)
            {
                 List<RecordType> rtypes = [Select Name, Id From RecordType where sObjectType='Opportunity' and isActive=true and Id=:new_oppValue[0].RecordTypeId];
                 if (rtypes.size()==1)
                 {    
                    if((rtypes[0].Name == 'AB Opportunity') && stagnames.contains(new_OppValue[0].StageName))
                    {   
                        oppProductList = [Select Id, PriceBookEntryId, OpportunityId, Source__c, Custom_Hardware_or_Software__c, Service__c, Input__c, Envelope_Finishing_System__c, Selective_Opener_Inbound_Only__c, OCR_Reading__c, Inline_Scale_or_Meter__c, Retrofit__c, Status__c from OpportunityLineItem where OpportunityId=:new_oppValue[0].Id];
                        if(oppProductList.size() > 0)
                        {                         
                            for (integer i=0; i<oppProductList.size(); i++)
                            {                         
                                if(oppProductList[i].Source__c ==null || oppProductList[i].Custom_Hardware_or_Software__c ==null || oppProductList[i].Service__c==null || oppProductList[i].Input__c==null || oppProductList[i].Envelope_Finishing_System__c == null || oppProductList[i].Selective_Opener_Inbound_Only__c ==null ||oppProductList[i].OCR_Reading__c == null || oppProductList[i].Inline_Scale_or_Meter__c ==null || oppProductList[i].Retrofit__c ==null || oppProductList[i].Status__c==null)
                                {                             
                                    priceBookEntryIds.add(oppProductList[i].PriceBookEntryId);
                                }
                            }
                            if(priceBookEntryIds.size()>0)
                            {  
                                List<PricebookEntry> productIdsList = new List<PricebookEntry>();
                                productIdsList = [select Name from PricebookEntry where id in :priceBookEntryIds];                      
                                if(productIdsList.size()>0)
                                {                             
                                    for (Integer j=0;j<productIdsList.size();j++)
                                    {
                                        message+=productIdsList[j].Name+',';                                     
                                    }
                                    return message;
                                }
                                else
                                {
                                    return message;
                                }                                                                               
                            }
                            else
                            {                                 
                                return message;
                            }
                        }
                        else
                        {                             
                            return message;
                        }
                    }
                    else
                    {                         
                        return message;
                    }
                 }
                 else
                 {                     
                    return message;
                 }            
            }
            else
            {                  
                return message;
            }
        }
        Catch(Exception e)  
        {
            System.debug('While Processing:'+e.getMessage());
            return message;
        }
    }
}
  • November 26, 2018
  • Like
  • 0
APEX CLASS

global class S_BchICaseG implements Database.Batchable<sObject> , Schedulable {
    
    public static final String sysGenerated = 'System Generated';
    public static final String instalOrDeInstall = 'Install/De-Install';
    public static final String fieldService = 'Field Service';
    
     public static final List<String> IPre = new list<String> { 'S self install' , 'S self deinstall' };
 
    List<String> LstCo = System.Label.List_Of_Co.split(',');
    
    global void execute(SchedulableContext sc) {

        S_BchICaseG batch = new S_BchICaseG();
        system.debug('batch executed');
        Database.executeBatch(batch, 1);
    }

  
    global Database.Querylocator start(Database.BatchableContext BC){
       
        String query = 'Select ID, P_Case_Cr_Trig__c, S_Pt_Case_Cre_Trig__c, P_Mn_Itm__c, S_Case_Cate__c, S_Tk_Ref__c, S_Carrier__c, S_Pt_Case_No__c, S__Contact__c, P_DelNo__c From S__Inst_Pd__c WHERE P_Case_Cr_Trig__c  = true And S_Pt_Case_Cre_Trig__c = false And P_Mn_Itm__c = true And (S_Case_Cate__c != null Or S_Case_Cate__c != \'\') AND S_Case_Cate__c NOT IN : IPre ';
        Obj_Lkd__c CS = Obj_Lkd__c.getOrgDefaults();        
        if (CS != null && CS.Lk_JBch_Int__c && !LstCo.isEmpty())
        {
            query = query +' AND S__Site__r.S__Account__r.Country_I2__c NOT IN :LstCo ORDER BY lastmodifieddate asc ';
        }
        Else
        {
            query = query +' ORDER BY lastmodifieddate asc ';
        }

        system.debug('query picked up the records');
        return Database.getQueryLocator(query);    
    }
    
    global void execute(Database.BatchableContext BC,List <sObject> scope)
    {
        List<Case> newCaseList = new List<Case>();
        String tsId = Case_RecordType__c.getInstance(P_Constant.NameTech_Sup).Id__c;
        Boolean isException = false;
        system.debug('Execute method');
        
        if(System.Now().minute() > 56 && System.Now().minute() < 59 && !Test.isRunningTest())
          System.abortJ(bc.getJId());
        
        for (S__Inst_Pd__c ip : (List<S__Inst_Pd__c>) scope)
        {
        system.debug('Entered for loop for case creation');
            Case caseRec = new Case();
            caseRec.S_Cs_Carrier__c = ip.S_Carrier__c;
            caseRec.Categories__c = fieldService;
            caseRec.S__Compo__c = ip.Id;
            caseRec.ContactId = ip.S__Contact__c;
            caseRec.Inst_Del_No__c = ip.P_DelNo__c;
            caseRec.PrntId = ip.S_Pt_Case_No__c;
            caseRec.Pu_Ord__c =  instalOrDeInstall ;
            caseRec.Reasons__c = sysGenerated; 
            caseRec.RecordTypeId = tsId ;
            caseRec.Su_Rsn__c = ip.S_Case_Cate__c;
            caseRec.S_Cs_Tk_Ref__c = ip.S_Tk_Ref__c;            
            caseRec.Subject = Label.P_Cs_Sub_&_Desc_Fr_Gb;
            caseRec.Description = Label.P_Cs_Sub_&_Desc_Fr_Gb;
            newCaseList.add(caseRec);
            
            ip.P_Case_Cr_Trig__c = false;
            ip.S_Carrier__c = '';
            ip.S_Tk_Ref__c = '';
        }
        
        SMWUtils.inBatchMode = true;
        System.debug('Begining of case creation');
        try{
            insert newCaseList;
        }catch (Exception e){
            system.debug('Exception Caught :'+e);
            system.debug('Exception in batch class S_BchICaseG - '+e.getMessage());
            isException=true;
        }
        System.debug('End of case creation :'+scope +isException);
        if(!isException)
            update scope; 
            System.debug('Exit of Case creation');       
    }

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

TEST CLASS


@isTest
private class S_BchICaseG_test {

    static testMethod void myUnitTest() {
        
        Product2 prod = new Product2(Name = 'Test');
        insert prod;
        
        S__Site__c site = new S__Site__c(
            Name = 'Test',
            S__Country__c = 'United Kingdom'
        );
        
        insert site;
        List<Case_RecordType__c> CaseRecordTypedata=P_TstDataFactory.crCustomSettingdataCase();
        if(!CaseRecordTypedata.isEmpty())
            insert CaseRecordTypedata;
       
        List<S__Inst_Pd__c> ipList = new List<S__Inst_Pd__c>();
        
        S__Inst_Pd__c ip = new S__Inst_Pd__c(
            Name = 'test', 
            P_CS_CrTRIG__c = true, 
            P_CS_CrTRAN_CD__c = '01',
            S__Site__c = site.Id,
            P_Sls_Org__c = 'DMT'
        );
        ip.P_Case_Cr_Trig__c = true;
        ip.S_Pt_Case_Cre_Trig__c = false;
        ip.P_Mn_Itm__c = true;
        ip.S_Case_Cate__c = 'S install';
        
        ipList.add(ip);
        
        insert ipList;

        Test.startTest();     
        
        try{
            S_BchICaseG batch = new S_BchICaseG();
            Database.executeBatch(batch);
        }catch(Exception e){
            System.debug('##### Exception ######'+e.getMessage());
        }
  
        Test.stopTest();       
    }
}

the bold italic and underlined part is not able to cover please help me out to cover this code.....
  • August 23, 2018
  • Like
  • 0
public class Sendp_SubsCToFu {       
    
    public MRes getRows (String sField, String sValue) {
            HttpResponse response;
            String[] eId;
            
            if(sField == 'AN') {
              response = makeGetCallout('anp', sValue);
              sValue = '';
            }
            else if(sField == 'ExternalId') {
                eId = sValue.split(':');
                response = makeGetCallout('conId', eId[0]);
            }
            // Parse the JSON response and populate the rows.
            System.debug('response'+response.getBody());
            MRes resp = (MRes)JSON.deserialize(response.getBody(), MRes.class);                       
            System.debug('resp'+resp); 
            return resp;        
        }       
        
        private HttpResponse makeGetCallout(String sAttr, String sValue) {
        P_Int_Details__c int = P_Int_Details__c.getValues('Saas');
            HttpRequest req = new HttpRequest();
            req.setHeader('Content-Type', int.Interface_Title__c);
            req.setHeader('Authorization', 'Basic ' + EncodingUtil.base64Encode(Blob.valueOf(int.Username__c+':'+int.Password__c)));
            req.setEndpoint(int.End_Point_URL__c+'&'+ sAttr + '=' + sValue ); 
            req.setMethod(int.Http_Method__c);
            req.setTimeout(Integer.valueOf(int.Timeout__c));
            HttpResponse res =new Http().send(req);
            return res;
        }
}
  • August 08, 2018
  • Like
  • 0
public class PageCountroller {
   
    public static List<SubscriptionResponse> subResList {get;set;}
    Public String Id;
    Public String Bpn {get; set;}
    Public boolean showSection {get; set;}

    Public PageCountroller() {
        Id = ApexPages.currentPage().getParameters().get('Id');
        system.debug('**********GettingCurrentPageAccountId'+Id);
        subResList = getSaasSubscription(Id);
        Bpn = [SELECT Name, AccountNumber FROM Account WHERE Id = :Id limit 1].AccountNumber;
    }
    
    public static List<SubscriptionResponse> getSaasSubscription(Id accountId) {
        
        SendS_SubscriptionC.MDMResponse responseFromMDM;
        String bpn = [SELECT Name, AccountNumber FROM Account WHERE Id = :accountId limit 1].AccountNumber;
        SendS_SubscriptionC saasCall = new SendS_SubscriptionC();     
        
        if(!String.isBlank(bpn)){
            responseFromMDM = sCall.getRowsByFilter('BPN',bpn );
            system.debug('*************ResponseFRomMDM'+ responseFromMDM);        
            return (processResponce(responseFromMDM));
        }
        else{
                return null;
            }
    }
    private static List<SubscriptionResponse> processResponce(SendS_SubscriptionC.MDMResponse response){
        List<SubscriptionResponse> subResList = new  List<SubscriptionResponse>();
        
        SubscriptionResponse subRes; 
        List<Plan> planltLocal = null;
        List<string> useridlist= new List<string>();
        Map<string,id> cntoktamap = new Map<String, id>();
        Plan planLocal = null;
        if(response != null){
            for(SendS_SubscriptionC.mdmProfile profileVar : response.profiles){              
                useridlist.add(profileVar.userId);
            }
            List<contact> cntlist=[SELECT Id,Okta_ID__c from contact WHERE Okta_ID__c= :useridlist];
            if(!cntlist.isEmpty())
            {
            for(Contact c : cntlist)
            {
                    cntoktamap.put(c.Okta_ID__c,c.id);
            }
            }
            for(SendS_SubscriptionC.mdmProfile profileVar : response.profiles){              
                        
                if(profileVar.subscriptionMemberships != null){
                    for(SendS_SubscriptionC.mdmSubscriptionMemberships subMembership : profileVar.subscriptionMemberships){
                        subRes = new SubscriptionResponse();
                        subRes.productId = subMembership.subscription.productId;
                        subRes.ariaSubscriptionAccountNum = subMembership.subscription.ariaSubscriptionAccountNum;
                        subRes.subscriptionDate = subMembership.subscription.subscriptionDate;
                        subRes.status = subMembership.subscription.status;                        
                        if(subMembership.subscription.plans != null){
                            planListLocal = new List<Plan>();
                            for(SendS_SubscriptionC.mdmPlans plan : subMembership.subscription.plans){
                                planLocal = new Plan();
                                planLocal.planId = plan.planId;
                                planLocal.status = plan.status;
                                planLocal.activationDate = plan.activationDate;
                                planListLocal.add(planLocal);
                            }
                        }
                        subRes.email = profileVar.email;
                        subRes.firstName = profileVar.firstName;
                        subRes.lastName = profileVar.lastName;
                        subRes.userId = cntoktamap.get(profileVar.userId);
                        subRes.planList = planListLocal;
                        subResList.add(subRes);
                  }
                }
               }
           }
        system.debug('**********subResList' + subResList);
        return subResList;        
    }
    
    public class SubscriptionResponse{
        public String productId {get;set;}
        public String email {get;set;}
        public String userId {get;set;}
        public String firstName{get;set;}
        public String lastName {get;set;}
        public String ariaSubscriptionAccountNum {get;set;}
        public String subscriptionDate{get;set;}
        public String status{get;set;}
        public List<Plan> planList {get;set;}              
    }
    public class Plan{
        public String planId {get;set;}
        public String status {get;set;}
        public String activationDate {get;set;}
    }
}
  • August 07, 2018
  • Like
  • 0
APEX CLASS


trigger updatePtCDetails on OtB__c (after update) 
{
    List<id> caseIds = new List<id>();
    List<id> PCaseids = new List<id>();
    List<case> prntchildlist = new List<case>();
    List<case> updcaselist=new List<case>();
    Set<String> gbS = SMCUtils.getSOrgs('G P');

    if(trigger.isAfter && trigger.isUpdate)
    {
        for(OtB__c B : trigger.new)        
        {
            if(B.Result__c == 'Success' && B.Dt_Issued__c != null)
                caseIds.add(B.Case__c);
        }
        system.debug('case ids from B -->'+caseIds);
        if(!caseIds.isEmpty()){
            for(Case cs :[select id, PtId, SX_Is_Pt_Case__c from case where id in :caseIds AND Reasons__c = 'System Generated' AND S_OG__c in :gbS]){
                if(cs.SX_Is_Pt_Case__c){
                    PCaseids.add(cs.id);
                }else
                {
                    if(cs.prntId!=null){
                        PCaseids.add(cs.PtId);
                    }else
                    {
                        PCaseids.add(cs.id);

                    }
                }          
            }
        }
        system.debug('parent ids list -->'+PCaseids);   
        if(!PCaseids.isEmpty()){
            prntchildlist=[select id,Reasons__c,C_Status__c,(select id,C_Completed_On__c from Cases) from case where id in :PCaseids];
        }
        system.debug('parent child list -->'+prntchildlist);
        for(Case parent : prntchildlist)
        {
            Boolean isDateNull=false;
            for(Case child : parent.cases)
            {
                if(child.C_Completed_On__c==null)
                {
                    isDateNull=true;
                    break;
                }
            }
            if(isDateNull==false)
            {
                parent.C_Status__c='Process Complete';
                updcaselist.add(parent);
            }   
        }
        if(!updcaselist.isEmpty())
        {
            system.debug('inside update for case list in B-->'+updcaselist);
            update updcaselist;
        }

    }
}


TEST CLASS


@isTest
public class updatePtCDetailsTest
{
    static testMethod void TestMethod1()
    {
        Test.startTest();
        List<OtB__c> otlist =[select id,Case__c,Result__c,Dt_Issued__c from OtB__c limit 1];   
            if(!ologlist.isEmpty())
            {
                otlist[0].Dt_Issued__c=system.today();
                otlist[0].Result__c='Success';
                update otlist;
            }    
        Test.stopTest();
    }
    static testMethod void TestMethod()
    {       
        Test.startTest();
        Set<String> gbS = SMCUtils.getSOrgs('G P');
        List<Case> cs=[select id, PtId, SX_Is_Pt_Case__c,CCDetails__c from case where Reasons__c = 'System Generated' AND S_OG__c in :gbS AND CCDetails__c!=null
        limit 1];
        if(!cs.isEmpty())
        {  
            List<OtB__c> otlist =[select id,Case__c,Result__c,Dt_Issued__c from OtB__c 
            where Case__c=:cs[0].CCDetails__c limit 1];
            if(!otlist.isEmpty())
            {
                otlist[0].Dt_Issued__c = null;
                otlist[0].Result__c='Success';
                update otlist;
            }
        }
        Test.stopTest();
    }
}

The bold and underlined part is not able to cover. please help me out for this.. urgent...
  • August 01, 2018
  • Like
  • 0
APEX CLASS

Public Class P_AccountTrigOperations{
    
    public static void upsertLocationOnAccount(List<Account> accountList){
        Set<id> accountIdSet =  new Set<id>();
        Map <id,S_Site__c> locationByAccountMap = new Map<id,S_Site__c>();
        List<S_Site__c> locationToUpdateList = new List<S_Site__c>();
        List<S_Site__c> locationToInsertList = new List<S_Site__c>();
        List<Account> AccountFilteredList=new List<Account>();
       
        List<S_Org_Region_and_Country__c> settingValues = S_Org_Region_and_Country__c.getall().values();
        Set<String> CountrySet = new Set<String>();
        for(S_Org_Region_and_Country__c settings : settingValues){
            if(settings.Application__C == 'GP')
            CountrySet.add(settings.Country__c);
        } 
        
        for(Account accObj : accountList){
            if(CountrySet.contains(accObj.BillingCountry)){
                    accountIdSet.add(accObj.id);
                    AccountFilteredList.add(accObj);
            }
        }
        
        for(S_Site__c locationObj :[Select Name,PX_COUNTRY_CODE__c,PX_CUSTOMER_ACCOUNT_GROUP__c,PX_DMT_AVAIL_HOURS__c,PX_LOCATION_ACCOUNT_ID__c,
                                        S_Account__c,S_City__c,S_Country__c,S_IsPartnerRecord__c,S_Latitude__c,S_Longitude__c,S_Site_Fax__c,S_Site_Phone__c,
                                        S_State__c,S_Street__c,S_Web_site__c,S_Zip__c,CurrencyCode from S_Site__c where S_Account__c in:accountIdSet]){
            locationByAccountMap.put(locationObj.S_Account__c,locationObj);
        }
        
        for(Account accObj : AccountFilteredList){
            if(!locationByAccountMap.isEmpty()){
                if(locationByAccountMap.containsKey(accObj.id)){
                    S_Site__c locToInsertOrUpdate = locationByAccountMap.get(accObj.id);
                    if(locToInsertOrUpdate!=null){
                        //assign values from account to location after confirming the matching fields on account
                        if(accObj.CurrencyCode!=null) locToInsertOrUpdate.CurrencyIsoCode    = accObj.CurrencyCode;
                        if(accObj.Name!=null) locToInsertOrUpdate.Name = accObj.Name;
                        if(accObj.PX_COUNTRY_CODE__c!=null) locToInsertOrUpdate.PX_COUNTRY_CODE__c    = accObj.PX_COUNTRY_CODE__c;
                        if(accObj.PX_CUSTOMER_ACCOUNT_GROUP__c!=null) locToInsertOrUpdate.PX_CUSTOMER_ACCOUNT_GROUP__c = accObj.PX_CUSTOMER_ACCOUNT_GROUP__c;

                        if(accObj.id!=null) locToInsertOrUpdate.S_Account__c = accObj.id;
                        if(accObj.BillingCity!=null) locToInsertOrUpdate.S_City__c = accObj.BillingCity;
                        if(accObj.BillingCountry!=null) locToInsertOrUpdate.S_Country__c =   accObj.BillingCountry;
                        if(accObj.S_Latitude__c!=null) locToInsertOrUpdate.S_Latitude__c = accObj.S_Latitude__c;
                        if(accObj.S_Longitude__c!=null) locToInsertOrUpdate.S_Longitude__c = accObj.S_Longitude__c;
                        if(accObj.PX_Fax__c!=null) locToInsertOrUpdate.S_Site_Fax__c = accObj.PX_Fax__c;
                        if(accObj.PX_Phone__c!=null) locToInsertOrUpdate.S_Site_Phone__c = accObj.PX_Phone__c;
                        if(accObj.BillingStreet!=null) locToInsertOrUpdate.S_Street__c = accObj.BillingStreet;

                        if(accObj.BillingPostalCode!=null) locToInsertOrUpdate.S_Zip__c =    accObj.BillingPostalCode;
                        locationToUpdateList.add(locToInsertOrUpdate);
                    }
                }
            }
            else{
                //assign values from account to location after confirming the matching fields on account
                S_Site__c locToInsertOrUpdate2 = new S_Site__c();
                if(accObj.CurrencyCode!=null) locToInsertOrUpdate2.CurrencyIsoCode   = accObj.CurrencyCode;
                if(accObj.Name!=null) locToInsertOrUpdate2.Name = accObj.Name;
                if(accObj.PX_COUNTRY_CODE__c!=null) locToInsertOrUpdate2.PBSMAX_COUNTRY_CODE_ISO2__c   = accObj.PBSMAX_COUNTRY_CODE_ISO2__c;
                if(accObj.PX_CUSTOMER_ACCOUNT_GROUP__c!=null) locToInsertOrUpdate2.PBSMAX_CUSTOMER_ACCOUNT_GROUP__c = accObj.PBSMAX_CUSTOMER_ACCOUNT_GROUP__c;

                if(accObj.id!=null) locToInsertOrUpdate2.S_Account__c =    accObj.id;
                if(accObj.BillingCity!=null) locToInsertOrUpdate2.S_City__c = accObj.BillingCity;
                if(accObj.BillingCountry!=null) locToInsertOrUpdate2.S_Country__c =  accObj.BillingCountry;
                if(accObj.S_Latitude__c!=null) locToInsertOrUpdate2.S_Latitude__c = accObj.S_Latitude__c;
                if(accObj.S_Longitude__c!=null) locToInsertOrUpdate2.S_Longitude__c = accObj.S_Longitude__c;
                if(accObj.PX_Fax__c!=null) locToInsertOrUpdate2.S_Site_Fax__c = accObj.PX_Fax__c;
                if(accObj.PX_Phone__c!=null) locToInsertOrUpdate2.S_Site_Phone__c =    accObj.PX_Phone__c;
                if(accObj.BillingStreet!=null) locToInsertOrUpdate2.S_Street__c =    accObj.BillingStreet;

                if(accObj.BillingPostalCode!=null) locToInsertOrUpdate2.S_Zip__c =   accObj.BillingPostalCode; 
                locationToInsertList.add(locToInsertOrUpdate2);
            }
        }
        
        if(!locationToUpdateList.isEmpty()){
            try{
                update locationToUpdateList;
            }
         catch(Exception e){
                    System.debug('@@@Exception'+e);
                }
         }
        if(!locationToInsertList.isEmpty()){
            try{
            insert locationToInsertList;
            }
             catch(Exception e){
                    System.debug('@@@Exception'+e);
                }

    }
}
}


TEST CLASS


@isTest (Seealldata =False)
public class P_AccountTrigOperationsTest{


   public static  Account createAccount (){
    Account acc=new Account();
    acc.Name = 'Test Account';
    acc.AccountNumber = 'T06';
    acc.Customer_Status__c = 'Active';
    acc.BillingCountry = 'Canada';
    acc.CurrencyIsoCode = 'USD';
    acc.Customer_Status__c = 'Active';
    acc.PX_COUNTRY_CODE__c='IM';
    acc.PX_CUSTOMER_ACCOUNT_GROUP__c='IIN';
    acc.S_Latitude__c=34.999999;
    acc.S_Longitude__c=09.989898;
    acc.PX_Fax__c='PBITR';
    acc.PX_Phone__c='PBI';
    acc.BillingPostalCode='MH';
    return acc;
    }
        
static testMethod void upsertLocationOnAccountTest(){

Test.startTest();
List<Account> acclist = new List<Account>();         
Account acc = createAccount ();
acclist.add(acc);
insert acclist;

        S_Site__c Location=new S_Site__c();
        Location.Name='TestPb';
        Location.S_Street__c='270/8 KC';
        Location.S_Zip__c='1234';
        Location.S_Country__c='Algeria';
        Location.S_Longitude__c=98.000000;
        Location.S_Latitude__c=97.999999;
        Location.S_City__c='PB';
        Location.S_State__c='PB';
        Location.S_Account__c  = acc.id;
        insert Location;
S_Site__c Loc= [SELECT Id,S_Account__c  FROM S_Site__c WHERE S_Account__c  =:acc.id LIMIT 1];
   
System.assertEquals(acc.Id,Loc.S_Account__c  );

acc.Name = 'Test Account1';
update acc;

P_AccountTrigOperations ato = new P_AccountTrigOperations();
P_AccountTrigOperations.upsertLocationOnAccount(acclist);
Location.S_Account__c  = null;
update Location;
P_AccountTrigOperations.upsertLocationOnAccount(acclist);
Test.stopTest();
}
}

The bold part is anable to cover. please help me out
I've written the below piece of code and called in after update context on lead but doesn't work. Can anyone help me to correct the code.
public class LeadHandler {
    public static void dedupeContactOnLeadConversion(List<Lead> newList,map<id, 
    Lead> oldLeadMap){
        List<String> email = new List<String>();
        List<String> firstName = new List<String>();
        List<String> lastName = new List<String>();
        
        for(Lead objLead: newList){
            if(!String.ISBLANK(objLead.Email) && objLead.IsConverted == false){
                email.add(objLead.Email);
            }
            if(!String.ISBLANK(objLead.FirstName) && objLead.IsConverted == false){
                firstName.add(objLead.FirstName);                
            }
            if(!String.ISBLANK(objLead.LastName) && objLead.IsConverted == false){
                lastName.add(objLead.LastName);   
            }
        }
        
        List<Contact> objContact = [Select Id, Email, FirstName, LastName from Contact where Email in: email OR FirstName in: firstName OR LastName in: lastName];
        
        for(Contact newContact: objContact){
            Database.LeadConvert lc = new Database.LeadConvert();
            lc.setContactId(newContact.Id);
            Database.LeadConvertResult listLeadConvertResult = Database.convertLead(lc, false);
        }
    }
}

I only want to write a trigger which will stop the creation of duplicate contact only when you're converting the lead.
Want to write a trigger on user, so for any user has einstein user package license, if any user of profile other than system admin and standard security is trying to update the user's profile should throw an error.

Also if the profile is changed to the new profile with prefix SM then also should throw the error.
public class errorMsgOnProfileUpdate {
    
    public static void errorMsgOnProfileChange (List<user> userList, Map<id,user> oldMap) {
        profile pf;
        userList = [Select Id, Profile.Name, ProfileId from User where  isActive = TRUE and Profile.UserLicense.LicenseDefinitionKey = 'SFDC' and Id in (SELECT UserID FROM UserPackageLicense WHERE (PackageLicenseId= '050800000004xiQ'))];
        pf = [Select Id, Name from Profile where Name = 'System administrator' or Name = 'Standard Security'];
        if(userList.size() > 0){
            for(User u: userList){
                if(trigger.isUpdate && u.Profile.Name != pf.Name && oldMap.get(u.id).ProfileId != u.ProfileId){
                    u.addError('Only system Administrator and security has access to edit profiles');
                }
            }  
        } 
    }
    
}
Please correct me as I'm gettin the exception error while updating the profile as below:

Error: Invalid Data.
Review all error messages below to correct your data.
Apex trigger UserTrigger caused an unexpected exception, contact your administrator: UserTrigger: execution of BeforeUpdate caused by: System.QueryException: Non-selective query against large object type (more than 200000 rows). Consider an indexed filter or contact salesforce.com about custom indexing. Even if a field is indexed a filter might still not be selective when: 1. The filter value includes null (for instance binding with a list that contains null) 2. Data skew exists whereby the number of matching rows is very large (for instance, filtering for a particular foreign key value that occurs many times): ()

 
I've written the below code to update the field on case object when we're getting email to case. But when I tried to write logic to fire case assignment rule based on whatever value we're having in emailMessae.toAddress, it's not working at all.
Public class emailMessageHelper {
    Public static void updateCase (list<EmailMessage> newEmailMessageList, map<Id, EmailMessage> oldMap){
        Set <Id> caseIdSet = new Set <Id>();
        list <Case> caseList = new List <Case>();
        Map<Id, Case> caseMap = new Map<Id, Case>();
        list<Case> newCaseList = new list<Case>();
        
        for (EmailMessage messageObj: newEmailMessageList)
        {
            caseIdSet.add(messageObj.ParentId);
        }
        
        if(caseIdSet.size()>0)
        {
            caseList=[Select Id, OwnerId, Owner.Email, Status, status_Alert__c from case where Id in :caseIdSet];
            for(case caseObj: caseList)
            {
                caseMap.put(caseObj.Id,caseObj);
            }
        }
        for (EmailMessage messageObj: newEmailMessageList){  

            Case caseObj = caseMap.get(messageObj.ParentId);
            caseObj.Source_Email__c = MessageObj.ToAddress;
            System.debug('messageObj.ToAddress abc '+messageObj.ToAddress);
            if(caseObj.status !='New' && caseObj.Status_Alert__c != 'New Email Received' && messageObj.incoming && messageObj.toAddress!= null ){
                caseobj.status_Alert__c = 'New Email received';                
               
                Database.DMLOptions dmlOpts = new Database.DMLOptions();
                dmlOpts.assignmentRuleHeader.useDefaultRule= true;
                caseobj.setOptions(dmlOpts); 
                
                newCaseList.add(caseObj);                
            }          
            else if(!messageObj.incoming){
                caseobj.status_Alert__c = '';
                newCaseList.add(caseObj);
            }
        }
        if(newCaseList.size() > 0){
            update newCaseList;
        }        
    }
}
I'm calling the method in After insert and After update context.
Can any one please help me out on this?
 
  • April 09, 2020
  • Like
  • 0
I've written the below code to update the field on case object when we're getting email to case. But when I tried to write logic to fire case assignment rule based on whatever value we're having in emailMessae.toAddress, it's not working at all.
Public class emailMessageHelper {
    Public static void updateCase (list<EmailMessage> newEmailMessageList, map<Id, EmailMessage> oldMap){
        Set <Id> caseIdSet = new Set <Id>();
        list <Case> caseList = new List <Case>();
        Map<Id, Case> caseMap = new Map<Id, Case>();
        list<Case> newCaseList = new list<Case>();
        
        for (EmailMessage messageObj: newEmailMessageList)
        {
            caseIdSet.add(messageObj.ParentId);
        }
        
        if(caseIdSet.size()>0)
        {
            caseList=[Select Id, OwnerId, Owner.Email, Status, status_Alert__c from case where Id in :caseIdSet];
            for(case caseObj: caseList)
            {
                caseMap.put(caseObj.Id,caseObj);
            }
        }
        for (EmailMessage messageObj: newEmailMessageList){  

            Case caseObj = caseMap.get(messageObj.ParentId);
            caseObj.Source_Email__c = MessageObj.ToAddress;
            System.debug('messageObj.ToAddress abc '+messageObj.ToAddress);
            if(caseObj.status !='New' && caseObj.Status_Alert__c != 'New Email Received' && messageObj.incoming && messageObj.toAddress!= null ){
                caseobj.status_Alert__c = 'New Email received';                
               
                Database.DMLOptions dmlOpts = new Database.DMLOptions();
                dmlOpts.assignmentRuleHeader.useDefaultRule= true;
                caseobj.setOptions(dmlOpts); 
                
                newCaseList.add(caseObj);                
            }          
            else if(!messageObj.incoming){
                caseobj.status_Alert__c = '';
                newCaseList.add(caseObj);
            }
        }
        if(newCaseList.size() > 0){
            update newCaseList;
        }        
    }
}

I'm calling the method in After insert and After update context.
Can any one please help me out on this?
 
  • April 08, 2020
  • Like
  • 0
I was having one custom button with JS code as below:
{!requireScript("/soap/ajax/30.0/connection.js")}
{!requireScript("/soap/ajax/30.0/apex.js")}

var opp = new sforce.SObject("Opportunity");
opp.id = "{!Opportunity.Id}";

try {

opp.isStatus = true;

var optresult = sforce.connection.update([opp]);
if(optresult[0].success=='false') {
alert(optresult[0].errors.message);
} else {

sforce.apex.execute('populateOpportunity', 'automatePopulatingOpp', {optyId:'{!Opportunity.Id}', action:'Default'});

alert('{!$Label.SuccessMsg}');
}
} catch(err) {
alert(err.message);
}
document.location = '/{!Opportunity.Id}';

I'm new to vf page implementation. I need to replace this JS with Vf page. I've written below vf page and custom controller.

VF Page
<apex:page standardController="Opportunity"  showHeader="false" extensions="oppController" >   
    <head>
        <style type='text/css'>
            .popupBackground{
            left: 20%;
            color:red;
            position: fixed;
            width: 450px;
            height: 100px;
            margin-left: -200px;
            top: 50px;
            }
            .popupBackground .close{
            position: absolute;
            background:#008CBA;
            color: white;
            bottom: 0;
            right: 10px;
            font-size: 10px;
            text-decoration: none;
            width:50px;
            }
        </style>
    </head>
    
    <apex:form rendered="{!showSuccessMsg}" id="opp">
        <apex:pageMessages id="errmsg"></apex:pageMessages> 
        <body onload="init();">
            <apex:outputPanel styleClass="popupBackground"  >
                <center>
                    <apex:outputText value="{!$Label.SuccessMsg}" escape="false"/>
                    <apex:commandButton value="OK" styleClass="close" onclick="parent.window.close();"/>
                </center>
            </apex:outputPanel>
        </body>
    </apex:form> 
</apex:page>

Custom Controller
public class oppController {
    public Id oppId;
    public Boolean showSuccessMsg{get;set;}
    public Boolean showErrorMsg{get;set;}
    
    public opptController(){
        showSuccessMsg = true;
        showErrorMsg = false;
        
        if(oppId != NULL){
            Opportunity opp = new Opportunity(Id = oppId);
            opp.isStatus = true;
            try{
                update opp;
                populateOpportunity.automatePopulatingOpp(oppId,'Default');
                showSuccessMsg = true;
                showErrorMsg = false;
                Error.LogSuccess(Label.SuccessMsg);
            }catch(Exception e){
                showSuccessMsg = false;
                showErrorMsg = true;
                Error.LogException(e);
            }
            showSuccessMsg = true;
            showErrorMsg = false;
            Error.LogSuccess(Label.SuccessMsg);
        }        
    }
}

Can anyone please help me out to correct this?
  • March 31, 2020
  • Like
  • 0
I've in build the lightning component and created a buttoon like below:
<div class="okButtonClass">
            <aura:if isTrue="{!!v.showSpinner}">
            <ui:button label="OK" press="{!c.okBtn}"/>
            </aura:if>
        </div>
Here is the controller.js file of lightnign component:
okBtn : function(component, event, helper) {
        // Close the action panel
        var dismissActionPanel = $A.get("e.force:closeQuickAction");
        dismissActionPanel.fire();
    }

Applied css as well but not able to change the background color and text color of button. Here us the css file:
 

.THIS .okButtonClass{
    position: relative;
    display: inline-block;
    float: right;
    background-color: #008CBA;
    color: white;
}

Created the lightning application:
 

<aura:application extends="ltng:outApp" access="GLOBAL" >
	<aura:dependency resource="c:OpportunityContainer"/>
</aura:application>
Below is my vf page:
<apex:page standardController="Opportunity"  showHeader="false">   
    <apex:includeLightning />
    <div id="lightning">
        <script>
        $Lightning.use("c:OppButtonApp", function(){
            $Lightning.createComponent("c:OpportunityContainer",{"recordId":"{!$CurrentPage.parameters.id}"},
                                       "lightning",function(cmp){
                                       });
        });
        </script>
    </div>
</apex:page>

I'm calling this vf page through one custom button and working fine.

But once we are clicking on the button created in lightning component through this vf page it's showing the below error:

This page has an error. You might just need to refresh it. Action failed: c:OpportunityContainer$controller$okBtn [Cannot read property 'fire' of undefined] Failing descriptor: {c:OpportunityContainer$controller$okBtn}

User-added image
Once we're clicking on this OK button on page it's throughing error. It's not able to find the controller.js.

Please anyone can help me to short out this error?
  • March 29, 2020
  • Like
  • 0
APEX CLASS
trigger AvoidDuplicateUsageEntry on Amendment__c (before insert) 
{
    for (Amendment__c amendment: Trigger.new)
    {
        if (amendment.Override_Warning__c == false)
        {
            try
            {
              Amendment__c[] a = [SELECT a.CreatedById, a.CreatedDate, a.Amendment__c from Amendment__c a where a.Resp__c = :amendment.Resp__c and a.LSD__c = :amendment.LSD__c ORDER BY CreatedDate desc];
              if (a.size() > 0)
              {
                  User u = [SELECT u.Name from User u where id = :a[0].CreatedById];
                  String amendmentStr = String.escapeSingleauotes(a[0].Amendment__c);
                  amendmentStr = amendmentStr.replace('\"', '\\\"');
                  String userStr = String.escapeSingleauotes(u.Name);
                  userStr = userStr.replace('\"', '\\\"');
                  String dateStr = a[0].CreatedDate.format('MM/dd/yyyy hh:mm a');
                  String errorJSON = 'var errorJSON = {timesUsed: ' + a.size() + ', amendment: \"' + amendmentStr + '\", user: \"' + userStr + '\", time: \"' + dateStr + '\"};';  
                  amendment.Resp__c.addError(errorJSON);
              } // endif
            }
            catch (aueryException e)
            {
            }
        } // endif
    } // endfor

}

TEST CLASS
@isTest
public class test_Test {
    
    static testMethod void avoidDuplicateEntryTest() {
        
        Profile p = [select id from profile where name='System Administrator'];
        User u = new User(alias = 'standt', email = 'standarduser@testorg.com', emailencodingkey = 'UTF-8', lastname = 'Testing', languagelocalekey = 'en_US',
                          localesidkey = 'en_US', profileid = p.Id, timezonesidkey = 'America/Los_Angeles',
                          username = 'testclassuser@testorg.com');
        insert u;
        
        System.runAs(u){
            Test.startTest();
            Resp__c resp = new  Resp__c();
            resp.status__c = 'Draft';
            insert resp;
            
            LSD__c ref = new  LSD__c();
            ref.Due_Date__c = system.today();
            insert ref;
            
            list <Amendment__c> as = new list <Amendment__c>();
            Amendment__c amend = new Amendment__c();
            amend.Override_Warning__c = False;
            amend.LSD__c = ref.Id;
            amend.Resp__c = resp.Id; 
            amend.Amendment__c = 'TestText';
            amend.CreatedById = u.Id;
            as.add(amend);
            
            Amendment__c amend1 = new Amendment__c();
            amend1.Override_Warning__c = False;
            amend1.LSD__c = ref.Id;
            amend1.Resp__c = resp.Id; 
            amend1.Amendment__c = 'TestText1';
            amend1.CreatedById = u.Id;
            as.add(amend1);
            insert as;
            
            system.debug('size' + as.size());
            Test.stopTest();
        }      
    }          
}

I am not able to cover the bold & underlined part of my apex class. I am inserting the list in my test class but while debugging I m not getting any value in the list in my test class so unable to cover the rest of the part.

Could anyone can help me in this what is wrong I am doing here.. Please....
  • August 29, 2019
  • Like
  • 0
APEX CLASS
public with sharing class ccController {
    public String firstName {get; set;}
    public String lastName {get; set;}
    public String email {get; set;}
    public String password {get; set {password = value == null ? value : value.trim(); } }
    public String confirmPassword {get; set { confirmPassword = value == null ? value : value.trim(); } }
    public String communityNickname {get; set { communityNickname = value == null ? value : value.trim(); } }    
    public ccController() {}    
    private boolean isValidPassword() {
        return password == confirmPassword;
    }
    public PageReference registerUser() {    
           // it's okay if password is null - we'll send the user a random password in that case
        if (!isValidPassword()) {
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.ERROR, Label.site.passwords_dont_match);
            ApexPages.addMessage(msg);
            return null;
        }    
        String profileId = null; // To be filled in by customer.
        String roleEnum = null; // To be filled in by customer.
        String accountId = ''; // To be filled in by customer.        
        String userName = email;
        User u = new User();
        u.Username = userName;
        u.Email = email;
        u.FirstName = firstName;
        u.LastName = lastName;
        u.CommunityNickname = communityNickname;
        u.ProfileId = profileId;        
        String userId = Site.createPortalUser(u, accountId, password);     
        if (userId != null) { 
            if (password != null && password.length() > 1) {
                return Site.login(userName, password, ApexPages.currentPage().getParameters().get('startURL'));
            }
            else {
                PageReference page = System.Page.ccPage;
                page.setRedirect(true);
                return page;

            }
        }
        return null;
    }
}

TEST CLASS

/**
* An apex page controller that supports self registration of users in communities that allow self registration
*/
@IsTest
public with sharing class ccControllerTEst {
    
    static testmethod void testCCController() {
        Account acc = new Account(Name = 'Test');
        insert acc;
        
        Profile p = [select id from profile where name='System Administrator'];
        User u = new User(alias = 'standt', email = 'standarduser@testorg.com', emailencodingkey = 'UTF-8', lastname = 'Testing', languagelocalekey = 'en_US',
                          localesidkey = 'en_US', profileid = p.Id, timezonesidkey = 'America/Los_Angeles',
                          username = 'testclassuser@testorg.com');
        insert u;
        
        ccController controller = new ccController();
        controller.firstName = 'FirstName';
        controller.lastName = 'LastName';
        controller.email = 'test@force.com';
        controller.communityNickname = 'test';
        // registerUser will always return null when the page isn't accessed as a guest user
        System.assert(controller.registerUser() == null); 
        
        controller.password = 'abcd1234';
        controller.confirmPassword = 'abcd123';
        System.assert(controller.registerUser() == null); 
        //String userId = Site.createPortalUser(u, acc.Id, controller.password);
        
    } 
}
  • August 06, 2019
  • Like
  • 0
Created two field (data type-picklist) on the opportunity and have to make the fields mandatory when advancing a F S opportunity beyond Stage 2.  Make mandatory for the profile F S S R and F S S M only. 

for this scenario have to create a validation rule. Please help me out for this..
 
and if the scenario will be changed to 

According to the above scenario 2 fields (data type-picklist) should be mandatory based on the user profile (F S S R or F S S M).  Instead we would like the validation rule to be if the Sales Occupy (a picklist field on opportunity) = Field Sales, then the 2 fields are mandatory. 
 
please help me to write the validation rule for both the scenarios...

Thank you!!
  • February 08, 2019
  • Like
  • 0
APEX CLASS
public class Async_SFDCtoNextNotifyC {
    public class NotifyCRespFuture extends System.WebServiceCalloutFuture {
        public SFDCtoNextNotifyC.NotifyCResType getValue() {
            SFDCtoNextNotifyC.NotifyCResType response = (SFDCtoNextNotifyC.NotifyCResType)System.WebServiceCallout.endInvoke(this);
            return response;
        }
    }
    public class AsyncSOAPOverHTTPs_0 {
        public String endpoint_x = 'https://nextb-dev.abb.com:443/CommonInterface/Customer-2.0';
        public Map<String,String> inputHttpHeaders_x;
        public String clientCertName_x;
        public Integer timeout_x;
        private String[] ns_map_type_info = new String[]{'https://nextb.abb.com/CommonInterface/Customer-2.0', 'SFDCtoNextNotifyC'};
        public Async_SFDCtoNextNotifyC.NotifyCRespFuture beginNotifyC(System.Continuation continuation,SFDCtoNextNotifyC.NotifyCReqType[] notifyC) {
            SFDCtoNextNotifyC.NotifyCType request_x = new SFDCtoNextNotifyC.NotifyCType();
            request_x.notifyCustomer = notifyCustomer;
            return (Async_SFDCtoNextNotifyC.NotifyCRespFuture) System.WebServiceCallout.beginInvoke(
              this,
              request_x,
              Async_SFDCtoNextNotifyC.NotifyCRespFuture.class,
              continuation,
              new String[]{endpoint_x,
              'notifyCAction2_0',
              'https://nextb.abb.com/CommonInterface/Customer-2.0',
              'notifyCustomersRequest',
              'https://nextb.abb.com/CommonInterface/Customer-2.0',
              'notifyCustomersResponse',
              'SFDCtoNextNotifyC.NotifyCResType'}
            );
        }
    }
}

TEST CLASS
@isTest
public class Async_SFDCtoNextNotifyCTest {
    
    static testmethod void NotifyCus(){
        Test.setMock(WebServiceMock.class, new NotifyCMock());
        new Async_SFDCtoNextNotifyC.AsyncSOAPOverHTTPs_0();
        new Async_SFDCtoNextNotifyC.NotifyCRespFuture();
    }
}

MOCK CLASS
@isTest
global class NotifyCMock implements WebServiceMock {
    
    global void doInvoke(
           Object stub,
           Object request,
           Map<String, Object> response,
           String endpoint,
           String soapAction,
           String requestName,
           String responseNS,
           String responseName,
           String responseType) {
               
        Async_SFDCtoNextNotifyC.AsyncSOAPOverHTTPs_0 response_x = new Async_SFDCtoNextNotifyC.AsyncSOAPOverHTTPs_0();
        SFDCtoNextNotifyC.NotifyCResType response1 = new SFDCtoNextNotifyC.NotifyCResType();
        
        response.put('response_x', response_x);
           }
}
  • November 28, 2018
  • Like
  • 0
public class ProReqClass 
{
    public String checkPro(Opportunity[] old_oppValue,Opportunity[] new_oppValue)
    {
        String message='';
        List<OpportunityLineItem> oppProductList = new List<OpportunityLineItem>();
        Set<Id> priceBookEntryIds = new Set<Id>();
        Set<String> productName = new Set<String>();
        Set<String> stagNames = new Set<String>();
        stagNames.add('5. Prove');
        stagNames.add('6. Negotiate');
        stagNames.add('7. Contract');
        stagNames.add('8. Won');
        stagNames.add('4. Negotiate');
        stagNames.add('5. Closed Won');
        
        try
        {
            if(new_oppValue[0].RecordTypeId !=null)
            {
                 List<RecordType> rtypes = [Select Name, Id From RecordType where sObjectType='Opportunity' and isActive=true and Id=:new_oppValue[0].RecordTypeId];
                 if (rtypes.size()==1)
                 {    
                    if((rtypes[0].Name == 'AB Opportunity') && stagnames.contains(new_OppValue[0].StageName))
                    {   
                        oppProductList = [Select Id, PriceBookEntryId, OpportunityId, Source__c, Custom_Hardware_or_Software__c, Service__c, Input__c, Envelope_Finishing_System__c, Selective_Opener_Inbound_Only__c, OCR_Reading__c, Inline_Scale_or_Meter__c, Retrofit__c, Status__c from OpportunityLineItem where OpportunityId=:new_oppValue[0].Id];
                        if(oppProductList.size() > 0)
                        {                         
                            for (integer i=0; i<oppProductList.size(); i++)
                            {                         
                                if(oppProductList[i].Source__c ==null || oppProductList[i].Custom_Hardware_or_Software__c ==null || oppProductList[i].Service__c==null || oppProductList[i].Input__c==null || oppProductList[i].Envelope_Finishing_System__c == null || oppProductList[i].Selective_Opener_Inbound_Only__c ==null ||oppProductList[i].OCR_Reading__c == null || oppProductList[i].Inline_Scale_or_Meter__c ==null || oppProductList[i].Retrofit__c ==null || oppProductList[i].Status__c==null)
                                {                             
                                    priceBookEntryIds.add(oppProductList[i].PriceBookEntryId);
                                }
                            }
                            if(priceBookEntryIds.size()>0)
                            {  
                                List<PricebookEntry> productIdsList = new List<PricebookEntry>();
                                productIdsList = [select Name from PricebookEntry where id in :priceBookEntryIds];                      
                                if(productIdsList.size()>0)
                                {                             
                                    for (Integer j=0;j<productIdsList.size();j++)
                                    {
                                        message+=productIdsList[j].Name+',';                                     
                                    }
                                    return message;
                                }
                                else
                                {
                                    return message;
                                }                                                                               
                            }
                            else
                            {                                 
                                return message;
                            }
                        }
                        else
                        {                             
                            return message;
                        }
                    }
                    else
                    {                         
                        return message;
                    }
                 }
                 else
                 {                     
                    return message;
                 }            
            }
            else
            {                  
                return message;
            }
        }
        Catch(Exception e)  
        {
            System.debug('While Processing:'+e.getMessage());
            return message;
        }
    }
}
  • November 26, 2018
  • Like
  • 0
APEX CLASS

global class S_BchICaseG implements Database.Batchable<sObject> , Schedulable {
    
    public static final String sysGenerated = 'System Generated';
    public static final String instalOrDeInstall = 'Install/De-Install';
    public static final String fieldService = 'Field Service';
    
     public static final List<String> IPre = new list<String> { 'S self install' , 'S self deinstall' };
 
    List<String> LstCo = System.Label.List_Of_Co.split(',');
    
    global void execute(SchedulableContext sc) {

        S_BchICaseG batch = new S_BchICaseG();
        system.debug('batch executed');
        Database.executeBatch(batch, 1);
    }

  
    global Database.Querylocator start(Database.BatchableContext BC){
       
        String query = 'Select ID, P_Case_Cr_Trig__c, S_Pt_Case_Cre_Trig__c, P_Mn_Itm__c, S_Case_Cate__c, S_Tk_Ref__c, S_Carrier__c, S_Pt_Case_No__c, S__Contact__c, P_DelNo__c From S__Inst_Pd__c WHERE P_Case_Cr_Trig__c  = true And S_Pt_Case_Cre_Trig__c = false And P_Mn_Itm__c = true And (S_Case_Cate__c != null Or S_Case_Cate__c != \'\') AND S_Case_Cate__c NOT IN : IPre ';
        Obj_Lkd__c CS = Obj_Lkd__c.getOrgDefaults();        
        if (CS != null && CS.Lk_JBch_Int__c && !LstCo.isEmpty())
        {
            query = query +' AND S__Site__r.S__Account__r.Country_I2__c NOT IN :LstCo ORDER BY lastmodifieddate asc ';
        }
        Else
        {
            query = query +' ORDER BY lastmodifieddate asc ';
        }

        system.debug('query picked up the records');
        return Database.getQueryLocator(query);    
    }
    
    global void execute(Database.BatchableContext BC,List <sObject> scope)
    {
        List<Case> newCaseList = new List<Case>();
        String tsId = Case_RecordType__c.getInstance(P_Constant.NameTech_Sup).Id__c;
        Boolean isException = false;
        system.debug('Execute method');
        
        if(System.Now().minute() > 56 && System.Now().minute() < 59 && !Test.isRunningTest())
          System.abortJ(bc.getJId());
        
        for (S__Inst_Pd__c ip : (List<S__Inst_Pd__c>) scope)
        {
        system.debug('Entered for loop for case creation');
            Case caseRec = new Case();
            caseRec.S_Cs_Carrier__c = ip.S_Carrier__c;
            caseRec.Categories__c = fieldService;
            caseRec.S__Compo__c = ip.Id;
            caseRec.ContactId = ip.S__Contact__c;
            caseRec.Inst_Del_No__c = ip.P_DelNo__c;
            caseRec.PrntId = ip.S_Pt_Case_No__c;
            caseRec.Pu_Ord__c =  instalOrDeInstall ;
            caseRec.Reasons__c = sysGenerated; 
            caseRec.RecordTypeId = tsId ;
            caseRec.Su_Rsn__c = ip.S_Case_Cate__c;
            caseRec.S_Cs_Tk_Ref__c = ip.S_Tk_Ref__c;            
            caseRec.Subject = Label.P_Cs_Sub_&_Desc_Fr_Gb;
            caseRec.Description = Label.P_Cs_Sub_&_Desc_Fr_Gb;
            newCaseList.add(caseRec);
            
            ip.P_Case_Cr_Trig__c = false;
            ip.S_Carrier__c = '';
            ip.S_Tk_Ref__c = '';
        }
        
        SMWUtils.inBatchMode = true;
        System.debug('Begining of case creation');
        try{
            insert newCaseList;
        }catch (Exception e){
            system.debug('Exception Caught :'+e);
            system.debug('Exception in batch class S_BchICaseG - '+e.getMessage());
            isException=true;
        }
        System.debug('End of case creation :'+scope +isException);
        if(!isException)
            update scope; 
            System.debug('Exit of Case creation');       
    }

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

TEST CLASS


@isTest
private class S_BchICaseG_test {

    static testMethod void myUnitTest() {
        
        Product2 prod = new Product2(Name = 'Test');
        insert prod;
        
        S__Site__c site = new S__Site__c(
            Name = 'Test',
            S__Country__c = 'United Kingdom'
        );
        
        insert site;
        List<Case_RecordType__c> CaseRecordTypedata=P_TstDataFactory.crCustomSettingdataCase();
        if(!CaseRecordTypedata.isEmpty())
            insert CaseRecordTypedata;
       
        List<S__Inst_Pd__c> ipList = new List<S__Inst_Pd__c>();
        
        S__Inst_Pd__c ip = new S__Inst_Pd__c(
            Name = 'test', 
            P_CS_CrTRIG__c = true, 
            P_CS_CrTRAN_CD__c = '01',
            S__Site__c = site.Id,
            P_Sls_Org__c = 'DMT'
        );
        ip.P_Case_Cr_Trig__c = true;
        ip.S_Pt_Case_Cre_Trig__c = false;
        ip.P_Mn_Itm__c = true;
        ip.S_Case_Cate__c = 'S install';
        
        ipList.add(ip);
        
        insert ipList;

        Test.startTest();     
        
        try{
            S_BchICaseG batch = new S_BchICaseG();
            Database.executeBatch(batch);
        }catch(Exception e){
            System.debug('##### Exception ######'+e.getMessage());
        }
  
        Test.stopTest();       
    }
}

the bold italic and underlined part is not able to cover please help me out to cover this code.....
  • August 23, 2018
  • Like
  • 0
public class PageCountroller {
   
    public static List<SubscriptionResponse> subResList {get;set;}
    Public String Id;
    Public String Bpn {get; set;}
    Public boolean showSection {get; set;}

    Public PageCountroller() {
        Id = ApexPages.currentPage().getParameters().get('Id');
        system.debug('**********GettingCurrentPageAccountId'+Id);
        subResList = getSaasSubscription(Id);
        Bpn = [SELECT Name, AccountNumber FROM Account WHERE Id = :Id limit 1].AccountNumber;
    }
    
    public static List<SubscriptionResponse> getSaasSubscription(Id accountId) {
        
        SendS_SubscriptionC.MDMResponse responseFromMDM;
        String bpn = [SELECT Name, AccountNumber FROM Account WHERE Id = :accountId limit 1].AccountNumber;
        SendS_SubscriptionC saasCall = new SendS_SubscriptionC();     
        
        if(!String.isBlank(bpn)){
            responseFromMDM = sCall.getRowsByFilter('BPN',bpn );
            system.debug('*************ResponseFRomMDM'+ responseFromMDM);        
            return (processResponce(responseFromMDM));
        }
        else{
                return null;
            }
    }
    private static List<SubscriptionResponse> processResponce(SendS_SubscriptionC.MDMResponse response){
        List<SubscriptionResponse> subResList = new  List<SubscriptionResponse>();
        
        SubscriptionResponse subRes; 
        List<Plan> planltLocal = null;
        List<string> useridlist= new List<string>();
        Map<string,id> cntoktamap = new Map<String, id>();
        Plan planLocal = null;
        if(response != null){
            for(SendS_SubscriptionC.mdmProfile profileVar : response.profiles){              
                useridlist.add(profileVar.userId);
            }
            List<contact> cntlist=[SELECT Id,Okta_ID__c from contact WHERE Okta_ID__c= :useridlist];
            if(!cntlist.isEmpty())
            {
            for(Contact c : cntlist)
            {
                    cntoktamap.put(c.Okta_ID__c,c.id);
            }
            }
            for(SendS_SubscriptionC.mdmProfile profileVar : response.profiles){              
                        
                if(profileVar.subscriptionMemberships != null){
                    for(SendS_SubscriptionC.mdmSubscriptionMemberships subMembership : profileVar.subscriptionMemberships){
                        subRes = new SubscriptionResponse();
                        subRes.productId = subMembership.subscription.productId;
                        subRes.ariaSubscriptionAccountNum = subMembership.subscription.ariaSubscriptionAccountNum;
                        subRes.subscriptionDate = subMembership.subscription.subscriptionDate;
                        subRes.status = subMembership.subscription.status;                        
                        if(subMembership.subscription.plans != null){
                            planListLocal = new List<Plan>();
                            for(SendS_SubscriptionC.mdmPlans plan : subMembership.subscription.plans){
                                planLocal = new Plan();
                                planLocal.planId = plan.planId;
                                planLocal.status = plan.status;
                                planLocal.activationDate = plan.activationDate;
                                planListLocal.add(planLocal);
                            }
                        }
                        subRes.email = profileVar.email;
                        subRes.firstName = profileVar.firstName;
                        subRes.lastName = profileVar.lastName;
                        subRes.userId = cntoktamap.get(profileVar.userId);
                        subRes.planList = planListLocal;
                        subResList.add(subRes);
                  }
                }
               }
           }
        system.debug('**********subResList' + subResList);
        return subResList;        
    }
    
    public class SubscriptionResponse{
        public String productId {get;set;}
        public String email {get;set;}
        public String userId {get;set;}
        public String firstName{get;set;}
        public String lastName {get;set;}
        public String ariaSubscriptionAccountNum {get;set;}
        public String subscriptionDate{get;set;}
        public String status{get;set;}
        public List<Plan> planList {get;set;}              
    }
    public class Plan{
        public String planId {get;set;}
        public String status {get;set;}
        public String activationDate {get;set;}
    }
}
  • August 07, 2018
  • Like
  • 0