78 lines
2.1 KiB
Go
78 lines
2.1 KiB
Go
|
package endpoints
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"github.com/gin-gonic/gin"
|
||
|
"github.com/go-playground/validator/v10"
|
||
|
"net/http"
|
||
|
"relynolli-server/models"
|
||
|
"relynolli-server/services"
|
||
|
)
|
||
|
|
||
|
type handlers struct{}
|
||
|
|
||
|
type getTotalRequest struct {
|
||
|
FuserId int `json:"fuserId"`
|
||
|
}
|
||
|
|
||
|
type getTotalResponse struct {
|
||
|
TotalProductPrice float64 `json:"total_product_price"`
|
||
|
}
|
||
|
|
||
|
type makeOrderRequest struct {
|
||
|
FuserId int `json:"fuserId" validate:"required"`
|
||
|
PhoneNumber string `json:"phoneNumber" validate:"required"`
|
||
|
FullName string `json:"fullName" validate:"required"`
|
||
|
Email string `json:"email" validate:"required,email"`
|
||
|
DeliveryType string `json:"deliveryType,omitempty"`
|
||
|
Address string `json:"address,omitempty"`
|
||
|
}
|
||
|
|
||
|
func (h handlers) GetTotal(c *gin.Context) {
|
||
|
req := getTotalRequest{}
|
||
|
err := c.ShouldBindJSON(&req)
|
||
|
if err != nil {
|
||
|
c.JSON(http.StatusBadRequest, models.Response{Status: http.StatusBadRequest, Info: "fuserId is not provided"})
|
||
|
return
|
||
|
}
|
||
|
total := services.GetTotal(req.FuserId)
|
||
|
c.JSON(http.StatusOK, getTotalResponse{TotalProductPrice: total})
|
||
|
}
|
||
|
|
||
|
func (h handlers) MakeOrder(c *gin.Context) {
|
||
|
// VALIDATION
|
||
|
validate := validator.New(validator.WithRequiredStructEnabled())
|
||
|
req := makeOrderRequest{}
|
||
|
err := c.ShouldBindJSON(&req)
|
||
|
if err != nil {
|
||
|
c.JSON(400, models.Response{Status: http.StatusBadRequest, Info: fmt.Sprintf("ERROR: %s", err.Error())})
|
||
|
return
|
||
|
}
|
||
|
|
||
|
validationErr := validate.Struct(req)
|
||
|
|
||
|
if validationErr != nil {
|
||
|
responseErr := validationErr.(validator.ValidationErrors)[0]
|
||
|
c.JSON(http.StatusBadRequest, models.Response{Status: http.StatusBadRequest, Info: fmt.Sprintf("Validation Error: Field %s should be %s", responseErr.Field(), responseErr.Tag())})
|
||
|
return
|
||
|
}
|
||
|
|
||
|
kassaResult, serviceErr := services.MakeOrder(req.FuserId, req.Email, req.FullName, req.PhoneNumber)
|
||
|
|
||
|
if serviceErr != nil {
|
||
|
c.JSON(http.StatusInternalServerError, models.Response{Status: http.StatusInternalServerError, Info: fmt.Sprintf("Error: %s", serviceErr.Error())})
|
||
|
return
|
||
|
}
|
||
|
|
||
|
c.JSON(http.StatusOK, kassaResult)
|
||
|
}
|
||
|
|
||
|
type Handlers interface {
|
||
|
GetTotal(c *gin.Context)
|
||
|
MakeOrder(c *gin.Context)
|
||
|
}
|
||
|
|
||
|
func GetHandlers() Handlers {
|
||
|
return &handlers{}
|
||
|
}
|