I really need help with my code. I am trying to update Account records with lookup field to right Pricebook2 based on Customer_Price_Group__c field on Account and Pricebook2.
Customer_Price_Group__c is on Account and on Pricebook2. I need to fetch and fill the lookup on Account record.
global class pricebookOnAccount implements Database.Batchable<sObject> {
global Database.Querylocator start(Database.BatchableContext BC) {
return Database.getQueryLocator([Select id, Customer_Price_Group__c, Price_book__c FROM Account WHERE Actual_Pricebook__c = FALSE AND Customer_Price_Group__c != null]);
}
global void execute(Database.BatchableContext BC,List<Account> scope) {
List<Account> accRec = [Select id, Customer_Price_Group__c, Price_book__c FROM Account WHERE Customer_Price_Group__c != null AND Actual_Pricebook__c = FALSE AND Id = :scope];
Map<id, Pricebook2> pricebooks = new Map<id, Pricebook2>();
for(Account record: accRec) {
pricebooks.put(record.Price_book__c, null);
}
pricebooks.putAll([SELECT id FROM Pricebook2 WHERE Year_is_actual__c = TRUE AND Customer_Price_Group__c = :accRec AND Id = :pricebooks.keySet()]);
for(Account a:accRec) {
a.Price_book__c = pricebooks.get(a.id);
}
update accRec;
}
global void finish(Database.BatchableContext BC){}
}
Now I am getting errors:
Line 12: Invalid bind expression type of Account for column of type String
Line 14: Illegal assignment from Pricebook2 to Id
WORKING CODE:
global class pricebookOnAccount implements Database.Batchable<sObject> {
global Database.Querylocator start(Database.BatchableContext BC) {
return Database.getQueryLocator([Select id, Customer_Price_Group__c, Price_book__c FROM Account WHERE Actual_Pricebook__c = FALSE AND Customer_Price_Group__c != null]);
}
global void execute(Database.BatchableContext BC,List<Account> scope) {
List<Account> accRec = [Select id, Customer_Price_Group__c, Price_book__c FROM Account WHERE Customer_Price_Group__c != null AND Actual_Pricebook__c = FALSE AND Id = :scope];
Map<String, Id> pricebookByGroup = new Map<String, Id>();
Set<String> priceGroups = new Set<String>();
for(Account record: accRec) {
priceGroups.add(record.Customer_Price_Group__c);
}
for(Pricebook2 record: [SELECT Customer_Price_Group__c FROM Pricebook2 WHERE Year_Is_Actual__c = true AND Customer_Price_Group__c = :priceGroups]) {
pricebookByGroup.put(record.Customer_Price_Group__c, record.Id);
}
for(Account record: accRec) {
record.Price_Book__c = pricebookByGroup.get(record.Customer_Price_Group__c);
}
update accRec;
}
global void finish(Database.BatchableContext BC){}
}