diff --git a/timespans/userbudget.go b/timespans/userbudget.go index 0fce67cd3..e403752bf 100644 --- a/timespans/userbudget.go +++ b/timespans/userbudget.go @@ -116,6 +116,21 @@ func (ub *UserBudget) getTariffPlan(storage StorageGetter) (tp *TariffPlan, err return ub.tariffPlan, err } +func (ub *UserBudget) getVolumeDiscount(storage StorageGetter) (float64, error) { + tariffPlan, err := ub.getTariffPlan(storage) + if err != nil { + return 0.0, err + } + thresholds := len(tariffPlan.VolumeDiscountThresholds) + for i, vd := range tariffPlan.VolumeDiscountThresholds { + if ub.VolumeDiscountSeconds >= vd.Volume && + (i > thresholds-2 || ub.VolumeDiscountSeconds < tariffPlan.VolumeDiscountThresholds[i+1].Volume) { + return vd.Discount, nil + } + } + return 0, nil +} + /* Returns user's avaliable minutes for the specified destination */ diff --git a/timespans/userbudget_test.go b/timespans/userbudget_test.go index 0d5a61f0d..d4e311cd5 100644 --- a/timespans/userbudget_test.go +++ b/timespans/userbudget_test.go @@ -295,6 +295,37 @@ func TestResetUserBudget(t *testing.T) { } +func TestGetVolumeDiscountHaving(t *testing.T) { + vd := &VolumeDiscount{100, 11} + seara := &TariffPlan{Id: "seara", SmsCredit: 100, VolumeDiscountThresholds: []*VolumeDiscount{vd}} + rifsBudget := &UserBudget{Id: "other", Credit: 21, tariffPlan: seara, ResetDayOfTheMonth: 10, VolumeDiscountSeconds: 100} + result, err := rifsBudget.getVolumeDiscount(nil) + if err != nil || result != 11 { + t.Errorf("Expected %v was %v", 11, result) + } +} + +func TestGetVolumeDiscountNotHaving(t *testing.T) { + vd := &VolumeDiscount{100, 11} + seara := &TariffPlan{Id: "seara", SmsCredit: 100, VolumeDiscountThresholds: []*VolumeDiscount{vd}} + rifsBudget := &UserBudget{Id: "other", Credit: 21, tariffPlan: seara, ResetDayOfTheMonth: 10, VolumeDiscountSeconds: 99} + result, err := rifsBudget.getVolumeDiscount(nil) + if err != nil || result != 0 { + t.Errorf("Expected %v was %v", 0, result) + } +} + +func TestGetVolumeDiscountNotSteps(t *testing.T) { + vd1 := &VolumeDiscount{100, 11} + vd2 := &VolumeDiscount{500, 20} + seara := &TariffPlan{Id: "seara", SmsCredit: 100, VolumeDiscountThresholds: []*VolumeDiscount{vd1, vd2}} + rifsBudget := &UserBudget{Id: "other", Credit: 21, tariffPlan: seara, ResetDayOfTheMonth: 10, VolumeDiscountSeconds: 551} + result, err := rifsBudget.getVolumeDiscount(nil) + if err != nil || result != 20 { + t.Errorf("Expected %v was %v", 20, result) + } +} + /*********************************** Benchmarks *******************************/ func BenchmarkGetSecondForPrefix(b *testing.B) {