+ Start a Discussion
JTull79JTull79 

Receiving APEX Code Error now that we started using Price Book

We have code created by consultant that allows us to have a product record type of Package.  When a user selects a package from the product list.  They can then unbundle it on the opportunity.  When they do this, it removes the package, inserts the individual products, and adds the configuration elements associated with the products.  This has worked for years until we created and started using price books.  Now we get the following error when we try to unbundle the package:

 

System.DmlException: Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception: PricebookEntryId (pricebook entry is in a different pricebook than the one assigned to the opportunity): [PricebookEntryId]

 

Class.ProductPackageUnbundle.unbundle: line 95, column 1

 

I have no APEX background but it appears that it is always trying to use the Standard Price book.  However, if I use the standard price book, I still get the error when I try to unbundle.  Any help anyone can provide as to what needs to be changed in the code would be greatly appreciated!

 

Here is the code:

 

public class ProductPackageUnbundle {
/*
  Onclick of Unbundle button on Opportunity Products related list
  Look for all opportunity line items with Record type of "Package"
  look to Master_Package_Product__c and insert products related and delete Package record
  use Selling amount from Package record if it is not null
  Create Configurtion elements using the default values.
  

 
*/
    public ProductPackageUnbundle(ApexPages.StandardController stdController) {
            
    }
    
    public final opportunity oppty = [select id,name,pricebook2id,currencyisocode from opportunity where id = :apexpages.currentpage().getparameters().get('id')];
    public final pricebook2 pb2 = [select id,name from pricebook2 where name = 'Standard Price Book'];
    public pagereference unbundle(){
    
      
      string sellingprice;
      //Select all opportunity line items that have a record type of "Package"
      recordtype rtype = [select id from recordtype where name = 'Package' and SobjectType='Product2' limit 1];
      if (rtype.id != null){
        system.debug('recordtype'+rtype.id);
      //selects all line items for opportunity that have record type of package
      list<opportunitylineitem> opliNew = [select id,pricebookentry.Product2Id,quantity from opportunitylineitem where pricebookentryid in (select id from pricebookentry where product2.RecordTypeId = :rtype.id) and opportunityid = :oppty.id];  
      
      if(opliNew.size()!=0){
        set<id> packageID = new set<id>();
        map<id,double> opliQty = new map<id,double>();
        for (opportunitylineitem opliLoop : opliNew){
          packageID.add(opliLoop.pricebookentry.product2id);
          opliQty.put(opliLoop.pricebookentry.product2Id,opliLoop.Quantity);  
        }
        
        list<master_package_product__c> mpp = [select id,name,product__c,package__c,master_configuration_element__c,package__r.name from master_package_product__c where package__c in :packageID and product__c != null];
        system.debug('MPP'+mpp);
        if(mpp.size()>0){
        // Loop through the records and create opportunity line items.
        set<string> mppPackageProduct = new set<string>();
        set<id> mppProduct = new set<id>();
        map<id,id> mppPackage = new map<id,id>();
        map<id,string> mppPackageName = new map<id,string>();
        for (Master_Package_Product__c mppLoop : mpp){
          mppProduct.add(mppLoop.product__c);
          mppPackageProduct.add((''+mppLoop.package__c + mppLoop.product__c));
          mppPackageName.put(mppLoop.package__c,mppLoop.package__r.name);
        }
        system.debug('mppProduct'+mppProduct);
        list<pricebookentry> pbe = [Select id,product2.Name, product2.description,product2.family,product2.Product_Solution__c,product2.Product_Category__c,product2.id,product2.type__c From pricebookentry Where product2.id in :mppProduct and isactive = true  limit 1000];
        // add pricebook entry to map used when looping through packages
        map<id,pricebookentry> pbeMap = new map<id,pricebookentry>();
        for (pricebookentry pbeLoop : pbe){
          pbeMap.put(pbeLoop.product2.id,pbeLoop);  
        }
        system.debug('PBEMAP'+pbeMap);
        list<opportunitylineitem> opliProduct = new list<opportunitylineitem>();
        string tempPackage;
        string tempProduct;
        
        for (string mppLoop2 : mppPackageProduct) {
              if(mppLoop2.length()==36){
                tempPackage = mppLoop2.substring(0,18);
                tempProduct = mppLoop2.substring(18,36);
              }else{
                tempPackage = '';
                tempProduct = '';
              }
              
              if(pbeMap.get(tempProduct)!=null){
                pricebookentry pbeTemp = pbeMap.get(tempProduct);
                  opportunitylineitem opliTemp = new opportunitylineitem();
                     system.debug('PBETEMP'+pbeTemp);
                  opliTemp.pricebookentryid=pbeTemp.id;
                
                //opliTemp.pricebookentryid=pbeLoop.Id;
                opliTemp.opportunityid=oppty.id;
                // for product type of service use qty from Original package
                //changed code to set qty to 1 except for Service with Qty other than 1 011711 DPC
                if(pbeTemp.product2.type__c == 'Service' && opliQty.get(tempPackage)!=null){
                  opliTemp.quantity = opliQty.get(tempPackage);
                  } else {
                  opliTemp.quantity = 1;
                }
                opliTemp.unitprice=0;
                if(mppPackageName.get(tempPackage)!= null){
                  opliTemp.Description = '' + mppPackageName.get(tempPackage);
                }
                opliTemp.OP_SFDC_ID__c = tempPackage;
                opliProduct.add(opliTemp);
          }
            }
            if(opliProduct.size()>0){
              insert opliProduct;
              //create Product Configuration Elements
              productPackageElements ppe = new productPackageElements();
              boolean fromPackage = true;
              string successCode = ppe.CreateElements(opliProduct, fromPackage);
              
              
              // Update the Percentage complete on Create
              productPackagePercentCalc pppc = new productPackagePercentCalc();
              pppc.updatePercentage(opliProduct);
              system.debug('\n\nDELETEOPLINEW'+opliNew);
              delete opliNew;
            }
        } else {
          //Error there should be products for packages
           ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'A package you selected has no products Call your Salesforce Administrator'));
        }
        //Lookup all related products from Master_Package_product
          
        
        
        
        
        PageReference opptyPage = new ApexPages.StandardController(oppty).view();
        opptyPage.setRedirect(true);
        return opptyPage;
      } else {
       ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'No Packages to Unbundle'));
       return null;
      }
      
      
    //End of Package code if statement
    }
      
      
      
    return null;  
    }
  public pagereference back(){
    //Sends the user back to the opportunity page
    PageReference opptyPage = new ApexPages.StandardController(oppty).view();
        opptyPage.setRedirect(true);
        return opptyPage;
  }


}

 

 

 

 

 

   

rohitsfdcrohitsfdc
Hello Jtull,
This code is not designed to work with pricebooks. Try updating the code with following code. if it works, fine, else the code needs to be revisited by a developer. Let me know the outcome
 
public class ProductPackageUnbundle {
/*
  Onclick of Unbundle button on Opportunity Products related list
  Look for all opportunity line items with Record type of "Package"
  look to Master_Package_Product__c and insert products related and delete Package record
  use Selling amount from Package record if it is not null
  Create Configurtion elements using the default values.
  

 
*/
    public ProductPackageUnbundle(ApexPages.StandardController stdController) {
            
    }
    
    public final opportunity oppty = [select id,name,pricebook2id,currencyisocode from opportunity where id = :apexpages.currentpage().getparameters().get('id')];
    public final pricebook2 pb2 = [select id,name from pricebook2 where name = 'Standard Price Book'];
    public pagereference unbundle(){
    
      
      string sellingprice;
      //Select all opportunity line items that have a record type of "Package"
      recordtype rtype = [select id from recordtype where name = 'Package' and SobjectType='Product2' limit 1];
      if (rtype.id != null){
        system.debug('recordtype'+rtype.id);
      //selects all line items for opportunity that have record type of package
      list<opportunitylineitem> opliNew = [select id,pricebookentry.Product2Id,quantity from opportunitylineitem where pricebookentryid in (select id from pricebookentry where product2.RecordTypeId = :rtype.id) and opportunityid = :oppty.id];  
      
      if(opliNew.size()!=0){
        set<id> packageID = new set<id>();
        map<id,double> opliQty = new map<id,double>();
        for (opportunitylineitem opliLoop : opliNew){
          packageID.add(opliLoop.pricebookentry.product2id);
          opliQty.put(opliLoop.pricebookentry.product2Id,opliLoop.Quantity);  
        }
        
        list<master_package_product__c> mpp = [select id,name,product__c,package__c,master_configuration_element__c,package__r.name from master_package_product__c where package__c in :packageID and product__c != null];
        system.debug('MPP'+mpp);
        if(mpp.size()>0){
        // Loop through the records and create opportunity line items.
        set<string> mppPackageProduct = new set<string>();
        set<id> mppProduct = new set<id>();
        map<id,id> mppPackage = new map<id,id>();
        map<id,string> mppPackageName = new map<id,string>();
        for (Master_Package_Product__c mppLoop : mpp){
          mppProduct.add(mppLoop.product__c);
          mppPackageProduct.add((''+mppLoop.package__c + mppLoop.product__c));
          mppPackageName.put(mppLoop.package__c,mppLoop.package__r.name);
        }
        system.debug('mppProduct'+mppProduct);
        list<pricebookentry> pbe = [Select id,product2.Name, product2.description,product2.family,product2.Product_Solution__c,product2.Product_Category__c,product2.id,product2.type__c From pricebookentry Where product2.id in :mppProduct and pricebook2.isStandard=true and isactive = true  limit 1000];
        // add pricebook entry to map used when looping through packages
        map<id,pricebookentry> pbeMap = new map<id,pricebookentry>();
        for (pricebookentry pbeLoop : pbe){
          pbeMap.put(pbeLoop.product2.id,pbeLoop);  
        }
        system.debug('PBEMAP'+pbeMap);
        list<opportunitylineitem> opliProduct = new list<opportunitylineitem>();
        string tempPackage;
        string tempProduct;
        
        for (string mppLoop2 : mppPackageProduct) {
              if(mppLoop2.length()==36){
                tempPackage = mppLoop2.substring(0,18);
                tempProduct = mppLoop2.substring(18,36);
              }else{
                tempPackage = '';
                tempProduct = '';
              }
              
              if(pbeMap.get(tempProduct)!=null){
                pricebookentry pbeTemp = pbeMap.get(tempProduct);
                  opportunitylineitem opliTemp = new opportunitylineitem();
                     system.debug('PBETEMP'+pbeTemp);
                  opliTemp.pricebookentryid=pbeTemp.id;
                
                //opliTemp.pricebookentryid=pbeLoop.Id;
                opliTemp.opportunityid=oppty.id;
                // for product type of service use qty from Original package
                //changed code to set qty to 1 except for Service with Qty other than 1 011711 DPC
                if(pbeTemp.product2.type__c == 'Service' && opliQty.get(tempPackage)!=null){
                  opliTemp.quantity = opliQty.get(tempPackage);
                  } else {
                  opliTemp.quantity = 1;
                }
                opliTemp.unitprice=0;
                if(mppPackageName.get(tempPackage)!= null){
                  opliTemp.Description = '' + mppPackageName.get(tempPackage);
                }
                opliTemp.OP_SFDC_ID__c = tempPackage;
                opliProduct.add(opliTemp);
          }
            }
            if(opliProduct.size()>0){
              insert opliProduct;
              //create Product Configuration Elements
              productPackageElements ppe = new productPackageElements();
              boolean fromPackage = true;
              string successCode = ppe.CreateElements(opliProduct, fromPackage);
              
              
              // Update the Percentage complete on Create
              productPackagePercentCalc pppc = new productPackagePercentCalc();
              pppc.updatePercentage(opliProduct);
              system.debug('\n\nDELETEOPLINEW'+opliNew);
              delete opliNew;
            }
        } else {
          //Error there should be products for packages
           ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'A package you selected has no products Call your Salesforce Administrator'));
        }
        //Lookup all related products from Master_Package_product
          
        
        
        
        
        PageReference opptyPage = new ApexPages.StandardController(oppty).view();
        opptyPage.setRedirect(true);
        return opptyPage;
      } else {
       ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR,'No Packages to Unbundle'));
       return null;
      }
      
      
    //End of Package code if statement
    }
      
      
      
    return null;  
    }
  public pagereference back(){
    //Sends the user back to the opportunity page
    PageReference opptyPage = new ApexPages.StandardController(oppty).view();
        opptyPage.setRedirect(true);
        return opptyPage;
  }


}