83 lines
2.6 KiB
Go
83 lines
2.6 KiB
Go
package model
|
||
|
||
import (
|
||
"context"
|
||
"fmt"
|
||
"strings"
|
||
|
||
"qnc-server/common/globalkey"
|
||
|
||
"github.com/zeromicro/go-zero/core/stores/cache"
|
||
"github.com/zeromicro/go-zero/core/stores/sqlx"
|
||
)
|
||
|
||
var _ ProductFeatureModel = (*customProductFeatureModel)(nil)
|
||
|
||
type (
|
||
// ProductFeatureModel is an interface to be customized, add more methods here,
|
||
// and implement the added methods in customProductFeatureModel.
|
||
ProductFeatureModel interface {
|
||
productFeatureModel
|
||
// SumFeatureCostPriceByProductId 汇总该产品下已关联且未删除的模块成本(feature.cost_price 之和)
|
||
SumFeatureCostPriceByProductId(ctx context.Context, productId string) (float64, error)
|
||
// SumFeatureCostPriceByProductIds 批量汇总,未出现在结果中的产品视为 0
|
||
SumFeatureCostPriceByProductIds(ctx context.Context, productIds []string) (map[string]float64, error)
|
||
}
|
||
|
||
customProductFeatureModel struct {
|
||
*defaultProductFeatureModel
|
||
}
|
||
)
|
||
|
||
// NewProductFeatureModel returns a model for the database table.
|
||
func NewProductFeatureModel(conn sqlx.SqlConn, c cache.CacheConf) ProductFeatureModel {
|
||
return &customProductFeatureModel{
|
||
defaultProductFeatureModel: newProductFeatureModel(conn, c),
|
||
}
|
||
}
|
||
|
||
func (m *customProductFeatureModel) SumFeatureCostPriceByProductId(ctx context.Context, productId string) (float64, error) {
|
||
query := `
|
||
SELECT COALESCE(SUM(f.cost_price), 0)
|
||
FROM product_feature pf
|
||
INNER JOIN feature f ON f.id = pf.feature_id AND f.del_state = ?
|
||
WHERE pf.product_id = ? AND pf.del_state = ?`
|
||
var sum float64
|
||
err := m.QueryRowNoCacheCtx(ctx, &sum, query, globalkey.DelStateNo, productId, globalkey.DelStateNo)
|
||
if err != nil {
|
||
return 0, err
|
||
}
|
||
return sum, nil
|
||
}
|
||
|
||
func (m *customProductFeatureModel) SumFeatureCostPriceByProductIds(ctx context.Context, productIds []string) (map[string]float64, error) {
|
||
out := make(map[string]float64)
|
||
if len(productIds) == 0 {
|
||
return out, nil
|
||
}
|
||
placeholders := strings.TrimSuffix(strings.Repeat("?,", len(productIds)), ",")
|
||
query := fmt.Sprintf(`
|
||
SELECT pf.product_id, COALESCE(SUM(f.cost_price), 0) AS total
|
||
FROM product_feature pf
|
||
INNER JOIN feature f ON f.id = pf.feature_id AND f.del_state = ?
|
||
WHERE pf.del_state = ? AND pf.product_id IN (%s)
|
||
GROUP BY pf.product_id`, placeholders)
|
||
args := make([]interface{}, 0, 2+len(productIds))
|
||
args = append(args, globalkey.DelStateNo, globalkey.DelStateNo)
|
||
for _, id := range productIds {
|
||
args = append(args, id)
|
||
}
|
||
var rows []struct {
|
||
ProductId string `db:"product_id"`
|
||
Total float64 `db:"total"`
|
||
}
|
||
err := m.QueryRowsNoCacheCtx(ctx, &rows, query, args...)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
for i := range rows {
|
||
out[rows[i].ProductId] = rows[i].Total
|
||
}
|
||
return out, nil
|
||
}
|