Skip to content

Commit

Permalink
order
Browse files Browse the repository at this point in the history
  • Loading branch information
Duchieuctk41 committed Nov 29, 2023
1 parent 8824b1a commit e2057e0
Show file tree
Hide file tree
Showing 10 changed files with 96 additions and 38 deletions.
24 changes: 21 additions & 3 deletions api/controllers/erp/order.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,9 @@ func (h *OrderController) Create(c *gin.Context) {
return
}

req.StoreId = utils.GetStoreIDFromContext(c.Request.Context())
//req.StoreId = utils.GetStoreIDFromContext(c.Request.Context())

if req.DiscountType != "" {
if req.DiscountType != nil {
if ok := req.DiscountType.CheckValid(); !ok {
c.JSON(http.StatusBadRequest, gin.H{
"error": req.DiscountType.ErrorMessage(),
Expand Down Expand Up @@ -73,7 +73,7 @@ func (h *OrderController) Update(c *gin.Context) {
return
}

req.StoreId = utils.GetStoreIDFromContext(c.Request.Context())
//req.StoreId = utils.GetStoreIDFromContext(c.Request.Context())

if ok := req.Status.CheckValid(); !ok {
c.JSON(http.StatusBadRequest, gin.H{
Expand All @@ -91,6 +91,24 @@ func (h *OrderController) Update(c *gin.Context) {
h.Response(c, http.StatusOK, "Success", order)
}

func (h *OrderController) GetList(c *gin.Context) {
req, err := utils.GetRequest(c, erpdto.GetListOrderRequest{})
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
return
}

orders, err := h.orderService.GetList(c.Request.Context(), req)
if err != nil {
h.ResponseError(c, err)
return
}

h.Response(c, http.StatusOK, "Success", orders)
}

func (h *OrderController) validateOrderItem(req []erpdto.OrderItemRequest) (err error) {
if len(req) == 0 {
return errors.New(api_errors.ErrOrderItemRequired)
Expand Down
2 changes: 1 addition & 1 deletion api_errors/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ var MapErrorCodeMessage = map[string]MessageAndStatus{
ErrPermissionDenied: {"Permission Denied", http.StatusForbidden},
ErrInvalidPassword: {"Invalid Password", http.StatusBadRequest},
ErrStoreNotFound: {"Store Not Found", http.StatusNotFound},
ErrOrderItemRequired: {"Order Item Required", http.StatusBadRequest},
ErrOrderItemRequired: {"order_items Required", http.StatusBadRequest},
ErrTypeInvalid: {"Only accept type 'percent' or 'amount'", http.StatusBadRequest},
ErrNotFound: {"Status Not Found", http.StatusNotFound},
ErrDateNotBetween: {"Date Not Between", http.StatusBadRequest},
Expand Down
2 changes: 1 addition & 1 deletion bootstrap/bootstrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@ package bootstrap
import (
controller "erp/api/controllers"
"erp/api/middlewares"
"erp/api/route"
config "erp/config"
infrastructure "erp/infrastructure"
"erp/lib"
repository "erp/repository"
"erp/route"
service "erp/service"
utils "erp/utils"

Expand Down
29 changes: 17 additions & 12 deletions dto/erp/order.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,27 @@ import uuid "github.com/satori/go.uuid"

type CreateOrderRequest struct {
OrderId uuid.UUID
Code string

Status StatusOrder `json:"status" binding:"required"` // confirm, delivery, complete, cancel
Note *string `json:"note"` // note for order

Amount float64 // total amount of order items
Total float64 `json:"total"` // grand total
Payment float64 `json:"payment"`
PaymentMethod string `json:"payment_method" binding:"required"`
Note *string `json:"note"` // note for order
Amount float64 // tổng tiền của toàn bộ sản phẩm
Total float64 `json:"total"` // grand total
Payment float64 `json:"payment"` // COD | Online

CustomerId *string `json:"customer_id"`
Code string
PaymentMethod string `json:"payment_method" binding:"required"`
CustomerId *string `json:"customer_id"`

DeliveryFee *float64 `json:"delivery_fee"`

Discount *float64 `json:"discount"`
DiscountType DiscountType `json:"discount_type"`
Discount *float64 `json:"discount"` // chiết khấu
DiscountType *DiscountType `json:"discount_type"`

PromoteCode *string `json:"promote_code"`
PromoteCode *string `json:"promote_code"` // mã giảm giá
PromoteFee *float64

OrderItems []OrderItemRequest `json:"order_items"`

StoreId string
}

type OrderItemRequest struct {
Expand Down Expand Up @@ -90,3 +88,10 @@ type UpdateOrderRequest struct {
Payment float64 `json:"payment"`
StoreId string
}

type GetListOrderRequest struct {
Limit int `json:"limit" form:"limit"`
Page int `json:"page" form:"page"`
Sort string `json:"sort" form:"sort"`
Search string `json:"search" form:"search"`
}
6 changes: 3 additions & 3 deletions models/order.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ type Order struct {
Discount *float64 `json:"discount,omitempty"`
DiscountType string `json:"discount_type" gorm:"default:null;"`

PromoteFee *float64 `json:"promote_fee,omitempty"`
PromoteCode *string `json:"promote_code,omitempty"`
StoreId uuid.UUID `json:"store_id" gorm:"not null"`
PromoteFee *float64 `json:"promote_fee,omitempty"`
PromoteCode *string `json:"promote_code,omitempty"`
//StoreId uuid.UUID `json:"store_id" gorm:"not null"`
}
6 changes: 3 additions & 3 deletions repository/erp_product.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ type ERPProductRepository interface {
Delete(ctx context.Context, id string) (err error)
GetOneByID(ctx context.Context, id string) (res *models.Product, err error)
GetList(ctx context.Context, req erpdto.GetListProductRequest) (res []*models.Product, total int64, err error)
GetListProductById(ctx context.Context, productIds []string, storeId string) (res []*models.Product, err error)
GetListProductById(ctx context.Context, productIds []string) (res []*models.Product, err error)
}

type productRepo struct {
Expand Down Expand Up @@ -72,8 +72,8 @@ func (r *productRepo) GetList(ctx context.Context, req erpdto.GetListProductRequ
return res, total, err
}

func (r *productRepo) GetListProductById(ctx context.Context, productIds []string, storeId string) (res []*models.Product, err error) {
if err = r.db.Model(&models.Product{}).Where("store_id = ? and id in (?)", storeId, productIds).Find(&res).Error; err != nil {
func (r *productRepo) GetListProductById(ctx context.Context, productIds []string) (res []*models.Product, err error) {
if err = r.db.Model(&models.Product{}).Where("id in (?)", productIds).Find(&res).Error; err != nil {
return nil, errors.Wrap(err, "get product by id failed")
}
return res, nil
Expand Down
18 changes: 18 additions & 0 deletions repository/order.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package repository
import (
"context"
"erp/api_errors"
erpdto "erp/dto/erp"
"erp/infrastructure"
"erp/models"
"erp/utils"
Expand All @@ -15,6 +16,7 @@ type OrderRepo interface {
Create(tx *TX, ctx context.Context, order *models.Order) error
Update(tx *TX, ctx context.Context, order *models.Order) error
GetOrderById(ctx context.Context, id string) (*models.Order, error)
GetList(ctx context.Context, req erpdto.GetListOrderRequest) ([]*models.Order, error)
}

type erpOrderRepository struct {
Expand Down Expand Up @@ -48,3 +50,19 @@ func (r *erpOrderRepository) GetOrderById(ctx context.Context, id string) (*mode

return &res, nil
}

func (r *erpOrderRepository) GetList(ctx context.Context, req erpdto.GetListOrderRequest) ([]*models.Order, error) {
var res []*models.Order
var count int64
query := r.db.WithContext(ctx).Model(&models.Order{})

if err := query.Count(&count).Error; err != nil {
return nil, errors.Wrap(err, "Count order failed")
}

if err := query.Offset(req.Page).Limit(req.Limit).Find(&res).Error; err != nil {
return nil, errors.Wrap(err, "Find order failed")
}

return res, nil
}
1 change: 1 addition & 0 deletions api/route/route.go → route/route.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ func NewRoute(

handler.POST("/v1/order/", middleware.Auth(true), orderController.Create)
handler.PUT("/v1/order/", middleware.Auth(true), orderController.Update)
handler.GET("/v1/order/", middleware.Auth(true), orderController.GetList)

handler.POST("/v1/promote/", middleware.Auth(true), promoteController.Create)

Expand Down
40 changes: 28 additions & 12 deletions service/erp/order.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (
type OrderService interface {
CreateFlow(ctx context.Context, req erpdto.CreateOrderRequest) (*models.Order, error)
UpdateFlow(ctx context.Context, req erpdto.UpdateOrderRequest) (*models.Order, error)
GetList(ctx context.Context, req erpdto.GetListOrderRequest) ([]*models.Order, error)
}

type erpOrderService struct {
Expand Down Expand Up @@ -70,7 +71,7 @@ func (s *erpOrderService) CreateFlow(ctx context.Context, req erpdto.CreateOrder
productIds, mapOrderItem := s.getProductIdsAndMapOrderItem(ctx, req.OrderItems)

// get list product
products, err := s.productService.GetListProductById(ctx, productIds, req.StoreId)
products, err := s.productService.GetListProductById(ctx, productIds)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -295,9 +296,13 @@ func (s *erpOrderService) handlePayment(tx *repository.TX, ctx context.Context,
return nil
}

func (s *erpOrderService) GetDiscount(ctx context.Context, discountType erpdto.DiscountType, total, discountReq float64) (float64, error) {
func (s *erpOrderService) GetDiscount(ctx context.Context, discountType *erpdto.DiscountType, total, discountReq float64) (float64, error) {
if discountType == nil {
return 0, nil
}

discount := discountReq
switch discountType {
switch *discountType {
case constants.TypePercent:
if discountReq <= 0 || discountReq > constants.MaxOfPercent {
return 0, errors.New(api_errors.ErrDiscountPercentInvalid)
Expand Down Expand Up @@ -451,14 +456,17 @@ func (s *erpOrderService) UpdateFlow(ctx context.Context, req erpdto.UpdateOrder
err = repository.WithTransaction(s.db, func(tx *repository.TX) error {

// if status == delivery, complete check payment
if err := s.handlePayment(tx, ctx, erpdto.CreateOrderRequest{
OrderId: req.OrderId,
Status: req.Status,
Payment: req.Payment,
CustomerId: utils.StringPointer(order.CustomerId.String()),
Total: order.Total,
}); err != nil {
return err
if order.CustomerId != nil {
customerId := utils.ValidUUID(order.CustomerId)
if err := s.handlePayment(tx, ctx, erpdto.CreateOrderRequest{
OrderId: req.OrderId,
Status: req.Status,
Payment: req.Payment,
CustomerId: utils.StringPointer(customerId.String()),
Total: order.Total,
}); err != nil {
return err
}
}
// if status == canceled, update order, update product quantity, sold
if req.Status == constants.Cancel {
Expand Down Expand Up @@ -520,7 +528,7 @@ func (s *erpOrderService) cancelOrder(tx *repository.TX, ctx context.Context, or
productIds, mapOrderItem := s.mapCancelOrderItem(orderItems)

// get product
products, err := s.productService.GetListProductById(ctx, productIds, order.StoreId.String())
products, err := s.productService.GetListProductById(ctx, productIds)

// update product quantity, sold
if err := s.updateCancelProQuantity(tx, ctx, products, mapOrderItem); err != nil {
Expand Down Expand Up @@ -585,3 +593,11 @@ func (s *erpOrderService) updateCancelProQuantity(tx *repository.TX, ctx context
}
return nil
}

func (s *erpOrderService) GetList(ctx context.Context, req erpdto.GetListOrderRequest) ([]*models.Order, error) {
orders, err := s.erpOrderRepo.GetList(ctx, req)
if err != nil {
return nil, err
}
return orders, nil
}
6 changes: 3 additions & 3 deletions service/erp/product.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ type (
Delete(ctx context.Context, id string) error
GetOne(ctx context.Context, id string) (*models.Product, error)
GetList(ctx context.Context, req erpdto.GetListProductRequest) ([]*models.Product, int64, error)
GetListProductById(ctx context.Context, productIds []string, storeId string) ([]*models.Product, error)
GetListProductById(ctx context.Context, productIds []string) ([]*models.Product, error)
}
productService struct {
productRepo repository.ERPProductRepository
Expand Down Expand Up @@ -95,6 +95,6 @@ func (u *productService) GetList(ctx context.Context, req erpdto.GetListProductR
return u.productRepo.GetList(ctx, req)
}

func (u *productService) GetListProductById(ctx context.Context, productIds []string, storeId string) ([]*models.Product, error) {
return u.productRepo.GetListProductById(ctx, productIds, storeId)
func (u *productService) GetListProductById(ctx context.Context, productIds []string) ([]*models.Product, error) {
return u.productRepo.GetListProductById(ctx, productIds)
}

0 comments on commit e2057e0

Please sign in to comment.