95 lines
2.0 KiB
Go
95 lines
2.0 KiB
Go
package users
|
|
|
|
import (
|
|
"backend/pkg/consts"
|
|
"backend/pkg/errorx"
|
|
"backend/providers/jwt"
|
|
|
|
"github.com/gofiber/fiber/v3"
|
|
"github.com/pkg/errors"
|
|
log "github.com/sirupsen/logrus"
|
|
hashids "github.com/speps/go-hashids/v2"
|
|
)
|
|
|
|
// @provider
|
|
type Controller struct {
|
|
svc *Service
|
|
hashIds *hashids.HashID
|
|
}
|
|
|
|
// List
|
|
func (c *Controller) List(ctx fiber.Ctx) error {
|
|
return ctx.JSON(nil)
|
|
}
|
|
|
|
// Charge
|
|
func (c *Controller) Charge(ctx fiber.Ctx) error {
|
|
claim := fiber.Locals[*jwt.Claims](ctx, consts.CtxKeyClaim)
|
|
log.Debug(claim)
|
|
|
|
// [tenantId, chargeAmount, timestamp]
|
|
code := ctx.Params("code")
|
|
if err := c.svc.Charge(ctx.Context(), claim, code); err != nil {
|
|
return err
|
|
}
|
|
|
|
return ctx.JSON(nil)
|
|
}
|
|
|
|
// Info
|
|
func (c *Controller) Info(ctx fiber.Ctx) error {
|
|
claim := fiber.Locals[*jwt.Claims](ctx, consts.CtxKeyClaim)
|
|
log.Debug(claim)
|
|
|
|
info := &UserInfo{}
|
|
|
|
balance, err := c.svc.GetTenantUserBalance(ctx.Context(), claim.TenantID, claim.UserID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
info.Balance = balance
|
|
|
|
tenant, err := c.svc.GetTenantByID(ctx.Context(), claim.TenantID)
|
|
if err != nil {
|
|
return errors.Wrapf(err, "get tenant: %d", claim.TenantID)
|
|
}
|
|
info.IsAdmin = tenant.BindUserID == claim.UserID
|
|
|
|
return ctx.JSON(info)
|
|
}
|
|
|
|
func (c *Controller) GetChargeCodes(ctx fiber.Ctx) error {
|
|
claim := fiber.Locals[*jwt.Claims](ctx, consts.CtxKeyClaim)
|
|
log.Debug(claim)
|
|
|
|
tenant, err := c.svc.GetTenantByID(ctx.Context(), claim.TenantID)
|
|
if err != nil {
|
|
return errors.Wrapf(err, "get tenant: %d", claim.TenantID)
|
|
}
|
|
|
|
if tenant.BindUserID != claim.UserID {
|
|
return errorx.RequestParseError
|
|
}
|
|
|
|
type generateCode struct {
|
|
Amount int64 `json:"amount"`
|
|
Code string `json:"code"`
|
|
}
|
|
|
|
amount := []int64{1, 5, 10, 20, 50, 100}
|
|
codes := []generateCode{}
|
|
for _, a := range amount {
|
|
code, err := c.svc.GenerateChargeCode(ctx.Context(), claim.TenantID, a*100)
|
|
if err != nil {
|
|
log.WithError(err).Errorf("generate charge code")
|
|
return errorx.InternalError
|
|
}
|
|
codes = append(codes, generateCode{
|
|
Amount: a * 100,
|
|
Code: code,
|
|
})
|
|
}
|
|
|
|
return ctx.JSON(codes)
|
|
}
|