Advertisement
Guest User

Update Invoice with Invoice Line Item Amounts

a guest
Feb 22nd, 2020
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.95 KB | None | 0 0
  1. trigger InvoiceLineItemTrigger on Invoice_Line_Item__c (after insert, after update, after delete, after undelete) {
  2.     // Get the parent Invoice Ids.
  3.     Set<Id> invoiceIds = new Set<Id>();
  4.     for (Invoice_Line_Item__c lineItem : Trigger.new) {
  5.         // Add the Invoice Id from each Line Item to the list
  6.         invoiceIds.add(lineItem.Invoice__c);
  7.     }
  8.  
  9.     // Map to relate parent Invoice Id to the Amount roll-up value from all child Invoice Line Item records
  10.     // The first time we see the Invoice, we will make the map entry
  11.     // Next time we will add the Amount to the existing value
  12.     Map<Id, Decimal> invoiceToAmountMap = new Map<Id, Decimal>();
  13.  
  14.     for (Invoice_Line_Item__c lineItem : [SELECT Id, Invoice__c, Amount__c
  15.                                             FROM Invoice_Line_Item__c
  16.                                             WHERE Invoice__c IN :invoiceIds]) {
  17.  
  18.         Decimal newInvoiceAmount = lineItem.Amount__c;
  19.         // If the map already has a value for this Invoice, add that to this amount
  20.         if (existingInvoiceAmount.containsKey(lineItem.Invoice__c)) {
  21.             Decimal existingMapValue = invoiceToAmountMap.get(lineItem.Invoice__c);
  22.             newInvoiceAmount = newInvoiceAmount + existingInvoiceAmount;
  23.         }
  24.         // Now put the new amount into the map
  25.         invoiceToAmountMap.put(lineItem.Invoice__c, newInvoiceAmount);
  26.     }
  27.  
  28.     // List to put the Invoice records that need their Amount__c roll-up updated
  29.     List<Invoice__c> invoicesToUpdate = new List<Invoice__c>();
  30.  
  31.     // Now we will make the Invoice records to update
  32.     for (Id invoiceId : invoiceToAmountMap.keySet()) {
  33.         Decimal invoiceAmount = invoiceToAmountMap.get(invoiceId);
  34.         Invoice__c tempInvoice = new Invoice__c(
  35.             Id = invoiceId,
  36.             Amount__c = invoiceAmount
  37.         );
  38.         invoicesToUpdate.add(tempInvoice);
  39.     }
  40.    
  41.     // update the invoices
  42.     update invoicesToUpdate;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement