I wrote an Opportunity Trigger that should run when an Opportunity is Closed Won.
This trigger should change the status of a custom object we use to record the status of subscriptions to specific products on a per account basis.
The idea was to change the status of all of these objects to "Deferred" and then change the ones that are being purchased to "Purchased".
Here's the code:
trigger ConvertProducts on Opportunity (after update) {
List<Id> accIds = new List<Id>();
List<Id> oppIds = new List<Id>();
for(Opportunity a : Trigger.new){
if(a.StageName == 'Closed Won'){
accIds.add(a.Account.Id);
oppIds.add(a.Id);
}
}
if(oppIds != null){
List<OpportunityLineItem> oppLineItemList = new List<OpportunityLineItem>([SELECT Id, OpportunityId, Opportunity.Account.Id, Name, Product2Id, UnitPrice FROM OpportunityLineItem WHERE OpportunityId IN :oppIds]);
List<ProductInformation__c> prodInfoList = new List<ProductInformation__c>([SELECT Id, Name, Account__c, Status__c, Product__c, Purchased_Date__c FROM ProductInformation__c WHERE Account__c IN :accIds]);
for(ProductInformation__c c : prodInfoList){
c.Status__c = 'Deferred';
c.Purchased_Date__c = null;
}
for(OpportunityLineItem a : oppLineItemList){
for(ProductInformation__c b : prodInfoList){
if(a.Opportunity.Account.Id == b.Account__c && a.Product2Id == b.Product__c){
b.Status__c = 'Purchased';
b.Purchased_Date__c = date.today();
}
}
}
update prodInfoList;
}
}