public class LoyaltyProgramHandler {
public void processTransaction(Id loyaltyProgramId, Decimal transactionAmount, String transactionType) {
// Retrieve the loyalty program record
Loyalty_Program__c loyaltyProgram = [SELECT Id, Promotion_Type__c, Is_Active__c
FROM Loyalty_Program__c
WHERE Id = :loyaltyProgramId
LIMIT 1];
if (!loyaltyProgram.Is_Active__c) {
throw new CustomException('Loyalty program is not active.');
}
if (loyaltyProgram.Promotion_Type__c == 'Cumulative') {
if (transactionType == 'Accrual') {
creditPoints(loyaltyProgramId, transactionAmount);
} else if (transactionType == 'Redemption') {
redeemPoints(loyaltyProgramId, transactionAmount);
} else {
throw new CustomException('Invalid transaction type.');
}
}
}
private void creditPoints(Id loyaltyProgramId, Decimal transactionAmount) {
// Assuming 1 point for every 2 dollars spent
Integer pointsEarned = (Integer)(transactionAmount / 2);
// Create a transaction journal record for accrual
Transaction_Journal__c journal = new Transaction_Journal__c(
Loyalty_Program__c = loyaltyProgramId,
Points_Earned__c = pointsEarned,
Transaction_Type__c = 'Accrual',
Transaction_Date__c = System.now()
);
insert journal;
// Update loyalty program points (pseudo-code)
Loyalty_Program__c loyaltyProgram = [SELECT Id, Points__c FROM Loyalty_Program__c WHERE Id = :loyaltyProgramId];
loyaltyProgram.Points__c += pointsEarned;
update loyaltyProgram;
}
private void redeemPoints(Id loyaltyProgramId, Decimal pointsToRedeem) {
// Retrieve current points
Loyalty_Program__c loyaltyProgram = [SELECT Id, Points__c FROM Loyalty_Program__c WHERE Id = :loyaltyProgramId];
if (pointsToRedeem > loyaltyProgram.Points__c) {
throw new CustomException('Insufficient points for redemption.');
}
// Create a transaction journal record for redemption
Transaction_Journal__c journal = new Transaction_Journal__c(
Loyalty_Program__c = loyaltyProgramId,
Points_Redeemed__c = pointsToRedeem,
Transaction_Type__c = 'Redemption',
Transaction_Date__c = System.now()
);
insert journal;
// Update loyalty program points
loyaltyProgram.Points__c -= pointsToRedeem;
update loyaltyProgram;
}
// Custom exception class
public class CustomException extends Exception {}
}