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
Siddharth LakhotiaSiddharth Lakhotia 

How can I look for one record in a agreegated table?

Hi,

I have an invoice module.

I want whenever invoices come from ERP system , it automatically sums up the value of Total Sum against a blanket no. and updates it on another object Invoice Details..

PS: I have already a trigger on Invoice details, sums up the value of Total Sum against a blanket no . , so whenever a sales rep selects a blanket no. against a project , the summed value of Total sum appears...

But sometimes invoice comes later in system , lets say after a month. In that case, I require whenever the invoice comes , it automatically updates the value on Invoice Details

How can it be done ? Do i need to write a trigger against it or a batch class will be required?
Syed Insha Jawaid 2Syed Insha Jawaid 2
Hi Siddharth

You cn create a trigger on Invoice which updates the related Invoice detail with the updated Total Sum value.

Cheers!!
Siddharth LakhotiaSiddharth Lakhotia
Can you tell me how ?
Syed Insha Jawaid 2Syed Insha Jawaid 2
Hi Siddharth

Create a trigger on Invoice.On its after Insert event iterate through the Invoices (triggerNew) and calculate sum of each of the Invoices w.r.t the blanket no.
You can use a Map for this purpose which would contain blanket No as the key and the total sum as the value.
Then query the invoice detail record using the blanket No key set from the map created earlier.
Then iterate through this list and add the new sum to the invoice detail record.

Pseudo Code: 

TRIGGER ON INVOICE <after insert> {
Map < String,Double >  mapOfBlanketNoVsTotalInvoiceSum = new Map < String, Double >();
for(Invoice inv : triggerNew) {
......
if(mapOfBlanketNoVsTotalInvoiceSum.containskey(inv .BLANKETNO) {
mapOfBlanketNoVsTotalInvoiceSum.put(inv .BLANKETNO, mapOfBlanketNoVsTotalInvoiceSum.get(inv .BLANKETNO) + inv.TOTALSUM));
} else {
mapOfBlanketNoVsTotalInvoiceSum.put(inv .BLANKETNO,  inv.TOTALSUM));
}
........  
}
List < INVOICE_DETAIL> lstOfInvoiceDetails = [SELECT Id , TOTLASUM, BLANKET_NO from INVOICE_DETAIL where BLANKETNO in : mapOfBlanketNoVsTotalInvoiceSum.KeySet()];
.......
for(INVOICE_DETAIL invdet : lstOfInvoiceDetails ) {
invdet .TOTALSUM += mapOfBlanketNoVsTotalInvoiceSum.get(invdet .BLANKET_NO);
}

update lstOfInvoiceDetails ;

Hope this helps!!!!!

Cheers!!