修复:完善上传契约与自动化闭环

统一 multipart 请求透传并补齐接口契约和边界校验;新增 AI 自动改价、暂时性失败重试、擦亮与确认发货幂等处理;修复聊天已读回执跨端同步误报警,并更新前端静态资源与回归测试。
This commit is contained in:
Christ committed 2026-08-20 19:03:29 +08:00
1 parent 44f0b5c559
commit 50eca2fca6
77 files changed
+2138 -274

No files matched your search

+69 -7
View File
@@ -87,7 +87,7 @@ func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult,
// systemPrompt 用于本次流程后续判断的系统Prompt
systemPrompt := buildSystemPrompt(
cfg.CustomPrompts, itemTitle, itemPrice, itemDesc,
cfg.MaxDiscountPercent, cfg.MaxDiscountAmount, cfg.MaxBargainRounds, bargainCount,
cfg.MaxDiscountPercent, cfg.MaxDiscountAmount, cfg.MaxBargainRounds, bargainCount, cfg.AutoAdjustPriceEnabled,
)
if !withinBargainLimit {
systemPrompt += "\n当前买家已经超过最大砍价轮次。不得继续降价,只能礼貌说明价格不再优惠。"
@@ -134,20 +134,32 @@ func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult,
return nil, nil
}
// reply 用于本次流程后续判断的回复
reply := strings.TrimSpace(resp.Choices[0].Message.Content)
reply, markerPrice, markerOK := extractExecutableOffer(strings.TrimSpace(resp.Choices[0].Message.Content))
if reply == "" {
return nil, nil
}
// minimumPrice 用于本次流程后续判断的minimumPrice
minimumPrice := minimumAllowedPrice(itemPrice, cfg.MaxDiscountPercent, cfg.MaxDiscountAmount, withinBargainLimit)
// quote 是仅在商家开启真实改价且模型结构化报价通过校验时返回的执行提案。
var quote *AIPriceQuoteProposal
// markerUnsafe 表示结构化报价突破最低价或高于商品标价,必须和正文越界同样拦截。
markerUnsafe := markerOK && (markerPrice+0.0001 < minimumPrice || markerPrice > itemPrice+0.0001)
if // offered、unsafe 用于本次流程后续判断的offered、unsafe
offered, unsafe := unsafeOfferedPrice(reply, minimumPrice); unsafe {
offered, unsafe := unsafeOfferedPrice(reply, minimumPrice); unsafe || markerUnsafe {
if markerUnsafe {
offered = markerPrice
}
a.logger.Warn("AI 报价超过折扣边界,使用安全回复", "offered", offered, "minimum", minimumPrice)
if minimumPrice >= itemPrice || !withinBargainLimit {
reply = "抱歉,当前价格已经是最低价,暂时不能再优惠了。"
} else {
reply = fmt.Sprintf("可以优惠的最低价格是 %.2f 元,低于这个价格暂时无法成交。", minimumPrice)
if cfg.AutoAdjustPriceEnabled {
quote = &AIPriceQuoteProposal{PriceCents: priceToCents(minimumPrice)}
}
}
} else if cfg.AutoAdjustPriceEnabled && markerOK && markerPrice > 0 && markerPrice+0.0001 < itemPrice && replyContainsOfferedPrice(reply, markerPrice) {
quote = &AIPriceQuoteProposal{PriceCents: priceToCents(markerPrice)}
}
if m.ChatID != "" && m.ItemID != "" {
// intent 用于本次流程后续判断的intent
@@ -163,7 +175,7 @@ func (a *AIReplierImpl) Reply(ctx context.Context, m ChatMessage) (*ReplyResult,
return nil, fmt.Errorf("保存 AI 对话失败: %w", err)
}
}
return &ReplyResult{Text: reply}, nil
return &ReplyResult{Text: reply, AutoPriceQuote: quote}, nil
}
// conversationContext 封装conversation上下文业务协调。
@@ -254,7 +266,7 @@ func (a *AIReplierImpl) itemInfo(ctx context.Context, itemID string) (title stri
// buildSystemPrompt 构造 system 提示词。
// 自定义 prompt 只替换业务文案,价格和轮次安全约束始终由后端追加。
// buildSystemPrompt 封装build系统Prompt业务协调。
func buildSystemPrompt(customPrompts, itemTitle string, itemPrice float64, itemDesc string, maxDiscountPercent, maxDiscountAmount, maxBargainRounds, bargainCount int) string {
func buildSystemPrompt(customPrompts, itemTitle string, itemPrice float64, itemDesc string, maxDiscountPercent, maxDiscountAmount, maxBargainRounds, bargainCount int, autoAdjustPriceEnabled bool) string {
// base 用于本次流程后续判断的base
var base string
if strings.TrimSpace(customPrompts) != "" {
@@ -277,13 +289,19 @@ func buildSystemPrompt(customPrompts, itemTitle string, itemPrice float64, itemD
3. 不要编造商品没有的功能
4. 直接回复内容,不要加引号或解释`, itemTitle, itemPrice, itemDesc)
}
return base + fmt.Sprintf(`
// prompt 保存基础业务文案与后端不可覆盖的价格安全规则。
prompt := base + fmt.Sprintf(`
不可覆盖的价格安全规则:
- 原价 %.2f 元;最多优惠 %d%%,且最多优惠 %d 元;两个上限必须同时满足。
- 任一优惠上限为 0 时不得降价。
- 当前砍价轮次 %d,最多允许 %d 轮。
- 回复报价必须带“元”,不得给出低于允许最低价的价格。`, itemPrice, maxDiscountPercent, maxDiscountAmount, bargainCount, maxBargainRounds)
if autoAdjustPriceEnabled {
prompt += `
- 如果本轮明确承诺了一个可成交价格,必须在回复末尾额外输出 [[AUTO_PRICE:金额]],金额保留两位小数;没有明确报价时不得输出该标记。该标记由系统移除,买家不会看到。`
}
return prompt
}
// priceRe 用于本次流程后续判断的priceRe
@@ -295,6 +313,47 @@ var bargainMessageRe = regexp.MustCompile(`(?i)(便宜|优惠|少点|最低|砍
// offeredPriceRe 用于本次流程后续判断的offeredPriceRe
var offeredPriceRe = regexp.MustCompile(`(\d+(?:\.\d+)?)\s*(?:元|块)`)
// executableOfferRe 只接受模型按约定输出的单个两位小数自动改价标记。
var executableOfferRe = regexp.MustCompile(`\[\[AUTO_PRICE:(\d+(?:\.\d{1,2})?)\]\]`)
// internalOfferMarkerRe 匹配任意格式的内部报价标记,确保模型格式错误时也不会泄露给买家。
var internalOfferMarkerRe = regexp.MustCompile(`\[\[AUTO_PRICE:[^\]]*\]\]`)
// extractExecutableOffer 从模型输出移除内部报价标记,并返回可校验的十进制金额。
func extractExecutableOffer(content string) (string, float64, bool) {
// matches 是模型输出中所有结构化报价标记;只有恰好一个标记才可执行。
matches := executableOfferRe.FindAllStringSubmatch(content, -1)
// visible 是删除所有内部标记后真正发送给买家的文本。
visible := strings.TrimSpace(internalOfferMarkerRe.ReplaceAllString(content, ""))
if len(matches) != 1 {
return visible, 0, false
}
// price 是标记中的元金额;err 表示模型输出无法解析为有限十进制数。
price, err := strconv.ParseFloat(matches[0][1], 64)
if err != nil || math.IsNaN(price) || math.IsInf(price, 0) {
return visible, 0, false
}
return visible, price, true
}
// priceToCents 把已经通过边界校验的元金额四舍五入为整数分。
func priceToCents(price float64) int64 {
return int64(math.Round(price * 100))
}
// replyContainsOfferedPrice 判断内部执行价格是否与买家可见正文中的元/块报价一致。
func replyContainsOfferedPrice(reply string, target float64) bool {
// match 是正文中当前待比较的显式价格匹配结果。
for _, match := range offeredPriceRe.FindAllStringSubmatch(reply, -1) {
// price 是买家可见的报价金额;err 表示该匹配无法解析为数值。
price, err := strconv.ParseFloat(match[1], 64)
if err == nil && math.Abs(price-target) < 0.0001 {
return true
}
}
return false
}
// minimumAllowedPrice 封装minimumAllowedPrice业务协调。
func minimumAllowedPrice(price float64, maxDiscountPercent, maxDiscountAmount int, allowDiscount bool) float64 {
if price <= 0 {
@@ -307,7 +366,10 @@ func minimumAllowedPrice(price float64, maxDiscountPercent, maxDiscountAmount in
byPercent := price * (1 - float64(maxDiscountPercent)/100)
// byAmount 用于本次流程后续判断的byAmount
byAmount := price - float64(maxDiscountAmount)
return math.Max(0, math.Max(byPercent, byAmount))
// minimum 是两个折扣边界中更严格的原始最低价。
minimum := math.Max(0, math.Max(byPercent, byAmount))
// 金额向上取整到分,避免显示或执行价格因普通四舍五入突破折扣上限。
return math.Ceil(minimum*100-0.0000001) / 100
}
// unsafeOfferedPrice 封装unsafeOfferedPrice业务协调。
+72 -3
View File
@@ -15,7 +15,7 @@ import (
// TestBuildSystemPrompt 自定义 prompt 替换变量,且始终追加价格与轮次安全约束。
func TestBuildSystemPrompt(t *testing.T) {
// got 用于本次流程后续判断的got
got := buildSystemPrompt("你是卖{item_title}的客服,价格{item_price}", "iPhone", 100, "手机", 0, 0, 3, 1)
got := buildSystemPrompt("你是卖{item_title}的客服,价格{item_price}", "iPhone", 100, "手机", 0, 0, 3, 1, false)
if !strings.Contains(got, "你是卖iPhone的客服,价格100.00") {
t.Fatalf("自定义 prompt 替换: got %q", got)
}
@@ -24,7 +24,7 @@ func TestBuildSystemPrompt(t *testing.T) {
}
// 0 必须保留为不允许优惠,不能静默改成默认值。
got = buildSystemPrompt("", "会员卡", 9.9, "月卡", 0, 0, 3, 0)
got = buildSystemPrompt("", "会员卡", 9.9, "月卡", 0, 0, 3, 0, false)
if !strings.Contains(got, "标题:会员卡") || !strings.Contains(got, "价格:9.90 元") {
t.Fatalf("默认模板缺商品信息: %q", got)
}
@@ -33,10 +33,37 @@ func TestBuildSystemPrompt(t *testing.T) {
}
// 显式折扣上限。
got = buildSystemPrompt("", "会员卡", 9.9, "月卡", 20, 50, 4, 2)
got = buildSystemPrompt("", "会员卡", 9.9, "月卡", 20, 50, 4, 2, true)
if !strings.Contains(got, "最多优惠 20%") || !strings.Contains(got, "最多优惠 50 元") {
t.Fatalf("显式折扣上限: %q", got)
}
if !strings.Contains(got, "[[AUTO_PRICE:金额]]") {
t.Fatalf("开启自动改价时缺少结构化报价约束: %q", got)
}
}
// TestExtractExecutableOffer 验证内部报价标记不会发送给买家,且重复或非法标记不可执行。
func TestExtractExecutableOffer(t *testing.T) {
// visible、price、ok 分别是买家可见文本、解析金额和可执行标记状态。
visible, price, ok := extractExecutableOffer("可以,90 元成交。 [[AUTO_PRICE:90.00]]")
if !ok || price != 90 || visible != "可以,90 元成交。" {
t.Fatalf("结构化报价解析异常: visible=%q price=%v ok=%v", visible, price, ok)
}
// visible、price、ok 复用以验证重复标记会被全部隐藏但不会执行。
visible, price, ok = extractExecutableOffer("90 元可以 [[AUTO_PRICE:90.00]] [[AUTO_PRICE:89.00]]")
if ok || price != 0 || strings.Contains(visible, "AUTO_PRICE") {
t.Fatalf("重复报价标记必须拒绝执行: visible=%q price=%v ok=%v", visible, price, ok)
}
}
// TestReplyContainsOfferedPrice 验证隐藏执行价格必须与买家正文中看到的明确报价一致。
func TestReplyContainsOfferedPrice(t *testing.T) {
if !replyContainsOfferedPrice("可以,90.00 元成交", 90) {
t.Fatal("相同的正文报价和执行价格应允许")
}
if replyContainsOfferedPrice("可以,95 元成交", 90) {
t.Fatal("隐藏执行价格与正文不一致时必须拒绝自动改价")
}
}
// TestMinimumAllowedPriceAndUnsafeOffer 封装TestMinimumAllowedPriceAndUnsafeOffer业务协调。
@@ -49,6 +76,10 @@ func TestMinimumAllowedPriceAndUnsafeOffer(t *testing.T) {
got := minimumAllowedPrice(100, 0, 20, true); got != 100 {
t.Fatalf("zero percent minimum=%v want 100", got)
}
if // got 用于本次流程后续判断的got
got := minimumAllowedPrice(99.99, 15, 100, true); got != 85 {
t.Fatalf("最低价必须向上取整到分: got=%v want 85", got)
}
if // unsafe 用于本次流程后续判断的unsafe
_, unsafe := unsafeOfferedPrice("最低可以 89 元", 90); !unsafe {
t.Fatal("低于最低价的报价应被拦截")
@@ -227,6 +258,44 @@ func TestAIReply_SuccessReturnsContent(t *testing.T) {
}
}
// TestAIReplyBuildsExecutableQuote 验证自动改价开启时只返回通过边界校验且已从正文移除标记的报价。
func TestAIReplyBuildsExecutableQuote(t *testing.T) {
// store、cleanup 是 AI 报价测试仓储及清理函数。
store, cleanup := newAIStore(t)
defer cleanup()
// ctx 是模型调用和本地商品读取共用的测试上下文。
ctx := context.Background()
// server 返回包含买家可见价格和内部自动改价标记的模型响应。
server := mockOpenAIServer(t, 0, "可以,90.00 元成交。 [[AUTO_PRICE:90.00]]")
// err 是保存 AI 自动改价测试设置时不应出现的数据库错误。
if _, err := store.DB.ExecContext(ctx, `INSERT INTO ai_reply_settings
(cookie_id,ai_enabled,auto_adjust_price_enabled,max_discount_percent,max_discount_amount,max_bargain_rounds,custom_prompts)
VALUES ('cid',1,1,10,20,3,'')`); err != nil {
t.Fatal(err)
}
// err 是保存带原价商品时不应出现的数据库错误。
if _, err := store.DB.ExecContext(ctx, `INSERT INTO item_info
(cookie_id,item_id,item_title,item_price,item_description) VALUES ('cid','item-quote','商品','100','描述')`); err != nil {
t.Fatal(err)
}
// err 是保存模型测试密钥时不应出现的错误。
if err := store.Settings.Set(ctx, "ai_api_key", "sk-test"); err != nil {
t.Fatal(err)
}
// err 是保存本地模型服务地址时不应出现的错误。
if err := store.Settings.Set(ctx, "ai_api_url", server.URL); err != nil {
t.Fatal(err)
}
// result 是通过价格边界校验后的 AI 回复与可执行报价。
result, err := NewAIReplier("cid", store, nil).Reply(ctx, chatMsg("能便宜点吗", "item-quote", "chat-quote"))
if err != nil || result == nil || result.AutoPriceQuote == nil || result.AutoPriceQuote.PriceCents != 9000 {
t.Fatalf("AI 可执行报价异常: result=%+v err=%v", result, err)
}
if strings.Contains(result.Text, "AUTO_PRICE") || result.Text != "可以,90.00 元成交。" {
t.Fatalf("内部报价标记不应发送给买家: %q", result.Text)
}
}
// TestAIReply_NonBargainMessageFallsThrough 封装TestAI回复NonBargain消息FallsThrough业务协调。
func TestAIReply_NonBargainMessageFallsThrough(t *testing.T) {
// s、cleanup 用于本次流程后续判断的s、cleanup
+22
View File
@@ -11,6 +11,7 @@ import (
"fmt"
"log/slog"
"strings"
"time"
"xianyu-go/internal/db"
)
@@ -22,8 +23,19 @@ type ReplyResult struct {
Source string // 回复来源:API/关键词/AI/默认
Skip bool // true 表示匹配到空回复,不发送任何内容
ReplyOnce bool // 仅默认回复使用,发送状态由 Handle 持久化
// AutoPriceQuote 是 AI 已明确承诺且通过价格边界校验的可执行报价。
AutoPriceQuote *AIPriceQuoteProposal
}
// AIPriceQuoteProposal 是等待回复发送成功后绑定到会话的 AI 报价。
type AIPriceQuoteProposal struct {
// PriceCents 是以分为单位的单件成交报价;订单执行时按已知购买数量折算总价。
PriceCents int64
}
// aiQuoteValidity 是 AI 报价从成功发送开始允许自动应用到新订单的时长。
const aiQuoteValidity = 30 * time.Minute
// APIReplier 外部 API 回复(优先级1)。返回 nil 表示无回复。
type APIReplier interface {
Reply(ctx context.Context, m ChatMessage) (*ReplyResult, error)
@@ -124,6 +136,16 @@ func (r *ReplyService) Handle(ctx context.Context, m ChatMessage) error {
return err
}
}
if res.Source == "AI" && res.AutoPriceQuote != nil && m.ChatID != "" && m.SenderUserID != "" && m.ItemID != "" {
// quote 把模型承诺价格绑定到当前账号、买家、商品和已成功发送的会话。
quote := db.AIBargainQuote{CookieID: r.cookieID, ChatID: m.ChatID, BuyerID: m.SenderUserID, ItemID: m.ItemID, PriceCents: res.AutoPriceQuote.PriceCents}
// expiresAt 是固定 30 分钟报价有效期的 Unix 秒时间。
expiresAt := time.Now().UTC().Add(aiQuoteValidity).Unix()
// err 是已发送报价写入失败原因,失败时必须阻止静默丢失自动改价承诺。
if err := r.store.AIReply.ReplacePendingQuote(ctx, quote, expiresAt); err != nil {
return fmt.Errorf("保存已发送的 AI 自动改价报价: %w", err)
}
}
}
if res.ReplyOnce && m.ChatID != "" {
if // err 用于本次流程后续判断的err
+35
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"testing"
"time"
"xianyu-go/internal/db"
)
@@ -71,6 +72,40 @@ func (r *recordingSender) SendImage(_ context.Context, chatID, toUserID, url str
return nil
}
// TestAIQuoteSavedOnlyAfterTextDelivery 验证 AI 报价只有在回复发送成功后才成为可执行报价。
func TestAIQuoteSavedOnlyAfterTextDelivery(t *testing.T) {
// store、cleanup 是回复链测试仓储及清理函数。
store, cleanup := newReplyStore(t)
defer cleanup()
// ctx 是回复发送与报价领取共用的测试上下文。
ctx := context.Background()
// result 是模拟 AI 已给出 9.90 元有效报价的回复结果。
result := &ReplyResult{Text: "可以,9.90 元成交", AutoPriceQuote: &AIPriceQuoteProposal{PriceCents: 990}}
// failedSender 模拟文本没有成功交给买家。
failedSender := &recordingSender{textErr: errors.New("send failed")}
// failedService 是注入发送失败替身的 AI 回复链。
failedService := NewReplyService("cid", store, failedSender, nil, &fakeAIReplier{result: result}, nil)
// err 是模拟发送失败时必须向调用方返回的错误。
if err := failedService.Handle(ctx, chatMsg("能便宜吗", "item-1", "chat-1")); err == nil {
t.Fatal("发送失败应返回错误")
}
// failedQuote 是发送失败后尝试领取的报价,必须为空。
failedQuote, err := store.AIReply.ClaimPendingQuote(ctx, "cid", "chat-1", "buyer1", "item-1", "order-failed", time.Now().Unix())
if err != nil || failedQuote != nil {
t.Fatalf("发送失败不应保存报价: quote=%+v err=%v", failedQuote, err)
}
// successService 是文本发送成功的 AI 回复链。
successService := NewReplyService("cid", store, &recordingSender{}, nil, &fakeAIReplier{result: result}, nil)
if err = successService.Handle(ctx, chatMsg("能便宜吗", "item-1", "chat-1")); err != nil {
t.Fatal(err)
}
// successQuote 是发送成功后与订单事实匹配的可执行报价。
successQuote, err := store.AIReply.ClaimPendingQuote(ctx, "cid", "chat-1", "buyer1", "item-1", "order-success", time.Now().Unix())
if err != nil || successQuote == nil || successQuote.PriceCents != 990 {
t.Fatalf("发送成功应保存报价: quote=%+v err=%v", successQuote, err)
}
}
// TestReplyOnceRetriesOnlyFailedParts 封装Test回复OnceRetriesOnly失败Parts业务协调。
func TestReplyOnceRetriesOnlyFailedParts(t *testing.T) {
// s、cleanup 用于本次流程后续判断的s、cleanup