重构价格管理模块,完全迁移到 GORM ORM

- 将价格相关处理函数从原生 SQL 完全迁移到 GORM
- 优化数据库查询逻辑,使用 GORM 的链式查询和更新方法
- 重构价格审核、更新和批量审核功能,使用事务处理
- 简化数据库操作,移除手动 SQL 查询和扫描逻辑
- 优化价格倍率计算方法,提高代码可读性和性能
This commit is contained in:
wood chen 2025-03-06 23:46:18 +08:00
parent 31f65a9301
commit 449f95d1b5
2 changed files with 276 additions and 288 deletions

View File

@ -81,10 +81,11 @@ func UpdateModelType(c *gin.Context) {
return
}
} else {
// 直接更新
existingType.TypeLabel = updateType.TypeLabel
existingType.SortOrder = updateType.SortOrder
if err := database.DB.Save(&existingType).Error; err != nil {
// 直接更新,只更新特定字段
if err := database.DB.Model(&existingType).Updates(map[string]interface{}{
"type_label": updateType.TypeLabel,
"sort_order": updateType.SortOrder,
}).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update model type"})
return
}

View File

@ -1,20 +1,17 @@
package handlers
import (
"database/sql"
"net/http"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"aimodels-prices/database"
"aimodels-prices/models"
)
func GetPrices(c *gin.Context) {
db := c.MustGet("db").(*sql.DB)
// 获取分页和筛选参数
page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "20"))
@ -30,75 +27,34 @@ func GetPrices(c *gin.Context) {
offset := (page - 1) * pageSize
// 构建查询条件
var conditions []string
var args []interface{}
// 构建查询
query := database.DB.Model(&models.Price{})
// 添加筛选条件
if channelType != "" {
conditions = append(conditions, "channel_type = ?")
args = append(args, channelType)
query = query.Where("channel_type = ?", channelType)
}
if modelType != "" {
conditions = append(conditions, "model_type = ?")
args = append(args, modelType)
}
// 组合WHERE子句
var whereClause string
if len(conditions) > 0 {
whereClause = "WHERE " + strings.Join(conditions, " AND ")
query = query.Where("model_type = ?", modelType)
}
// 获取总数
var total int
countQuery := "SELECT COUNT(*) FROM price"
if whereClause != "" {
countQuery += " " + whereClause
}
err := db.QueryRow(countQuery, args...).Scan(&total)
if err != nil {
var total int64
if err := query.Count(&total).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to count prices"})
return
}
// 使用分页查询
query := `
SELECT id, model, model_type, billing_type, channel_type, currency, input_price, output_price,
price_source, status, created_at, updated_at, created_by,
temp_model, temp_model_type, temp_billing_type, temp_channel_type, temp_currency,
temp_input_price, temp_output_price, temp_price_source, updated_by
FROM price`
if whereClause != "" {
query += " " + whereClause
}
query += " ORDER BY created_at DESC LIMIT ? OFFSET ?"
args = append(args, pageSize, offset)
rows, err := db.Query(query, args...)
if err != nil {
// 获取分页数据
var prices []models.Price
if err := query.Order("created_at DESC").Limit(pageSize).Offset(offset).Find(&prices).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch prices"})
return
}
defer rows.Close()
var prices []models.Price
for rows.Next() {
var price models.Price
if err := rows.Scan(
&price.ID, &price.Model, &price.ModelType, &price.BillingType, &price.ChannelType, &price.Currency,
&price.InputPrice, &price.OutputPrice, &price.PriceSource, &price.Status,
&price.CreatedAt, &price.UpdatedAt, &price.CreatedBy,
&price.TempModel, &price.TempModelType, &price.TempBillingType, &price.TempChannelType, &price.TempCurrency,
&price.TempInputPrice, &price.TempOutputPrice, &price.TempPriceSource, &price.UpdatedBy); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to scan price"})
return
}
prices = append(prices, price)
}
c.JSON(http.StatusOK, gin.H{
"total": total,
"prices": prices,
"total": total,
"data": prices,
})
}
@ -110,46 +66,33 @@ func CreatePrice(c *gin.Context) {
}
// 验证模型厂商ID是否存在
db := c.MustGet("db").(*sql.DB)
var providerExists bool
err := db.QueryRow("SELECT EXISTS(SELECT 1 FROM provider WHERE id = ?)", price.ChannelType).Scan(&providerExists)
if err != nil || !providerExists {
var provider models.Provider
if err := database.DB.Where("id = ?", price.ChannelType).First(&provider).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid provider ID"})
return
}
// 检查同一厂商下是否已存在相同名称的模型
var modelExists bool
err = db.QueryRow("SELECT EXISTS(SELECT 1 FROM price WHERE channel_type = ? AND model = ? AND status = 'approved')",
price.ChannelType, price.Model).Scan(&modelExists)
if err != nil {
var count int64
if err := database.DB.Model(&models.Price{}).Where("channel_type = ? AND model = ? AND status = 'approved'",
price.ChannelType, price.Model).Count(&count).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to check model existence"})
return
}
if modelExists {
if count > 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "Model with the same name already exists for this provider"})
return
}
now := time.Now()
result, err := db.Exec(`
INSERT INTO price (model, model_type, billing_type, channel_type, currency, input_price, output_price,
price_source, status, created_by, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', ?, ?, ?)`,
price.Model, price.ModelType, price.BillingType, price.ChannelType, price.Currency,
price.InputPrice, price.OutputPrice, price.PriceSource, price.CreatedBy,
now, now)
if err != nil {
// 设置状态和创建者
price.Status = "pending"
// 创建记录
if err := database.DB.Create(&price).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create price"})
return
}
id, _ := result.LastInsertId()
price.ID = uint(id)
price.Status = "pending"
price.CreatedAt = now
price.UpdatedAt = now
c.JSON(http.StatusCreated, price)
}
@ -164,67 +107,100 @@ func UpdatePriceStatus(c *gin.Context) {
return
}
db := c.MustGet("db").(*sql.DB)
now := time.Now()
// 查找价格记录
var price models.Price
if err := database.DB.Where("id = ?", id).First(&price).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Price not found"})
return
}
// 开始事务
tx := database.DB.Begin()
if input.Status == "approved" {
// 如果是批准,将临时字段的值更新到正式字段
_, err := db.Exec(`
UPDATE price
SET model = COALESCE(temp_model, model),
model_type = COALESCE(temp_model_type, model_type),
billing_type = COALESCE(temp_billing_type, billing_type),
channel_type = COALESCE(temp_channel_type, channel_type),
currency = COALESCE(temp_currency, currency),
input_price = COALESCE(temp_input_price, input_price),
output_price = COALESCE(temp_output_price, output_price),
price_source = COALESCE(temp_price_source, price_source),
status = ?,
updated_at = ?,
temp_model = NULL,
temp_model_type = NULL,
temp_billing_type = NULL,
temp_channel_type = NULL,
temp_currency = NULL,
temp_input_price = NULL,
temp_output_price = NULL,
temp_price_source = NULL,
updated_by = NULL
WHERE id = ?`, input.Status, now, id)
if err != nil {
updateMap := map[string]interface{}{
"status": input.Status,
"updated_at": time.Now(),
}
// 如果临时字段有值,则更新主字段
if price.TempModel != nil {
updateMap["model"] = *price.TempModel
}
if price.TempModelType != nil {
updateMap["model_type"] = *price.TempModelType
}
if price.TempBillingType != nil {
updateMap["billing_type"] = *price.TempBillingType
}
if price.TempChannelType != nil {
updateMap["channel_type"] = *price.TempChannelType
}
if price.TempCurrency != nil {
updateMap["currency"] = *price.TempCurrency
}
if price.TempInputPrice != nil {
updateMap["input_price"] = *price.TempInputPrice
}
if price.TempOutputPrice != nil {
updateMap["output_price"] = *price.TempOutputPrice
}
if price.TempPriceSource != nil {
updateMap["price_source"] = *price.TempPriceSource
}
// 清除所有临时字段
updateMap["temp_model"] = nil
updateMap["temp_model_type"] = nil
updateMap["temp_billing_type"] = nil
updateMap["temp_channel_type"] = nil
updateMap["temp_currency"] = nil
updateMap["temp_input_price"] = nil
updateMap["temp_output_price"] = nil
updateMap["temp_price_source"] = nil
updateMap["updated_by"] = nil
if err := tx.Model(&price).Updates(updateMap).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update price status"})
return
}
} else {
// 如果是拒绝,清除临时字段
_, err := db.Exec(`
UPDATE price
SET status = ?,
updated_at = ?,
temp_model = NULL,
temp_model_type = NULL,
temp_billing_type = NULL,
temp_channel_type = NULL,
temp_currency = NULL,
temp_input_price = NULL,
temp_output_price = NULL,
temp_price_source = NULL,
updated_by = NULL
WHERE id = ?`, input.Status, now, id)
if err != nil {
if err := tx.Model(&price).Updates(map[string]interface{}{
"status": input.Status,
"updated_at": time.Now(),
"temp_model": nil,
"temp_model_type": nil,
"temp_billing_type": nil,
"temp_channel_type": nil,
"temp_currency": nil,
"temp_input_price": nil,
"temp_output_price": nil,
"temp_price_source": nil,
"updated_by": nil,
}).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update price status"})
return
}
}
// 提交事务
if err := tx.Commit().Error; err != nil {
tx.Rollback()
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to commit transaction"})
return
}
c.JSON(http.StatusOK, gin.H{
"message": "Status updated successfully",
"status": input.Status,
"updated_at": now,
"updated_at": time.Now(),
})
}
// UpdatePrice 更新价格
func UpdatePrice(c *gin.Context) {
id := c.Param("id")
var price models.Price
@ -234,23 +210,20 @@ func UpdatePrice(c *gin.Context) {
}
// 验证模型厂商ID是否存在
db := c.MustGet("db").(*sql.DB)
var providerExists bool
err := db.QueryRow("SELECT EXISTS(SELECT 1 FROM provider WHERE id = ?)", price.ChannelType).Scan(&providerExists)
if err != nil || !providerExists {
var provider models.Provider
if err := database.DB.Where("id = ?", price.ChannelType).First(&provider).Error; err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid provider ID"})
return
}
// 检查同一厂商下是否已存在相同名称的模型(排除当前正在编辑的记录)
var modelExists bool
err = db.QueryRow("SELECT EXISTS(SELECT 1 FROM price WHERE channel_type = ? AND model = ? AND id != ? AND status = 'approved')",
price.ChannelType, price.Model, id).Scan(&modelExists)
if err != nil {
var count int64
if err := database.DB.Model(&models.Price{}).Where("channel_type = ? AND model = ? AND id != ? AND status = 'approved'",
price.ChannelType, price.Model, id).Count(&count).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to check model existence"})
return
}
if modelExists {
if count > 0 {
c.JSON(http.StatusBadRequest, gin.H{"error": "Model with the same name already exists for this provider"})
return
}
@ -263,76 +236,73 @@ func UpdatePrice(c *gin.Context) {
}
currentUser := user.(*models.User)
now := time.Now()
var query string
var args []interface{}
// 查找现有记录
var existingPrice models.Price
if err := database.DB.Where("id = ?", id).First(&existingPrice).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Price not found"})
return
}
// 根据用户角色决定更新方式
if currentUser.Role == "admin" {
// 管理员直接更新主字段
query = `
UPDATE price
SET model = ?, model_type = ?, billing_type = ?, channel_type = ?, currency = ?,
input_price = ?, output_price = ?, price_source = ?,
updated_by = ?, updated_at = ?, status = 'approved',
temp_model = NULL, temp_model_type = NULL, temp_billing_type = NULL,
temp_channel_type = NULL, temp_currency = NULL, temp_input_price = NULL,
temp_output_price = NULL, temp_price_source = NULL
WHERE id = ?`
args = []interface{}{
price.Model, price.ModelType, price.BillingType, price.ChannelType, price.Currency,
price.InputPrice, price.OutputPrice, price.PriceSource,
currentUser.Username, now, id,
existingPrice.Model = price.Model
existingPrice.ModelType = price.ModelType
existingPrice.BillingType = price.BillingType
existingPrice.ChannelType = price.ChannelType
existingPrice.Currency = price.Currency
existingPrice.InputPrice = price.InputPrice
existingPrice.OutputPrice = price.OutputPrice
existingPrice.PriceSource = price.PriceSource
existingPrice.Status = "approved"
existingPrice.UpdatedBy = &currentUser.Username
existingPrice.TempModel = nil
existingPrice.TempModelType = nil
existingPrice.TempBillingType = nil
existingPrice.TempChannelType = nil
existingPrice.TempCurrency = nil
existingPrice.TempInputPrice = nil
existingPrice.TempOutputPrice = nil
existingPrice.TempPriceSource = nil
if err := database.DB.Save(&existingPrice).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update price"})
return
}
} else {
// 普通用户更新临时字段
query = `
UPDATE price
SET temp_model = ?, temp_model_type = ?, temp_billing_type = ?, temp_channel_type = ?,
temp_currency = ?, temp_input_price = ?, temp_output_price = ?, temp_price_source = ?,
updated_by = ?, updated_at = ?, status = 'pending'
WHERE id = ?`
args = []interface{}{
price.Model, price.ModelType, price.BillingType, price.ChannelType, price.Currency,
price.InputPrice, price.OutputPrice, price.PriceSource,
currentUser.Username, now, id,
existingPrice.TempModel = &price.Model
existingPrice.TempModelType = &price.ModelType
existingPrice.TempBillingType = &price.BillingType
existingPrice.TempChannelType = &price.ChannelType
existingPrice.TempCurrency = &price.Currency
existingPrice.TempInputPrice = &price.InputPrice
existingPrice.TempOutputPrice = &price.OutputPrice
existingPrice.TempPriceSource = &price.PriceSource
existingPrice.Status = "pending"
existingPrice.UpdatedBy = &currentUser.Username
if err := database.DB.Save(&existingPrice).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update price"})
return
}
}
_, err = db.Exec(query, args...)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update price"})
return
}
// 获取更新后的价格信息
err = db.QueryRow(`
SELECT id, model, model_type, billing_type, channel_type, currency, input_price, output_price,
price_source, status, created_at, updated_at, created_by,
temp_model, temp_model_type, temp_billing_type, temp_channel_type, temp_currency,
temp_input_price, temp_output_price, temp_price_source, updated_by
FROM price WHERE id = ?`, id).Scan(
&price.ID, &price.Model, &price.ModelType, &price.BillingType, &price.ChannelType, &price.Currency,
&price.InputPrice, &price.OutputPrice, &price.PriceSource, &price.Status,
&price.CreatedAt, &price.UpdatedAt, &price.CreatedBy,
&price.TempModel, &price.TempModelType, &price.TempBillingType, &price.TempChannelType, &price.TempCurrency,
&price.TempInputPrice, &price.TempOutputPrice, &price.TempPriceSource, &price.UpdatedBy)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get updated price"})
return
}
c.JSON(http.StatusOK, price)
c.JSON(http.StatusOK, existingPrice)
}
// DeletePrice 删除价格
func DeletePrice(c *gin.Context) {
id := c.Param("id")
db := c.MustGet("db").(*sql.DB)
_, err := db.Exec("DELETE FROM price WHERE id = ?", id)
if err != nil {
// 查找价格记录
var price models.Price
if err := database.DB.Where("id = ?", id).First(&price).Error; err != nil {
c.JSON(http.StatusNotFound, gin.H{"error": "Price not found"})
return
}
// 删除记录
if err := database.DB.Delete(&price).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete price"})
return
}
@ -352,123 +322,140 @@ type PriceRate struct {
// GetPriceRates 获取价格倍率
func GetPriceRates(c *gin.Context) {
db := c.MustGet("db").(*sql.DB)
rows, err := db.Query(`
SELECT model, model_type, billing_type, channel_type,
CASE
WHEN currency = 'USD' THEN input_price / 2
ELSE input_price / 14
END as input_rate,
CASE
WHEN currency = 'USD' THEN output_price / 2
ELSE output_price / 14
END as output_rate
FROM price
WHERE status = 'approved'
ORDER BY model, channel_type`)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch price rates"})
var prices []models.Price
if err := database.DB.Where("status = 'approved'").Find(&prices).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch prices"})
return
}
defer rows.Close()
var rates []PriceRate
for rows.Next() {
var rate PriceRate
if err := rows.Scan(
&rate.Model,
&rate.ModelType,
&rate.Type,
&rate.ChannelType,
&rate.Input,
&rate.Output); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to scan price rate"})
return
// 按模型分组
modelMap := make(map[string]map[uint]models.Price)
for _, price := range prices {
if _, exists := modelMap[price.Model]; !exists {
modelMap[price.Model] = make(map[uint]models.Price)
}
modelMap[price.Model][price.ChannelType] = price
}
// 计算倍率
var rates []PriceRate
for model, providers := range modelMap {
// 找出基准价格通常是OpenAI的价格
var basePrice models.Price
var found bool
for _, price := range providers {
if price.ChannelType == 1 { // 假设OpenAI的ID是1
basePrice = price
found = true
break
}
}
if !found {
continue
}
// 计算其他厂商相对于基准价格的倍率
for channelType, price := range providers {
if channelType == 1 {
continue // 跳过基准价格
}
// 计算输入和输出的倍率
inputRate := 0.0
if basePrice.InputPrice > 0 {
inputRate = price.InputPrice / basePrice.InputPrice
}
outputRate := 0.0
if basePrice.OutputPrice > 0 {
outputRate = price.OutputPrice / basePrice.OutputPrice
}
rates = append(rates, PriceRate{
Model: model,
ModelType: price.ModelType,
Type: price.BillingType,
ChannelType: channelType,
Input: inputRate,
Output: outputRate,
})
}
rates = append(rates, rate)
}
c.JSON(http.StatusOK, rates)
}
// ApproveAllPrices 批量通过所有待审核的价格
func ApproveAllPrices(c *gin.Context) {
var input struct {
Status string `json:"status" binding:"required,eq=approved"`
}
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
// 查找所有待审核的价格
var pendingPrices []models.Price
if err := database.DB.Where("status = 'pending'").Find(&pendingPrices).Error; err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to fetch pending prices"})
return
}
db := c.MustGet("db").(*sql.DB)
now := time.Now()
// 开始事务
tx := database.DB.Begin()
// 获取当前用户
user, exists := c.Get("user")
if !exists {
c.JSON(http.StatusUnauthorized, gin.H{"error": "User not found"})
return
}
currentUser := user.(*models.User)
for _, price := range pendingPrices {
updateMap := map[string]interface{}{
"status": "approved",
"updated_at": time.Now(),
}
// 只有管理员可以批量通过
if currentUser.Role != "admin" {
c.JSON(http.StatusForbidden, gin.H{"error": "Admin permission required"})
return
// 如果临时字段有值,则更新主字段
if price.TempModel != nil {
updateMap["model"] = *price.TempModel
}
if price.TempModelType != nil {
updateMap["model_type"] = *price.TempModelType
}
if price.TempBillingType != nil {
updateMap["billing_type"] = *price.TempBillingType
}
if price.TempChannelType != nil {
updateMap["channel_type"] = *price.TempChannelType
}
if price.TempCurrency != nil {
updateMap["currency"] = *price.TempCurrency
}
if price.TempInputPrice != nil {
updateMap["input_price"] = *price.TempInputPrice
}
if price.TempOutputPrice != nil {
updateMap["output_price"] = *price.TempOutputPrice
}
if price.TempPriceSource != nil {
updateMap["price_source"] = *price.TempPriceSource
}
// 清除所有临时字段
updateMap["temp_model"] = nil
updateMap["temp_model_type"] = nil
updateMap["temp_billing_type"] = nil
updateMap["temp_channel_type"] = nil
updateMap["temp_currency"] = nil
updateMap["temp_input_price"] = nil
updateMap["temp_output_price"] = nil
updateMap["temp_price_source"] = nil
updateMap["updated_by"] = nil
if err := tx.Model(&price).Updates(updateMap).Error; err != nil {
tx.Rollback()
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to approve prices"})
return
}
}
// 查询待审核的价格数量
var pendingCount int
err := db.QueryRow("SELECT COUNT(*) FROM price WHERE status = 'pending'").Scan(&pendingCount)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to count pending prices"})
// 提交事务
if err := tx.Commit().Error; err != nil {
tx.Rollback()
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to commit transaction"})
return
}
if pendingCount == 0 {
c.JSON(http.StatusOK, gin.H{
"message": "No pending prices to approve",
"count": 0,
})
return
}
// 批量更新所有待审核的价格
result, err := db.Exec(`
UPDATE price
SET model = COALESCE(temp_model, model),
model_type = COALESCE(temp_model_type, model_type),
billing_type = COALESCE(temp_billing_type, billing_type),
channel_type = COALESCE(temp_channel_type, channel_type),
currency = COALESCE(temp_currency, currency),
input_price = COALESCE(temp_input_price, input_price),
output_price = COALESCE(temp_output_price, output_price),
price_source = COALESCE(temp_price_source, price_source),
status = ?,
updated_at = ?,
temp_model = NULL,
temp_model_type = NULL,
temp_billing_type = NULL,
temp_channel_type = NULL,
temp_currency = NULL,
temp_input_price = NULL,
temp_output_price = NULL,
temp_price_source = NULL,
updated_by = NULL
WHERE status = 'pending'`, input.Status, now)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to approve all prices"})
return
}
updatedCount, _ := result.RowsAffected()
c.JSON(http.StatusOK, gin.H{
"message": "All pending prices approved successfully",
"count": updatedCount,
"updated_at": now,
"message": "All pending prices approved successfully",
"count": len(pendingPrices),
})
}