mirror of
https://github.com/grassrootseconomics/farmstar-survey-backend.git
synced 2024-11-19 00:16:45 +01:00
80 lines
2.3 KiB
Go
80 lines
2.3 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) bootstrapRedeemRoute() {
|
||
|
r.PB.OnBeforeServe().Add(func(e *core.ServeEvent) error {
|
||
|
e.Router.POST("/redeem", func(c echo.Context) error {
|
||
|
requestData := struct {
|
||
|
DistributorPhone string `json:"distributor_phone"`
|
||
|
Distributor string `json:"distributor"`
|
||
|
FarmerPhone string `json:"farmer_phone"`
|
||
|
Redemption string `json:"redemption_options"`
|
||
|
}{}
|
||
|
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 {
|
||
|
distributorRecord, err := r.PB.Dao().FindFirstRecordByData("users", "phone", requestData.DistributorPhone)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
if distributorRecord.GetString("participant_type") != "distributor" {
|
||
|
return apis.NewNotFoundError("User is not registered as a distributor", err)
|
||
|
}
|
||
|
|
||
|
farmerRecord, err := r.PB.Dao().FindFirstRecordByData("users", "phone", requestData.FarmerPhone)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
if farmerRecord.GetString("participant_type") != "farmer" {
|
||
|
return apis.NewNotFoundError("User is not registered as a farmer", err)
|
||
|
}
|
||
|
|
||
|
redemptionCollection, err := r.PB.Dao().FindCollectionByNameOrId("redemption")
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
|
||
|
redemptionRecord := models.NewRecord(redemptionCollection)
|
||
|
redemptionForm := forms.NewRecordUpsert(r.PB, redemptionRecord)
|
||
|
redemptionForm.SetDao(txDao)
|
||
|
|
||
|
redemptionForm.LoadData(map[string]any{
|
||
|
"distributor_initiator": distributorRecord.Id,
|
||
|
"distributor": requestData.Distributor,
|
||
|
"farmer": farmerRecord.Id,
|
||
|
"fsp_redemption_request": requestData.Redemption,
|
||
|
})
|
||
|
|
||
|
if err := redemptionForm.Submit(); err != nil {
|
||
|
return apis.NewBadRequestError("Failed to submit distributor 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
|
||
|
})
|
||
|
}
|