私有函数返回 0 而不是 salesforce APEX 中的值

问题描述 投票:0回答:1

我为 salesforce opportunityLineItemSchedule 创建了以下 APEX 处理程序类 验证总收入总和的对象不会大于总收入总和 所有计划收入。

`public class OpportunityLineItemScheduleHandler {
    public static void handleBeforeInsertUpdate(List<OpportunityLineItemSchedule> newSchedules) {
        Set<Id> oppLineItemIds = new Set<Id>();
        Map<Id, OpportunityLineItem> oppLineItems = new Map<Id, OpportunityLineItem>();

        // Collect OpportunityLineItem Ids from new schedules
        for (OpportunityLineItemSchedule schedule : newSchedules) {
            oppLineItemIds.add(schedule.OpportunityLineItemId);
        }

        // Query for OpportunityLineItems using the collected Ids
        oppLineItems.putAll([SELECT Id, Gross_Revenue_Calc__c
                             FROM OpportunityLineItem
                             WHERE Id IN :oppLineItemIds]);

        for (OpportunityLineItemSchedule schedule : newSchedules) {
            OpportunityLineItem oppLineItem = oppLineItems.get(schedule.OpportunityLineItemId);
            Decimal sumOfRevenue = getSumRevenueOnSchedule(schedule.OpportunityLineItemId);

            System.debug(sumOfRevenue);

            if (oppLineItem != null && sumOfRevenue > oppLineItem.Gross_Revenue_Calc__c) {
                schedule.addError('Sum of Product Schedule should not exceed Gross Revenue on Opportunity Product.');
            }
        }
    }



    private static Decimal getSumRevenueOnSchedule(Id OpportunityLineItemId) {
        Decimal scheduleRevenue = 0;
        List<OpportunityLineItemSchedule> relatedSchedules = [SELECT Revenue FROM OpportunityLineItemSchedule WHERE OpportunityLineItemId = :OpportunityLineItemId];
        
        for (OpportunityLineItemSchedule innerSchedule : relatedSchedules) {
            scheduleRevenue += innerSchedule.Revenue;
        }

        return scheduleRevenue;
    }
}
`

我无法理解为什么我从 getSumRevenueOnSchedule() 函数中得到 o 而不是获得所有收入的总和。 这里需要帮助

提前致谢

triggers salesforce
1个回答
0
投票

在 OpportunityLineItemSchedule 的

before insert
中,内容尚未在数据库中。
SELECT Revenue FROM OpportunityLineItemSchedule
不会返回正在插入的“当前”记录。它将返回过去插入的内容(如果有的话),但不会包含类似于
trigger.new
的内容。如果您知道如何捕获调试日志,您可能会看到查询返回 0 行。

before update
稍微好一些,它应该开始返回一些东西 - 但它仍然是错误的。您的查询将返回此编辑发生之前数据库中的内容。因此,您将汇总旧的收入值,而不是用户在编辑中实际更改的内容。如果他们改变了收入以外的领域——那就太好了,它会自行纠正。如果他们将收入从 50 更改为 100 -> 您的查询将报告 50,旧值。

“Befores”通常适用于数据质量检查(对于验证规则来说太复杂)和字段预填充。 “副作用”(例如汇总、创建子记录、调用外部系统)更适合“之后”触发器。尝试重新安排触发器中的调用以将函数执行为

after insert, after update
(并将关键字添加到触发器的顶行!)并查看它是否表现更好。

© www.soinside.com 2019 - 2024. All rights reserved.