From 54e0a5a0c46bd3ec50b1ae51639cf995914e0555 Mon Sep 17 00:00:00 2001 From: vipg Date: Fri, 14 Nov 2025 17:59:50 +0800 Subject: [PATCH] add --- .../futures_trade_record/src/logic/variety.go | 257 ------------------ .../src/logic/variety_create.go | 193 +++++++++++++ 2 files changed, 193 insertions(+), 257 deletions(-) delete mode 100644 backend/futures_trade_record/src/logic/variety.go create mode 100644 backend/futures_trade_record/src/logic/variety_create.go diff --git a/backend/futures_trade_record/src/logic/variety.go b/backend/futures_trade_record/src/logic/variety.go deleted file mode 100644 index 6581970..0000000 --- a/backend/futures_trade_record/src/logic/variety.go +++ /dev/null @@ -1,257 +0,0 @@ -package service - -import ( - "database/sql" - "futures_trade_record/db" - "futures_trade_record/logger" - "net/http" - "time" - - "github.com/gin-gonic/gin" - "github.com/google/uuid" - "go.uber.org/zap" -) - -// Variety 品种主表结构体 -type Variety struct { - ID string `json:"id"` - Deleted bool `json:"deleted"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` -} - -// VarietyName 品种名称子表结构体 -type VarietyName struct { - ID string `json:"id"` - VarietyID string `json:"variety_id"` - Name string `json:"name" binding:"required"` - Deleted bool `json:"deleted"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` -} - -// VarietyCode 品种代码子表结构体 -type VarietyCode struct { - ID string `json:"id"` - VarietyID string `json:"variety_id"` - Code string `json:"code" binding:"required"` - Deleted bool `json:"deleted"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` -} - -// VarietyTick 品种跳点子表结构体 -type VarietyTick struct { - ID string `json:"id"` - VarietyID string `json:"variety_id"` - Tick float64 `json:"tick"` - Deleted bool `json:"deleted"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` -} - -// VarietyTickPrice 品种跳点价格子表结构体 -type VarietyTickPrice struct { - ID string `json:"id"` - VarietyID string `json:"variety_id"` - Price float64 `json:"price"` - Deleted bool `json:"deleted"` - CreatedAt time.Time `json:"created_at"` - UpdatedAt time.Time `json:"updated_at"` -} - -// CreateVarietyRequest 创建品种请求参数 -type CreateVarietyRequest struct { - Name string `json:"name" binding:"required"` - Code string `json:"code" binding:"required"` - Tick float64 `json:"tick"` - TickPrice float64 `json:"tick_price"` -} - -// CreateVarietyHandler 创建品种接口处理函数 -func CreateVarietyHandler(c *gin.Context) { - var req CreateVarietyRequest - if err := c.ShouldBindJSON(&req); err != nil { - logger.ZapLogger.Error("请求参数绑定失败", zap.Error(err)) - c.JSON(http.StatusBadRequest, gin.H{ - "code": http.StatusBadRequest, - "message": "无效的请求参数: " + err.Error(), - }) - return - } - - // 生成主表ID - varietyID := uuid.New().String() - - // 开启数据库事务 - tx, err := db.DB.Begin() - if err != nil { - logger.ZapLogger.Error("开启事务失败", zap.Error(err)) - c.JSON(http.StatusInternalServerError, gin.H{ - "code": http.StatusInternalServerError, - "message": "服务器内部错误", - }) - return - } - defer func() { - if r := recover(); r != nil { - tx.Rollback() - } - }() - - // 插入主表 - now := time.Now() - _, err = tx.Exec(` - INSERT INTO variety (id, deleted, created_at, updated_at) - VALUES ($1, $2, $3, $4) - `, varietyID, false, now, now) - if err != nil { - tx.Rollback() - logger.ZapLogger.Error("插入品种主表失败", zap.Error(err)) - c.JSON(http.StatusInternalServerError, gin.H{ - "code": http.StatusInternalServerError, - "message": "创建品种失败", - }) - return - } - - // 插入名称子表 - _, err = tx.Exec(` - INSERT INTO variety_name (id, variety_id, name, deleted, created_at, updated_at) - VALUES ($1, $2, $3, $4, $5, $6) - `, uuid.New().String(), varietyID, req.Name, false, now, now) - if err != nil { - tx.Rollback() - logger.ZapLogger.Error("插入品种名称表失败", zap.Error(err)) - c.JSON(http.StatusInternalServerError, gin.H{ - "code": http.StatusInternalServerError, - "message": "创建品种失败", - }) - return - } - - // 插入代码子表 - _, err = tx.Exec(` - INSERT INTO variety_code (id, variety_id, code, deleted, created_at, updated_at) - VALUES ($1, $2, $3, $4, $5, $6) - `, uuid.New().String(), varietyID, req.Code, false, now, now) - if err != nil { - tx.Rollback() - logger.ZapLogger.Error("插入品种代码表失败", zap.Error(err)) - c.JSON(http.StatusInternalServerError, gin.H{ - "code": http.StatusInternalServerError, - "message": "创建品种失败", - }) - return - } - - // 插入跳点子表 - _, err = tx.Exec(` - INSERT INTO variety_tick (id, variety_id, tick, deleted, created_at, updated_at) - VALUES ($1, $2, $3, $4, $5, $6) - `, uuid.New().String(), varietyID, req.Tick, false, now, now) - if err != nil { - tx.Rollback() - logger.ZapLogger.Error("插入品种跳点表失败", zap.Error(err)) - c.JSON(http.StatusInternalServerError, gin.H{ - "code": http.StatusInternalServerError, - "message": "创建品种失败", - }) - return - } - - // 插入跳点价格子表 - _, err = tx.Exec(` - INSERT INTO variety_tick_price (id, variety_id, price, deleted, created_at, updated_at) - VALUES ($1, $2, $3, $4, $5, $6) - `, uuid.New().String(), varietyID, req.TickPrice, false, now, now) - if err != nil { - tx.Rollback() - logger.ZapLogger.Error("插入品种跳点价格表失败", zap.Error(err)) - c.JSON(http.StatusInternalServerError, gin.H{ - "code": http.StatusInternalServerError, - "message": "创建品种失败", - }) - return - } - - // 提交事务 - if err := tx.Commit(); err != nil { - tx.Rollback() - logger.ZapLogger.Error("提交事务失败", zap.Error(err)) - c.JSON(http.StatusInternalServerError, gin.H{ - "code": http.StatusInternalServerError, - "message": "创建品种失败", - }) - return - } - - c.JSON(http.StatusOK, gin.H{ - "code": http.StatusOK, - "message": "品种创建成功", - "data": gin.H{ - "variety_id": varietyID, - }, - }) -} - -// GetVarietyListHandler 获取品种列表接口 -func GetVarietyListHandler(c *gin.Context) { - rows, err := db.DB.Query(` - SELECT variety_id, name, code, tick, tick_price - FROM variety_info_view - ORDER BY variety_id DESC - `) - if err != nil { - logger.ZapLogger.Error("查询品种列表失败", zap.Error(err)) - c.JSON(http.StatusInternalServerError, gin.H{ - "code": http.StatusInternalServerError, - "message": "获取品种列表失败", - }) - return - } - defer rows.Close() - - var varieties []gin.H - for rows.Next() { - var ( - varietyID string - name sql.NullString - code sql.NullString - tick sql.NullFloat64 - price sql.NullFloat64 - ) - - if err := rows.Scan(&varietyID, &name, &code, &tick, &price); err != nil { - logger.ZapLogger.Error("扫描品种数据失败", zap.Error(err)) - c.JSON(http.StatusInternalServerError, gin.H{ - "code": http.StatusInternalServerError, - "message": "获取品种列表失败", - }) - return - } - - varieties = append(varieties, gin.H{ - "variety_id": varietyID, - "name": name.String, - "code": code.String, - "tick": tick.Float64, - "tick_price": price.Float64, - }) - } - - if err := rows.Err(); err != nil { - logger.ZapLogger.Error("行迭代错误", zap.Error(err)) - c.JSON(http.StatusInternalServerError, gin.H{ - "code": http.StatusInternalServerError, - "message": "获取品种列表失败", - }) - return - } - - c.JSON(http.StatusOK, gin.H{ - "code": http.StatusOK, - "message": "success", - "data": varieties, - }) -} \ No newline at end of file diff --git a/backend/futures_trade_record/src/logic/variety_create.go b/backend/futures_trade_record/src/logic/variety_create.go new file mode 100644 index 0000000..c8a6849 --- /dev/null +++ b/backend/futures_trade_record/src/logic/variety_create.go @@ -0,0 +1,193 @@ +package logic + +import ( + "net/http" + "futures_trade_record/db" // 数据库操作相关包 + "time" // 时间处理包 + "github.com/google/uuid" // UUID生成工具 + "github.com/gin-gonic/gin" // Gin框架,用于处理HTTP请求 + "go.uber.org/zap" // 日志库 +) + +// CreateVarietyRequest 注册请求参数结构 +// 用于接收客户端发送的JSON数据,绑定并验证必填字段 +type CreateVarietyRequest struct { + Name string `json:"name" binding:"required"` // 品种名称,必填 + Code string `json:"code" binding:"required"` // 品种代码,必填 +} + +// CreateVarietyResponse 注册响应结构 +// 统一的API响应格式,包含成功状态、提示信息和数据 +type CreateVarietyResponse struct { + Success bool `json:"success"` // 操作是否成功 + Message string `json:"message"` // 提示信息 + Data CreateData `json:"data"` // 响应数据 +} + +// CreateVarietyData 响应数据结构 +// 包含创建成功后的品种ID +type CreateVarietyData struct { + VarietyID string `json:"variety_id"` // 品种唯一标识ID +} + +// CreateVarietyHandler 处理品种创建逻辑 +// 接收HTTP请求,完成参数验证、数据库事务处理并返回响应 +func CreateVarietyHandler(c *gin.Context) { + startTime := time.Now() // 记录请求开始时间,用于统计耗时 + // 获取或生成请求ID,用于追踪整个请求链路 + reqID := c.Request.Header.Get("X-RegisterRequest-ID") + if reqID == "" { + reqID = uuid.New().String() + zap.L().Debug("✨ 生成新的请求ID", zap.String("req_id", reqID)) + } + + // 记录请求接收日志,包含关键追踪信息 + zap.L().Info("📥 收到品种创建请求", + zap.String("req_id", reqID), + zap.String("path", c.Request.URL.Path), + zap.String("method", c.Request.Method), + ) + + var req CreateRequest + // 绑定并验证请求参数(检查name和code是否存在) + if err := c.ShouldBindJSON(&req); err != nil { + zap.L().Warn("⚠️ 请求参数验证失败", + zap.String("req_id", reqID), + zap.Error(err), + zap.Any("request_body", c.Request.Body), + ) + // 返回参数错误响应 + c.JSON(http.StatusBadRequest, CreateResponse{ + Success: false, + Message: "请求参数错误:name和code为必填项", + }) + return + } + + // 记录通过验证的请求参数 + zap.L().Debug("✅ 请求参数验证通过", + zap.String("req_id", reqID), + zap.String("name", req.Name), + zap.String("code", req.Code), + ) + + // 开启数据库事务,确保多表操作原子性(要么全成功,要么全失败) + tx, err := db.DB.Begin() + if err != nil { + zap.L().Error("❌ 事务开启失败", + zap.String("req_id", reqID), + zap.Error(err), + ) + c.JSON(http.StatusInternalServerError, CreateResponse{ + Success: false, + Message: "系统错误,请稍后重试", + }) + return + } + // 延迟执行的恢复函数,处理panic情况 + defer func() { + if r := recover(); r != nil { // 捕获panic + // 回滚事务 + if err := tx.Rollback(); err != nil { + zap.L().Error("💥 panic后事务回滚失败", + zap.String("req_id", reqID), + zap.Error(err), + ) + } + zap.L().Error("💥 事务处理发生panic", + zap.String("req_id", reqID), + zap.Any("recover", r), + ) + // 返回系统错误响应 + c.JSON(http.StatusInternalServerError, CreateResponse{ + Success: false, + Message: "系统错误,请稍后重试", + }) + } + }() + + // 1. 在variety表中创建记录并获取自动生成的ID + var varietyID string + err = tx.QueryRow("INSERT INTO variety DEFAULT VALUES RETURNING id").Scan(&varietyID) + if err != nil { + tx.Rollback() // 操作失败,回滚事务 + zap.L().Error("❌ variety表插入失败", + zap.String("req_id", reqID), + zap.Error(err), + ) + c.JSON(http.StatusInternalServerError, CreateResponse{ + Success: false, + Message: "创建品种记录失败", + }) + return + } + + zap.L().Debug("📝 variety表插入成功", + zap.String("req_id", reqID), + zap.String("variety_id", varietyID), + ) + + // 2. 插入品种名称到name表(与variety_id关联) + _, err = tx.Exec("INSERT INTO name (variety_id, name) VALUES ($1, $2)", varietyID, req.Name) + if err != nil { + tx.Rollback() // 操作失败,回滚事务 + zap.L().Error("❌ name表插入失败", + zap.String("req_id", reqID), + zap.String("variety_id", varietyID), + zap.Error(err), + ) + c.JSON(http.StatusInternalServerError, CreateResponse{ + Success: false, + Message: "保存名称信息失败", + }) + return + } + + // 3. 插入品种代码到code表(与variety_id关联) + _, err = tx.Exec("INSERT INTO code (variety_id, code) VALUES ($1, $2)", varietyID, req.Code) + if err != nil { + tx.Rollback() // 操作失败,回滚事务 + zap.L().Error("❌ code表插入失败", + zap.String("req_id", reqID), + zap.String("variety_id", varietyID), + zap.Error(err), + ) + c.JSON(http.StatusInternalServerError, CreateResponse{ + Success: false, + Message: "保存代码信息失败", + }) + return + } + + // 提交事务(所有操作成功后确认提交) + if err := tx.Commit(); err != nil { + tx.Rollback() // 提交失败时尝试回滚 + zap.L().Error("❌ 事务提交失败", + zap.String("req_id", reqID), + zap.String("variety_id", varietyID), + zap.Error(err), + ) + c.JSON(http.StatusInternalServerError, CreateResponse{ + Success: false, + Message: "数据提交失败,请稍后重试", + }) + return + } + + // 记录请求处理耗时 + duration := time.Since(startTime) + zap.L().Info("✅ 品种创建请求处理完成", + zap.String("req_id", reqID), + zap.String("variety_id", varietyID), + zap.Duration("duration", duration), + ) + + // 返回成功响应,包含创建的品种ID + c.JSON(http.StatusOK, CreateResponse{ + Success: true, + Message: "创建成功", + Data: CreateData{ + VarietyID: varietyID, + }, + }) +} \ No newline at end of file