common/structs/storage/article.go

101 lines
2.6 KiB
Go

package storage
import (
v2 "gitea.timerzz.com/kedaya_haitao/common/structs/v2"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
type Storage struct {
ArticleApi
}
type ArticleApi interface {
Upsert(article v2.Article) error
Find(query FindArticleQuery) (articles []v2.Article, err error)
List(query PageListQuery) (articles []v2.Article, total int64, err error)
Get(query GetArticleQuery) (article v2.Article, err error)
}
type articleApi struct {
db *gorm.DB
}
// Upsert 插入或者更新商品
func (a *articleApi) Upsert(article v2.Article) error {
return a.db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "pid"}, {Name: "brand"}},
DoUpdates: clause.AssignmentColumns([]string{"name", "english_name", "available", "updated_at", "cost_price", "sell_price", "rate", "remark"}),
}).Create(&article).Error
}
type FindArticleQuery struct {
ID uint `query:"id"`
Keyword string `query:"keyword"`
Brand string `query:"brand"`
Pid string `query:"pid"`
Available *bool `query:"available"`
}
func (l *FindArticleQuery) Scope(db *gorm.DB) *gorm.DB {
if l.ID != 0 {
db = db.Where("`id` = ?", l.ID)
}
if l.Keyword != "" {
db = db.Where("(`name` LIKE ? OR `english_name LIKE ? OR `remark` LIKE ? )", "%"+l.Keyword+"%", "%"+l.Keyword+"%", "%"+l.Keyword+"%")
}
if l.Brand != "" {
db = db.Where("`brand` = ?", l.Brand)
}
if l.Pid != "" {
db = db.Where("`pid` = ?", l.Pid)
}
if l.Available != nil {
db = db.Where("`available` = ?", *l.Available)
}
return db
}
func (a *articleApi) Find(query FindArticleQuery) (articles []v2.Article, err error) {
err = a.db.Scopes(query.Scope).Find(&articles).Error
return
}
func (a *articleApi) List(query PageListQuery) (articles []v2.Article, total int64, err error) {
err = a.db.Scopes(query.Scoper.Scope).Count(&total).Error
if err != nil {
return
}
err = a.db.Scopes(query.Scope).Find(&articles).Error
return
}
type GetArticleQuery struct {
ID uint `query:"id"`
Brand string `query:"brand"`
Pid string `query:"pid"`
History bool `query:"history"`
}
func (g *GetArticleQuery) Scope(db *gorm.DB) *gorm.DB {
db = db.Preload("Providers").Preload("Sellers")
if g.ID != 0 {
db = db.Where("`id` = ?", g.ID)
}
if g.Brand != "" {
db = db.Where("`brand` = ?", g.Brand)
}
if g.Pid != "" {
db = db.Where("`pid` = ?", g.Pid)
}
if g.History {
db = db.Preload("Providers.HistoryPrice").Preload("Sellers.HistoryPrice")
}
return db
}
func (a *articleApi) Get(query GetArticleQuery) (article v2.Article, err error) {
err = a.db.Scopes(query.Scope).First(&article).Error
return
}