forked from ebhomengo/niki
70 lines
1.7 KiB
Go
70 lines
1.7 KiB
Go
package order
|
|
|
|
import (
|
|
richerror "git.gocasts.ir/ebhomengo/niki/pkg/rich_error"
|
|
"git.gocasts.ir/ebhomengo/niki/purchaseapp/entity"
|
|
"git.gocasts.ir/ebhomengo/niki/purchaseapp/service/order"
|
|
"git.gocasts.ir/ebhomengo/niki/types"
|
|
"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 order.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: types.ID(req.UserID),
|
|
TotalAmount: types.Price(req.TotalAmount),
|
|
TotalDiscount: types.Price(req.TotalDiscount),
|
|
ShippingID: types.ID(req.ShippingID),
|
|
PaymentMethod: req.PaymentMethod,
|
|
ProcessStatus: entity.WaitingToPay,
|
|
PaymentStatus: entity.UnPaid,
|
|
Address: req.Address,
|
|
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
|
|
}
|
|
}
|