getLowestSmartRate function
Implementation
SmartRate getLowestSmartRate(List<SmartRate> smartRates, int deliveryDays,
SmartRateAccuracy deliveryAccuracy) {
SmartRate? lowestRate;
for (SmartRate rate in smartRates) {
if (rate.price == null) {
continue; // Skip this rate if it doesn't have a price
}
if (lowestRate != null && lowestRate.price == null) {
// somehow a rate with null got selected in the last iteration, throw an error
// the guard clause above should have prevented this, so this should never happen
throw FilteringException(
'A smart rate with null price was selected in the last iteration');
}
if (rate.timeInTransit == null) {
continue; // Skip this rate if it doesn't have a time in transit
}
int? estimatedDeliveryDays =
rate.timeInTransit?.bySmartRateAccuracy(deliveryAccuracy);
if (estimatedDeliveryDays == null) {
continue; // Skip this rate if it doesn't have a time in transit for the given accuracy
}
if (estimatedDeliveryDays > deliveryDays) {
continue; // Skip this rate if the estimated delivery days is greater than the given delivery days
}
// if there's no lowest rate yet, use it
if (lowestRate == null) {
lowestRate = rate;
continue;
}
// if the rate is lower than the current lowest rate, use it
if (rate.price! < lowestRate.price!) {
lowestRate = rate;
continue;
}
}
if (lowestRate == null) {
throw FilteringException(ErrorMessages.noMatchingRatesFound);
}
return lowestRate;
}