添加优惠券功能,实现价格计算
This commit is contained in:
@@ -22,6 +22,8 @@
|
||||
- [ ] Limiter
|
||||
- [ ] Compress
|
||||
|
||||
错误处理类型转换失败问题
|
||||
|
||||
transition 服务,查询后立即完成,提供是否访问接口参数,统一主动与回调调用
|
||||
|
||||
callback 结果直接由 api 端提供,不通过前端转发
|
||||
|
||||
@@ -819,4 +819,40 @@ comment on column bill.created_at is '创建时间';
|
||||
comment on column bill.updated_at is '更新时间';
|
||||
comment on column bill.deleted_at is '删除时间';
|
||||
|
||||
-- coupon 优惠券
|
||||
drop table if exists coupon cascade;
|
||||
create table coupon (
|
||||
id serial primary key,
|
||||
user_id int references "user" (id)
|
||||
on update cascade
|
||||
on delete cascade,
|
||||
code varchar(255) not null unique,
|
||||
remark varchar(255),
|
||||
amount decimal(12, 2) not null default 0,
|
||||
min_amount decimal(12, 2) not null default 0,
|
||||
status int not null default 0,
|
||||
expire_at timestamp,
|
||||
created_at timestamp default current_timestamp,
|
||||
updated_at timestamp default current_timestamp,
|
||||
deleted_at timestamp
|
||||
);
|
||||
create index coupon_user_id_index on coupon (user_id);
|
||||
create index coupon_code_index on coupon (code);
|
||||
create index coupon_status_index on coupon (status);
|
||||
create index coupon_deleted_at_index on coupon (deleted_at);
|
||||
|
||||
-- coupon表字段注释
|
||||
comment on table coupon is '优惠券表';
|
||||
comment on column coupon.id is '优惠券ID';
|
||||
comment on column coupon.user_id is '用户ID';
|
||||
comment on column coupon.code is '优惠券代码';
|
||||
comment on column coupon.remark is '优惠券备注';
|
||||
comment on column coupon.amount is '优惠券金额';
|
||||
comment on column coupon.min_amount is '最低消费金额';
|
||||
comment on column coupon.status is '优惠券状态:0-未使用,1-已使用,2-已过期';
|
||||
comment on column coupon.expire_at is '过期时间';
|
||||
comment on column coupon.created_at is '创建时间';
|
||||
comment on column coupon.updated_at is '更新时间';
|
||||
comment on column coupon.deleted_at is '删除时间';
|
||||
|
||||
-- endregion
|
||||
@@ -144,3 +144,37 @@ func (ldt *LocalDateTime) UnmarshalJSON(b []byte) error {
|
||||
}
|
||||
|
||||
// endregion
|
||||
|
||||
// region err
|
||||
|
||||
type ServiceErr struct {
|
||||
code int
|
||||
name string
|
||||
msg string
|
||||
}
|
||||
|
||||
func (e ServiceErr) Code() int {
|
||||
return e.code
|
||||
}
|
||||
|
||||
func (e ServiceErr) Name() string {
|
||||
return e.name
|
||||
}
|
||||
|
||||
func (e ServiceErr) Error() string {
|
||||
return e.msg
|
||||
}
|
||||
|
||||
func NewErr(name, msg string, code ...int) ServiceErr {
|
||||
_code := 400
|
||||
if len(code) > 0 {
|
||||
_code = code[0]
|
||||
}
|
||||
return ServiceErr{
|
||||
name: name,
|
||||
msg: msg,
|
||||
code: _code,
|
||||
}
|
||||
}
|
||||
|
||||
// endregion
|
||||
|
||||
26
web/error.go
26
web/error.go
@@ -2,18 +2,32 @@ package web
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"platform/web/common"
|
||||
"reflect"
|
||||
|
||||
"github.com/gofiber/fiber/v2"
|
||||
)
|
||||
|
||||
func ErrorHandler(c *fiber.Ctx, err error) error {
|
||||
code := fiber.StatusInternalServerError
|
||||
message := "服务器异常"
|
||||
var e *fiber.Error
|
||||
if errors.As(err, &e) {
|
||||
code = e.Code
|
||||
message = e.Message
|
||||
|
||||
var code int
|
||||
var message string
|
||||
|
||||
var fiberErr *fiber.Error
|
||||
var serviceErr common.ServiceErr
|
||||
if errors.As(err, &fiberErr) {
|
||||
code = fiberErr.Code
|
||||
message = fiberErr.Message
|
||||
} else if errors.As(err, &fiberErr) {
|
||||
code = serviceErr.Code()
|
||||
message = serviceErr.Error()
|
||||
} else {
|
||||
code = fiber.StatusInternalServerError
|
||||
message = "服务器异常"
|
||||
slog.Debug("未处理的异常", slog.String("type", reflect.TypeOf(err).Name()), slog.String("error", err.Error()))
|
||||
}
|
||||
|
||||
c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8)
|
||||
return c.Status(code).SendString(message)
|
||||
}
|
||||
|
||||
34
web/models/coupon.gen.go
Normal file
34
web/models/coupon.gen.go
Normal file
@@ -0,0 +1,34 @@
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
|
||||
package models
|
||||
|
||||
import (
|
||||
"platform/web/common"
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
const TableNameCoupon = "coupon"
|
||||
|
||||
// Coupon mapped from table <coupon>
|
||||
type Coupon struct {
|
||||
ExpireAt time.Time `gorm:"column:expire_at" json:"expire_at"`
|
||||
CreatedAt common.LocalDateTime `gorm:"column:created_at;default:CURRENT_TIMESTAMP" json:"created_at"`
|
||||
UpdatedAt common.LocalDateTime `gorm:"column:updated_at;default:CURRENT_TIMESTAMP" json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `gorm:"column:deleted_at" json:"deleted_at"`
|
||||
ID int32 `gorm:"column:id;primaryKey;autoIncrement:true" json:"id"`
|
||||
UserID int32 `gorm:"column:user_id" json:"user_id"`
|
||||
Status int32 `gorm:"column:status;not null" json:"status"`
|
||||
Code string `gorm:"column:code;not null" json:"code"`
|
||||
Remark string `gorm:"column:remark" json:"remark"`
|
||||
Amount float64 `gorm:"column:amount;not null" json:"amount"`
|
||||
MinAmount float64 `gorm:"column:min_amount;not null" json:"min_amount"`
|
||||
}
|
||||
|
||||
// TableName Coupon's table name
|
||||
func (*Coupon) TableName() string {
|
||||
return TableNameCoupon
|
||||
}
|
||||
359
web/queries/coupon.gen.go
Normal file
359
web/queries/coupon.gen.go
Normal file
@@ -0,0 +1,359 @@
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
// Code generated by gorm.io/gen. DO NOT EDIT.
|
||||
|
||||
package queries
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
"gorm.io/gorm/schema"
|
||||
|
||||
"gorm.io/gen"
|
||||
"gorm.io/gen/field"
|
||||
|
||||
"gorm.io/plugin/dbresolver"
|
||||
|
||||
"platform/web/models"
|
||||
)
|
||||
|
||||
func newCoupon(db *gorm.DB, opts ...gen.DOOption) coupon {
|
||||
_coupon := coupon{}
|
||||
|
||||
_coupon.couponDo.UseDB(db, opts...)
|
||||
_coupon.couponDo.UseModel(&models.Coupon{})
|
||||
|
||||
tableName := _coupon.couponDo.TableName()
|
||||
_coupon.ALL = field.NewAsterisk(tableName)
|
||||
_coupon.ExpireAt = field.NewTime(tableName, "expire_at")
|
||||
_coupon.CreatedAt = field.NewField(tableName, "created_at")
|
||||
_coupon.UpdatedAt = field.NewField(tableName, "updated_at")
|
||||
_coupon.DeletedAt = field.NewField(tableName, "deleted_at")
|
||||
_coupon.ID = field.NewInt32(tableName, "id")
|
||||
_coupon.UserID = field.NewInt32(tableName, "user_id")
|
||||
_coupon.Status = field.NewInt32(tableName, "status")
|
||||
_coupon.Code = field.NewString(tableName, "code")
|
||||
_coupon.Remark = field.NewString(tableName, "remark")
|
||||
_coupon.Amount = field.NewFloat64(tableName, "amount")
|
||||
_coupon.MinAmount = field.NewFloat64(tableName, "min_amount")
|
||||
|
||||
_coupon.fillFieldMap()
|
||||
|
||||
return _coupon
|
||||
}
|
||||
|
||||
type coupon struct {
|
||||
couponDo
|
||||
|
||||
ALL field.Asterisk
|
||||
ExpireAt field.Time
|
||||
CreatedAt field.Field
|
||||
UpdatedAt field.Field
|
||||
DeletedAt field.Field
|
||||
ID field.Int32
|
||||
UserID field.Int32
|
||||
Status field.Int32
|
||||
Code field.String
|
||||
Remark field.String
|
||||
Amount field.Float64
|
||||
MinAmount field.Float64
|
||||
|
||||
fieldMap map[string]field.Expr
|
||||
}
|
||||
|
||||
func (c coupon) Table(newTableName string) *coupon {
|
||||
c.couponDo.UseTable(newTableName)
|
||||
return c.updateTableName(newTableName)
|
||||
}
|
||||
|
||||
func (c coupon) As(alias string) *coupon {
|
||||
c.couponDo.DO = *(c.couponDo.As(alias).(*gen.DO))
|
||||
return c.updateTableName(alias)
|
||||
}
|
||||
|
||||
func (c *coupon) updateTableName(table string) *coupon {
|
||||
c.ALL = field.NewAsterisk(table)
|
||||
c.ExpireAt = field.NewTime(table, "expire_at")
|
||||
c.CreatedAt = field.NewField(table, "created_at")
|
||||
c.UpdatedAt = field.NewField(table, "updated_at")
|
||||
c.DeletedAt = field.NewField(table, "deleted_at")
|
||||
c.ID = field.NewInt32(table, "id")
|
||||
c.UserID = field.NewInt32(table, "user_id")
|
||||
c.Status = field.NewInt32(table, "status")
|
||||
c.Code = field.NewString(table, "code")
|
||||
c.Remark = field.NewString(table, "remark")
|
||||
c.Amount = field.NewFloat64(table, "amount")
|
||||
c.MinAmount = field.NewFloat64(table, "min_amount")
|
||||
|
||||
c.fillFieldMap()
|
||||
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *coupon) GetFieldByName(fieldName string) (field.OrderExpr, bool) {
|
||||
_f, ok := c.fieldMap[fieldName]
|
||||
if !ok || _f == nil {
|
||||
return nil, false
|
||||
}
|
||||
_oe, ok := _f.(field.OrderExpr)
|
||||
return _oe, ok
|
||||
}
|
||||
|
||||
func (c *coupon) fillFieldMap() {
|
||||
c.fieldMap = make(map[string]field.Expr, 11)
|
||||
c.fieldMap["expire_at"] = c.ExpireAt
|
||||
c.fieldMap["created_at"] = c.CreatedAt
|
||||
c.fieldMap["updated_at"] = c.UpdatedAt
|
||||
c.fieldMap["deleted_at"] = c.DeletedAt
|
||||
c.fieldMap["id"] = c.ID
|
||||
c.fieldMap["user_id"] = c.UserID
|
||||
c.fieldMap["status"] = c.Status
|
||||
c.fieldMap["code"] = c.Code
|
||||
c.fieldMap["remark"] = c.Remark
|
||||
c.fieldMap["amount"] = c.Amount
|
||||
c.fieldMap["min_amount"] = c.MinAmount
|
||||
}
|
||||
|
||||
func (c coupon) clone(db *gorm.DB) coupon {
|
||||
c.couponDo.ReplaceConnPool(db.Statement.ConnPool)
|
||||
return c
|
||||
}
|
||||
|
||||
func (c coupon) replaceDB(db *gorm.DB) coupon {
|
||||
c.couponDo.ReplaceDB(db)
|
||||
return c
|
||||
}
|
||||
|
||||
type couponDo struct{ gen.DO }
|
||||
|
||||
func (c couponDo) Debug() *couponDo {
|
||||
return c.withDO(c.DO.Debug())
|
||||
}
|
||||
|
||||
func (c couponDo) WithContext(ctx context.Context) *couponDo {
|
||||
return c.withDO(c.DO.WithContext(ctx))
|
||||
}
|
||||
|
||||
func (c couponDo) ReadDB() *couponDo {
|
||||
return c.Clauses(dbresolver.Read)
|
||||
}
|
||||
|
||||
func (c couponDo) WriteDB() *couponDo {
|
||||
return c.Clauses(dbresolver.Write)
|
||||
}
|
||||
|
||||
func (c couponDo) Session(config *gorm.Session) *couponDo {
|
||||
return c.withDO(c.DO.Session(config))
|
||||
}
|
||||
|
||||
func (c couponDo) Clauses(conds ...clause.Expression) *couponDo {
|
||||
return c.withDO(c.DO.Clauses(conds...))
|
||||
}
|
||||
|
||||
func (c couponDo) Returning(value interface{}, columns ...string) *couponDo {
|
||||
return c.withDO(c.DO.Returning(value, columns...))
|
||||
}
|
||||
|
||||
func (c couponDo) Not(conds ...gen.Condition) *couponDo {
|
||||
return c.withDO(c.DO.Not(conds...))
|
||||
}
|
||||
|
||||
func (c couponDo) Or(conds ...gen.Condition) *couponDo {
|
||||
return c.withDO(c.DO.Or(conds...))
|
||||
}
|
||||
|
||||
func (c couponDo) Select(conds ...field.Expr) *couponDo {
|
||||
return c.withDO(c.DO.Select(conds...))
|
||||
}
|
||||
|
||||
func (c couponDo) Where(conds ...gen.Condition) *couponDo {
|
||||
return c.withDO(c.DO.Where(conds...))
|
||||
}
|
||||
|
||||
func (c couponDo) Order(conds ...field.Expr) *couponDo {
|
||||
return c.withDO(c.DO.Order(conds...))
|
||||
}
|
||||
|
||||
func (c couponDo) Distinct(cols ...field.Expr) *couponDo {
|
||||
return c.withDO(c.DO.Distinct(cols...))
|
||||
}
|
||||
|
||||
func (c couponDo) Omit(cols ...field.Expr) *couponDo {
|
||||
return c.withDO(c.DO.Omit(cols...))
|
||||
}
|
||||
|
||||
func (c couponDo) Join(table schema.Tabler, on ...field.Expr) *couponDo {
|
||||
return c.withDO(c.DO.Join(table, on...))
|
||||
}
|
||||
|
||||
func (c couponDo) LeftJoin(table schema.Tabler, on ...field.Expr) *couponDo {
|
||||
return c.withDO(c.DO.LeftJoin(table, on...))
|
||||
}
|
||||
|
||||
func (c couponDo) RightJoin(table schema.Tabler, on ...field.Expr) *couponDo {
|
||||
return c.withDO(c.DO.RightJoin(table, on...))
|
||||
}
|
||||
|
||||
func (c couponDo) Group(cols ...field.Expr) *couponDo {
|
||||
return c.withDO(c.DO.Group(cols...))
|
||||
}
|
||||
|
||||
func (c couponDo) Having(conds ...gen.Condition) *couponDo {
|
||||
return c.withDO(c.DO.Having(conds...))
|
||||
}
|
||||
|
||||
func (c couponDo) Limit(limit int) *couponDo {
|
||||
return c.withDO(c.DO.Limit(limit))
|
||||
}
|
||||
|
||||
func (c couponDo) Offset(offset int) *couponDo {
|
||||
return c.withDO(c.DO.Offset(offset))
|
||||
}
|
||||
|
||||
func (c couponDo) Scopes(funcs ...func(gen.Dao) gen.Dao) *couponDo {
|
||||
return c.withDO(c.DO.Scopes(funcs...))
|
||||
}
|
||||
|
||||
func (c couponDo) Unscoped() *couponDo {
|
||||
return c.withDO(c.DO.Unscoped())
|
||||
}
|
||||
|
||||
func (c couponDo) Create(values ...*models.Coupon) error {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
return c.DO.Create(values)
|
||||
}
|
||||
|
||||
func (c couponDo) CreateInBatches(values []*models.Coupon, batchSize int) error {
|
||||
return c.DO.CreateInBatches(values, batchSize)
|
||||
}
|
||||
|
||||
// Save : !!! underlying implementation is different with GORM
|
||||
// The method is equivalent to executing the statement: db.Clauses(clause.OnConflict{UpdateAll: true}).Create(values)
|
||||
func (c couponDo) Save(values ...*models.Coupon) error {
|
||||
if len(values) == 0 {
|
||||
return nil
|
||||
}
|
||||
return c.DO.Save(values)
|
||||
}
|
||||
|
||||
func (c couponDo) First() (*models.Coupon, error) {
|
||||
if result, err := c.DO.First(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*models.Coupon), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c couponDo) Take() (*models.Coupon, error) {
|
||||
if result, err := c.DO.Take(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*models.Coupon), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c couponDo) Last() (*models.Coupon, error) {
|
||||
if result, err := c.DO.Last(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*models.Coupon), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c couponDo) Find() ([]*models.Coupon, error) {
|
||||
result, err := c.DO.Find()
|
||||
return result.([]*models.Coupon), err
|
||||
}
|
||||
|
||||
func (c couponDo) FindInBatch(batchSize int, fc func(tx gen.Dao, batch int) error) (results []*models.Coupon, err error) {
|
||||
buf := make([]*models.Coupon, 0, batchSize)
|
||||
err = c.DO.FindInBatches(&buf, batchSize, func(tx gen.Dao, batch int) error {
|
||||
defer func() { results = append(results, buf...) }()
|
||||
return fc(tx, batch)
|
||||
})
|
||||
return results, err
|
||||
}
|
||||
|
||||
func (c couponDo) FindInBatches(result *[]*models.Coupon, batchSize int, fc func(tx gen.Dao, batch int) error) error {
|
||||
return c.DO.FindInBatches(result, batchSize, fc)
|
||||
}
|
||||
|
||||
func (c couponDo) Attrs(attrs ...field.AssignExpr) *couponDo {
|
||||
return c.withDO(c.DO.Attrs(attrs...))
|
||||
}
|
||||
|
||||
func (c couponDo) Assign(attrs ...field.AssignExpr) *couponDo {
|
||||
return c.withDO(c.DO.Assign(attrs...))
|
||||
}
|
||||
|
||||
func (c couponDo) Joins(fields ...field.RelationField) *couponDo {
|
||||
for _, _f := range fields {
|
||||
c = *c.withDO(c.DO.Joins(_f))
|
||||
}
|
||||
return &c
|
||||
}
|
||||
|
||||
func (c couponDo) Preload(fields ...field.RelationField) *couponDo {
|
||||
for _, _f := range fields {
|
||||
c = *c.withDO(c.DO.Preload(_f))
|
||||
}
|
||||
return &c
|
||||
}
|
||||
|
||||
func (c couponDo) FirstOrInit() (*models.Coupon, error) {
|
||||
if result, err := c.DO.FirstOrInit(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*models.Coupon), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c couponDo) FirstOrCreate() (*models.Coupon, error) {
|
||||
if result, err := c.DO.FirstOrCreate(); err != nil {
|
||||
return nil, err
|
||||
} else {
|
||||
return result.(*models.Coupon), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (c couponDo) FindByPage(offset int, limit int) (result []*models.Coupon, count int64, err error) {
|
||||
result, err = c.Offset(offset).Limit(limit).Find()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
if size := len(result); 0 < limit && 0 < size && size < limit {
|
||||
count = int64(size + offset)
|
||||
return
|
||||
}
|
||||
|
||||
count, err = c.Offset(-1).Limit(-1).Count()
|
||||
return
|
||||
}
|
||||
|
||||
func (c couponDo) ScanByPage(result interface{}, offset int, limit int) (count int64, err error) {
|
||||
count, err = c.Count()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
err = c.Offset(offset).Limit(limit).Scan(result)
|
||||
return
|
||||
}
|
||||
|
||||
func (c couponDo) Scan(result interface{}) (err error) {
|
||||
return c.DO.Scan(result)
|
||||
}
|
||||
|
||||
func (c couponDo) Delete(models ...*models.Coupon) (result gen.ResultInfo, err error) {
|
||||
return c.DO.Delete(models)
|
||||
}
|
||||
|
||||
func (c *couponDo) withDO(do gen.Dao) *couponDo {
|
||||
c.DO = *do.(*gen.DO)
|
||||
return c
|
||||
}
|
||||
@@ -25,6 +25,7 @@ var (
|
||||
Channel *channel
|
||||
Client *client
|
||||
ClientPermissionLink *clientPermissionLink
|
||||
Coupon *coupon
|
||||
Node *node
|
||||
Permission *permission
|
||||
Product *product
|
||||
@@ -52,6 +53,7 @@ func SetDefault(db *gorm.DB, opts ...gen.DOOption) {
|
||||
Channel = &Q.Channel
|
||||
Client = &Q.Client
|
||||
ClientPermissionLink = &Q.ClientPermissionLink
|
||||
Coupon = &Q.Coupon
|
||||
Node = &Q.Node
|
||||
Permission = &Q.Permission
|
||||
Product = &Q.Product
|
||||
@@ -80,6 +82,7 @@ func Use(db *gorm.DB, opts ...gen.DOOption) *Query {
|
||||
Channel: newChannel(db, opts...),
|
||||
Client: newClient(db, opts...),
|
||||
ClientPermissionLink: newClientPermissionLink(db, opts...),
|
||||
Coupon: newCoupon(db, opts...),
|
||||
Node: newNode(db, opts...),
|
||||
Permission: newPermission(db, opts...),
|
||||
Product: newProduct(db, opts...),
|
||||
@@ -109,6 +112,7 @@ type Query struct {
|
||||
Channel channel
|
||||
Client client
|
||||
ClientPermissionLink clientPermissionLink
|
||||
Coupon coupon
|
||||
Node node
|
||||
Permission permission
|
||||
Product product
|
||||
@@ -139,6 +143,7 @@ func (q *Query) clone(db *gorm.DB) *Query {
|
||||
Channel: q.Channel.clone(db),
|
||||
Client: q.Client.clone(db),
|
||||
ClientPermissionLink: q.ClientPermissionLink.clone(db),
|
||||
Coupon: q.Coupon.clone(db),
|
||||
Node: q.Node.clone(db),
|
||||
Permission: q.Permission.clone(db),
|
||||
Product: q.Product.clone(db),
|
||||
@@ -176,6 +181,7 @@ func (q *Query) ReplaceDB(db *gorm.DB) *Query {
|
||||
Channel: q.Channel.replaceDB(db),
|
||||
Client: q.Client.replaceDB(db),
|
||||
ClientPermissionLink: q.ClientPermissionLink.replaceDB(db),
|
||||
Coupon: q.Coupon.replaceDB(db),
|
||||
Node: q.Node.replaceDB(db),
|
||||
Permission: q.Permission.replaceDB(db),
|
||||
Product: q.Product.replaceDB(db),
|
||||
@@ -203,6 +209,7 @@ type queryCtx struct {
|
||||
Channel *channelDo
|
||||
Client *clientDo
|
||||
ClientPermissionLink *clientPermissionLinkDo
|
||||
Coupon *couponDo
|
||||
Node *nodeDo
|
||||
Permission *permissionDo
|
||||
Product *productDo
|
||||
@@ -230,6 +237,7 @@ func (q *Query) WithContext(ctx context.Context) *queryCtx {
|
||||
Channel: q.Channel.WithContext(ctx),
|
||||
Client: q.Client.WithContext(ctx),
|
||||
ClientPermissionLink: q.ClientPermissionLink.WithContext(ctx),
|
||||
Coupon: q.Coupon.WithContext(ctx),
|
||||
Node: q.Node.WithContext(ctx),
|
||||
Permission: q.Permission.WithContext(ctx),
|
||||
Product: q.Product.WithContext(ctx),
|
||||
|
||||
@@ -205,7 +205,25 @@ func (data *CreateResourceData) GetName() string {
|
||||
|
||||
func (data *CreateResourceData) GetPrice() float64 {
|
||||
if data.price == 0 {
|
||||
data.price = 0.01
|
||||
var count int
|
||||
switch data.Type {
|
||||
case 1:
|
||||
count = int(data.DailyLimit)
|
||||
case 2:
|
||||
count = int(data.Quota)
|
||||
}
|
||||
|
||||
seconds := int(data.Live)
|
||||
if seconds == 180 {
|
||||
seconds = 150
|
||||
}
|
||||
|
||||
times := int(data.Expire)
|
||||
if data.Type == 2 {
|
||||
times = 1
|
||||
}
|
||||
|
||||
data.price = float64(count*seconds*times) / 30000
|
||||
}
|
||||
return data.price
|
||||
}
|
||||
@@ -229,7 +247,7 @@ func createResource(data *CreateResourceData, uid int32) (*m.Resource, error) {
|
||||
Type: data.Type,
|
||||
Live: data.Live,
|
||||
Quota: data.Quota,
|
||||
Expire: common.LocalDateTime(time.Now().Add(time.Duration(data.Expire) * time.Second)),
|
||||
Expire: common.LocalDateTime(time.Now().Add(time.Duration(data.Expire) * 24 * time.Hour)),
|
||||
DailyLimit: data.DailyLimit,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
|
||||
"github.com/smartwalle/alipay/v3"
|
||||
"github.com/wechatpay-apiv3/wechatpay-go/services/payments/native"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var Transaction = &transactionService{}
|
||||
@@ -26,10 +27,60 @@ type transactionService struct {
|
||||
|
||||
func (s *transactionService) PrepareTransaction(ctx context.Context, q *q.Query, uid int32, data *TransactionPrepareData) (*TransactionPrepareResult, error) {
|
||||
var subject = data.Subject
|
||||
var amount = data.Amount
|
||||
var expire = data.ExpireAt
|
||||
var tType = data.Type
|
||||
var method = data.Method
|
||||
var amount = data.Amount
|
||||
if data.CouponCode != "" {
|
||||
coupon, err := q.Coupon.WithContext(ctx).
|
||||
Where(
|
||||
q.Coupon.Code.Eq(data.CouponCode),
|
||||
q.Coupon.Status.Eq(0),
|
||||
).
|
||||
Take()
|
||||
if err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, errors.New("优惠券不存在或已失效")
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !coupon.ExpireAt.IsZero() && coupon.ExpireAt.Before(time.Now()) {
|
||||
_, err = q.Coupon.
|
||||
Where(q.Coupon.ID.Eq(coupon.ID)).
|
||||
Update(q.Coupon.Status, 2)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return nil, errors.New("优惠券已过期")
|
||||
}
|
||||
|
||||
if data.Amount < coupon.MinAmount {
|
||||
return nil, errors.New("订单金额未达到使用优惠券的条件")
|
||||
}
|
||||
|
||||
switch {
|
||||
// 该优惠券不属于当前用户
|
||||
default:
|
||||
return nil, errors.New("优惠券不属于当前用户")
|
||||
|
||||
// 公开优惠券
|
||||
case coupon.UserID == 0:
|
||||
amount = amount - coupon.Amount
|
||||
|
||||
// 指定用户的优惠券
|
||||
case coupon.UserID == uid:
|
||||
amount = amount - coupon.Amount
|
||||
if coupon.ExpireAt.IsZero() {
|
||||
_, err = q.Coupon.
|
||||
Where(q.Coupon.ID.Eq(coupon.ID)).
|
||||
Update(q.Coupon.Status, 1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 生成订单号
|
||||
tradeNo, err := ID.GenSerial(ctx)
|
||||
@@ -78,7 +129,7 @@ func (s *transactionService) PrepareTransaction(ctx context.Context, q *q.Query,
|
||||
|
||||
// 不支持的支付方式
|
||||
default:
|
||||
return nil, errors.New("不支持的支付方式")
|
||||
return nil, ErrTransactionNotSupported
|
||||
}
|
||||
|
||||
// 保存交易订单
|
||||
@@ -140,11 +191,11 @@ func (s *transactionService) VerifyTransaction(ctx context.Context, data *Transa
|
||||
return nil, err
|
||||
}
|
||||
if resp.Code != alipay.CodeSuccess {
|
||||
slog.Warn("支付宝交易取消失败", "code", resp.Code, "sub_code", resp.SubCode, "msg", resp.Msg)
|
||||
slog.Warn("支付宝交易查询失败", "code", resp.Code, "sub_code", resp.SubCode, "msg", resp.Msg)
|
||||
return nil, errors.New("交易查询失败")
|
||||
}
|
||||
if resp.TradeStatus != alipay.TradeStatusSuccess {
|
||||
return nil, errors.New("交易未完成")
|
||||
return nil, ErrTransactionNotPaid
|
||||
}
|
||||
|
||||
transId = resp.TradeNo
|
||||
@@ -167,7 +218,7 @@ func (s *transactionService) VerifyTransaction(ctx context.Context, data *Transa
|
||||
return nil, err
|
||||
}
|
||||
if *resp.TradeState != "SUCCESS" {
|
||||
return nil, errors.New("交易未完成")
|
||||
return nil, ErrTransactionNotPaid
|
||||
}
|
||||
|
||||
transId = *resp.TransactionId
|
||||
@@ -179,7 +230,7 @@ func (s *transactionService) VerifyTransaction(ctx context.Context, data *Transa
|
||||
|
||||
// 不支持的支付方式
|
||||
default:
|
||||
return nil, errors.New("不支持的支付方式")
|
||||
return nil, ErrTransactionNotSupported
|
||||
}
|
||||
|
||||
return &TransactionVerifyResult{
|
||||
@@ -289,11 +340,12 @@ const (
|
||||
)
|
||||
|
||||
type TransactionPrepareData struct {
|
||||
Subject string
|
||||
Amount float64
|
||||
ExpireAt time.Time
|
||||
Type TransactionType
|
||||
Method TransactionMethod
|
||||
Subject string
|
||||
Amount float64
|
||||
ExpireAt time.Time
|
||||
Type TransactionType
|
||||
Method TransactionMethod
|
||||
CouponCode string
|
||||
}
|
||||
|
||||
type TransactionPrepareResult struct {
|
||||
@@ -322,3 +374,8 @@ type TransactionCompleteData struct {
|
||||
type TransactionCompleteResult struct {
|
||||
Trade *m.Trade
|
||||
}
|
||||
|
||||
var (
|
||||
ErrTransactionNotPaid = common.NewErr("transaction", "交易未完成")
|
||||
ErrTransactionNotSupported = common.NewErr("transaction", "不支持的支付方式")
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user