feat: add percentage sum validation on farmers survey

This commit is contained in:
Mohamed Sohail 2024-02-21 20:44:50 +03:00
parent a99907f2b9
commit ce8a3920da
Signed by: kamikazechaser
GPG Key ID: 7DD45520C01CD85D

View File

@ -1,6 +1,8 @@
package router
import (
"strconv"
"github.com/labstack/echo/v5"
"github.com/pocketbase/pocketbase/apis"
"github.com/pocketbase/pocketbase/core"
@ -51,6 +53,22 @@ func (r *RouterContainer) bootstrapFarmerSurveyRoute() {
return apis.NewBadRequestError("Failed to read request data", err)
}
budgetSplit, err := validatePercentage(requestData.CropsProtectionExpenditurePercentage, requestData.FertilizerExpenditurePercentage, requestData.SeedsExpenditurePercentage)
if err != nil {
return apis.NewBadRequestError("Could not validate budget split percentage", err)
}
if !budgetSplit {
return apis.NewNotFoundError("Budget split percentage should add up to 100% ", err)
}
fertilizerSplit, err := validatePercentage(requestData.SyntheticFertilizersExpenditurePercentage, requestData.NaturalFertilizersExpenditure)
if err != nil {
return apis.NewBadRequestError("Could not validate fertilizer split percentage", err)
}
if !fertilizerSplit {
return apis.NewNotFoundError("Fertilizer split percentage should add up to 100% ", err)
}
if err := r.PB.Dao().RunInTransaction(func(txDao *daos.Dao) error {
userRecord, err := r.PB.Dao().FindFirstRecordByData("users", "phone", requestData.Phone)
if err != nil {
@ -211,3 +229,15 @@ func (r *RouterContainer) bootstrapFarmerSurveyRoute() {
return nil
})
}
func validatePercentage(inputs ...string) (bool, error) {
sum := 0
for _, numStr := range inputs {
num, err := strconv.Atoi(numStr)
if err != nil {
return false, err
}
sum += num
}
return sum == 100, nil
}