feat: 追踪数据操作者

main
熊二 2 years ago
parent 96a717a9e9
commit 645326b148
  1. 7
      app/db.go
  2. 40
      app/rts.go

@ -65,6 +65,10 @@ type Goods struct {
Name string `json:"name"` // 商品名称
Price float32 `json:"price"` // 商品当前价格
Prices []Price `json:"prices,omitempty"` // 商品价格列表
CreatedBy uint `json:"created_by"` // 商品创建者ID
Creator *User `json:"creator,omitempty" gorm:"foreignKey:CreatedBy"` // 商品创建者
UpdatedBy uint `json:"updated_by"` // 商品更新者ID
Updater *User `json:"updater,omitempty" gorm:"foreignKey:UpdatedBy"` // 商品更新者
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
@ -75,8 +79,9 @@ type Price struct {
ID uint `json:"id" gorm:"primarykey"`
GoodsID uint `json:"goods_id"` // 管理商品
Price float32 `json:"price"` // 商品价格
CreatedBy uint `json:"created_by"` // 价格创建者ID
Creator *User `json:"creator,omitempty" gorm:"foreignKey:CreatedBy"` // 价格创建者
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
DeletedAt gorm.DeletedAt `json:"-" gorm:"index"`
}

@ -295,14 +295,37 @@ func CreateGoods(w *ResponseWriter, r *Request) {
w.Error(NewError(2, "商品价格错误"))
return
}
// 加载登录用户信息
ut, ok := UserTokenFromContext(r.Context())
if !ok {
w.Error(NewError(1, "找不到登录用户消息"))
return
}
// 防止商品重名
var goods Goods
err := DB.First(&goods, "name = ?", name).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
goods = Goods{
Name: name,
Price: price,
CreatedBy: ut.UserID,
Creator: ut.User,
UpdatedBy: ut.UserID,
Updater: ut.User,
}
err = DB.Create(&goods).Error
err = DB.Transaction(func(tx *gorm.DB) error {
if err := tx.Create(&goods).Error; err != nil {
return err
}
return tx.Create(&Price{
GoodsID: goods.ID,
Price: goods.Price,
CreatedBy: goods.CreatedBy,
CreatedAt: goods.CreatedAt,
}).Error
})
if err != nil {
w.Error(NewError(3, "创建商品失败"))
} else {
@ -328,6 +351,15 @@ func UpdateGoods(w *ResponseWriter, r *Request) {
w.Error(NewError(2, "商品价格错误"))
return
}
// 加载登录用户信息
ut, ok := UserTokenFromContext(r.Context())
if !ok {
w.Error(NewError(1, "找不到登录用户消息"))
return
}
// 查询商品
var goods Goods
err := DB.First(&goods, "id = ?", id).Error
if errors.Is(err, gorm.ErrRecordNotFound) {
@ -355,6 +387,8 @@ func UpdateGoods(w *ResponseWriter, r *Request) {
if goods.Price == price {
if goods.Name != name {
goods.Name = name
goods.UpdatedBy = ut.UserID
goods.Updater = ut.User
err = DB.Save(&goods).Error
if err != nil {
w.Error(err)
@ -369,6 +403,8 @@ func UpdateGoods(w *ResponseWriter, r *Request) {
err = DB.Transaction(func(tx *gorm.DB) error {
goods.Name = name
goods.Price = price
goods.UpdatedBy = ut.UserID
goods.Updater = ut.User
if err = tx.Save(&goods).Error; err != nil {
return err
}
@ -376,6 +412,8 @@ func UpdateGoods(w *ResponseWriter, r *Request) {
return tx.Create(&Price{
GoodsID: goods.ID,
Price: goods.Price,
CreatedBy: ut.UserID,
Creator: ut.User,
}).Error
})
if err != nil {

Loading…
Cancel
Save