mirror of
https://github.com/grassrootseconomics/farmstar-survey-backend.git
synced 2024-12-12 11:16:10 +01:00
feat: add percentage sum validation on farmers survey
This commit is contained in:
parent
a99907f2b9
commit
ce8a3920da
@ -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
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user