daShangDao_centerBook/erp/erp_api.go
2026-02-28 14:27:33 +08:00

90 lines
2.9 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package erp
import (
"crypto/rand"
"database/sql"
"fmt"
"github.com/gin-gonic/gin"
"math/big"
"net/http"
"time"
)
type InsertFilterSetRequest struct {
AddTxt string `json:"add_txt" binding:"required"`
}
type Response struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
// HandleInsertFilterSet 返回一个用于插入 ERP 过滤设置的处理器。
// 用途:解析请求体并将过滤设置写入 zhishu 数据库,返回插入结果。
// 参数:
// - db: zhishu 数据库连接(必需)
// 行为:
// 1) 校验参数2) 执行插入3) 返回插入的记录 ID。
func HandleInsertFilterSet(db *sql.DB) gin.HandlerFunc {
return func(c *gin.Context) {
var req InsertFilterSetRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, Response{Code: 500, Msg: "请求参数错误: " + err.Error(), Data: nil})
return
}
if db == nil {
c.JSON(http.StatusInternalServerError, Response{Code: 500, Msg: "ERP数据库未初始化", Data: nil})
return
}
id, err := insertFilterSet(db, req.AddTxt)
if err != nil {
c.JSON(http.StatusInternalServerError, Response{Code: 500, Msg: "插入失败: " + err.Error(), Data: nil})
return
}
c.JSON(http.StatusOK, Response{Code: 200, Msg: "插入成功", Data: map[string]interface{}{"id": id}})
}
}
// insertFilterSet 将过滤设置写入 ERP (zhishu) 数据库。
// 参数 db 为 zhishu 数据库连接bookName 为过滤项内容。
// 返回值:新记录的主键 ID若失败返回错误。
func insertFilterSet(db *sql.DB, bookName string) (int64, error) {
if db == nil {
return 0, fmt.Errorf("Zhishu数据库未初始化")
}
id := generateRandom19DigitID() // 随机 19 位数字
stmt := "INSERT INTO t_filter_set (id, filter_type, limitation_type, add_way, add_txt, sort, create_time) VALUES (?, ?, ?, ?, ?, ?, ?)"
_, err := db.Exec(stmt, id, "1", "1", "0", bookName, "1", time.Now())
if err != nil {
return 0, err
}
return id, nil
}
// 生成 19 位随机数字 ID
// 生成 19 位随机数字 ID不会溢出
func generateRandom19DigitID() int64 {
min, _ := new(big.Int).SetString("1000000000000000000", 10) // 10^18
max, _ := new(big.Int).SetString("9999999999999999999", 10) // 10^19 - 1
diff := new(big.Int).Sub(max, min)
n, err := rand.Int(rand.Reader, diff)
if err != nil {
// 如果随机生成失败,则使用时间戳作为回退
return time.Now().UnixNano()
}
return new(big.Int).Add(n, min).Int64()
}
// RegisterERPRoutes 注册 ERP 相关的路由到 Gin 引擎。
// 用途:集中管理 ERP 接口的路由挂载,避免在 main.go 中分散注册。
// 参数:
// - r: Gin 引擎实例
// - db: zhishu 数据库连接
// 当前注册:插入过滤设置接口,可在此处继续扩展其他 ERP 路由。
func RegisterERPRoutes(r *gin.Engine, db *sql.DB) {
r.POST("/api/erp/insertFilterSet", HandleInsertFilterSet(db))
}