forked from ebhomengo/niki
69 lines
1.6 KiB
Go
69 lines
1.6 KiB
Go
package order
|
|
|
|
import (
|
|
entity "git.gocasts.ir/ebhomengo/niki/domain/order/entity"
|
|
order "git.gocasts.ir/ebhomengo/niki/domain/order/service"
|
|
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
|
|
"github.com/labstack/echo/v4"
|
|
"net/http"
|
|
"time"
|
|
)
|
|
|
|
type Handler struct {
|
|
orderSvc *order.Service
|
|
}
|
|
|
|
func New(orderSvc order.Service) *Handler {
|
|
return &Handler{orderSvc: &orderSvc}
|
|
}
|
|
|
|
func (h *Handler) CreateOrderHandler(c echo.Context) error {
|
|
var req CreateOrderRequest
|
|
if err := c.Bind(&req); err != nil {
|
|
msg, code := getErrorDataFromRichError(err)
|
|
return echo.NewHTTPError(code, msg)
|
|
}
|
|
|
|
orderItems := req.OrderItems
|
|
order := entity.Order{
|
|
ID: 0,
|
|
UserID: req.UserID,
|
|
TotalAmount: req.TotalAmount,
|
|
TotalDiscount: req.TotalDiscount,
|
|
ShippingID: req.ShippingID,
|
|
PaymentMethod: req.PaymentMethod,
|
|
ProcessStatus: entity.WaitingToPay,
|
|
PaymentStatus: entity.UnPaid,
|
|
AddressID: req.AddressID,
|
|
CreatedAt: time.Now(),
|
|
UpdatedAt: time.Now(),
|
|
}
|
|
resp, lErr := h.orderSvc.CreateOrder(order, orderItems)
|
|
|
|
if lErr != nil {
|
|
msg, code := getErrorDataFromRichError(lErr)
|
|
return echo.NewHTTPError(code, msg)
|
|
}
|
|
return c.JSON(http.StatusOK, resp)
|
|
}
|
|
|
|
func getErrorDataFromRichError(err error) (message string, code int) {
|
|
switch err.(type) {
|
|
case richerror.RichError:
|
|
re := err.(richerror.RichError)
|
|
|
|
return re.Message(), mapKindToCode(re.Kind())
|
|
default:
|
|
return err.Error(), http.StatusBadRequest
|
|
}
|
|
}
|
|
|
|
func mapKindToCode(kind richerror.Kind) int {
|
|
switch kind {
|
|
case richerror.KindInvalid:
|
|
return http.StatusUnprocessableEntity
|
|
default:
|
|
return http.StatusBadRequest
|
|
}
|
|
}
|