Files
cmautobuy/admin/handler/web/ai_match.go
T

82 lines
2.6 KiB
Go

package web
import (
"context"
"errors"
"log"
"net/http"
"net/url"
"strings"
"time"
"github.com/gin-gonic/gin"
"cmautobuy/admin/service"
)
func (h *Handler) SybAIMatchCreate(c *gin.Context) {
actor := currentUser(c)
snapshot, err := service.LoadActiveAIMatchSnapshot(c.Request.Context(), h.db, h.aiSecrets, h.aiPolicy)
if err != nil {
h.sybRedirectAIMatchError(c, "AI 规格匹配未开始:"+err.Error())
return
}
batch, err := service.CreateAIMatchBatch(h.db, actor, c.PostFormArray("ids"), snapshot, time.Now())
if err != nil {
message := "AI 规格匹配批次未创建,数据没有被改动。"
if service.IsValidationError(err) {
message = "AI 规格匹配未开始:" + err.Error()
}
h.sybRedirectAIMatchError(c, message)
return
}
actorCopy := *actor
go func() {
if runErr := service.RunAIMatchBatch(context.Background(), h.db, actorCopy, batch.BatchID, snapshot); runErr != nil {
log.Printf("ai_match_batch_failed batch_id=%s error=%v", batch.BatchID, runErr)
if interruptErr := service.MarkAIMatchBatchInterrupted(h.db, batch.BatchID); interruptErr != nil {
log.Printf("ai_match_batch_interrupt_failed batch_id=%s error=%v", batch.BatchID, interruptErr)
}
}
}()
h.sybRedirectAIMatch(c, batch.BatchID, "AI 规格匹配已开始,可在进度窗口查看逐条结果")
}
// sybRedirectAIMatchError 使用独立参数返回列表,让页面明确弹出 AI 失败提示。
// 普通列表状态仍使用 msg,避免同步、采集等操作结果被误当成 AI 错误。
func (h *Handler) sybRedirectAIMatchError(c *gin.Context, message string) {
params := url.Values{}
appendSybFormState(params, c)
if message != "" {
params.Set("ai_error", strings.TrimSpace(message))
}
c.Redirect(http.StatusSeeOther, "/syb?"+params.Encode())
}
func (h *Handler) SybAIMatchStatus(c *gin.Context) {
view, err := service.GetAIMatchBatchView(h.db, currentUser(c), c.Param("batch_id"))
if errors.Is(err, service.ErrForbidden) {
c.JSON(http.StatusForbidden, gin.H{"error": "没有权限查看这个 AI 匹配批次"})
return
}
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "读取 AI 匹配进度失败,请稍后重试"})
return
}
if view == nil {
c.JSON(http.StatusNotFound, gin.H{"error": "AI 匹配批次不存在"})
return
}
c.JSON(http.StatusOK, view)
}
func (h *Handler) sybRedirectAIMatch(c *gin.Context, batchID, message string) {
params := url.Values{}
appendSybFormState(params, c)
params.Set("ai_batch_id", strings.TrimSpace(batchID))
if message != "" {
params.Set("msg", message)
}
c.Redirect(http.StatusSeeOther, "/syb?"+params.Encode())
}