Search code examples
salesforceapex-codeapex

Get Sale ID to acquire child objects items quantity and check then with stock


Continuing with my trials of solving the problematic with initial skills of apex development I have the next problematic:

I'm trying to get Sales__c Id with status 'Sold', with the Sale Id check inside the Order_Item__c that belongs to the Sale values Vehicle_Name__c,Item_Quantity__c.

Then search by Vehicle_Name__c inside Vehicle__c and check if Vehicle__c.Quantity__c <= Order_Item__c.Item_Quantity__c

This is what I managed to do so far but its not working and I have no clue on how to continue.

Could someone help me please with the code?

trigger SaleCheckout on Sales__c (before update) {

    Set<String> sale = new Set<String>();

    for (Sales__c s : Trigger.new){
        sale.add(s.Id);

        //Sale ID
        System.debug('1-- Sale ID: '+ sale);        
    }

    List<Order_Item__c> orders = [SELECT Id,Vehicle_Name__c,Item_Quantity__c FROM Order_Item__c WHERE Sale__c  IN : sale];
    // Orders with Sale ID
    System.debug('2-- Orders IDs: ' + orders);



}

Solution

  • Your object structure is unclear. I think you have the following objects:

    Sales__c with fields: Id, Status
    Order_Item__c with fields: Id, Sale__c, Vehicle_Name__c, Item_Quantity__c
    Vehicle__c with fields: Id, Name, Quantity__c

    I'm not sure why you are referencing vehicles by name instead of Id, but that's your call. If that's the case, something like this should work:

    trigger SaleCheckout on Sales__c (before update) {
      List<Order_Item__c> orders = [SELECT Vehicle_Name__c, Item_Quantity__c FROM Order_Item__c WHERE Sale__c IN :Trigger.new AND Sale__r.Status = 'Sold'];
      System.debug('2-- Orders IDs: ' + orders);
    
      Set<String> vehicleNames = new Set<String>();
      for (Order_Item__c order : orders)
      {
        vehicleNames.add(order.Vehicle_Name__c);
      }
    
      List<Vehicle__c> vehicles = [SELECT Name, Quantity__c FROM Vehicle__c WHERE Name IN :vehicleNames];
      for (Vehicle__c vehicle : vehicles)
      {
        for (Order_Item__c order: orders)
        {
          if (order.Vehicle_Name__c == vehicle.Name && vehicle.Quantity__c < order.Item_Quatity__c)
          {
            //do something here, let's say we want to fail the sale
            Trigger.newMap.get(order.Sale__c).addError('You are trying to sell more cars than we have! You sold ' + String.valueOf(order.Item_Quantity__c) + ' cars of type ' + order.Vehicle_Name__c + ' and we only have ' + String.valueOf(vehicle.Quantity__c) + ' on the lot!');
          }
        }
      }
    }
    

    This assumes that you don't have multiple orders for the same car, in which case you'd probably have to add up the quantities of multiple orders. Keep in mind I just wrote that code out in SO and it can easily contain errors.