Skip to content

Instantly share code, notes, and snippets.

@liuxiachanghong
Last active February 22, 2021 03:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liuxiachanghong/7ac277f158f64ec54a3f4c3543a15832 to your computer and use it in GitHub Desktop.
Save liuxiachanghong/7ac277f158f64ec54a3f4c3543a15832 to your computer and use it in GitHub Desktop.
trigger Booking2EditionTrigger on Booking__c (after insert, after update, after delete) {
// prepare set collection for bulk udpate at the end of the trigger
List<Edition__c> editionsUpdate = new List<Edition__c>();
Set<String> editionIds = new Set<String>();
editionIds.add('firstEdition');
// loop the triggered booking
for (Booking__c booking : Trigger.new){
// find edition of the triggering booking
Edition__c targetEdition = new Edition__c();
targetEdition = [
SELECT Id, ActualTotal__c, EstimateTotal__c, SuspendedTotal__c, CancelledTotal__c
FROM Edition__c
WHERE Id = :booking.Edition__c
LIMIT 1
];
// provide variables
Decimal actual = 0;
Decimal estimate = 0;
Decimal suspended = 0;
Decimal cancelled = 0;
// if edition is already run the rollup process, then skip
If (!editionIds.contains(targetEdition.Id) && editionIds!=null) {
editionIds.add(targetEdition.Id);
// find all related bookings of the edition
List<Booking__c> relatedBookings = [
SELECT NetCost__c,Edition__c,Status__c
FROM Booking__c
WHERE Edition__c = :targetEdition.Id
];
//store the rolled-up values by booking status
for (Booking__c eachBooking : relatedBookings){
if (eachBooking.Status__c !=null && eachBooking.Status__c == 'Actual') {actual += eachBooking.NetCost__c;}
else if (eachBooking.Status__c !=null && eachBooking.Status__c == 'Estimate') {estimate += eachBooking.NetCost__c;}
else if (eachBooking.Status__c !=null && eachBooking.Status__c == 'Suspended') {suspended += eachBooking.NetCost__c;}
else if (eachBooking.Status__c !=null && eachBooking.Status__c == 'Cancelled') {cancelled += eachBooking.NetCost__c;}
}
// assign the rolled-up values to each field
if(actual!=null) {targetEdition.ActualTotal__c = actual ;}
if(estimate!=null) {targetEdition.EstimateTotal__c = estimate ;}
if(suspended!=null){targetEdition.SuspendedTotal__c = suspended;}
if(cancelled!=null){targetEdition.CancelledTotal__c = cancelled;}
// add to the collection
editionsUpdate.add(targetEdition);
}
}
// bulk update
update editionsUpdate;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment