Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ```
- trigger SchedulePayment on Opportunity(after insert, after update) {
- if (Trigger.isInsert) {
- for (Opportunity o: Trigger.new) {
- Decimal expectedRevenue = o.ExpectedRevenue;
- Date paymentDate = o.Payment_Start_Date__c;
- Integer monthsBetweenStartAndEnd = o.Payment_Start_Date__c.monthsBetween(o.CloseDate);
- for (Integer i = 0; i < monthsBetweenStartAndEnd; i++) {
- // Create Payments when opportunity is created
- Payment_Schedule__c payment = new Payment_Schedule__c();
- payment.Amount__c = expectedRevenue / monthsBetweenStartAndEnd;
- payment.Payment_Date__c = paymentDate;
- payment.Opportunity__c = o.id;
- insert payment;
- // Assure we get the next month for the next payment record
- paymentDate = paymentDate.addMonths(1);
- }
- }
- } else if (Trigger.isUpdate) {
- for (Opportunity o: trigger.new) {
- Decimal expectedRevenue = o.ExpectedRevenue;
- Date paymentDate = o.Payment_Start_Date__c;
- Date endDate = o.CloseDate;
- Integer monthsBetweenStartAndEnd = o.Payment_Start_Date__c.monthsBetween(o.CloseDate);
- // query related payment records.
- List < Payment_Schedule__c > payments = [select NAME, Payment_Date__c from Payment_Schedule__c where Opportunity__c != null and Opportunity__c in: trigger.new];
- Date lastScheduledPayment = payments.get(payments.Size() - 1).Payment_Date__c;
- Integer extraMonths = payments.Size() - monthsBetweenStartAndEnd;
- Integer monthsToAdd = monthsBetweenStartAndEnd - payments.Size();
- // this is to make sure we insert the correct months for new records on update
- boolean addMonths = true;
- for (Payment_Schedule__c payment: payments) {
- // remove records if time is shortened.
- if (extraMonths > 0) {
- delete payment;
- extraMonths--;
- }
- // add records if time has been extended.
- else if (extraMonths < 0) {
- // this is to make sure we insert the correct months for new records on update
- if (addMonths == true) {
- paymentDate = paymentDate.addMonths(monthsToAdd);
- }
- Payment_Schedule__c newPayment = new Payment_Schedule__c();
- newPayment.Amount__c = expectedRevenue / monthsBetweenStartAndEnd;
- newPayment.Payment_Date__c = paymentDate;
- newPayment.Opportunity__c = o.id;
- insert newPayment;
- addMonths = false;
- paymentDate = paymentDate.addMonths(1);
- // update the revenue of previous inserted records when a new record is inserted.
- payment.Amount__c = expectedRevenue / monthsBetweenStartAndEnd;
- update payment;
- }
- else if (extraMonths == 0) {
- // update payment records.
- payment.Payment_Date__c = paymentDate;
- payment.Amount__c = expectedRevenue / monthsBetweenStartAndEnd;
- update payment;
- paymentDate = paymentDate.addMonths(1);
- }
- }
- }
- }
- }
- }
- ```
Add Comment
Please, Sign In to add comment