• Akshay Mhetre
  • NEWBIE
  • 155 Points
  • Member since 2020

  • Chatter
    Feed
  • 0
    Best Answers
  • 5
    Likes Received
  • 0
    Likes Given
  • 31
    Questions
  • 15
    Replies

I am used to insert dummy data in test classes,but here I dont know what to do,for which object do I need to insert dummy records. Please Help

@RestResource(urlMapping='/v1/sample/')
global with sharing class sample {
    @HttpPost
    global static void sample(){
        RestRequest req  = RestContext.request;
        String docUpload=req.requestBody.toString();
        system.debug('*****docUpload*****' +docUpload); 
        String username;
        String password; 
        try{
            Id d;
            system.debug( JSON.deserializeUntyped(docUpload)); 
            requestWrapper jsonParsed =(requestWrapper) JSON.deserialize(docUpload,requestWrapper.class);
            username = jsonParsed.username;
            password = jsonParsed.password;          
            if(String.isNotBlank(username))
            {
                String username1 = 'thilak';
				String password1 = 'thilak';            
                username1 = username;
                password1 = password;
                RestContext.response.responseBody =Blob.valueOf('test');
                RestContext.response.statusCode = 200;
            }
            else
            { 
                RestContext.response.statusCode = 201;
                RestContext.response.responseBody = Blob.valueOf(JSON.serialize('bitmap not coming properly'));
            }
        } 
        catch(Exception e) {
            RestContext.response.statusCode = 400;
            RestContext.response.responseBody = Blob.valueOf(JSON.serialize('Something went wrong'));
        }
    }
    Public class requestWrapper{
        Public String username;
        Public String password; 
    }
}

@AuraEnabled
    public static void updateApplicationSeqNumber(String OpptyIdSet){
        
        Opportunity givenOpportunity = [Select Id, Application_Sequence_Number__c, Application_number__c from Opportunity where Id =: OpptyIdSet WITH SECURITY_ENFORCED];
       
            System_Configuration__c seqNumber = System_Configuration__c.getValues('System Configuration');

            //for(Opportunity op : opptyList){
                    
                if(seqNumber.Application_Date__c == System.today()){
                    if(seqNumber.Application_Sequence_No__c==null){
                        seqNumber.Application_Sequence_No__c=1;
                    }else{
                        seqNumber.Application_Sequence_No__c=seqNumber.Application_Sequence_No__c+1;
                    }
                    givenOpportunity.Application_Sequence__c = seqNumber.Application_Sequence_No__c;
                }
                else{
                    givenOpportunity.Application_Sequence__c=00001;
                    seqNumber.Application_Sequence_No__c=00001;
                    seqNumber.Application_Date__c =System.today();
                }
                
                String text=String.valueOf(givenOpportunity.Application_Sequence__c);
                text=text.substringBefore('.');
                
                text=text.leftPad(5, '0');  
                
                String todayYear = String.valueOf(System.today().Year()).right(2);
                String todayMonth = String.valueOf(system.today().Month()).length() == 1 ? '0' + String.valueOf(system.today().Month()) : String.valueOf(system.today().Month());
                String todayDay = String.valueOf(system.today().day()).length() == 1 ? '0' + String.valueOf(system.today().day()) : String.valueOf(system.today().day());
                String datePrefix = todayDay + '' + todayMonth + '' + todayYear;
                String finalLeadNumber = '';
                if(Test.isRunningTest() == false){
                    String applicationNameString = datePrefix +  text;

                    
                    Long appvalue = Long.valueOf(applicationNameString);
                    if (String.valueOf(appvalue).length() == 10) {
                        //adding '0' to Lead No pattern if date ranges in 01-09
                        finalLeadNumber = 'A' + '' + '0' + '' + String.valueOf(appvalue);
                    } else {
                        finalLeadNumber = 'A' + '' + String.valueOf(appvalue);
                    }
                    givenOpportunity.Application_number__c = finalLeadNumber;
                    
                }
           // }
            update seqNumber;
            update givenOpportunity;
            
        
    }

 

  @isTest
    public static void updateApplicationSeqNumberTest(){
        
        Opportunity opun1 = new Opportunity();
        opun1.StageName = 'Qualification';
        opun1.CloseDate = Date.newInstance(2021, 1, 11);
        opun1.Name = 'testone';
        insert opun1;
        
        Test.startTest();
        UniqueLeadNumberHandler.updateApplicationSeqNumber(opun1.Id);
        Test.stopTest();
    }

 

Hello   I am retrieving fields from FieldSet with Values. I am trying to make those fields null but no luck..  Help me to make fields Null.( getFieldPath() )    
for(SObject s:obj){ if(s.getFieldPath()!= Id){ s.getFieldPath() =null; lstobj.add(s); } }

public static Boolean getMerchandise(List<Schema.FieldSetMember> lstFields, String objectName, String oppID) {
Map<String, Schema.SObjectType> GlobalDescribeMap = Schema.getGlobalDescribe();
Schema.SObjectType SObjectTypeObj = GlobalDescribeMap.get(ObjectName);
Schema.DescribeSObjectResult DescribeSObjectResultObj = SObjectTypeObj.getDescribe();
system.debug('DescribeSObjectResultObj'+DescribeSObjectResultObj.getName());
String queryString = 'SELECT Id';

for(Schema.FieldSetMember f : lstFields) {
queryString +=', ' +f.getFieldPath() ;
}
queryString += ' FROM '+DescribeSObjectResultObj.getName();
queryString += ' WHERE Loan_Application__c=\'' +oppId + '\'';
system.debug('queryString==>'+queryString);
SObject obj= Database.query(queryString);
system.debug('obj==>'+obj);

for(SObject s:obj){
if(s.getFieldPath()!= Id){
s.getFieldPath() =null;
lstobj.add(s);
}
}
upsert lstobj;
return true;
}
 

 

 

@RestResource(urlMapping='/multifileapi/*')
global with sharing class IND_MultipleFileUplaod_API
{
private static List<KV> keyValues;
@HttpPost
global static void doPost(){

Blob body = RestContext.request.requestBody;
String blobStr = EncodingUtil.base64Encode(body);

String encodedBoundary = blobStr.substring(0,blobStr.indexof('Q29udGVudC1EaXNwb3NpdGlvbjo'));

String actualBoundary = EncodingUtil.base64decode(encodedBoundary).toString().replace('\n','').replace('\r','');

String actualBody = EncodingUtil.base64decode(blobStr).toString().replace('\n','').replace('\r','');
actualBody = actualBody.replaceFirst(actualBoundary, '');
actualBody = actualBody.substring(0,actualBody.length()-2);

List<String> keyValueStr = actualBody.split(actualBoundary);
getKeyValue(keyValueStr);
RestResponse res = RestContext.response;
if (res == null) {
res = new RestResponse();
RestContext.response = res;
}
res.responseBody = Blob.valueOf(JSON.serialize(keyValues));
}

private static List<KV> getKeyValue(List<String> pairs){
keyValues = new List<KV>();
for(String s:pairs){
KV kv = new KV();
kv.key = s.substring(s.indexOf('\"')+1,s.lastIndexOf('\"'));
kv.value = s.substring(s.lastIndexOf('\"')+1);
kv.contentDisposition = s.substring(s.indexOf('Content-Disposition: ')+21,s.indexOf(';'));
keyValues.add(kv);
}
return keyValues;
}

private class KV{
String contentDisposition;
String key;
String value;

}
}

Below are 3 classes connected to each other. Help me to write a TEST CLASS.

public class IND_NeSLAgreementStatusRequest extends ParentAPIRequest{
public string Deal_No {get;set;}
public IND_NeSLAgreementStatusRequest(Applicant__c app,String loanAppId){

this.Deal_No = 'RJG01179D';//app.Opportunity__r.Parent_Deal_number__c;
validate(System.Label.NeSLAgreementStatus);
}

public override Map<String,String> getHttpRequestHeaders(){
Map<String,String> requestHeaderMap = Utilities.getHeaders();
return requestHeaderMap;
}

public override boolean validate(String serviceName){
if(this.Deal_No == null && String.isBlank(this.Deal_No)){
throw new IND_Exception(System.Label.deal_Number);
}
return true;
}
}


==========================

public class IND_NeSLAgreementStatusService {

public static IND_NeSLAgreementStatusRequest getNeSLAgreementStatusRequest(Applicant__c app,String loanAppId){
try{
IND_NeSLAgreementStatusRequest neSLAgreementStatusRequest = new IND_NeSLAgreementStatusRequest(app,loanAppId);//only validation and setting headers
return neSLAgreementStatusRequest;
}
catch(Exception ex){
ErrorLoggerUtil.logErrorEvent('IND_NeSLAgreementStatusRequest', 'getNeSLAgreementStatusRequest', System.Label.Apex, ex,loanAppId);
throw new IND_Exception(ex.getMessage());
}
}
}
=========================================================
public class IND_NeSLAgreementStatusResponse extends ParentAPIResponse {

public class Response {
public String status;
public String respDesc;
public List<Content> content;
}

public Response response;

public class Content {
public String Status_Code;
public String Status_Description;
public String Esign_Link;
}

}

Case Object--Lookup---AML_Check__c Object

When BECVO(Profile)-users update the picklist value(BE_CVO_Decision__c) to "False Positive" 
on AML_Check__c Object record,

---then---

Status field on Case Object record will also change to'Pending with CMU'.
I want to assigne those case to 'CMU QUEUE'.
By considering these conditions please tell me the code,How can I assign that case to 'CMU QUEUE'.


Hello Experts,  
  1. There are 2 objects. Lookup(Applicant) and Bank . (Lookup Relationship). 
  2. There is One checkbox is on ApplicantAreYouSure__c
  3. There is One PicklistApplicant_Type__c with values -- MaleFemale Both.                                   
Create Bank Record only when--
  1. On Applicant when AreYouSure__c=true, then it will ask for Applicant_Type__c  New? or Old ?, or both of them? 
  2. If Applicant_Type__c =both, then bank record needs to be created only for ‘Male’, and stamp the relevant applicant’s Applicant Id.
  3. If it’s checked for only one of them, then create a record for the one for which the flag is true and stamp the relevant applicant’s Applicant Id. 
  4. If AreYouSure__c=false , then don't create a record.

Hello Experts,

In apex, I am fetching 10 fields and Values by getRecords method and storing in lstRecords=[ ], those fields and Values are displaying in LWC component.

Now I want to split those values. ForExample. 3 of 10 wants to show only in payInRec collapsible section only.(those 3 fields should not come in lstRecords=[ ]. 

Fields Api Name:-

"Service_Charges__c"  ,   "Documentation_Charges__c  , "Dealer_Expence_Reimburse_Amt__c"  

**Just tell me How can I write a code in for loop to restrict those fields and display only sepcific fields.??

<template>
<tbody>
            <template for:each={lstRecords} for:item="keyValue"> 
                <tr key={keyValue.key}>
                    <th scope="col"  height="40" >
                        <div><b>{keyValue.key}</b></div>
                    </th>
                    <th scope="col"  height="40" >
                         <div>{keyValue.value}</div>
                    </th>
                </tr>
            </template>

            <template>
             --HERE I want to display those 3 fields.--
               </template>
              </template>
JS-->
import { LightningElement,wire,api,track } from 'lwc';
import getRecords from '@salesforce/apex/LoanDetailsForCAM.getRecords';
export default class LoanDetails extends LightningElement {
    @api recordId;
    @track lstRecords =[];
    @track payInRec =[];
    @wire (getRecords,{ opp :'$recordId' })fetchData(value) {
    const {
            data,
            error
        } = value;
        if(data){
        for (let key in data) { *IN this loop I want to show only 7 fields.
        this.lstRecords.push({value:data[key], key:key});
        }
        }
        else if(error){
        console.log(error);
        this.lstRecords = [];
        }
          if(data){
        for (let key in data){
*IN this loop I want to show only 3 fields.
        this.payInRec.push({value:data[key], key:key});
        }
        }
        else if(error){
        console.log(error);
        this.payInRec = [];
        }
        }}

 

trigger sendEmailtoinitiator on Case (after update) {
    
    
    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    
    Map<Id, Case> objMap = new Map<Id, Case>([ SELECT Id, Allocated_By__r.Email FROM Case WHERE Id IN : Trigger.new ]);
    for (Case newCase : Trigger.new){
        if((newCase.RCU_Stage__c == 'RCU Completion'|| newCase.RCU_Stage__c == 'RCU Clear' || newCase.RCU_Stage__c == 'RCU Negative')  
             && newCase.RCU_completion_Status__c !=null && newCase.Completion_Submit__c == true ){
            
            Messaging.SingleEmailMessage mail =  new Messaging.SingleEmailMessage();
            
           
            String[] toAddresses = new String[] {(objMap.get(newCase.Id).Allocated_By__r.Email)};
            mail.setToAddresses(toAddresses);
            
           
            
            EmailTemplate et = [select id,Subject,Body from EmailTemplate where developername='CaseStageEmailAlert'];
            mail.setTemplateId(et.Id );
            mail.setWhatId(newCase.Id);
            mail.setSubject(et.Subject);
          
            mail.setPlainTextBody(et.Body);
           
          mail.setTreatBodiesAsTemplate(true);
            
            
            //adding email to master list
            mails.add(mail);
            
        }
    }
    
           
            Messaging.sendEmail(mails);
}
 

Hello Experts,

In my org, there are 3 Public group.PG-A,PG-B,PG-C.

PG-A has 2 Users having RCU Initiator profile.

PG-B and PG-C each has 1 user.

I have a requirment,

When Case passes from PG-A (RCU_Stage__c='RCU Initiator') user to PG-B (RCU_Stage__c='RCU Verification') to PG-C (RCU_Stage__c='RCU Completion'), Once RCU_Stage__c become 'RCU Completion', email should send to the User who passed the case to PG-B user.

Allocated_By__c is the case field which shows the User (Who send the case to 'RCU Verification' (PG-B) stage.

***I dont want to write HardCoded email id in sendTo***

My Code-

trigger sendEmailtoinitiator on Case (after update) {
    
    //master list to hold the emails we'll send
    List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
    
    for (Case newCase : Trigger.new){
        if(newCase.RCU_Stage__c == 'RCU Completion' ){
            //Create a new Email
            Messaging.SingleEmailMessage mail =  new Messaging.SingleEmailMessage();
            
           //Setting list of people to get the email
            List<String> sendTo = new List<String>();
           // sendTo.add(newCase.Allocated_By_Text__c);
            sendTo.add(newCase.Allocated_By__c);
            mail.setToAddresses(sendTo);
            
            //Setting ReplyTo email 
            mail.setReplyTo(newCase.OwnerId);
            
            //list of people who should be CC
            List<String> ccTo = new List<String>();
            ccTo.add(newCase.CreatedById);
            mail.setCcAddresses(ccTo);
            
            //Email TemplateId (NOT SURE)
            EmailTemplate et = [select id,Subject from EmailTemplate where developername='CaseStageEmailAlert'];
            mail.setTemplateId(et.Id );
            
            //Subject
            //mail.setSubject('Case reached at Completion Stage');
            mail.setSubject(et.Subject);
            
            //adding email to master list
            mails.add(mail);
            
        }
    }
    
            //Send email to master list
            Messaging.sendEmail(mails);
}

 

Hello

I have a requirmnet, When user click Risk Rafer button,RCU Sub Stage is getting select as RCU Completion - Fresh....Now when user clicking  on submit button (Completion_Submit__c), RCU Sub Stage field should change from RCU Completion - Fresh to 'UW Confirmation Awaited'.

But its not changing to  'UW Confirmation Awaited'..its remaining as it is (RCU Completion - Fresh).

My Code--

 if(oldMap.get(caseRecord.Id).RCU_completion_Status__c != caseRecord.RCU_completion_Status__c
                   && caseMap.get('RCU Completion') == caseRecord.RecordTypeId) {
                       caseRecord.RCU_Completion_date__c = System.now();
                       if(caseRecord.RCU_completion_Status__c == 'Risk Refer'  && oldMap.get(caseRecord.Id).Completion_Submit__c != caseRecord.Completion_Submit__c ) {
                           caseRecord.RCU_Sub_Stage__c = 'UW Confirmation Awaited'; 
                            
                       }
                   }

 

User-added image

User-added image

User-added image

Error element myRule_1_A1 (FlowActionCall).
Probably Limit Exceeded or 0 recipients --- Probably Limit Exceeded or 0 recipients

Flow Details
Flow API Name: RCU_Email_alert
Type: Record Change Process
Version: 1
Status: Active

Flow Interview Details
Interview Label: RCU_Email_alert-1_InterviewLabel
Interview GUID: 2360926e2f91946c38bb3db0096017d1a6e20dd-7350
Current User: Automated Process (0058p000000HgMq)
Start time: 15/11/2021, 3:53 pm

 

There are 3 Users.. User1,User2,User3.
All 4 Users have same profile.

Scenario:-

On case object there is 1 Picklist field --> Stage__c
There are 3 stages of cases --> Initiation,Verification,Completion (Picklists value of Stage__c)
Case is moving from User1(Initiator) to User2(Verifier) to User3(Completion).
 Once case reaches to Users3 (Means at Completion Stage),Email Should send only to User1(to Initiator) (who sent the case to User2).
           
For above requirment I created Process Builder,It works fine..But Email goes only to previous case owner. I am expecting it should go only to whom who assigned case to User2.

Please Help with apex triggers or class.

if(
                    (caseMap.get('RCU Completion') == caseRecord.RecordTypeId
                     && oldMap.get(caseRecord.Id).Completion_Submit__c != caseRecord.Completion_Submit__c
                     && yB_RCUUtility.rcuNegativeCompletionList.contains(caseRecord.RCU_completion_Status__c)
                     
                    )) {
                        caseRecord.RCU_Stage__c = 'RCU Negative';
                        caseRecord.RCU_Sub_Stage__c = 'RCU Negative';
                        caseRecord.RecordTypeId = caseMap.get('RCU Negative');
                       
                        caseRecord.setOptions(dmlOpts);
                    }
                
                if(
                    (caseMap.get('RCU Completion') == caseRecord.RecordTypeId
                     && oldMap.get(caseRecord.Id).RCU_completion_Status__c != caseRecord.RCU_completion_Status__c
                     && caseRecord.RCU_completion_Status__c == 'Rework' && caseRecord.RCU_Initiator__c != null
                     
                    )) {
                        caseRecord.OwnerId = caseRecord.RCU_Initiator__c;
                        caseRecord.RCU_Stage__c = 'RCU Initiated';
                        caseRecord.RecordTypeId = caseMap.get('RCU Initiation');
                        
                        caseRecord.RCU_Total_Sample_Count__c = 0;
                        caseRecord.RCU_Verification_Status_Count__c = 0;
                        caseRecord.RCU_Verification_End_Date__c = null;
                        caseRecord.RCU_Completion_date__c = null;
                        
                        caseRecord.RCU_Initiator_Action_Complete__c = false;
                        caseRecord.RCU_Screen_All_set_flg__c = false;
                        
                    }
                
                if( caseMap.get('RCU Initiation') == caseRecord.RecordTypeId
                   && oldMap.get(caseRecord.Id).RCU_Ratification_Status__c != caseRecord.RCU_Ratification_Status__c &&
                   caseRecord.RCU_Ratification_Status__c!=null && caseRecord.RCU_Ratification_Status__c == 'Reinitiate'
                  ) {
                      caseRecord.OwnerId = caseRecord.RCU_Initiator__c;
                      caseRecord.RCU_Stage__c = 'RCU Initiated';
                      caseRecord.RecordTypeId = caseMap.get('RCU Initiation');
                      
                      caseRecord.RCU_Total_Sample_Count__c = 0;
                      caseRecord.RCU_Verification_Status_Count__c = 0;
                      caseRecord.RCU_Verification_End_Date__c = null;
                      caseRecord.RCU_Completion_date__c = null;
                  }
                
                
                
                System.debug('RCU_completion_Status__c' +caseRecord.RCU_completion_Status__c );
                string recodid=caseMap.get('RCU Initiation');                
                if(
                    (caseMap.get('RCU Completion') == caseRecord.RecordTypeId
                     && oldMap.get(caseRecord.Id).Completion_Submit__c != caseRecord.Completion_Submit__c
                     && (caseRecord.RCU_completion_Status__c == 'Recommended'||
                         caseRecord.RCU_completion_Status__c == 'CNV')
                     
                    )) {
                        caseRecord.RCU_Stage__c = 'RCU Clear';
                        caseRecord.recordTypeId=recodid;
                        if (caseRecord.RCU_Stage__c == 'RCU Clear'){
                            System.debug('==caseRecord.RCU_Stage__c=='+caseRecord.RCU_Stage__c);
                            if(caseRecord.RCU_Initiator_Group_Id__c!= '')
                            {
                                System.debug('==caseRecord.RCU_Initiator_Group_Id__c=='+caseRecord.RCU_Initiator_Group_Id__c);   
                                caseRecord.OwnerId = caseRecord.RCU_Initiator_Group_Id__c; 
                                System.debug('==caseRecord.OwnerId=='+caseRecord.OwnerId);  
                            }  
                        }
                        caseRecord.RCU_Sub_Stage__c ='RCU Clear';     
                        
                      
                    }
              
                if(
                    (caseMap.get('RCU Ratification') == caseRecord.RecordTypeId
                     && oldMap.get(caseRecord.Id).Flag__c != caseRecord.Flag__c
                     && (caseRecord.RCU_Ratification_Status__c == 'Ratified RPD' || caseRecord.RCU_Ratification_Status__c == 'Ratified RDD')
                     
                    )) {
                        caseRecord.RCU_Stage__c = 'RCU Clear';
                        
                    }
                if (caseRecord.RCU_Stage__c == 'RCU Clear'){
                    
                    if(caseMap.get('RCU Ratification') == caseRecord.RecordTypeId ||
                       caseMap.get('RCU Negative') == caseRecord.RecordTypeId ||
                       caseMap.get('RCU Initiation') == caseRecord.RecordTypeId ||
                       caseMap.get('RCU Completion') == caseRecord.RecordTypeId){
                           caseRecord.recordTypeId=recodid;
                           caseRecord.RCU_Sub_Stage__c ='RCU Clear';
                       }
                  
                    System.debug('==caseRecord.RCU_Stage__c=='+caseRecord.RCU_Stage__c);
                    if(String.isNotBlank(caseRecord.RCU_Initiator_Group_Id__c))
                    {
                        System.debug('==caseRecord.RCU_Initiator_Group_Id__c=='+caseRecord.RCU_Initiator_Group_Id__c);   
                        caseRecord.OwnerId = caseRecord.RCU_Initiator_Group_Id__c; 
                        System.debug('==caseRecord.OwnerId=='+caseRecord.OwnerId);  
                    }  
                }
                if(oldMap.get(caseRecord.Id).ownerId != caseRecord.ownerId
                   && caseMap.get('RCU Initiation') == caseRecord.RecordTypeId
                   && String.valueOf(caseRecord.ownerId).startsWithIgnoreCase('005')
                   && runningUser.Profile.Name == 'RCU Initiator') {
                       caseRecord.RCU_Initiator__c = runningUser.id;
                    
                       caseRecord.RCU_Initiation_Date__c = System.now();
                       caseRecord.RCU_Initiation_Started__c = 'Yes';
                   }
                if(oldMap.get(caseRecord.Id).RCU_completion_Status__c != caseRecord.RCU_completion_Status__c
                   && caseMap.get('RCU Completion') == caseRecord.RecordTypeId) {
                       caseRecord.RCU_Completion_date__c = System.now();
                       if(caseRecord.RCU_completion_Status__c == 'Risk Refer') {
                           caseRecord.RCU_Sub_Stage__c = 'UW Confirmation Awaited';
                       }
                   }
                if(caseMap.get('RCU Negative') == caseRecord.RecordTypeId
                   && oldMap.get(caseRecord.Id).RCU_Negative_Decision__C != caseRecord.RCU_Negative_Decision__C
                   && caseRecord.RCU_Negative_Decision__C=='Query'
                  ) {
                      caseRecord.RCU_Sub_Stage__c = 'RCU Negative Query Raised';
                      System.debug('rcuQueueNegativeId: ');
                  }
                if(oldMap.get(caseRecord.Id).RCU_Stage__c != caseRecord.RCU_Stage__c
                   && caseMap.get('RCU Negative') == caseRecord.RecordTypeId
                   && caseRecord.RCU_Stage__C == 'RCU Ratification') {
                       caseRecord.RecordTypeId = caseMap.get('RCU Ratification');
                       caseRecord.RCU_Ratification_Status__c = 'New';
                       
                   }
public class YB_RCUReportVFController {
    
     public Id caseId;
     public YB_RCUReportWrapper rcuReportData{get;set;}
    
      public YB_RCUReportVFController()
    {
        this.caseId = Apexpages.currentpage().getparameters().get('id');
        this.rcuReportData = new YB_RCUReportWrapper(this.caseId);
        
        
    }

}

Hello Experts,

I recevied one request from Client that, just like Admin can edit List View's Filters, Client also wants to give permission to particular profile to Edit List View's Filters.

Possible?? Any Way??

User-added image

 

@AuraEnabled
     public static void updateFilesMainCase(String contentVersionIds,String recordId)
     {
     System.debug('============contentVersionIds===='+contentVersionIds);
         if(contentVersionIds != null){
             String[] contentVersionIdArr = contentVersionIds.split(',');
        Set<String> contentDocumentIds = new Set<String>();
        for(String docId : contentVersionIdArr)
        {
            if(docId != null && docId.length() > 0)
                contentDocumentIds.add(docId);
        }
        System.debug('============contentDocumentIds===='+contentDocumentIds);
      //  List<Case> listCase = [select Type,Subject from Case where Id=:recordId];
       String imgTitle;
        List<User> agencyName= [Select Id ,Contact.Account.Name,Profile.Name from User where Id =:UserInfo.getUserId() AND Profile.Name='RCU Agent Community'];
        if(agencyName.size()> 0){
            imgTitle = agencyName[0].Contact.Account.Name+'-'+String.valueOf(System.now());
            }
        System.debug('============imgTitle===='+imgTitle);
        List<ContentVersion> versionList = [SELECT FileExtension, Title FROM ContentVersion 
                                            WHERE ContentDocumentId IN :contentDocumentIds and IsLatest=true ] ;
        List<ContentVersion> contentVersionsToUpdate = new List<ContentVersion>();
        for(ContentVersion contVersion : versionList)
        {
            if(imgTitle != null){
              contVersion.Title = imgTitle;  
            }
        }
         update versionList;   
         System.debug('recordId: '+recordId);
        List<Case> caselist= [Select Id, isAgentReportUploaded__c From Case Where ParentId=:RecordId]; 
         for(Case subC: caseList){
             subC.isAgentReportUploaded__c = true;
         }
         if(!caselist.isEmpty()){
             update caselist;
         }
        //return imgTitle;
       } 
        // return 'error';
         }
}
@AuraEnabled
    public static List<Case> submitSubCases(Id RecordId) {
        List<Case> csUpdateList = new List<Case>();
        List<Case> isAgentUploaded = [Select Id,isAgentReportUploaded__c from Case WHERE 
                                          ParentId=:RecordId AND isAgentReportUploaded__c = false 
                                          ];
        if(isAgentUploaded.size() == 0){
            String subStage =[Select Id, RCU_Sub_Stage__c from Case where Id=:RecordId].RCU_Sub_Stage__c;
            if(subStage == 'Rework'){
            List<Case> subCaselist= [Select Id, RCU_Sub_Stage__c From Case Where ParentId=:RecordId]; 
            if(subCaselist != null && subCaselist.size()>0){
                for(Case c:subCaselist)
                {
                    c.RCU_Sub_Stage__c = 'Agent Rework Submitted'; 
                    csUpdateList.add(c);
                }
            }
        }
        try {
            if (csUpdateList.size() > 0) {
                System.debug('csUpdateList: '+csUpdateList.size());
                update csUpdateList;
            }
        } catch(Exception ex) {
            System.debug(ex.getMessage());
        }
        return csUpdateList;
       } 
        else{
            return isAgentUploaded;
        }
        //System.debug('Successfully Agent Rework Submitted to All the Cases.');
        //return csUpdateList;
    }
  @AuraEnabled
    public static string getProfileCached(Id RecordId){
        Id profileId = UserInfo.getProfileId();
        String profileName =[Select Id, Name from Profile where Id=:profileId].Name;
        system.debug('Profile Name'+profileName);
        if('RCU Agent Community' == profileName){
            List<Case> caselist= [Select Id, RecordTypeId, OwnerId, Agent_Decision__c, Allocated_By__C, RCU_Sampling_Status__c
                                  From Case Where ParentId=:RecordId and RCU_Agency_Action__c <>'Accepted'];
            if(caseList != null && caseList.size()>0){
                return 'show';
            }else{
                return 'hide';
            }
        }
        return 'hide';
    }
Hello Everyone....Here I am sharing some methods from class which are not getting covered. Need help
 
 @AuraEnabled(cacheable = true)
    public static string getProfile(Id RecordId){
        Id profileId = UserInfo.getProfileId();
        String profileName =[Select Id, Name from Profile where Id=:profileId].Name;
        system.debug('Profile Name'+profileName);
        if('RCU Agent Community' == profileName){
            List<Case> caselist= [Select Id, RecordTypeId, OwnerId, Agent_Decision__c, Allocated_By__C, RCU_Sampling_Status__c
                                  From Case Where ParentId=:RecordId and RCU_Agency_Action__c <>'Accepted'];
            if(caseList != null && caseList.size()>0){
                return 'show';
            }else{
                return 'hide';
            }
        }
        return 'hide';
    }

Below are 3 classes connected to each other. Help me to write a TEST CLASS.

public class IND_NeSLAgreementStatusRequest extends ParentAPIRequest{
public string Deal_No {get;set;}
public IND_NeSLAgreementStatusRequest(Applicant__c app,String loanAppId){

this.Deal_No = 'RJG01179D';//app.Opportunity__r.Parent_Deal_number__c;
validate(System.Label.NeSLAgreementStatus);
}

public override Map<String,String> getHttpRequestHeaders(){
Map<String,String> requestHeaderMap = Utilities.getHeaders();
return requestHeaderMap;
}

public override boolean validate(String serviceName){
if(this.Deal_No == null && String.isBlank(this.Deal_No)){
throw new IND_Exception(System.Label.deal_Number);
}
return true;
}
}


==========================

public class IND_NeSLAgreementStatusService {

public static IND_NeSLAgreementStatusRequest getNeSLAgreementStatusRequest(Applicant__c app,String loanAppId){
try{
IND_NeSLAgreementStatusRequest neSLAgreementStatusRequest = new IND_NeSLAgreementStatusRequest(app,loanAppId);//only validation and setting headers
return neSLAgreementStatusRequest;
}
catch(Exception ex){
ErrorLoggerUtil.logErrorEvent('IND_NeSLAgreementStatusRequest', 'getNeSLAgreementStatusRequest', System.Label.Apex, ex,loanAppId);
throw new IND_Exception(ex.getMessage());
}
}
}
=========================================================
public class IND_NeSLAgreementStatusResponse extends ParentAPIResponse {

public class Response {
public String status;
public String respDesc;
public List<Content> content;
}

public Response response;

public class Content {
public String Status_Code;
public String Status_Description;
public String Esign_Link;
}

}

public class YB_RCUReportVFController {
    
     public Id caseId;
     public YB_RCUReportWrapper rcuReportData{get;set;}
    
      public YB_RCUReportVFController()
    {
        this.caseId = Apexpages.currentpage().getparameters().get('id');
        this.rcuReportData = new YB_RCUReportWrapper(this.caseId);
        
        
    }

}

Hello Experts,  
  1. There are 2 objects. Lookup(Applicant) and Bank . (Lookup Relationship). 
  2. There is One checkbox is on ApplicantAreYouSure__c
  3. There is One PicklistApplicant_Type__c with values -- MaleFemale Both.                                   
Create Bank Record only when--
  1. On Applicant when AreYouSure__c=true, then it will ask for Applicant_Type__c  New? or Old ?, or both of them? 
  2. If Applicant_Type__c =both, then bank record needs to be created only for ‘Male’, and stamp the relevant applicant’s Applicant Id.
  3. If it’s checked for only one of them, then create a record for the one for which the flag is true and stamp the relevant applicant’s Applicant Id. 
  4. If AreYouSure__c=false , then don't create a record.

User-added image

User-added image

Error element myRule_1_A1 (FlowActionCall).
Probably Limit Exceeded or 0 recipients --- Probably Limit Exceeded or 0 recipients

Flow Details
Flow API Name: RCU_Email_alert
Type: Record Change Process
Version: 1
Status: Active

Flow Interview Details
Interview Label: RCU_Email_alert-1_InterviewLabel
Interview GUID: 2360926e2f91946c38bb3db0096017d1a6e20dd-7350
Current User: Automated Process (0058p000000HgMq)
Start time: 15/11/2021, 3:53 pm

 

Hello Everyone...

I have one picklist  Hunter_Final_Status__c  having Pending,Clear,Decline,Suspect values.

Condition:: Once any of (Hunter_Final_Status__c) above value is selected, that value should populate/Display in Hunter_Status__c (Text).

 

public class PL_FIAutoAllocationCounterResetBatch  implements Database.Batchable<sObject> {
    
    public Database.QueryLocator start(Database.BatchableContext BC){
        String query = 'SELECT id, Count__c FROM Sales_To_CPA_Allocation_Rule1__c WHERE Count__c !=0';
        return Database.getQueryLocator(query);

    }
    
    public void execute(Database.BatchableContext BC, List<Sales_To_CPA_Allocation_Rule1__c> scope){
        List<Sales_To_CPA_Allocation_Rule1__c> lstRulesToUpdate = new List<Sales_To_CPA_Allocation_Rule1__c>();
        for(Sales_To_CPA_Allocation_Rule1__c rule : scope){
             rule.Count__c = 0;
            lstRulesToUpdate.add(rule);
        }
        if(lstRulesToUpdate.size() > 0){
        update lstRulesToUpdate;
        }
    }
    
    public void finish(Database.BatchableContext BC){
    }
}

Please help me.

Hello Everyone...I am not aware how to write a test class  which include Try Catch and having Aura unabled.... Please help. So I can learn too.

public with sharing class FISuperVisorRefireChecker {

    @AuraEnabled
    public static string refireCase(String recordId){
        try {
            if(String.isNotBlank(recordId)){
                List<Case> caseToUpdate = [select Id,FI_Stage__C,Decision__c,Agent_Case_Status__c,Fi_Agent__c,FI_Refire_Toggle__c
            from case where Id=: recordId];
            for(Case caseRecord: caseToUpdate){
                    if(String.isNotBlank(caseRecord.Decision__c) && !caseRecord.FI_Refire_Toggle__c){
                        return 'You cannot refire your decisioned case';
                    }
                    else if(caseRecord.Agent_Case_Status__c == 'Refire'){
                        return 'This case is already re-fired.'; 
                    }else if(caseRecord.FI_Agent__c == null){
                        return 'Please assign an agent before re-firing.'; 
                    }else if(caseRecord.FI_Stage__C == 'FI Verification In Progress'){
                        return 'You cannot refire as the case is still assigned to the agent.';
                    }
                    else{
                        caseRecord.Agent_Case_Status__c = 'Refire';
                    }
                } 
                update caseToUpdate;
                return 'Case was refired.Please ask agent to check';
            }else{
                return 'Something went wrong please try again';
            }
            
            
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
            //return JSON.serialize(e.getMessage());
        }
    }
}

Stack Trace:: Class.SharingUtilityTest.testSetup: line 90, column 1

Error:: System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, AgentMapping: execution of BeforeInsert

caused by: System.QueryException: unexpected token: 'in'

Class.AgentMappingTriggerHandlerException.beforeInsert: line 50, column 1
Trigger.AgentMapping: line 15, column 1: [ ]

---Method from AgentMappingTriggerHandlerException line 50---

  public static void beforeInsert(List<FI_Agent_Mapping__c> AgentMappingList){
       
        List<String> useridList = new List<String>();
        List<Id> pincodeList = new List<Id>();
        for(FI_Agent_Mapping__c obj : AgentMappingList){
            useridList.add(String.valueOf(obj.get('Fi_Agent__c')));
            pincodeList.add(obj.PinCode__c);
        }
        String agentmappingquery='select id,Pincode_Map__c,Fi_Agent__c from FI_Agent_Mapping__c where in: pincodeList AND Fi_Agent__c IN:useridList';
     //line 50-->   List<FI_Agent_Mapping__c> targetobj=Database.query(agentmappingquery);
        if(targetobj.size() > 0){
            AgentMappingList.get(0).addError( 'User Has already Mapped to the same pincode');   
        }  
    } 

---Trigger---

trigger AgentMapping on FI_Agent_Mapping__c (after insert, after update,before insert, before update) {
if(Trigger.isBefore && Trigger.IsUpdate){
        AgentMappingTriggerHandlerException.beforeUpdate(Trigger.OldMap, Trigger.NewMap, Trigger.New);
    }
    
    if (Trigger.isAfter && Trigger.IsInsert) {
         AgentMappingTriggerHandlerException.afterInsert(Trigger.OldMap, Trigger.NewMap, Trigger.New); 
    }
    
    if(Trigger.IsAfter && Trigger.IsUpdate){
        AgentMappingTriggerHandlerException.afterUpdate(Trigger.OldMap, Trigger.NewMap, Trigger.New);
    }
    
    if(Trigger.IsBefore && Trigger.IsInsert){
        AgentMappingTriggerHandlerException.beforeInsert(Trigger.New);
    }
}

----Main Test Class----

public without sharing class SharingUtility {
    public static void recalculateSharing(String ObjectAPIName, Map<Id,String> sObjectIdVsStage, Map<Id,sObject> sObjectMap) {
            List<sObject> sharingList = new List<sObject>();
            List<Record_Access__mdt> recordAccessMeta = new List<Record_Access__mdt>();
            map<Id, Sobject> shareMap = new Map<Id, Sobject>();
            recordAccessMeta = [SELECT MasterLabel, rowCause__c, userField__c, access__c FROM Record_Access__mdt WHERE MasterLabel IN: sObjectIdVsStage.values() AND Object_API_Name__c =:ObjectAPIName];
            for(Id loanid : sObjectIdVsStage.keyset()) {
                for(Record_Access__mdt mdt: recordAccessMeta) {
                    if(mdt.MasterLabel.equalsIgnoreCase(sObjectIdVsStage.get(loanid)) && sObjectMap.get(loanid).get(mdt.userField__c)!=null ){
                        System.debug('in If');
                        String userid = mdt.userField__c;
                        sharingList.add(getLoanShareRecord(loanid,string.valueof(sObjectMap.get(loanid).get(userid)),mdt.access__c,mdt.rowCause__c));
                        shareMap.putall(sharingList); //when same cpa agent do D1 and D2  duplicate record is getting added in list so make it unique adding in map
                    }
                }
            }
            List<Database.upsertResult> srList = Database.upsert(shareMap.values(), true);
            for(Database.upsertResult dr : srList) {
                if (dr.isSuccess()) {
                    System.debug('Successfully account with ID: ' + dr.getId());
                }
                else {
                    for(Database.Error err : dr.getErrors()) {
                        System.debug('The following error has occurred.');                    
                        System.debug(err.getStatusCode() + ': ' + err.getMessage());
                        System.debug('Account fields that affected this error: ' + err.getFields());
                    }
                }
            }
    }
    public static void shareCaseRecordwithAgent (String sobj,Map<String,String> usercaseMap,String access, String reason){
         caseShareRecordBulk(sobj, usercaseMap, access, reason);
    }
    public static sObject getLoanShareRecord (String parentId, String userId, String access, String reason){
        String sObjectName = Id.valueOf(parentId).getSObjectType().getDescribe().getName();
        System.debug('sObjectName:: '+sObjectName);
        if(sObjectName.endsWithIgnoreCase('__c')) { 
            system.debug('sObjectName:'+sObjectName);
            sObjectName = sObjectName.removeEnd('__c')+'__Share';
            sObject obj = Schema.getGlobalDescribe().get(sObjectName).newSObject();
            obj.put('AccessLevel', access != null ?access : 'Read');
            obj.put('ParentId', parentId);
            obj.put('UserOrGroupId', userId);
            obj.put('rowCause', 'reason');//
            return obj;    
        }
        else if(sObjectName.equalsIgnorecase('Account')) {
            sObjectName = 'AccountShare';
            sObject obj = accountShareRecord(sObjectName,parentId,userId,access,reason);
                 return obj;    
        }else if(sObjectName.equalsIgnorecase('DocumentChecklistItem')) {
            sObjectName = 'DocumentChecklistItemShare';
            sObject obj = docCheckItemShareRecord(sObjectName,parentId,userId,access,reason);
                 return obj;    
        } else if(sObjectName.equalsIgnorecase('Case')) {
              sObjectName = 'CaseShare';
              sObject obj =caseShareRecord(sObjectName,parentId,userId,access,reason);
                 return obj;    
                } else if(sObjectName.equalsIgnorecase('Opportunity')) {
                    sObject obj = opportunityTeamRecord(sObjectName,parentId,userId,access,reason);
                    System.debug('Opportunity Share:: '+obj);
                 return obj;    
                }else{
                  system.debug('inside else:'+sObjectName);
                  return null; 
                }
    }
    @testvisible
    private static sObject opportunityTeamRecord(String sobj,String parentId, String userId, String access, String reason){
        if(userId.startsWith('005')){
        OpportunityTeamMember oldTeamMemberRec = getPrevCreatedOppShare(parentId, userId);
        OpportunityTeamMember oppTeamMember = new OpportunityTeamMember();
        if(oldTeamMemberRec != null){
            oppTeamMember.Id = oldTeamMemberRec.Id;
            oppTeamMember.OpportunityAccessLevel =  access;
        }else{
            oppTeamMember.OpportunityId = parentId;
            oppTeamMember.UserId = userId;
            oppTeamMember.OpportunityAccessLevel =  access;
            oppTeamMember.TeamMemberRole ='Team Member'; 
        }
            System.debug('oppTeamMember:: '+oppTeamMember);
            return oppTeamMember;
        }else{
            return opportunityShareRecord(sobj, parentId, userId, access, reason);
        }
     }
    @testvisible
    private static OpportunityTeamMember getPrevCreatedOppShare(string parentId, string userId){
        try{
        OpportunityTeamMember oppTeamMember = [SELECT Id FROM OpportunityTeamMember WHERE OpportunityId=:parentId AND UserId=:userId Limit 1];
        if(oppTeamMember != null){
            return oppTeamMember;
        }else{
            return null;
        }
        }catch(Exception e){   
            return null;
        }
    }
    @testvisible
    private static sObject opportunityShareRecord(String sobj,String parentId, String userId, String access, String reason){
       OpportunityShare oppShare = new OpportunityShare(OpportunityAccessLevel=access, OpportunityId = parentId,  UserOrGroupId = userId);
        return oppShare;
    }
    @testvisible
    private static sObject accountShareRecord (String sobj,String parentId, String userId, String access, String reason){
          sObject obj = Schema.getGlobalDescribe().get(sobj).newSObject();
          obj.put('AccountAccessLevel', access != null ?access : 'Read');
          obj.put('OpportunityAccessLevel','Read');
          //obj.put('AccountAccessLevel', access != null ?access : 'Read');
          obj.put('AccountId', parentId);
          obj.put('UserOrGroupId', userId);
          // obj.put('rowCause', reason);
          return obj;
     }
    @testvisible
    private static void removeAccess (Set<Id> parentId){
        // delete all the existing sharing of these loan applications 
        System.debug('In removeAccess');
        list<OpportunityShare> loanShareRecords = new list<OpportunityShare>();
        loanShareRecords = [SELECT Id FROM OpportunityShare WHERE OpportunityId in :parentId];
        Database.DeleteResult[] drList = Database.delete(loanShareRecords, false);
    }
    @testvisible
    private static sObject docCheckItemShareRecord (String sobj,String parentId, String userId, String access, String reason){
        sObject obj = Schema.getGlobalDescribe().get(sobj).newSObject();
        obj.put('AccessLevel', access != null ?access : 'Read');
        obj.put('ParentId', parentId);
        obj.put('UserOrGroupId', userId);
        return obj;
     }
    @testvisible
    private static sObject caseShareRecord (String sobj,String parentId, String userId, String access, String reason){
        String query = 'select id from CaseShare where UserOrGroupId =: userId and CaseId =: parentId';
        List<SObject> targetObjRecords = Database.query(query);
        delete targetObjRecords;
        CaseShare obj = new CaseShare(CaseAccessLevel = access ,CaseId = parentId, UserOrGroupId = userId, RowCause = reason);
        return obj;
     }
    @testvisible
    private static void caseShareRecordBulk (String sobj,Map<String,String> parentId,String access, String reason){
        List<Sobject> caseshareList= new List<Sobject>();
        List<String> userIdList=parentId.values();
        Set<String> CaseIdList=parentId.keySet();
        String query = 'select id from CaseShare where UserOrGroupId in: userIdList and CaseId in: CaseIdList';
        List<SObject> targetObjRecords = Database.query(query);
        if(targetObjRecords.size() > 0){
        delete targetObjRecords;    
        }else{
        sendNotification(parentId);    
        }
        for (String key : parentId.keySet()) {
            Sobject sObjec = Schema.getGlobalDescribe().get('CaseShare').newSobject();
            sObjec.put('CaseAccessLevel',access);
            sObjec.put('CaseId',key);
            sObjec.put('UserOrGroupId',parentId.get(key));
            sObjec.put('RowCause',reason);
            caseshareList.add(sObjec); 
        }        
        insert caseshareList;
     }
    @testvisible
    public static void agentMappingShareRecord(Map<String,String> parentId,String access, String reason){
        List<Sobject> caseshareList= new List<Sobject>();
        Set<String> userIdList=parentId.keySet();
        List<String> CaseIdList=parentId.values();
        String query = 'select id from FI_Agent_Mapping__Share where UserOrGroupId in: userIdList and ParentId in: CaseIdList';
        List<SObject> targetObjRecords = Database.query(query);
        delete targetObjRecords;
        for (String key : parentId.keySet()) {
            Sobject sObjec = Schema.getGlobalDescribe().get('FI_Agent_Mapping__Share').newSobject();
            sObjec.put('AccessLevel',access);
            sObjec.put('ParentId',key);
            sObjec.put('UserOrGroupId',parentId.get(key));
            sObjec.put('RowCause',reason);
            caseshareList.add(sObjec); 
        }        
        insert caseshareList;
     }
    public static void setDefaultOwner(List<Loan_Application_Actors__c> loanApplicationActorsList){
        insert loanApplicationActorsList;
    }
    @testvisible
    public static void removeAccess(Map<String,String> parentId){
        List<String> userIdList=parentId.values();
        Set<String> CaseIdList=parentId.keySet();
        String query = 'select id,UserOrGroupId,CaseAccessLevel,CaseId from CaseShare where UserOrGroupId in: userIdList and CaseId in: CaseIdList';
        List<sObject> targetObjRecords = Database.query(query);
        if(targetObjRecords.size() > 0){
            delete targetObjRecords;    
        }
    }
    public static void sendNotification(Map<String,String> caseuser){
        Id typeId = [SELECT Id FROM CUstomNotificationType WHERE DeveloperName = 'FI_Agent_Notification'].Id;
        for (String key : caseuser.keySet()) {
            Messaging.CustomNotification notification = new Messaging.CustomNotification();
            notification.setBody('FI Case Has Been Assigned To You');
            notification.setTitle('FI Case Has Been Assigned To You');
            notification.setSenderId(Userinfo.getUserId());
            notification.setNotificationTypeId(typeId );
            notification.setTargetId(key); // target object id
            notification.send(new Set<String> { caseuser.get(key) }); // target user id.
        } 
    }
    public static List<Case> getCasesToShare(Set<Id> loanAppIdSet){
      return  [SELECT Id, Loan_Application__c FROM Case WHERE Loan_Application__c IN: loanAppIdSet];
    }
    public static void tvrCasesValidation(map<Id, Opportunity> lstCPAReviewApplications, map<Id, Opportunity>newMap){
                    if(lstCPAReviewApplications.size() > 0){
                List<AggregateResult> lstAggrReult = [SELECT COUNT(Id) cnt, Loan_Application__c  FROM Case WHERE Loan_Application__c IN: lstCPAReviewApplications.KeySet() AND Type Like 'TVR%' GROUP BY Loan_Application__c];
                System.debug('lstAggrReult:: '+lstAggrReult);
                if(lstAggrReult.size() > 0){
                for(AggregateResult aggrResult :  lstAggrReult){ 
                    String oppId = String.ValueOf(aggrResult.get('Loan_Application__c'));
                    Opportunity loanApplication = newMap.get(oppId);
                    System.debug('aggrResult:: '+aggrResult);
                    if(Integer.ValueOf(aggrResult.get('cnt')) < 2){
                    loanApplication.addError('Before Submitting to CPA Review, it is must to raise TVR CPV');
                    }
                }
                }else{
                    newMap.values()[0].addError('Before Submitting to CPA Review, it is must to raise TVR CPV');
                }
            }
    }
}

After execution of test ,Its showing errors for these two fields--

  FAM3.Fi_Agent__c='FAMagent3';
  FAM3.PinCode__c='400 003';

Main Class::::

public class AgentMappingTriggerHandlerException  extends Exception {
public static void afterInsert(map<Id, FI_Agent_Mapping__c> oldMap, map<Id, FI_Agent_Mapping__c> newMap, List<FI_Agent_Mapping__c> newList){
    
        Map<String,String> AgentMappingMap = new Map<String,String>();
        Map<String,String> GroupMap = new Map<String,String>();
        Map<String,String> agentmappingUserMap = new Map<String,String>();
        List<String> AgencyList  = new List<String>();
        
        for(Sobject obj : newList){
            AgentMappingMap.put(String.valueOf(obj.get('Id')),String.valueOf(obj.get('Agency_Name__c')));
            AgencyList.add(String.valueOf(obj.get('Agency_Name__c')));
        }
    system.debug('AgentMappingMap==='+AgentMappingMap);
    
        
        String groupquery='select id,name from Group where name in: AgencyList';
        List<Sobject> targetobj=Database.query(groupquery);
        if(targetobj.size() > 0){
            for(Sobject obj : targetobj){
                GroupMap.put(String.valueOf(obj.get('Name')),String.valueOf(obj.get('Id')));   
                
            }
            system.debug('Group Map==='+GroupMap);
        }
    
     for(Sobject obj : newList){
            agentmappingUserMap.put(String.valueOf(obj.get('Id')),GroupMap.get(String.valueOf(AgentMappingMap.get(String.valueOf(obj.get('Id'))))));
     system.debug('agentmappingUserMap=='+agentmappingUserMap);   
     }
    
        SharingUtility.agentMappingShareRecord(agentmappingUserMap,'Edit', 'Manual');        
     }
    
    public static void beforeUpdate(map<Id, FI_Agent_Mapping__c> oldMap, map<Id, FI_Agent_Mapping__c> newMap, List<FI_Agent_Mapping__c> newList){
           
    }

    public static void afterUpdate(map<Id, FI_Agent_Mapping__c> olaMap, map<Id, FI_Agent_Mapping__c> newMap, List<FI_Agent_Mapping__c> newList){
    }
   
    public static void beforeInsert(List<FI_Agent_Mapping__c> AgentMappingList){
       
        List<String> useridList = new List<String>();
        List<Id> pincodeList = new List<Id>();
        for(FI_Agent_Mapping__c obj : AgentMappingList){
            useridList.add(String.valueOf(obj.get('Fi_Agent__c')));
            pincodeList.add(obj.PinCode__c);
        }
        String agentmappingquery='select id,Pincode_Map__c,Fi_Agent__c from FI_Agent_Mapping__c where PinCode__c in: pincodeList';
        List<FI_Agent_Mapping__c> targetobj=Database.query(agentmappingquery);
        if(targetobj.size() > 0){
            AgentMappingList.get(0).addError( 'User Has already Mapped to the same pincode');   
        }
    } 
}

Please Correct my Test class:::

@isTest
public class AgentMappingTriggerHandlerExceptionTest {
    
@isTest         
    public static void afterInsertTest(){
    
     FI_Agent_Mapping__c FAM1 = new FI_Agent_Mapping__c();
      FAM1.Name ='FAMname1';
      FAM1.Agency_Name__c='A R ASSOCIATES';
      FAM1.Fi_Agent__c='FAMagent1';
      FAM1.PinCode__c='400 001';
      insert FAM1;
      
      FI_Agent_Mapping__c FAM2 = new FI_Agent_Mapping__c();
      FAM2.Name ='FAMname2';
      FAM2.Agency_Name__c= 'COGENT';
      FAM2.Fi_Agent__c='FAMagent2';
      FAM2.PinCode__c='400 002';
      insert FAM2;
       
      
      Map<Id,FI_Agent_Mapping__c> afterInsertMap  =  New Map<Id,FI_Agent_Mapping__c>();
      FI_Agent_Mapping__c FAM3 = new FI_Agent_Mapping__c();
      FAM3.Name ='FAMname3';
      FAM3.Agency_Name__c= 'BEST SERVICES';
      FAM3.Fi_Agent__c='FAMagent3';
      FAM3.PinCode__c='400 003';
      insert FAM3;
      afterInsertMap.put(FAM3.Id,FAM3);
      
      List<FI_Agent_Mapping__c> newListA = new List<FI_Agent_Mapping__c>();
      FI_Agent_Mapping__c FAM4 = new FI_Agent_Mapping__c();
      FAM4.Name ='FAMname4';
      FAM4.Agency_Name__c='BANRAD FINSERV';
      FAM4.Fi_Agent__c='FAMagent4';
      FAM4.PinCode__c='400 004';
      insert FAM4;
      newListA.add(FAM4);
        
       Test.startTest();
       AgentMappingTriggerHandlerException.afterInsert(afterInsertMap,afterInsertMap,newListA ); 
       Test.stopTest();
      
    }
@isTest
    public static void beforeUpdateTest(){
        
    }
@isTest
    public static void afterUpdateTest(){
        
    }
@isTest
    public static void beforeInsertTest(){
    
    }
}

 

Hi All,

I am writing a test class for a batch class but my current code coverage is 0% and not able to cover. I am geetting error as:
System.DmlException: Insert failed. First exception on row 0; first error: FIELD_FILTER_VALIDATION_EXCEPTION, Value does not exist or does not match filter criteria.: [Account__c]
Batch class is as belows:
global class UpdatePickUpstatusBatch implements 
    Database.Batchable<sObject>, Database.Stateful {
    

    global Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator('SELECT ID, Pickup_Date__c, Pickup_Status__c, Name FROM Pickup_Request__c Where Pickup_Date__c != null and Pickup_Status__c==\'Waitlisted\'');

    }

    global void execute(Database.BatchableContext bc, List<Pickup_Request__c> PRScope){
        // process each batch of records
        List<Pickup_Request__c> updateprlist = new List<Pickup_Request__c>();
        for (Pickup_Request__c pr : PRScope) {
           if(Date.today()==pr.Pickup_Date__c-Integer.valueof(Label.PickDateDaysforBatch))
           {
               pr.Pickup_Status__c = 'Open';
               updateprlist.add(pr);
                // make http callouts here Start
                
                
                // End              
           }
        }
        if(!updateprlist.IsEmpty()){
            update updateprlist;
        }
    }    

    global void finish(Database.BatchableContext bc){
        
    }    

}

My test class is as belows:
 
@isTest
public class UpdatePickUpstatusBatch_Test {
    static testMethod void UpdatePickUpstatusBatchtest1(){
    
    Schema.DescribeSObjectResult ACCobj1 = Schema.SObjectType.Account;
    Map<String,Schema.RecordTypeInfo> rtMapByName = ACCobj1 .getRecordTypeInfosByName();
    Schema.RecordTypeInfo rtByName = rtMapByName.get('Site');
    ID ACCSiteRecTypeid = rtByName.getRecordTypeId(); 
    
    Schema.DescribeSObjectResult ACCobj2 = Schema.SObjectType.Account;
    Map<String,Schema.RecordTypeInfo> rtMapByName2 = ACCobj2 .getRecordTypeInfosByName();
    Schema.RecordTypeInfo rtByName2 = rtMapByName2.get('Customer');
    ID ACCCustRecTypeid = rtByName2.getRecordTypeId(); 
    
    Schema.DescribeSObjectResult ACCobj3 = Schema.SObjectType.Account;
    Map<String,Schema.RecordTypeInfo> rtMapByName3 = ACCobj3 .getRecordTypeInfosByName();
    Schema.RecordTypeInfo rtByName3 = rtMapByName3.get('Billing');
    ID ACCBillingRecTypeid = rtByName3.getRecordTypeId(); 
    
        
        
        Account AccRecCustomer = new Account();
            AccRecCustomer.Name = 'Acme';
            AccRecCustomer.Phone = '1234';            
            AccRecCustomer.RecordTypeId= ACCCustRecTypeid;
            AccRecCustomer.Password__c = 'test data';
            AccRecCustomer.Status__c = 'Active';
        insert AccRecCustomer;
        
        Account AccRec = new Account();
            AccRec.Name = 'Acme';
            AccRec.Phone = '1234';
            AccRec.Parent = AccRecCustomer;
        
           //AccRec.Parent =  AccRecCustomer.id;
            AccRec.Status__c = 'Active';
            AccRec.RecordTypeId= ACCSiteRecTypeid;
            AccRec.Password__c = 'test data';
        insert AccRec;
        
        Account AccRecBilling = new Account();
            AccRecBilling.Name = 'Acme';
            AccRecBilling.Parent = AccRecCustomer;
            AccRecBilling.Phone = '1234';
            AccRecBilling.Status__c = 'Active';
            AccRecBilling.RecordTypeId= ACCBillingRecTypeid;
            
        insert AccRecBilling;

               
        Contact ConRec = new Contact();
            ConRec.FirstName = 'John';
            ConRec.LastName = 'Smith';
            ConRec.Phone = '1234';
            ConRec.Email = 'abc@gmail.com';
            
        insert ConRec;
        
         Contact ConRec1 = new Contact();
            ConRec1.FirstName = 'John1';
            ConRec1.LastName = 'Smith1';
            ConRec1.Phone = '12345';
            ConRec1.Email = 'abc1@gmail.com';
            
        insert ConRec1;
        
        Address__c AddRec = new Address__c();
            AddRec.Address1__c = 'G  370 Docklands Dr';
            AddRec.Country__c = 'AUSTRALIA';
            AddRec.State__c = 'VIC';
            AddRec.Suburb__c = 'Docklands';
            AddRec.Zipcode__c = 3008;
            AddRec.Shipping_Address_Validation_Status__c = 'Verified by Experian';
            AddRec.Shipping_Address_Validation_Timestamp__c = system.today();
            
        Insert AddRec;
        String AddRecId = AddRec.id; 
        CustAddrAssoc__c  CustAddRec = new CustAddrAssoc__c ();
            CustAddRec.Account__c = AccRec.id;
            CustAddRec.Address__c = AddRec.id; 
            CustAddRec.Type__c = 'Site';
            CustAddRec.InActive__c = false;
        
        Insert CustAddRec;
        
        Suburbs__c  SuburRec = new Suburbs__c ();
            SuburRec.Name = 'DOCKLANDS';
            SuburRec.Post_Code__c = '3008';
            SuburRec.State__c = 'VIC';
            SuburRec.Depot__c = 'MEL';
            SuburRec.City__c = '818 Bourke Street';
         
        insert SuburRec; 
        
        Holiday__c  HolRec = new Holiday__c ();
            HolRec.Name = 'ADELAIDE CUP DAY';
            HolRec.Type__c = 'Normal';
            HolRec.State_Name__c = 'VIC';
            HolRec.Start_Date__c = System.today();
            HolRec.End_Date__c = System.today()+2;
        Insert HolRec ;
        
        Pickup_Request__c  PickReqRec = new Pickup_Request__c();
        
           /** PickReqRec.Pickup_Type__c = 'Pickup';
            PickReqRec.Pickup_Status__c = 'Draft';
            PickReqRec.Source__c = 'Email';
            PickReqRec.Third_Party_Contact__c = ConRec1.id;
            PickReqRec.Contact__c = ConRec.id;
            PickReqRec.Billing_A_c__c = AccRecBilling.id;
            PickReqRec.Ready_Time__c = '12:00';
            PickReqRec.Close_Time__c = '19:00';
            PickReqRec.SuburbT__c = 'DOCKLANDS';
            PickReqRec.Pickup_Date__c = System.today()+1;
            PickReqRec.State__c = 'test Sate';
            PickReqRec.Service__c ='Priority';
            PickReqRec.Total_Wt__c = 3000;
            //PickReqRec.Address__c = AddRec.id;
            PickReqRec.password__c = 'test data';
            
        Insert PickReqRec;**/
       
            PickReqRec.Pickup_Type__c = 'Pickup';
            PickReqRec.Pickup_Status__c = 'Waitlisted';
            PickReqRec.Source__c = 'Email';
            PickReqRec.Third_Party_Contact__c = ConRec1.id;
            PickReqRec.Contact__c = ConRec.id;
            PickReqRec.Billing_A_c__c = AccRecBilling.id;
            PickReqRec.Ready_Time__c = '12:00';
            PickReqRec.Close_Time__c = '19:00';
            PickReqRec.SuburbT__c = 'DOCKLANDS';
            PickReqRec.Pickup_Date__c = System.today()+1;
            PickReqRec.State__c = 'test Sate';
            PickReqRec.Service__c ='Priority';
            PickReqRec.Total_Wt__c = 3000;
            PickReqRec.Address__c = CustAddRec.id;
            PickReqRec.password__c = 'test data';
            PickReqRec.Destination_SuburbL__c = SuburRec.id;
            PickReqRec.H_cm__c = 444;
            PickReqRec.Item_Description__c ='Item';
            PickReqRec.L_cm__c = 44;
            PickReqRec.No_of_Items__c =4;
            PickReqRec.Customer__c = AccRecCustomer.id;
            //PickReqRec.Customer__c = AccRec.id;
        	PickReqRec.Account__c =AccRec.id;

            PickReqRec.W_cm__c = 400;
            PickReqRec.Food_Stuff__c  = 'Yes';
            
        Insert PickReqRec;
        
        
       
        Pickup_Request__c PickReqRecObj = [Select id ,Pickup_Status__c ,Pickup_Date__c from Pickup_Request__c  where id =:PickReqRec.id LIMIT 1];
        
        System.debug('----->'+PickReqRecObj );

        //PickReqRec.Pickup_Status__c = 'Open';
        //update PickReqRec;
        
        Test.startTest();

        UpdatePickUpstatusBatch UpdateBatch = new UpdatePickUpstatusBatch();
          //DataBase.executeBatch(UpdateBatch);
        ID batchprocessid = Database.executeBatch(UpdateBatch);
        Test.stopTest();
    }
}

Below is the look up filter:
Object-Pickup Request
Field label: Site
Field API: Account__c
User-added image

When I removed the filter then my code coverage becomes 72% but that is not a correct approach. I need not have to remove the filter infact I do need to cover the same in my test class which I am not getting.

Kindly help me

Thanks & Regards,
Harjeet
 

trigger getmanager on Opp__c ( before update){
Set<Id> id= new Set<Id>();
Set<String> empid=new Set<String>();
Set<String> mngid=new Set<String>();
List<Opp__c> OppyLocation = new List<Opp__c>();

for (Opp__c opp:trigger.old){
  id.add(trigger.newmap.get(opp.id).Current_Year_Rep__c );
  system.debug('id:'+id);
  }
for (HR__c empnum: [select Employee_Number__c from HR__c where  id  in :id ]){
    empid.add(empnum.Employee_Number__c);
      }
      
    system.debug('id:'+id);
    system.debug('empid:'+empid);
 
 for (Contact con: [select Employee_Id__c,Reports_To_Employee_Id__c from contact where Employee_Id__c in:empid]){
    mngid.add(con.Reports_To_Employee_Id__c );
    }
    system.debug('mngid:'+mngid);
    
 for (HR__c empnu: [select Employee_Number__c,Name from HR__c where Employee_Number__c in: mngid]){

      for (Opp__c opp:trigger.new){
     opp.Cureent_Year_Rep_Manager__c=empnu.id; 
     system.debug('emp:'+ empnu.id );
     system.debug('emp:'+ empnu.Name );

     OppyLocation.add(opp);
     
      
         }
             }

  
  
      
      
}