• Rohit Tanti
  • NEWBIE
  • -7 Points
  • Member since 2019

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 2
    Likes Given
  • 0
    Questions
  • 12
    Replies
How to find out those accounts who's opportunity is more than 2? 
Got Issue In Below Code.
if((
                   Schema.SObjectType.Custom_Setting__c.isCreateable() &&
                   Schema.SObjectType.Custom_Setting__c.fields.Name.isCreateable() &&
                   Schema.SObjectType.Custom_Setting__c.fields.UserName__c.isCreateable() &&
                   Schema.SObjectType.Custom_Setting__c.fields.Password__c.isCreateable() ) ||
                                      
                   (Schema.sObjectType.Custom_Setting__c.isUpdateable() &&
                   Schema.SObjectType.Custom_Setting__c.fields.Name.isUpdateable()  ) {
                   
                   
                    Custom_Setting__c cs = new Custom_Setting__c(UserName__c = username, Password__c = password, Name = usr.Name);
                    upsert cs Name;
                   
                   }
public  class InvoiceDetails_custom {
    
    @AuraEnabled
    public static string  InsertInvoiceDetails(String loanApplicationId, date InvoiceDate, string InvoiceNo,decimal CashOnHire,string InvoiceType,String ChasisNumber,String EngineNumber) {
        
        String Message1='invoice number found';
        String Message2='invoice number found';
        String Message3='inserted';
        String Message4='Locked';
        boolean found=false;
        list<Invoice_Details__c> Invdetails=[select id,Invoice_Date__c,Invoice_No__c,Invoice_Approval_Status__c from Invoice_Details__c where Loan_Application__c=:loanApplicationId];
        
        boolean isCurrentInvoiceApproved = false;   
        
        if(Invdetails != null && Invdetails.size() > 0){
            if(Invdetails[0].Invoice_Approval_Status__c != null &&  Invdetails[0].Invoice_Approval_Status__c == 'Approved' ){
                isCurrentInvoiceApproved = true;
            }
        }
        //getting the dealer details based on the passed opportunty ID
        List<string> dealername = new List<string>();
        list<opportunity> dealerDetails=[select id,Name,Dealer__c,RecordType.developername from opportunity where id=:loanApplicationId];
        String recordTypeName=dealerDetails[0].RecordType.developername;
        system.debug('recordTypeName--->' +recordTypeName);
        for(opportunity op:dealerDetails)
        {
            dealername.add(op.Dealer__c);
        }
        //get the numberof opportuniies based on the dealer name
        list<ID> opIdList= new list<ID>();
        list<opportunity> oppdetails=[select id,Name from opportunity where Dealer__c In:dealername];
        for(opportunity op1:oppdetails)
        {
            opIdList.add(op1.Id);
        }
        system.debug('list***' +opIdList.size());
        list<Invoice_Details__c> InvdetailsOnOpp=[select id,Invoice_Date__c,Invoice_No__c,Invoice_Approval_Status__c,Chasis_Number__c,Engine_number__c from Invoice_Details__c where Loan_Application__c In:opIdList];
        system.debug('++++InvdetailsOnOpp+++' +InvdetailsOnOpp.size());
        for(Invoice_Details__c inv1:InvdetailsOnOpp)
        {
            if(recordTypeName == 'Consumer_Durable' && inv1.Invoice_No__c==InvoiceNo && !isCurrentInvoiceApproved)
            {
                system.debug('inv1.Invoice_Approval_Status__c' +inv1.Invoice_Approval_Status__c);
                
                system.debug('entered Consumer_Durable state');
                found=true;
                system.debug('found' +found);
                return Message2;
            }
            else if(recordTypeName == 'Two_Wheeler' && !isCurrentInvoiceApproved && (inv1.Invoice_No__c==InvoiceNo || inv1.Chasis_Number__c ==ChasisNumber || inv1.Engine_number__c == EngineNumber))
            {
                system.debug('entered two wheeler state');
                found=true;
                system.debug('found' +found);
                return Message2;
            }
        }
        
        
        //list<Invoice_Details__c> invDetails= new list<Invoice_Details__c >();
        if(!found){
            list<Invoice_Details__c> Invdetail=[select id,Invoice_Date__c,Invoice_No__c  from Invoice_Details__c where Loan_Application__c=:loanApplicationId];
            system.debug('not found state');    
            if(Invdetail.isEmpty())
            {
                try{
                    Invoice_Details__c c = new Invoice_Details__c();
                    c.Invoice_Date__c=InvoiceDate;
                    c.Invoice_No__c=InvoiceNo;
                    c.Invoice_Type__c=InvoiceType;
                    c.Loan_Application__c=loanApplicationId;
                    c.Invoice_Amount__c=CashOnHire;
                    c.Chasis_Number__c=ChasisNumber;
                    c.Engine_number__c=EngineNumber;
                    insert c;
                    return Message3; 
                }
                catch(Exception e)
                {
                    System.debug('Exception type caught: ' + e.getTypeName());    
                    System.debug('Message: ' + e.getMessage());    
                    System.debug('Cause: ' + e.getCause());    // returns null
                    System.debug('Line number: ' + e.getLineNumber());    
                    System.debug('Stack trace: ' + e.getStackTraceString());
                    system.debug('error message' +e.getMessage());
                    return e.getMessage();
                }
                
            }
            else{
                // string Approved='Locked';
                // string Approved=Invdetail[0].Approved__c;
                Id InvoiceId = Invdetail[0].id;    
                try{
                    Invoice_Details__c c = new Invoice_Details__c();
                    Invoice_Details__c invoicedet=[select id,Invoice_Date__c,Invoice_No__c,Invoice_Type__c,Invoice_Amount__c from Invoice_Details__c where id=:InvoiceId];
                    c.Id=invoicedet.id;
                    c.Invoice_Date__c=InvoiceDate;
                    c.Invoice_No__c=InvoiceNo;
                    c.Invoice_Type__c=InvoiceType;
                    //c.Loan_Application__c=loanApplicationId;
                    c.Invoice_Amount__c=CashOnHire;
                    c.Chasis_Number__c=ChasisNumber;
                    c.Engine_number__c=EngineNumber;
                    update c;
                    return Message3;
                }
                catch(Exception e)
                {
                    System.debug('Exception type caught: ' + e.getTypeName());    
                    System.debug('Message: ' + e.getMessage());    
                    System.debug('Cause: ' + e.getCause());    // returns null
                    System.debug('Line number: ' + e.getLineNumber());    
                    System.debug('Stack trace: ' + e.getStackTraceString());
                    system.debug('error message' +e.getMessage());
                    return e.getMessage();
                    
                }
            }
        }
        
        return Message3;
    }
    
    public class InvoiceDetailswrapper{
        @AuraEnabled
        public opportunity opportuntyObject {get;set;}
        @AuraEnabled
        public list<Invoice_Details__c> invoiceList {get;set;}
    }
    @AuraEnabled
    public static InvoiceDetailswrapper  getLoanApplicationdetails(String loanApplicationId) {
        String test='test';
        InvoiceDetailswrapper invoiceWrapper = new InvoiceDetailswrapper();
        
        list<opportunity> details=[select id,Name,RecordType.developername from opportunity where id=:loanApplicationId];
        if(details.size()!= null && details.size() >0)
        {
            invoiceWrapper.opportuntyObject = details[0];
        }
        list<Invoice_Details__c> InvdetailsOnOpp=[select id,Invoice_Date__c,Invoice_No__c,Invoice_Amount__c,Loan_Application__r.name,Invoice_Type__c,Invoice_Approval_Status__c,Chasis_Number__c,Engine_number__c from Invoice_Details__c where Loan_Application__c =:loanApplicationId];
        system.debug('invdetaisl***' +InvdetailsOnOpp);
        if(InvdetailsOnOpp.size()!= null && InvdetailsOnOpp.size() >0)
        {
            invoiceWrapper.invoiceList=InvdetailsOnOpp;
        }
        
        system.debug('***loan details2' +InvdetailsOnOpp);
        return invoiceWrapper;
    }
    
    @AuraEnabled
    public static String Newinvoice(String loanApplicationId, date InvoiceDate, string InvoiceNo,decimal CashOnHire,string InvoiceType,String ChasisNumber,String EngineNumber)
    {
        
        list<Invoice_Details__c> Invdetail=[select id,Invoice_Date__c,Invoice_No__c from Invoice_Details__c where Loan_Application__c=:loanApplicationId];
        if(Invdetail.isEmpty())
        {
            try{
                Invoice_Details__c c = new Invoice_Details__c();
                c.Invoice_Date__c=InvoiceDate;
                c.Invoice_No__c=InvoiceNo;
                c.Invoice_Type__c=InvoiceType;
                c.Loan_Application__c=loanApplicationId;
                c.Invoice_Amount__c=CashOnHire;
                c.Chasis_Number__c=ChasisNumber;
                c.Engine_number__c=EngineNumber;
                
                insert c;
                String result1=Approval(loanApplicationId,c.Id); 
                return result1;
                //salesmanger details for the opporunity
            }catch(Exception e)
            {
                return e.getMessage();
            }
        }
        else{
            system.debug('***********entered update condition');
            try{
                Id InvoiceId = Invdetail[0].id;    
                Invoice_Details__c c = new Invoice_Details__c();
                Invoice_Details__c invoicedet=[select id,Invoice_Date__c,Invoice_No__c,Invoice_Type__c,Invoice_Amount__c from Invoice_Details__c where id=:InvoiceId];
                c.Id=invoicedet.id;
                c.Invoice_Date__c=InvoiceDate;
                c.Invoice_No__c=InvoiceNo;
                c.Invoice_Type__c=InvoiceType;
                //c.Loan_Application__c=loanApplicationId;
                c.Invoice_Amount__c=CashOnHire;
                c.Chasis_Number__c=ChasisNumber;
                c.Engine_number__c=EngineNumber;
                update c;
                system.debug('updated' +c.Id);
                String result2=Approval(loanApplicationId,c.Id);
                return result2;
            }catch(Exception e)
            {
                return e.getMessage();
            }
        }        
    }
    
    @AuraEnabled
    public static String Approval(String loanApplicationId,id objectID)
    {
        
        
        List<Id> Approver = new List<Id>();
        list<user> userList=[select Id,Name,Profile.UserLicense.Name,ManagerID,Manager.Name from User where  id=:UserInfo.getUserId() AND isActive=true];
        String UserLicense = userList[0].Profile.UserLicense.Name;
        String ManagerID= userList[0].ManagerID;
        //list<user> ManagerUser= [select id,ManagerID, Manager.Name from user where ManagerID =:ManagerID];
        
        
        //String managerName= u[0].Manager;
        system.debug('userlicense' +UserLicense);
        for(user op3:userList)
        {
            if(op3.Profile.UserLicense.Name == 'Salesforce' )
            {
                Approver.add(op3.Id);
                string approvedMessage = 'success';
                return approvedMessage;
            }
            else if(op3.Profile.UserLicense.Name == 'Partner Community')
            {
                
                system.debug('***Manger name-->' +op3.Profile.UserLicense.Name);
                Id UserID= getUserId(ManagerID);
                system.debug('UserID' +UserID);
                //Approver.add(op3.ManagerID);
                if(UserId == null)
                {
                    system.debug('***user id is null');
                    String message='no userId found';
                    return message;
                }
                else
                {
                    system.debug('***user id is not null');
                    Approver.add(UserId);
                    
                }
            }
            
            
        }
        system.debug('Approver---->ID' +Approver);
        //  system.debug('salesofficer' +so);
        list<Invoice_Details__c> invdetailsUpdate=[select id,Approver__c from Invoice_Details__c where Loan_Application__c=:loanApplicationId];
        user userdetails=[select id,name from user where id in:Approver];
        Invoice_Details__c c = new Invoice_Details__c();
        c.Id=objectID;
        c.Approver__c=userdetails.name;
        update c;
        system.debug('userDetails' +userdetails);
        system.debug('InvoiceDetailsResult' +c); 
        //approval process 
        // system.debug(so);    
        Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
        req.setObjectId(objectID);
        req.setProcessDefinitionNameOrId('DuplicateInvoiceNumber');
        //List<Id> appList = new List<Id>();
        //appList.add('0056F0000082Ooo');
        req.setNextApproverIds(Approver);
        req.setSkipEntryCriteria(true);
        
        Approval.ProcessResult processResult = Approval.process(req);
        system.debug('****status' +processResult.getInstanceStatus());
        string StatusResult = processResult.getInstanceStatus();
        
        
        String message1='success';
        return message1;
    }
    
    public static Id getUserId(string ManagerID)
    {
        system.debug('***managerName**' +ManagerID);
        list<user> managerlist =[select id,Profile.UserLicense.Name,ManagerId,Manager.Name from user where Id=:ManagerID And isActive=true];
        system.debug('userList' +managerlist);
        
        if(managerlist[0].Profile.UserLicense.Name == 'salesforce')
        {
            system.debug('***manager id is null' +managerlist[0].Profile.UserLicense.Name);
            return managerlist[0].id;
        }
        else if(managerlist[0].Profile.UserLicense.Name == 'Partner Community'){
            system.debug('***partner comunity' +managerlist[0].Profile.UserLicense.Name);
            if(managerlist[0].ManagerId != null){
                system.debug('managerlist[0].Manager.Name' +managerlist[0].Manager.Name);
                getUserId(managerlist[0].ManagerId);
            }else{
                return null;
            }
            
        }
        
        return null;
    }

    @AuraEnabled
    public static list<Invoice_Details__c> getApproverDetails(String loanApplicationId)
    {
          list<Invoice_Details__c> InvApproverList=[select id,Invoice_Date__c,Invoice_No__c,Approver__c,Invoice_Approval_Status__c from Invoice_Details__c where Loan_Application__c=:loanApplicationId];
        if(InvApproverList.size() != null)
        {
          system.debug('&&&InvApproverList--' +InvApproverList);
                return InvApproverList;
            }
        else{
        return null;
        }
    }
           
}
 
Hi,

This was working perfectly fine from past so many months and suddenly 2 days back this started throwing an error while executing test classes.

Code to execute
List<Contact> listContact = ContactTestDataFactory.createContact(1, 'FirstName', 'LastName'); insert listContact;

ContactTestDataFactory Test Class -
//Create Contact object 
public static List<Contact> createContact(Integer no_of_contact,String FirstName, String LastName){ 

List<String> lstSalutation = new List<String>{'Mr.','Ms.','Mrs.','Miss.','Dr.','U.S. Senator','U.S. Representative','Governor','Governor’s Cabinet Secretaries','Attorney General','State Senator','State Representative','Judge','Mayor','Consul-General','Ambassador','Ambassador to the U.S.','President of a Country','Former President','Lady','Police Chief','Chief Marshal','Dean','Professor','Priest','Pastor','Monsignor','Cantor','Rabbi','Nun or Sister','Brother','Bishop','Cardinal','Swami'}; 

List<Contact> listContact= new List<Contact>(); Contact objCon = new Contact(); 

for(Integer i=0;i<no_of_contact ;i++){ 
objCon = new Contact(); 
objCon.FirstName= FirstName; 
objCon.LastName= LastName; 
objCon.Salutation= lstSalutation[i]; objCon.Giving_Status__c= 'Prospect'; objCon.npe01__Primary_Address_Type__c = 'Residence'; objCon.MailingStreet = 'test'+i; 
objCon.Street_2__c = 'test 2'+i; objCon.MailingState='test'+i; objCon.MailingCity='test'+i; objCon.MailingCountry='test'+i; 
objCon.Gender__c = 'Female'; 
objCon.FirstName= FirstName; if(i/2 == 0){ objCon.Gender__c= 'Male'; 
} 
else{ 
objCon.Gender__c= 'Female'; 
} 
objCon.Unique_ID__c = String.valueOf(i); listContact.add(objCon); 
} 
System.debug('listContact'+listContact); 
return listContact; 
}

ERROR thrown - 
System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, npsp.TDTM_Contact: execution of AfterInsert

caused by: System.DmlException: Insert failed. First exception on row 0; first error: DUPLICATE_VALUE, duplicate value found: <unknown> duplicates value on record with id: <unknown>: []

(npsp)






: []

Any help would be really really appreciated.

I checked other post from Stackexcahnge as well and tried work around but no luck yet.
Stack excahnge similar issue link - https://salesforce.stackexchange.com/questions/79799/how-to-debug-the-mysterious-duplicate-value-found-unknown-duplicates-value-o


--
Kind Regards
Mustafa
I have a requirement to call Flow 2 after all transaction processing from Flow 1 has been completed and to avoid creating duplicate records in Flow 2.   The issue is that I need all records, including cascading record updates, to all be fully finished before I call Flow 2. 

I'm using an Apex Action to watch the transaction processing and determine when it's safe to call Flow 2, and also to prevent duplicate records from getting sent for processing.  But the way I have the Apex code written right now, all invoked flows are getting started sequentially rather than in parallel, and therefore the queries in the flows aren't bulkified.  This causes me to hit the dreaded Too Many SOQL Queries limit.

How do I invoke multiple flows in parallel so that their SOQL operations get bulkified?   I haven't found any documentation online that answers this.

Details of the required automation below, and code snippet follows after.

Automation Requirement
Flow 1 is an automation that runs when a Campaign Member is updated.  This Flow, in some scenarios, may update or create other Campaign Member records (which triggers a cascading Process Builder).

Flow 2 is an automation that runs and sums up the Campaign Member status at the Account level.  It creates/updates records in a junction object called Account Campaign Status having the following fields:
- Account (lookup)
- Campaign (lookup)
- Overall status (text field)  - logic-derived status based on the "highest ranking" status of any contact in this account that belongs to the given Campaign

If I try to call Flow 2 directly from Flow 1, I run into 1 of 2 problems:
- If a record already exists in Account Campaign Status, I hit a governor limit if more than 12 Contacts from the same Account are in the Campaign.  The limit is around preventing more than 12 concurrent updates.
If a record doesn't already exist in Account Campaign Status, and I have multiple Contacts from the same Account, I get multiple new rows created instead of just 1 row.  I think this is because all the flows are running in parallel and therefore none of them find a record in the system at first, and then all of them try to therefore create a record.  So instead of 1 record getting created, I get 12 if there are 12 separate contacts.

Below is the transaction control code I created to compile all the account/campaign combinations and, when all upstream transactions have finished, call Flow 2. 
public class AccountCampaignRollupAction {
 static Map<ID, Set<ID>> toCalculate = new Map<ID, Set<ID>>();    
    @InvocableMethod(label='Launch Account Campaign Rollup' description='If all transactions are done processing, calls an invokable flow to roll up campaign status at the account level')   
    public static void start( List<AccountCampaignRollupRequest> requests ){
        Set<ID> nextSet;
        //go through the list of requests and pull out the unique combinations of account/campaign ID 
        //for later processing
        for( AccountCampaignRollupRequest nextReq : requests ){
            nextSet = toCalculate.get( nextReq.accountId );
            if( nextSet == null ){
                nextSet = new Set<ID>();
            }
            system.debug('Acct: ' + nextReq.accountId + ', Campaign: ' + nextReq.masterCampaignId);
            nextSet.add( nextReq.masterCampaignId );
            toCalculate.put( nextReq.accountId, nextSet );
        }//for
        
        Map<String,Object> flowVars = new Map<String,Object>();
        Flow.Interview myFlow;
        
        //now that we've built up our unique list, see if we're done with all transactions.
        //If we're not done, don't do any processing yet.
        //The static toCalculate variable will keep compiling more IDs for processing.
        if( TransactionControl.activeTransactionCount() < 1 ){
            //all transactions finished.  It's safe to kick off the calculations.
            for( ID nextAcct : toCalculate.keySet() ){
                nextSet = toCalculate.get( nextAcct );
                for( ID nextCampaign : nextSet){
                    flowVars.clear();
                    flowVars.put('InputAccountId', nextAcct );
                    flowVars.put('InputMasterCampaignId', nextCampaign);
                    system.debug('Calling flow with map: ' + flowVars);
              //HERE'S THE PROBLEM SECTION.   Because this flow is invoked in a for-loop, the flows
              //launch sequentially and their queries aren't getting bulkified.  
              //Is it possible to make a bulkified call to launch multiple flows?
              //Or if it's not possible, how do I pass in a list of account-campaign pairs
              //and then query them from the flow?
                    myFlow = Flow.Interview.createInterview( 'Account_Campaign_Status_Rollup', flowVars );
                    myFlow.start();
                }//inner for               
            }//outer for          
        }//if
        else {
            system.debug( 'Transactions still running.  Not calling flow yet' );
        }
    } 
    
    public class AccountCampaignRollupRequest{
        @InvocableVariable(required=true)
        public ID accountId;
        
        @InvocableVariable(required=true)
        public ID masterCampaignId;
    }
}

 
I'm wondering if this is just a glitch in Salesforce and if anyone has any workaround. I currently have a Trigger on ContentDocumentLink that sends an email to the owner of a custom object record when a File or Note is created and attached to that record. The trigger also attaches file information and the body of the Note if it's a ContentNote being inserted. The trigger handles the logic in differentiating Notes from other file types. The problem is when the user hits the button to create a new Note in classic or in the Console, an empty, untitled, new note record is inserted instantly firing my trigger before the user has time to add content to the body. In Lightning it at least allows the user to fill out the header of the note before saving, but saves before the note body is filled out. Cancelling out of creating the note still leaves the blank note saved and attached to the record. Any help in understanding why the note saves before the user hits the save button would be appreciated.
Hi,

I am new to Lightning Component with fair knowledge in Apex and VF. I have a custom object(B) that is lookup relationship field to the Contact record. I want to create a Lightning Component to display the Contact's related custom object (B) in Gmail (Lightning for Gmail side panel). So whenever I access an Email, the component will display that contact's related custom object. Please help with the code! Thanks.
  • July 25, 2018
  • Like
  • 2

 
Hi all,

We need to implement the following pattern at my org:
  • callout to external data source
  • if that callout takes too long (according to some configurable threshold), log an error (ie do some DML)
  • if that callout timed out on the remote server, try it again
Recognizing the potential for the dreaded "You have uncommitted work pending. Please commit or rollback before calling out." error, I put the error logging code in a future method, thus isolating the DML from the callouts. However, the error is still being thrown. I reduced the issue down to this pattern:
public static void foo() {
    Http http = new Http();
    HttpRequest req = new Httprequest();
    req.setEndpoint('https://test.salesforce.com'); //whatever endpoint
    req.setMethod('GET');
    http.send(req); //works fine
    bar();
    http.send(req); //throws calloutexception
}

@future public static void bar() {

}
Am I correct to assume that calling a future method counts as a DML operation? Is there any documentation I'm missing somewhere?

 
I am creating a form in Visualforce. Since my form is a bit long, it is hard for users to remember the error message at the top and revise it. On top of the error message, I want to create a validation when users typing in their information.
For example, there are 2 field, users name and email. Users cannot leave the name field blank, if so, I want to show a message of "This field is required to fill in" beside the field. And for email field, I want to have another message to remind users to insert a valid email.
Is there anyway in visualforce to do so? Thanks for your help.
Got Issue In Below Code.
if((
                   Schema.SObjectType.Custom_Setting__c.isCreateable() &&
                   Schema.SObjectType.Custom_Setting__c.fields.Name.isCreateable() &&
                   Schema.SObjectType.Custom_Setting__c.fields.UserName__c.isCreateable() &&
                   Schema.SObjectType.Custom_Setting__c.fields.Password__c.isCreateable() ) ||
                                      
                   (Schema.sObjectType.Custom_Setting__c.isUpdateable() &&
                   Schema.SObjectType.Custom_Setting__c.fields.Name.isUpdateable()  ) {
                   
                   
                    Custom_Setting__c cs = new Custom_Setting__c(UserName__c = username, Password__c = password, Name = usr.Name);
                    upsert cs Name;
                   
                   }
Hi, I currently have the professional edition. I have two regional managers and they each have a team of salesmen, those salesmen have assigned accounts/opportunities, I want the regional managers to see their salesmen accounts ONLY. Is that possible without assigning them those accounts/opps?