My requirement is to take any pricebook entry made in the standard pricebook and replicate/update it in a second price book. With the code below I keep getting the error FIELD_INTEGRITY_EXCEPTION, This price definition already exists in this price book. I have read everything I could find, but I cannot figure out what I need to change.
Any help would be much appreciated.
global class pricebookEntryCopybatch implements Database.Batchable<sObject>{
public final string query;
Set<Id> pbeIds = new Set<Id>();
Pricebook2 stdPrice = [Select id, isActive from Pricebook2 where isStandard=true limit 1];
Pricebook2 fdaPrice = [Select id, isActive from Pricebook2 where Name='FDA Pricebook' limit 1];
global pricebookEntryCopybatch(){
query = 'Select Id, Pricebook2Id, isActive, SystemModStamp from PriceBookEntry ';
}
global Database.querylocator start(Database.BatchableContext BC){
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<sObject> scope){
for(sObject s : scope){
for(PricebookEntry pbe : (List<PricebookEntry>)scope){
if(pbe.Pricebook2Id == stdPrice.Id && pbe.IsActive == true && pbe.SystemModStamp > Datetime.now().addMinutes(-15)){
pbeIds.add(pbe.id);
}
}
List<PricebookEntry> pbeforinsert = new List<PricebookEntry>();
system.debug('***************************************stdPrice ' +stdPrice);
system.debug('***************************************fdaPrice ' +fdaPrice);
List<PricebookEntry> stdPBE = [SELECT Pricebook2Id, IsActive, UnitPrice, Id, Product2Id, CurrencyIsoCode FROM PricebookEntry Where Id in: pbeIds];
for(PricebookEntry pbecopy : stdPBE){
PricebookEntry pbesToAdd = new PricebookEntry();{
pbesToAdd.Pricebook2Id = fdaPrice.Id;
pbesToAdd.IsActive = pbecopy.IsActive;
pbesToAdd.Product2Id = pbecopy.Product2Id;
pbesToAdd.UnitPrice = pbecopy.UnitPrice;
pbesToAdd.CurrencyIsoCode = pbecopy.CurrencyIsoCode;
pbeforinsert.add(pbesToAdd);
}
}
insert pbeforinsert;
}
}
global void finish(Database.BatchableContext BC){
}
}