98 lines
2.2 KiB
Go
98 lines
2.2 KiB
Go
package orders
|
|
|
|
import (
|
|
"backend/app/errorx"
|
|
"backend/app/http/posts"
|
|
"backend/app/http/tenants"
|
|
"backend/app/http/users"
|
|
"backend/app/requests"
|
|
"backend/database/models/qvyun_v2/public/model"
|
|
"backend/providers/jwt"
|
|
|
|
"github.com/gofiber/fiber/v3"
|
|
"github.com/jinzhu/copier"
|
|
"github.com/samber/lo"
|
|
log "github.com/sirupsen/logrus"
|
|
)
|
|
|
|
// @provider
|
|
type OrderController struct {
|
|
svc *Service
|
|
userSvc *users.Service
|
|
tenantSvc *tenants.Service
|
|
postSvc *posts.Service
|
|
log *log.Entry `inject:"false"`
|
|
}
|
|
|
|
func (c *OrderController) Prepare() error {
|
|
c.log = log.WithField("module", "orders.OrderController")
|
|
return nil
|
|
}
|
|
|
|
// Orders show user orders
|
|
// @Router /api/v1/orders [get]
|
|
// @Bind claim local
|
|
// @Bind pagination query
|
|
// @Bind filter query
|
|
func (c *OrderController) List(ctx fiber.Ctx, claim *jwt.Claims, pagination *requests.Pagination, filter *UserOrderFilter) (*requests.Pager, error) {
|
|
pagination.Format()
|
|
pager := &requests.Pager{
|
|
Pagination: *pagination,
|
|
}
|
|
|
|
filter.UserID = claim.UserID
|
|
orders, total, err := c.svc.GetOrders(ctx.Context(), pagination, filter)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
pager.Total = total
|
|
|
|
pager.Items = lo.FilterMap(orders, func(item model.Orders, _ int) (UserOrder, bool) {
|
|
var o UserOrder
|
|
if err := copier.Copy(&o, item); err != nil {
|
|
return o, false
|
|
}
|
|
return o, true
|
|
})
|
|
|
|
return pager, nil
|
|
}
|
|
|
|
// Create order
|
|
// @Router /api/v1/orders [post]
|
|
// @Bind claim local
|
|
// @Bind hash
|
|
// @Bind tenantSlug cookie key(tenant)
|
|
func (c *OrderController) Create(ctx fiber.Ctx, claim *jwt.Claims, tenantSlug, hash string) (*UserOrder, error) {
|
|
user, err := c.userSvc.GetUserByID(ctx.Context(), claim.UserID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
tenant, err := c.tenantSvc.GetTenantBySlug(ctx.Context(), tenantSlug)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
post, err := c.postSvc.GetPostByHash(ctx.Context(), tenant.ID, hash)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if tenant.ID != post.TenantID {
|
|
return nil, errorx.BadRequest
|
|
}
|
|
|
|
order, err := c.svc.Create(ctx.Context(), user, post)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
var userOrder UserOrder
|
|
if err := copier.Copy(&userOrder, order); err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &userOrder, nil
|
|
}
|