- 同步商品与订单时处理线上删除状态并联动自动化规则\n- 过滤卖家系统中的购买订单,修复订单逻辑删除与数据库迁移\n- 修复聊天新消息自动滚动,并统一前端颜色令牌与硬编码颜色检查
648 lines
26 KiB
Go
648 lines
26 KiB
Go
package server
|
||
|
||
import (
|
||
"context"
|
||
"encoding/json"
|
||
"fmt"
|
||
"io"
|
||
"net/http"
|
||
"net/http/httptest"
|
||
"strings"
|
||
"testing"
|
||
)
|
||
|
||
// TestRefreshOrdersNoBrowser 浏览器未启用时仍应完成订单列表发现。
|
||
func TestRefreshOrdersNoBrowser(t *testing.T) {
|
||
srv, _, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
|
||
req := httptest.NewRequest(http.MethodPost, "/api/orders/refresh", strings.NewReader(""))
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "订单列表同步完成") {
|
||
t.Fatalf("无浏览器仍应同步列表,got %d body=%s", rec.Code, rec.Body.String())
|
||
}
|
||
}
|
||
|
||
func TestRefreshOrdersDiscoversNewOrdersWithoutBrowser(t *testing.T) {
|
||
srv, store, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||
if strings.Contains(req.URL.Query().Get("api"), "order.detail") {
|
||
body := `{"ret":["SUCCESS::调用成功"],"data":{"utArgs":{"orderStatus":"待发货"},"components":[{"render":"orderInfoVO","data":{"itemInfo":{"buyAmount":"2"},"priceInfo":{"amount":{"value":"19.90"}}}}]}}`
|
||
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
|
||
}
|
||
body := `{"ret":["SUCCESS::调用成功"],"data":{"module":{"nextPage":"false","totalCount":"1","items":[{` +
|
||
`"commonData":{"orderId":"sold-new-1","itemId":"item-new","orderStatus":"待发货","inRefund":"false"},` +
|
||
`"buyerInfoVO":{"buyerId":"buyer-1","name":"张三","phone":"13800000000","address":"上海市"},` +
|
||
`"priceVO":{"totalPrice":"19.90","buyNum":"2"},` +
|
||
`"rightVO":{"btnList":[{"tradeAction":"SKIP_PIN"}]}}]}}}`
|
||
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
|
||
}))
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
req := httptest.NewRequest(http.MethodPost, "/api/orders/refresh", nil)
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"discovered":1`) {
|
||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||
}
|
||
order, err := store.Orders.Get(context.Background(), "sold-new-1")
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if order.CookieID != "acc1" || order.ItemID != "item-new" || order.OrderStatus != "pending_ship" ||
|
||
order.Amount != "19.90" || order.Quantity != "2" || order.IsBargain != 1 || order.ReceiverName != "张三" {
|
||
t.Fatalf("discovered order=%+v", order)
|
||
}
|
||
}
|
||
|
||
func TestRefreshOrdersSoftDeletesOrdersMissingFromSellerList(t *testing.T) {
|
||
srv, store, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
ctx := context.Background()
|
||
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,item_id,buyer_id,cookie_id,order_status) VALUES ('buyer-order','buy-item','seller-account','acc1','pending_ship')`)
|
||
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||
if strings.Contains(req.URL.Query().Get("api"), "order.detail") {
|
||
body := `{"ret":["SUCCESS::调用成功"],"data":{"utArgs":{"orderStatus":"待发货"},"components":[{"render":"orderInfoVO","data":{"itemInfo":{"buyAmount":"1"},"priceInfo":{"amount":{"value":"10.00"}}}}]}}`
|
||
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
|
||
}
|
||
body := `{"ret":["SUCCESS::调用成功"],"data":{"module":{"nextPage":"false","totalCount":"1","items":[{` +
|
||
`"commonData":{"orderId":"seller-order","itemId":"seller-item","orderStatus":"待发货"},` +
|
||
`"buyerInfoVO":{"buyerId":"buyer-1"},"priceVO":{"totalPrice":"10.00","buyNum":"1"}}]}}}`
|
||
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
|
||
}))
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
req := httptest.NewRequest(http.MethodPost, "/api/orders/refresh", nil)
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"soft_deleted":1`) {
|
||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||
}
|
||
var deletedAt string
|
||
if err := store.DB.QueryRowContext(ctx, `SELECT COALESCE(deleted_at,'') FROM orders WHERE order_id=?`, "buyer-order").Scan(&deletedAt); err != nil || deletedAt == "" {
|
||
t.Fatalf("缺失订单应逻辑删除,deleted_at=%q err=%v", deletedAt, err)
|
||
}
|
||
if _, err := store.Orders.Get(ctx, "buyer-order"); err == nil {
|
||
t.Fatal("逻辑删除的购买订单不应再出现在活动订单查询中")
|
||
}
|
||
}
|
||
|
||
func TestMissingRefreshResultsAreCounted(t *testing.T) {
|
||
targets := []refreshTarget{{OrderID: "a"}, {OrderID: "b"}, {OrderID: "c"}}
|
||
missing := missingRefreshTargetIDs(targets, map[string]struct{}{"b": {}})
|
||
if len(missing) != 2 || missing[0] != "a" || missing[1] != "c" {
|
||
t.Fatalf("missing=%v", missing)
|
||
}
|
||
}
|
||
|
||
// TestRefreshSingleOrderUsesGoMTop 单订单刷新不依赖浏览器。
|
||
func TestRefreshSingleOrderUsesGoMTop(t *testing.T) {
|
||
srv, store, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
srv.MTop = withMTopTransport(roundTripFunc(func(req *http.Request) (*http.Response, error) {
|
||
body := `{"ret":["SUCCESS::调用成功"],"data":{"utArgs":{"orderStatus":"待发货"},"components":[{"render":"orderInfoVO","data":{"itemInfo":{"buyAmount":"2","specName":"套餐","specValue":"30天"},"priceInfo":{"amount":{"value":"19.90"}}}}]}}`
|
||
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: req}, nil
|
||
}))
|
||
ctx := context.Background()
|
||
store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, cookie_id, order_status) VALUES ('ord-x','item1','acc1','2')`)
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
|
||
req := httptest.NewRequest(http.MethodPost, "/api/orders/ord-x/refresh", nil)
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != http.StatusOK {
|
||
t.Fatalf("Go MTOP 刷新应成功,got %d body=%s", rec.Code, rec.Body.String())
|
||
}
|
||
}
|
||
|
||
// TestRefreshSingleOrderNotFound 单订单刷新不存在订单 404。
|
||
func TestRefreshSingleOrderNotFound(t *testing.T) {
|
||
srv, _, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
// 注入非 nil Browser 但内部 playwright 不可用,订单查询先行 404。
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
|
||
req := httptest.NewRequest(http.MethodPost, "/api/orders/no-such/refresh", nil)
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
// Browser==nil → 503;先校验此路径不 panic。
|
||
if rec.Code != http.StatusServiceUnavailable && rec.Code != http.StatusNotFound {
|
||
t.Fatalf("expected 503/404, got %d body=%s", rec.Code, rec.Body.String())
|
||
}
|
||
}
|
||
|
||
// TestUpdateOrder 更新订单字段(status 归一)。
|
||
func TestUpdateOrder(t *testing.T) {
|
||
srv, store, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
ctx := context.Background()
|
||
store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, buyer_id, order_status, cookie_id) VALUES ('ord-u','item1','b1','2','acc1')`)
|
||
store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id,item_id,item_title) VALUES ('acc1','item1','旧标题')`)
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
|
||
body := `{"status":"shipped","receiver_name":"张三","receiver_phone":"13800000000","receiver_address":"北京","item_title":"新标题"}`
|
||
req := httptest.NewRequest(http.MethodPut, "/api/orders/ord-u", strings.NewReader(body))
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != 200 {
|
||
t.Fatalf("update status=%d body=%s", rec.Code, rec.Body.String())
|
||
}
|
||
|
||
// 验证已写入。
|
||
req2 := httptest.NewRequest(http.MethodGet, "/api/orders/ord-u", nil)
|
||
req2.AddCookie(cookie)
|
||
rec2 := httptest.NewRecorder()
|
||
h.ServeHTTP(rec2, req2)
|
||
var got map[string]any
|
||
json.Unmarshal(rec2.Body.Bytes(), &got)
|
||
if got["order_status"] != "shipped" || got["receiver_name"] != "张三" {
|
||
t.Fatalf("更新未生效: %+v", got)
|
||
}
|
||
item, err := store.Items.Get(ctx, "acc1", "item1")
|
||
if err != nil || item.ItemTitle != "新标题" {
|
||
t.Fatalf("商品标题未保存: item=%+v err=%v", item, err)
|
||
}
|
||
}
|
||
|
||
func TestUpdateOrderUsesNewItemIDForTitle(t *testing.T) {
|
||
srv, store, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
ctx := context.Background()
|
||
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,item_id,order_status,cookie_id) VALUES ('ord-new-item','old-item','2','acc1')`)
|
||
_, _ = store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id,item_id,item_title) VALUES ('acc1','old-item','旧商品')`)
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
req := httptest.NewRequest(http.MethodPut, "/api/orders/ord-new-item", strings.NewReader(`{"item_id":" new-item ","item_title":"新商品"}`))
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != http.StatusOK {
|
||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||
}
|
||
order, _ := store.Orders.Get(ctx, "ord-new-item")
|
||
if order.ItemID != "new-item" {
|
||
t.Fatalf("order item_id=%q", order.ItemID)
|
||
}
|
||
newItem, err := store.Items.Get(ctx, "acc1", "new-item")
|
||
if err != nil || newItem.ItemTitle != "新商品" {
|
||
t.Fatalf("new item=%+v err=%v", newItem, err)
|
||
}
|
||
oldItem, _ := store.Items.Get(ctx, "acc1", "old-item")
|
||
if oldItem.ItemTitle != "旧商品" {
|
||
t.Fatalf("old item title changed: %+v", oldItem)
|
||
}
|
||
}
|
||
|
||
func TestImportOrdersRejectsInvalidAmountWithoutWritingOrder(t *testing.T) {
|
||
srv, store, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
req := httptest.NewRequest(http.MethodPost, "/api/orders/import", strings.NewReader(
|
||
`[{"order_id":"bad-import-amount","cookie_id":"acc1","amount":"1e3"}]`,
|
||
))
|
||
req.Header.Set("Content-Type", "application/json")
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "普通格式") {
|
||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||
}
|
||
if _, err := store.Orders.Get(context.Background(), "bad-import-amount"); err == nil {
|
||
t.Fatal("invalid imported amount must not create an order")
|
||
}
|
||
}
|
||
|
||
func TestImportOrdersRejectsUnknownStatusWithoutWritingOrder(t *testing.T) {
|
||
srv, store, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
req := httptest.NewRequest(http.MethodPost, "/api/orders/import", strings.NewReader(
|
||
`[{"order_id":"bad-import-status","cookie_id":"acc1","status":"anything","amount":"10"}]`,
|
||
))
|
||
req.Header.Set("Content-Type", "application/json")
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "不支持的订单状态") {
|
||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||
}
|
||
if _, err := store.Orders.Get(context.Background(), "bad-import-status"); err == nil {
|
||
t.Fatal("unknown imported status must not create an order")
|
||
}
|
||
}
|
||
|
||
func TestImportOrdersRollsBackOrderWhenItemWriteFails(t *testing.T) {
|
||
srv, store, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
ctx := context.Background()
|
||
_, _ = store.DB.ExecContext(ctx, `CREATE TRIGGER reject_import_item BEFORE INSERT ON item_info
|
||
WHEN NEW.item_id='reject-import-item' BEGIN SELECT RAISE(ABORT,'forced item failure'); END`)
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
req := httptest.NewRequest(http.MethodPost, "/api/orders/import", strings.NewReader(
|
||
`[{"order_id":"import-tx","cookie_id":"acc1","item_id":"reject-import-item","item_title":"商品","amount":"¥1,200.50"}]`,
|
||
))
|
||
req.Header.Set("Content-Type", "application/json")
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "补全商品信息失败") {
|
||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||
}
|
||
if _, err := store.Orders.Get(ctx, "import-tx"); err == nil {
|
||
t.Fatal("order must roll back when imported item write fails")
|
||
}
|
||
}
|
||
|
||
func TestUpdateOrderRejectsInvalidAmount(t *testing.T) {
|
||
srv, store, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
ctx := context.Background()
|
||
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,item_id,amount,order_status,cookie_id) VALUES ('ord-amount','item1','9.9','2','acc1')`)
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
req := httptest.NewRequest(http.MethodPut, "/api/orders/ord-amount", strings.NewReader(`{"amount":"abc"}`))
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != http.StatusBadRequest {
|
||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||
}
|
||
order, _ := store.Orders.Get(ctx, "ord-amount")
|
||
if order.Amount != "9.9" {
|
||
t.Fatalf("invalid amount was stored: %q", order.Amount)
|
||
}
|
||
}
|
||
|
||
func TestValidOrderAmountMatchesAnalyticsDecimalFormat(t *testing.T) {
|
||
for _, invalid := range []string{"abc", "1e3", "+Inf", "NaN", "-1", "1.", "1,2", "12,34", "1,,000"} {
|
||
if validOrderAmount(invalid) {
|
||
t.Fatalf("%q must be rejected", invalid)
|
||
}
|
||
}
|
||
for input, want := range map[string]string{"": "", "0": "0", "12.50": "12.50", "¥1,200.50": "1200.50", "¥12.50": "12.50"} {
|
||
got, ok := normalizeOrderAmount(input)
|
||
if !ok || got != want {
|
||
t.Fatalf("normalize(%q)=%q,%v want %q,true", input, got, ok, want)
|
||
}
|
||
}
|
||
}
|
||
|
||
func TestChunkRefreshTargetsBoundsBrowserBatchSize(t *testing.T) {
|
||
targets := make([]refreshTarget, 205)
|
||
for i := range targets {
|
||
targets[i].OrderID = fmt.Sprintf("o-%d", i)
|
||
}
|
||
chunks := chunkRefreshTargets(targets, 100)
|
||
if len(chunks) != 3 || len(chunks[0]) != 100 || len(chunks[1]) != 100 || len(chunks[2]) != 5 {
|
||
t.Fatalf("unexpected chunk sizes: %d/%d/%d total=%d", len(chunks[0]), len(chunks[1]), len(chunks[2]), len(chunks))
|
||
}
|
||
}
|
||
|
||
func TestUpdateOrderAndItemTitleRollBackTogether(t *testing.T) {
|
||
srv, store, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
ctx := context.Background()
|
||
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,item_id,amount,order_status,cookie_id) VALUES ('ord-tx','old-item','9.9','2','acc1')`)
|
||
_, _ = store.DB.ExecContext(ctx, `CREATE TRIGGER reject_tx_item BEFORE INSERT ON item_info
|
||
WHEN NEW.item_id='tx-fail' BEGIN SELECT RAISE(ABORT,'forced item failure'); END`)
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
req := httptest.NewRequest(http.MethodPut, "/api/orders/ord-tx", strings.NewReader(`{"item_id":"tx-fail","item_title":"new","amount":"20"}`))
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != http.StatusInternalServerError {
|
||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||
}
|
||
order, _ := store.Orders.Get(ctx, "ord-tx")
|
||
if order.ItemID != "old-item" || order.Amount != "9.9" {
|
||
t.Fatalf("order must roll back with item failure: %+v", order)
|
||
}
|
||
}
|
||
|
||
func TestUpdateOrderRejectsUnknownStatus(t *testing.T) {
|
||
srv, store, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
ctx := context.Background()
|
||
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,item_id,order_status,cookie_id) VALUES ('ord-status','item1','2','acc1')`)
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
req := httptest.NewRequest(http.MethodPut, "/api/orders/ord-status", strings.NewReader(`{"status":"anything"}`))
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != http.StatusBadRequest {
|
||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||
}
|
||
order, _ := store.Orders.Get(ctx, "ord-status")
|
||
if order.OrderStatus != "2" {
|
||
t.Fatalf("invalid status changed order: %+v", order)
|
||
}
|
||
}
|
||
|
||
func TestUpdateOrderCanExplicitlyClearFields(t *testing.T) {
|
||
srv, store, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
ctx := context.Background()
|
||
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders
|
||
(order_id,item_id,buyer_id,order_status,cookie_id,amount,receiver_phone)
|
||
VALUES ('ord-clear','item1','b1','2','acc1','99.9','13800000000')`)
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
|
||
req := httptest.NewRequest(http.MethodPut, "/api/orders/ord-clear", strings.NewReader(`{"amount":"","receiver_phone":""}`))
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != http.StatusOK {
|
||
t.Fatalf("clear status=%d body=%s", rec.Code, rec.Body.String())
|
||
}
|
||
order, err := store.Orders.Get(ctx, "ord-clear")
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if order.Amount != "" || order.ReceiverPhone != "" || order.ItemID != "item1" {
|
||
t.Fatalf("explicit clear mismatch: %+v", order)
|
||
}
|
||
}
|
||
|
||
func TestListOrdersSearchUsesBackendPaginationScope(t *testing.T) {
|
||
srv, store, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
ctx := context.Background()
|
||
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,item_id,buyer_id,order_status,cookie_id) VALUES
|
||
('ord-search-1','item-search','buyer-a','2','acc1'),
|
||
('ord-search-2','item-other','buyer-b','2','acc1')`)
|
||
_, _ = store.DB.ExecContext(ctx, `INSERT INTO item_info (cookie_id,item_id,item_title) VALUES ('acc1','item-search','Unique Product Name')`)
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
req := httptest.NewRequest(http.MethodGet, "/api/orders?search=unique&page=1&page_size=1", nil)
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != http.StatusOK {
|
||
t.Fatalf("search status=%d body=%s", rec.Code, rec.Body.String())
|
||
}
|
||
var response struct {
|
||
Total int `json:"total"`
|
||
Data []map[string]any `json:"data"`
|
||
}
|
||
if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
if response.Total != 1 || len(response.Data) != 1 || response.Data[0]["order_id"] != "ord-search-1" {
|
||
t.Fatalf("backend search response=%+v", response)
|
||
}
|
||
}
|
||
|
||
// TestUpdateOrderBadJSON 非法 JSON 应 400。
|
||
func TestUpdateOrderBadJSON(t *testing.T) {
|
||
srv, store, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
ctx := context.Background()
|
||
store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, cookie_id) VALUES ('ord-bad','item1','acc1')`)
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
|
||
req := httptest.NewRequest(http.MethodPut, "/api/orders/ord-bad", strings.NewReader("not-json"))
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != http.StatusBadRequest {
|
||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||
}
|
||
}
|
||
|
||
// TestManualShipOrdersStatusOnlySuccess mtop ConsignContext 成功路径。
|
||
func TestManualShipOrdersStatusOnlySuccess(t *testing.T) {
|
||
srv, store, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
ctx := context.Background()
|
||
store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, buyer_id, order_status, cookie_id, chat_id) VALUES ('ord-m','item1','b1','2','acc1','chat1')`)
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
|
||
body := `{"order_ids":["ord-m"],"ship_mode":"status_only"}`
|
||
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader(body))
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != 200 {
|
||
t.Fatalf("manual ship status=%d body=%s", rec.Code, rec.Body.String())
|
||
}
|
||
var res map[string]any
|
||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||
if res["success"] != true {
|
||
t.Fatalf("应成功: %+v", res)
|
||
}
|
||
results, _ := res["results"].([]any)
|
||
if len(results) != 1 {
|
||
t.Fatalf("应1条结果,got %d", len(results))
|
||
}
|
||
// 订单状态应已变为 shipped。
|
||
var ord map[string]any
|
||
req2 := httptest.NewRequest(http.MethodGet, "/api/orders/ord-m", nil)
|
||
req2.AddCookie(cookie)
|
||
rec2 := httptest.NewRecorder()
|
||
h.ServeHTTP(rec2, req2)
|
||
json.Unmarshal(rec2.Body.Bytes(), &ord)
|
||
if ord["order_status"] != "shipped" {
|
||
t.Errorf("订单状态应为 shipped,got %v", ord["order_status"])
|
||
}
|
||
}
|
||
|
||
func TestManualShipOrdersRejectsNonPendingStatus(t *testing.T) {
|
||
srv, store, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
ctx := context.Background()
|
||
_, _ = store.DB.ExecContext(ctx, `INSERT INTO orders (order_id,item_id,buyer_id,order_status,cookie_id,chat_id) VALUES ('ord-cancelled','item1','b1','cancelled','acc1','chat1')`)
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader(`{"order_ids":["ord-cancelled"],"ship_mode":"status_only"}`))
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "仅待发货订单") {
|
||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||
}
|
||
order, _ := store.Orders.Get(ctx, "ord-cancelled")
|
||
if order.OrderStatus != "cancelled" {
|
||
t.Fatalf("status changed: %+v", order)
|
||
}
|
||
}
|
||
|
||
// TestManualShipOrdersConsignFail mtop ConsignContext 失败(非 success ret)。
|
||
func TestManualShipOrdersConsignFail(t *testing.T) {
|
||
srv, store, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
ctx := context.Background()
|
||
store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, buyer_id, order_status, cookie_id, chat_id) VALUES ('ord-f','item1','b1','2','acc1','chat1')`)
|
||
|
||
// 覆盖 mtop client:返回非 success ret。
|
||
prev := srv.MTop
|
||
srv.MTop = newMockMTop(t, mtopResp{ret: []string{"FAIL_BIZ_ORDER_NOT_FOUND::订单不存在"}})
|
||
defer func() { srv.MTop = prev }()
|
||
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
body := `{"order_ids":["ord-f"],"ship_mode":"status_only"}`
|
||
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader(body))
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != 200 {
|
||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||
}
|
||
var res map[string]any
|
||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||
if res["success"] != false {
|
||
t.Fatalf("整体应失败: %+v", res)
|
||
}
|
||
}
|
||
|
||
// TestManualShipOrdersOrderNotFound 订单不存在 → failed。
|
||
func TestManualShipOrdersOrderNotFound(t *testing.T) {
|
||
srv, _, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
|
||
body := `{"order_ids":["no-such-ord"],"ship_mode":"status_only"}`
|
||
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader(body))
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != 200 {
|
||
t.Fatalf("status=%d", rec.Code)
|
||
}
|
||
var res map[string]any
|
||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||
if res["failed_count"] != float64(1) {
|
||
t.Fatalf("应1失败,got %+v", res)
|
||
}
|
||
}
|
||
|
||
// TestManualShipOrdersBadMode 非法发货模式 400。
|
||
func TestManualShipOrdersBadMode(t *testing.T) {
|
||
srv, _, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
|
||
body := `{"order_ids":["ord-x"],"ship_mode":"bogus"}`
|
||
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader(body))
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != http.StatusBadRequest {
|
||
t.Fatalf("非法模式应 400,got %d", rec.Code)
|
||
}
|
||
}
|
||
|
||
// TestManualShipOrdersEmpty 缺少订单 ID 400。
|
||
func TestManualShipOrdersEmpty(t *testing.T) {
|
||
srv, _, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
|
||
body := `{"order_ids":[],"ship_mode":"status_only"}`
|
||
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader(body))
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != http.StatusBadRequest {
|
||
t.Fatalf("空订单应 400,got %d", rec.Code)
|
||
}
|
||
}
|
||
|
||
// TestManualShipOrdersBadJSON 非法 JSON 400。
|
||
func TestManualShipOrdersBadJSON(t *testing.T) {
|
||
srv, _, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
|
||
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader("not-json"))
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != http.StatusBadRequest {
|
||
t.Fatalf("非法 JSON 应 400,got %d", rec.Code)
|
||
}
|
||
}
|
||
|
||
// TestManualShipOrdersFullDeliveryNoAutomation full_delivery 但自动化未初始化 → failed。
|
||
func TestManualShipOrdersFullDeliveryNoAutomation(t *testing.T) {
|
||
srv, store, cleanup := newTestServer(t)
|
||
defer cleanup()
|
||
ctx := context.Background()
|
||
store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, buyer_id, order_status, cookie_id, chat_id) VALUES ('ord-full','item1','b1','2','acc1','chat1')`)
|
||
h := srv.Router()
|
||
cookie := loginHelper(t, h)
|
||
|
||
body := `{"order_ids":["ord-full"],"ship_mode":"full_delivery"}`
|
||
req := httptest.NewRequest(http.MethodPost, "/api/orders/manual-ship", strings.NewReader(body))
|
||
req.AddCookie(cookie)
|
||
rec := httptest.NewRecorder()
|
||
h.ServeHTTP(rec, req)
|
||
if rec.Code != 200 {
|
||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||
}
|
||
var res map[string]any
|
||
json.Unmarshal(rec.Body.Bytes(), &res)
|
||
if res["failed_count"] != float64(1) {
|
||
t.Fatalf("应1失败,got %+v", res)
|
||
}
|
||
results, _ := res["results"].([]any)
|
||
if len(results) != 1 {
|
||
t.Fatalf("结果数异常: %d", len(results))
|
||
}
|
||
r0, _ := results[0].(map[string]any)
|
||
if !strings.Contains(r0["message"].(string), "自动化") {
|
||
t.Fatalf("应提示自动化未初始化,got %v", r0["message"])
|
||
}
|
||
}
|
||
|
||
// TestIsStableOrderStatus 稳定状态判定。
|
||
func TestIsStableOrderStatus(t *testing.T) {
|
||
stable := map[string]bool{"shipped": true, "completed": true, "cancelled": true}
|
||
unstable := map[string]bool{"pending_ship": false, "processing": false, "": false, "unknown": false}
|
||
for s, want := range stable {
|
||
if got := isStableOrderStatus(s); got != want {
|
||
t.Errorf("isStableOrderStatus(%q)=%v want %v", s, got, want)
|
||
}
|
||
}
|
||
for s, want := range unstable {
|
||
if got := isStableOrderStatus(s); got != want {
|
||
t.Errorf("isStableOrderStatus(%q)=%v want %v", s, got, want)
|
||
}
|
||
}
|
||
}
|
||
|
||
// TestAtoiDefault atoiDefault 表驱动。
|
||
func TestAtoiDefault(t *testing.T) {
|
||
cases := map[string]int{"": 5, "abc": 5, "3": 3, "12": 12}
|
||
for in, want := range cases {
|
||
if got := atoiDefault(in, 5); got != want {
|
||
t.Errorf("atoiDefault(%q)=%d want %d", in, got, want)
|
||
}
|
||
}
|
||
}
|