function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
sumit dsumit d 

Trigger to delete assets

Hi All,
I want to delete assets when its related opportunity line item is deleted.
i have a trigger helper given below:-
public  without sharing class OpportunityLineItemTriggerHelper {
    
    public static List<OpportunityLineItem> newOpportunityLineItem = new List<OpportunityLineItem>();
    public static List<OpportunityLineItem> oldOpportunityLineItem = new List<OpportunityLineItem>();
    public static Map<Id, OpportunityLineItem> newMapOpportunityLineItem = new Map<Id, OpportunityLineItem>();
    public static Map<Id, OpportunityLineItem> oldMapOpportunityLineItem = new Map<Id, OpportunityLineItem>(); 
    
    Public static void deleteAssets(){
        
        list<id> ProductIds=new list<id>();
        for(Product2 prod :  [SELECT id,Name
                              FROM Product2 
                              ] )
        {
            ProductIds.add(Prod.id);
        }  
        List<Asset> deleteListAsset = new List<Asset>();
        //Collecting all child records related to Parent records
        list<Asset> listOfAssets = [ select id, Product2Id 
                                     from Asset 
                                     where Product2Id in :ProductIds ];
        for(OpportunityLineItem oli : oldOpportunityLineItem){
            for(Asset ast : listOfAssets){
                if (ast.Product2Id == oli.Product2Id){
                    deleteListAsset.add(ast);
                    
                }
             }
            System.debug('deleteListAsset'+deleteListAsset);
        }
        
        system.debug('listOfAssets'+listOfAssets);
        //deleting Asset records
        if( deleteListAsset.Size() > 0 ){
             delete deleteListAsset;
        }
     }
 }
Can anyone help me with this requirement if i am doing it wrong?
Any suggestions?
Andrew GAndrew G
Hi

i'm concerned about how you are treating Assets.
Lets think through the "usual" relationship between Products and Assets, with an example.
Product 1 is a PC.  When I sell the PC (as a product), it becomes an Asset, so AS-001.  If I sell another PC, it becomes AS-002.  Both Assets have a relation to the Product 1 (the PC model).
So now lets look at your requirement:
If i have an Oppty with an OLI for Product 1 (the PC).  Your requirement is that if I delete the OLI for the PC (Product 1), you want to delete the Assets associated with that Product, so AS-001 and AS-002 are deleted from the system.  
The idea of creating the Asset in the first place is to give a place holder for records like Warranty or Service calls/reminders. All that is out the window if you delete the Asset because a unrelated OLI has the same underlying product.

Regards
Andrew