I'm starting out new in APEX. I created below method to call inside a trigger. I know my code below is not efficient calling loop inside a loop to avoid SOQL. I looked online for a day before posting this to look. Any suggestions? I'm not able to figure our how use Maps or Sets to achieve this.
public Static List<Quote> getFactors(List<Quote> lstq){
List<Margin_Factor__c> lstMarginFactors = [
SELECT
Channel__c, Cost__c, Deal_type__c, Margin_type__c, Margin_Unit__c,
Product_type__c, Range_High__c, Range_low__c, Swing_Type__c
FROM Margin_Factor__c
];
for (Quote q: lstq){
for (Margin_Factor__c m: lstMarginFactors){
// Acquisition Cost in $/MWh
if(m.Channel__c==q.Sales_Channel__c && m.Deal_type__c==q.Enrollment_Type__c && m.Margin_type__c=='COA' && m.Range_low__c <= q.Term_MWh__c && m.Range_high__c > q.Term_MWh__c){
q.COA_Factor_MWh__c = m.Cost__c;
}
// Cost to Serve in $/Month/ESID
if(m.Channel__c==q.Sales_Channel__c && m.Deal_type__c==q.Enrollment_Type__c && m.Margin_type__c=='CTS' && m.Range_low__c <= q.Term_MWh__c && m.Range_high__c > q.Term_MWh__c){
q.CTS_Factor_per_Month__c = m.Cost__c;
}
// Extra margin in $/MWh
if(m.Channel__c==q.Sales_Channel__c && m.Deal_type__c==q.Enrollment_Type__c && m.Margin_type__c=='Extra' && m.Range_low__c <= q.Term_MWh__c && m.Range_high__c > q.Term_MWh__c){
q.Extra_Margin_MWh__c = m.Cost__c;
}
}
}
return lstq;
}
There are about 4 fields in common between Quote
and Margin_factor__c
custom object. And additional 2 fields that define range for a field in Quote
. I'm not sure how I can map.
Margin_Factor__c
has factors maintained based on common fields as described below:
Common fields between quote and Margin_Factor__c
are Channel
, Deal_type
and Term_MWh__c
on quote that fall between Range_high
and Range_low
in MarginFactor
. I have to derive corresponding factors from MarginFactor
based on the values from Quote
.