Last active
May 31, 2017 13:16
-
-
Save tfuda/fead43c41b4ef415a7fdc510d96b1823 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// get active benefits for Contact, order by expiration date ascending | |
List<Benefit__c> beneList = [SELECT Id, BenefitLevel__c FROM Benefit__c WHERE Contact__c = :contactId ORDER BY ExpirationDate__c ASC]; | |
// Get set of BenefitLevels referenced by the above | |
Map<Id, Benefit__c> beneMap = new Map<Id, Benefit__c>(beneList); | |
// get usage discount codes associated with these benefit levels | |
List<DiscountCodeBenefitLevelLink__c> memberDiscounts = [SELECT DiscountCode__r.Id, DiscountCode__r.MemberUsageLimit__c... | |
FROM DCBLL__c WHERE BenefitLevel__c IN :beneLevelSet]; | |
// Map the Discount Codes by their Id and by their corresponding Benefit Level | |
Map<Id, DiscountCode__c> discountCodeMap | |
Map<Id, List<DiscountCode__c>> beneLevelDiscountCodeMap | |
// Get the DCU objects for these Benefit/DiscountCode combinations | |
List<DiscountCodeUsage__c> dcuList = [SELECT Id, Key, Benefit__c, DiscountCode__c, UsageCount__c FROM DiscountCodeUsage__c | |
WHERE Benefit__c IN :beneMap.keySet() AND DiscountCode__c IN : discountCodeMap.keySet()]; | |
// Map the above by their Key field (contatenation of Discount.Id and Benefit.Id) | |
Map<String, DiscountCodeUsage__c> dcuMap | |
// For each TOI | |
discountAmount = 0; | |
for (TicketOrderItem__c item : itemList) { | |
for (Benefit__c bene: beneList) { | |
// Get the DC associated with this Benefit and determine the discount amount. | |
List<DiscountCode__c> dcList = beneLevelDiscountCodeMap.get(bene.BenefitLevel__c); | |
for (DiscountCode__c dc : dcList) { | |
if (thisDiscountAmount > maxDiscountAmount) { | |
// If it's a limited usage discount | |
if (dc.MemberUsageLimit__c != null) { | |
// Check to see if a DCU already exists | |
DiscountCodeUsage__c dcu = dcuMap.get(appliedDC.Id + bene.Id); | |
if (dcu != null) { | |
// Check to see if we've reached the usage limit... if so, continue | |
if (dcu.UsageCount__c + item.Quantity > dcu.MemberUsageLimit__c) { | |
continue; | |
} | |
dcu.UsageCount += item.Quantity; | |
} else { | |
dcu = new DiscountCodeUsage__c(MemberUsageLimit__c = appliedDC.MemberUsageLimit__c, DiscountCode__c = applieDC.Id, Benefit__c = beneId); | |
dcu.UsageCount__c = toi.Quantity | |
item.DiscountCodeUsage__r = dcu; | |
} | |
// Apply the discount code to the item | |
item.DiscountCode__c = dc.Id; | |
... | |
} | |
} | |
} | |
} | |
// At this point, the maximal discount, based on the Contact's active Benefits, will be applied to the item | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment