mirror of
https://github.com/grassrootseconomics/farmstar-survey-backend.git
synced 2024-12-22 07:27:33 +01:00
75 lines
2.0 KiB
Go
75 lines
2.0 KiB
Go
package router
|
|
|
|
import (
|
|
"github.com/labstack/echo/v5"
|
|
"github.com/pocketbase/pocketbase/apis"
|
|
"github.com/pocketbase/pocketbase/core"
|
|
"github.com/pocketbase/pocketbase/daos"
|
|
"github.com/pocketbase/pocketbase/forms"
|
|
"github.com/pocketbase/pocketbase/models"
|
|
)
|
|
|
|
func (r *RouterContainer) bootstrapRegistrationRoute() {
|
|
r.PB.OnBeforeServe().Add(func(e *core.ServeEvent) error {
|
|
e.Router.POST("/registration", func(c echo.Context) error {
|
|
requestData := struct {
|
|
Name string `json:"name"`
|
|
Phone string `json:"phone"`
|
|
Gender string `json:"gender"`
|
|
AgeGroup string `json:"age_group"`
|
|
ParticipantType string `json:"participant_type"`
|
|
}{}
|
|
if err := c.Bind(&requestData); err != nil {
|
|
return apis.NewBadRequestError("Failed to read request data", err)
|
|
}
|
|
|
|
if err := r.PB.Dao().RunInTransaction(func(txDao *daos.Dao) error {
|
|
address, err := r.ussd.GetAddress(c.Request().Context(), requestData.Phone)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
if address == "" {
|
|
return apis.NewNotFoundError("Phone # not registered on Sarafu Network", nil)
|
|
}
|
|
|
|
usersCollection, err := r.PB.Dao().FindCollectionByNameOrId("users")
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
userRecord := models.NewRecord(usersCollection)
|
|
userForm := forms.NewRecordUpsert(r.PB, userRecord)
|
|
userForm.SetDao(txDao)
|
|
|
|
userForm.LoadData(map[string]any{
|
|
"name": requestData.Name,
|
|
"phone": requestData.Phone,
|
|
"gender": requestData.Gender,
|
|
"age_group": requestData.AgeGroup,
|
|
"participant_type": requestData.ParticipantType,
|
|
"blockchain_address": address,
|
|
"activated": true,
|
|
})
|
|
|
|
if err := userForm.Submit(); err != nil {
|
|
return apis.NewBadRequestError("Failed to submit user details", err)
|
|
}
|
|
|
|
return nil
|
|
|
|
}); err != nil {
|
|
c.JSON(400, map[string]any{"ok": "false", "error": err.Error()})
|
|
|
|
return nil
|
|
}
|
|
|
|
c.JSON(200, map[string]any{"ok": "true"})
|
|
|
|
return nil
|
|
})
|
|
|
|
return nil
|
|
})
|
|
}
|