+ Start a Discussion
Pairin MasonPairin Mason 

field integrity exception: PricebookEntryId (When inserting OpportunityLineItem)

Hi there,

The error:
Insert failed. First exception on row 0; first error: FIELD_INTEGRITY_EXCEPTION, field integrity exception: PricebookEntryId (pricebook entry currency code does not match opportunity currency code): [PricebookEntryId]

I keep getting this error in my unit test when I try inserting a OpportunityLineItem. It worked fine before.
I checked the pricebook's CurrencyIsoCode and Opportunity's CurrencyIsoCode in the debug and they matched perfectly, but OpportunityLineItem's CurrencyIsoCode displayed as a null. 

Here are my code:

=== My Unit Test ==

  Opportunity oppTest1 = new Opportunity();
  oppTest1.Name = 'TestOppty1';
  oppTest1.StageName = 'Quotation';
  oppTest1.Link_to_Quote_or_Proposal__c = 'test';
  oppTest1.Evaluation_Goals__c = 'test goal';
  oppTest1.Squiggly__c = 'Email';
  oppTest1.CloseDate = Date.today();
  oppTest1.CurrencyIsoCode = 'CAD';
  oppTest1.AccountId = TestAccount.Id;
  insert oppTest1;
 

  insert OpportunityHelper.CreateOpporLineItem(oppTest1, SupportProduct); 
 
  return oppTest1;
 
}


=== OpportunityHelper Class===

public static OpportunityLineItem CreateOpporLineItem(Opportunity opp, Product2 prod)
{
  PricebookEntry pBookEntry = GetPricebookEntry(prod, opp.CurrencyIsoCode);
 
  OpportunityLineItem item = new OpportunityLineItem();

  item.PricebookEntryId = pBookEntry.Id;
  item.OpportunityId = opp.Id;
  item.Asset_Id__c = null;
  item.Quantity = 1;
  item.UnitPrice = pBookEntry.UnitPrice;
  item.ServiceDate = opp.CloseDate;

  insert item;
  return item;
}

public static PricebookEntry GetPricebookEntry(Product2 prod, string cIso)
{
  return GetPricebookEntry(prod, DefaultPricebook, cIso);
}

public static PricebookEntry GetPricebookEntry(Product2 prod, Pricebook2 pbook, string cIso)
{
  if (prod == null || [SELECT count() FROM PricebookEntry WHERE Pricebook2Id = :pbook.Id AND CurrencyIsoCode = :cIso AND Product2Id = :prod.Id] <= 0)
   return null;
 
  return [SELECT Id, Name, UnitPrice, CurrencyIsoCode FROM PricebookEntry WHERE Pricebook2Id = :pbook.Id AND CurrencyIsoCode = :cIso AND Product2Id = :prod.Id LIMIT 1];
}

Any idea?

KevinPKevinP
Assuming you have multi-currency enabled? what is the value of the Opportunity.OpportunityCurrency field?
Pairin MasonPairin Mason

Thank you KevinP.

Yes, I have multi-currency enabled. 

It seems that my issue was solved by setting the CurrencyIsoCode='CAD' in the test account which will be used in my test opportunity. 

 

Account TestAcc = new Account(name=nameStr, billingcountry=country, type='Customer', CurrencyIsoCode='CAD'); 

 

As I traced back the issue, I found that a trigger on Opportunity has changed my test Opportunity.CurrencyIsoCode to the default's currency code of the Account Owner when the test Opportunity was inserted.

By leaving out the CurrencyIsoCode when creating a test account, it caused the error.