Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e4d4a6fa79 | ||
|
|
1b4f7cd392 | ||
|
|
ddc18f5370 | ||
|
|
19060d2ce1 | ||
|
|
a24c2068ef | ||
|
|
6752b149d8 | ||
|
|
a38688cdd3 |
@@ -2,8 +2,8 @@
|
||||
generated: true (请先修改 Gitea Wiki,禁止直接编辑本文件)
|
||||
wiki_page: Business-Rules-and-Glossary
|
||||
wiki_url: https://git.ilapage.cn/OPC/goauto/wiki/Business-Rules-and-Glossary.-
|
||||
wiki_revision: 76037bfdf5e986c478055e7338c21ee1ba561bad
|
||||
synchronized_at: 2026-09-30T01:50:31Z
|
||||
wiki_revision: 9dfe6566032003ed16f7c693d5d257500b7c5025
|
||||
synchronized_at: 2026-10-05T07:05:36Z
|
||||
<!-- gitea-wiki-mirror:end -->
|
||||
|
||||
<!-- gitea-wiki-mirror:start -->
|
||||
@@ -70,7 +70,7 @@ Admin 的「创建时间」范围按 SYB 货运单列表的 `t_stock.created`(
|
||||
- 关联虾皮商品档案:命中存活记录直接关联;命中软删除记录则复活并保留原有人工映射;均不存在时创建最小档案。命中既有档案时只补写为空的参考图与售价,不覆盖人工修改过的标题、店铺和映射。
|
||||
- 重新解析只读取已保存的原始 JSON,不请求 SYB 接口,永不改写 `RawJSON`;标记 `manuallyConfirmed` 的明细默认跳过重新解析,除非显式指定强制覆盖。
|
||||
- 人工修正的颜色/尺码视为与解析成功同等可信,同样会合并进虾皮商品档案;标记为已人工确认。
|
||||
- Admin 商品列表的订单号筛选每行一个、去空去重后精确匹配,最多 100 个且单项最长 64 字符;店铺名称使用包含匹配。店铺、订单号与解析状态之间使用 AND,不再用该筛选框搜索蝦皮商品 ID 或商品标题。
|
||||
- #353:Admin SYB 商品页仅从「店铺管理」选择店铺,支持最多 50 家多选,停用但未删除的店铺仍可选。所选店铺之间为 OR,与订单号、解析状态、处理阶段、采购类型及来源创建日期等条件为 AND,筛选后分页。订单号按完整值精确查询,最多 100 个去重非空值,每个最多 64 字符,不检索虾皮商品 ID 或标题。店铺名称与同步规则使用相同的首尾去空白、全角 ASCII 折半角及大小写归一,不合并名称中间空格。旧 API 保留 shopName 包含查询;新 Admin 不允许自由输入或选择已删除店铺。店铺改名后,保留旧名称的历史商品可能无法通过新名称选项查到,此限制已获用户接受。
|
||||
- SYB 商品数据本身不保存 PDD 订单号、快递单号、支付或有效订单状态;Admin 的采购任务创建入口位于 SYB 商品列表,任务事实仍写入独立采购域。
|
||||
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
generated: true (请先修改 Gitea Wiki,禁止直接编辑本文件)
|
||||
wiki_page: Troubleshooting
|
||||
wiki_url: https://git.ilapage.cn/OPC/goauto/wiki/Troubleshooting
|
||||
wiki_revision: 03ea269058b50fea2be7842b9c284018987c82d9
|
||||
synchronized_at: 2026-09-21T08:14:54Z
|
||||
wiki_revision: 40e77a656d1c21d72454ad722a4f71a0a4491241
|
||||
synchronized_at: 2026-10-05T07:18:16Z
|
||||
<!-- gitea-wiki-mirror:end -->
|
||||
|
||||
# 故障排查
|
||||
@@ -104,3 +104,11 @@ adb -s <device-serial> exec-out run-as cn.ilapage.goauto.agent cat files/purchas
|
||||
```
|
||||
|
||||
先列出文件,再读取本次任务/attempt 的准确文件名;不得扩大为导出所有应用数据或完整数据库。新版安装前的失败不会补生成日志;需要用户授权后重试才能产生新证据。Release 若禁止 run-as 则停止,不更改权限绕过;首版没有导出界面。该功能用于确定拒绝分支,并不代表已经修复对应采购故障。
|
||||
## SYB 商品列表查询等待(#355)
|
||||
|
||||
实现绑定 `a24c206`,仅 Web 客户端;2026-10-05 与 #353/#354 合并至 main `1b4f7cd` 并配套发布 Server/Web 至现有 167 服务器。已通过本地合成测试及线上只读页面验证:列表请求实际等待预算为 60000ms,原筛选组合超过 10 秒后正常返回。发布记录和回退目标见 #355 工单。
|
||||
|
||||
- `web/src/api/goauto/syb-products.js` 的 `listSybProducts` 为 `GET /api/admin/v1/syb-products` 单独设置默认 `timeout: 60000`,覆盖 SYB 商品页搜索、翻页和修改每页数量。全局请求默认仍为 10000ms,其他页面及详情、AI 匹配、采购、采集、退货操作的原超时不变。
|
||||
- 保留现有加载、错误提示、取消和旧请求隔离逻辑,不增加自动重试。慢请求在 10~60 秒间完成时不再被原 10 秒客户端预算提前中止;超过 60 秒仍会超时,上游更短的超时也可能先终止请求。
|
||||
- 此调整不优化后端执行速度。处理阶段筛选当前先加载候选并计算阶段、后分页;不选店铺且采购类型为全部时,候选可能很大。遇到持续慢查询,应另行分析候选预筛选与数据库执行计划,不能据此认为延长前端预算已解决后端性能问题。
|
||||
- 只需发布包含该提交的 Web 资源即可生效,不要求数据库迁移、Android 安装或后端参数变更;发布仍需人工授权。
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
generated: true (请先修改 Gitea Wiki,禁止直接编辑本文件)
|
||||
wiki_page: Android-Agent-API-Contract
|
||||
wiki_url: https://git.ilapage.cn/OPC/goauto/wiki/Android-Agent-API-Contract.-
|
||||
wiki_revision: f92513e7184fe704d2b9d1c6606b16a86d8d3fb8
|
||||
synchronized_at: 2026-09-30T01:58:59Z
|
||||
wiki_revision: 60bac77693f31b33162a65dc902456f324774f7b
|
||||
synchronized_at: 2026-10-05T07:06:06Z
|
||||
<!-- gitea-wiki-mirror:end -->
|
||||
|
||||
<!-- gitea-wiki-mirror:start -->
|
||||
@@ -83,6 +83,8 @@ POST /api/admin/v1/syb-products/reparse-batch
|
||||
PATCH /api/admin/v1/syb-products/{productId}/correction
|
||||
```
|
||||
|
||||
#353 SYB 商品列表店铺筛选:Admin 使用重复的 shopIds 查询参数,表示 1~50 个店铺管理 ID,集合内按 OR 匹配。shopIds 不可与旧 shopName 同传;非法、不存在或软删除的 ID 返回 422。服务端读取管理店铺(包含停用店铺),用与店铺同步一致的首尾去空白、全角 ASCII 折半角及大小写归一规则,与已存 SYB 商品的原始店铺名比较。其他筛选条件按 AND 组合,筛选后分页;无匹配时返回空列表,不放宽为全部店铺。旧 shopName 包含查询只供旧客户端兼容,新 Admin 仅提交管理店铺 ID。管理店铺改名后,历史商品保留的旧名称可能无法按新店铺选项查询,此限制已获 #353 用户确认。
|
||||
|
||||
`import` 允许已认证的管理员(admin)和采购员(purchaser)调用(#236),仍须通过 Casbin 权限校验;其他角色返回 403。采购员的 POST 权限由既有启动权限对账写入,不需要新增数据库迁移。操作人取已认证 claims,不接受客户端冒名。请求体提交 `dateFrom`、`dateTo` 后创建持久化后台任务并立即以 `202` 返回 `runId` 和 `status=running`;关闭弹窗、刷新或离开页面不影响任务。没有启用店铺时必须在读取凭据、登录、验证码 OCR 和任意 SYB 网络请求之前返回 `422`。任意时刻只能有一条 `running` 记录,内存锁与数据库唯一执行槽共同阻止单进程和跨进程重复导入;冲突时返回正在执行任务的日期范围。
|
||||
|
||||
`sync-runs` 列表支持 `page`、`pageSize`、`status`、`dateFrom`、`dateTo`,详情返回日期范围、状态(`running` / `succeeded` / `partial_success` / `failed` / `interrupted`)、处理天数、货运单/明细/新增/覆盖数量、店铺准入与跳过数量、店铺筛选快照哈希、按店铺的 `accepted` / `skipped` 统计、操作人和起止时间。列表和详情对已登录角色只读开放。服务启动时遗留的 `running` 任务改为 `interrupted`;中途失败或中断已经写入的数据保留,重新导入仍按唯一键覆盖。
|
||||
|
||||
@@ -32,6 +32,22 @@ func (handler Handler) logInternalFailure(c *gin.Context, stage string, err erro
|
||||
}
|
||||
|
||||
func (handler Handler) List(c *gin.Context) {
|
||||
var shopIDs []uint64
|
||||
if values, present := c.Request.URL.Query()["shopIds"]; present {
|
||||
if len(values) == 0 || len(values) > 50 {
|
||||
writeError(c, invalidRequest("shopIds 数量必须为 1 到 50 个"))
|
||||
return
|
||||
}
|
||||
shopIDs = make([]uint64, 0, len(values))
|
||||
for _, value := range values {
|
||||
id, err := strconv.ParseUint(value, 10, 64)
|
||||
if err != nil || id == 0 {
|
||||
writeError(c, invalidRequest("shopIds 必须是有效的店铺 ID"))
|
||||
return
|
||||
}
|
||||
shopIDs = append(shopIDs, id)
|
||||
}
|
||||
}
|
||||
page, err := queryInt(c.Query("page"), 1)
|
||||
if err != nil {
|
||||
writeError(c, invalidRequest("page 必须是正整数"))
|
||||
@@ -47,7 +63,7 @@ func (handler Handler) List(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
response, err := service.List(c.Request.Context(), ListRequest{
|
||||
Page: page, PageSize: pageSize, ShopName: c.Query("shopName"), OrderCodes: []string{c.Query("orderCodes")}, ParseStatus: strings.TrimSpace(c.Query("parseStatus")), ProcessStage: strings.TrimSpace(c.Query("processStage")), CreatedFrom: strings.TrimSpace(c.Query("createdFrom")), CreatedTo: strings.TrimSpace(c.Query("createdTo")), PurchaseType: strings.TrimSpace(c.Query("purchaseType")),
|
||||
Page: page, PageSize: pageSize, ShopName: c.Query("shopName"), ShopIDs: shopIDs, OrderCodes: []string{c.Query("orderCodes")}, ParseStatus: strings.TrimSpace(c.Query("parseStatus")), ProcessStage: strings.TrimSpace(c.Query("processStage")), CreatedFrom: strings.TrimSpace(c.Query("createdFrom")), CreatedTo: strings.TrimSpace(c.Query("createdTo")), PurchaseType: strings.TrimSpace(c.Query("purchaseType")),
|
||||
})
|
||||
if err != nil {
|
||||
writeError(c, err)
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
|
||||
"go-admin/app/goauto/models"
|
||||
"go-admin/app/goauto/purchase"
|
||||
"go-admin/app/goauto/sybshop"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
@@ -42,6 +43,7 @@ func NewService(db *gorm.DB) *Service { return &Service{DB: db} }
|
||||
type ListRequest struct {
|
||||
Page, PageSize int
|
||||
ShopName string
|
||||
ShopIDs []uint64
|
||||
OrderCodes []string
|
||||
ParseStatus string
|
||||
ProcessStage string
|
||||
@@ -95,7 +97,47 @@ func (service *Service) List(ctx context.Context, request ListRequest) (ListResp
|
||||
if createdTo != nil {
|
||||
query = query.Where("syb_stock_created_at < ?", *createdTo)
|
||||
}
|
||||
if request.ShopName = strings.TrimSpace(request.ShopName); request.ShopName != "" {
|
||||
if request.ShopName = strings.TrimSpace(request.ShopName); request.ShopName != "" && len(request.ShopIDs) > 0 {
|
||||
return ListResponse{}, invalidRequest("shopName 和 shopIds 不能同时使用")
|
||||
}
|
||||
if len(request.ShopIDs) > 0 {
|
||||
if len(request.ShopIDs) > 50 {
|
||||
return ListResponse{}, invalidRequest("一次最多选择 50 个店铺")
|
||||
}
|
||||
selected := make(map[uint64]struct{}, len(request.ShopIDs))
|
||||
for _, id := range request.ShopIDs {
|
||||
if id == 0 {
|
||||
return ListResponse{}, invalidRequest("shopIds 必须是有效的店铺 ID")
|
||||
}
|
||||
selected[id] = struct{}{}
|
||||
}
|
||||
var shops []models.SYBShop
|
||||
if err := service.DB.WithContext(ctx).Where("id IN ?", request.ShopIDs).Find(&shops).Error; err != nil {
|
||||
return ListResponse{}, internalError(err)
|
||||
}
|
||||
if len(shops) != len(selected) {
|
||||
return ListResponse{}, invalidRequest("所选店铺不存在或已删除")
|
||||
}
|
||||
shopNames := make(map[string]struct{}, len(shops))
|
||||
for _, shop := range shops {
|
||||
shopNames[shop.NormalizedName] = struct{}{}
|
||||
}
|
||||
var sourceNames []string
|
||||
if err := service.DB.WithContext(ctx).Model(&models.SYBProduct{}).Distinct("shop_name").Pluck("shop_name", &sourceNames).Error; err != nil {
|
||||
return ListResponse{}, internalError(err)
|
||||
}
|
||||
matchedNames := make([]string, 0)
|
||||
for _, name := range sourceNames {
|
||||
if _, ok := shopNames[sybshop.Normalize(name)]; ok {
|
||||
matchedNames = append(matchedNames, name)
|
||||
}
|
||||
}
|
||||
if len(matchedNames) == 0 {
|
||||
query = query.Where("1 = 0")
|
||||
} else {
|
||||
query = query.Where("shop_name IN ?", matchedNames)
|
||||
}
|
||||
} else if request.ShopName != "" {
|
||||
if len([]rune(request.ShopName)) > 255 {
|
||||
return ListResponse{}, invalidRequest("店铺名称不能超过 255 个字符")
|
||||
}
|
||||
|
||||
@@ -74,6 +74,57 @@ func TestServiceListFiltersByOrderCodesShopAndParseStatus(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceListFiltersByManagedShopIDs(t *testing.T) {
|
||||
db := openTestDB(t)
|
||||
orders := []struct{ name, code string }{
|
||||
{" ABC店 ", "ORDER-A"}, {"第二店", "ORDER-B"}, {"其他店", "ORDER-C"},
|
||||
}
|
||||
for i, fixture := range orders {
|
||||
order := realOrder()
|
||||
order.Code, order.ShopName, order.StockID = fixture.code, fixture.name, order.StockID+uint64(i)
|
||||
detail := realDetailA()
|
||||
detail.ID += uint64(i)
|
||||
if _, err := sybimport.ApplyDetail(context.Background(), db, order, detail); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
shops := []models.SYBShop{
|
||||
{DisplayName: "ABC店", NormalizedName: "abc店", Enabled: true},
|
||||
{DisplayName: "第二店", NormalizedName: "第二店", Enabled: false},
|
||||
{DisplayName: "未出现店", NormalizedName: "未出现店", Enabled: true},
|
||||
}
|
||||
if err := db.Create(&shops).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
service := sybimport.NewService(db)
|
||||
result, err := service.List(context.Background(), sybimport.ListRequest{ShopIDs: []uint64{shops[0].ID, shops[1].ID}, OrderCodes: []string{"ORDER-A", "ORDER-B", "ORDER-C"}})
|
||||
if err != nil || result.Total != 2 {
|
||||
t.Fatalf("multi-shop OR and order-code AND: result=%+v err=%v", result, err)
|
||||
}
|
||||
result, err = service.List(context.Background(), sybimport.ListRequest{ShopIDs: []uint64{shops[2].ID}})
|
||||
if err != nil || result.Total != 0 {
|
||||
t.Fatalf("unmatched managed shop must return empty: result=%+v err=%v", result, err)
|
||||
}
|
||||
for _, request := range []sybimport.ListRequest{
|
||||
{ShopIDs: []uint64{shops[0].ID}, ShopName: "ABC"},
|
||||
{ShopIDs: []uint64{shops[0].ID, 999999}},
|
||||
{ShopIDs: []uint64{0}},
|
||||
{ShopIDs: make([]uint64, 51)},
|
||||
} {
|
||||
_, err := service.List(context.Background(), request)
|
||||
if code := serviceErrCode(t, err); code != sybimport.CodeInvalidRequest {
|
||||
t.Fatalf("request %+v: %s", request, code)
|
||||
}
|
||||
}
|
||||
if err := db.Delete(&shops[0]).Error; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = service.List(context.Background(), sybimport.ListRequest{ShopIDs: []uint64{shops[0].ID}})
|
||||
if code := serviceErrCode(t, err); code != sybimport.CodeInvalidRequest {
|
||||
t.Fatalf("deleted shop: %s", code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceListRejectsTooManyOrTooLongOrderCodes(t *testing.T) {
|
||||
service := sybimport.NewService(openTestDB(t))
|
||||
tooMany := make([]string, 101)
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
package sybimport_test
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"go-admin/app/goauto/sybimport"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func TestListHandlerShopIDsValidation(t *testing.T) {
|
||||
db := openTestDB(t)
|
||||
gin.SetMode(gin.TestMode)
|
||||
router := gin.New()
|
||||
router.GET("/syb-products", (sybimport.Handler{DB: db}).List)
|
||||
for _, target := range []string{
|
||||
"/syb-products?shopIds=",
|
||||
"/syb-products?shopIds=abc",
|
||||
"/syb-products?shopIds=0",
|
||||
"/syb-products?shopIds=1&shopName=test",
|
||||
"/syb-products?shopIds=999999",
|
||||
} {
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, target, nil))
|
||||
if response.Code != http.StatusUnprocessableEntity {
|
||||
t.Fatalf("%s: expected 422, got %d %s", target, response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/syb-products?shopName=legacy", nil))
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("legacy shopName: %d %s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,14 @@
|
||||
import request from '@/utils/request'
|
||||
|
||||
export function listSybProducts(params, options = {}) {
|
||||
return request({ url: '/api/admin/v1/syb-products', method: 'get', params, ...options })
|
||||
return request({ url: '/api/admin/v1/syb-products', method: 'get', params, timeout: 60000, paramsSerializer: { serialize(values) {
|
||||
const query = new URLSearchParams()
|
||||
for (const [key, value] of Object.entries(values)) {
|
||||
if (Array.isArray(value)) value.forEach(item => query.append(key, String(item)))
|
||||
else if (value !== undefined && value !== null && value !== '') query.append(key, String(value))
|
||||
}
|
||||
return query.toString()
|
||||
} }, ...options })
|
||||
}
|
||||
|
||||
export function getSybProduct(productId) {
|
||||
|
||||
@@ -5,9 +5,22 @@
|
||||
<el-form :model="query" :inline="true" class="search-form" @submit.prevent="search">
|
||||
<div class="search-row search-row-primary">
|
||||
<el-form-item label="店铺">
|
||||
<el-autocomplete v-model="query.shopName" class="shop-input" placeholder="选择或输入店铺" clearable value-key="displayName" :fetch-suggestions="suggestSybShops">
|
||||
<template #default="{ item }"><div class="shop-option" :title="item.displayName"><span class="shop-option-name">{{ item.displayName }}</span><el-tag v-if="!item.enabled" size="small" type="info" effect="plain">已停用</el-tag></div></template>
|
||||
</el-autocomplete>
|
||||
<el-select
|
||||
v-model="query.shopIds"
|
||||
class="shop-input"
|
||||
multiple
|
||||
filterable
|
||||
collapse-tags
|
||||
collapse-tags-tooltip
|
||||
clearable
|
||||
:multiple-limit="50"
|
||||
:loading="shopOptionsLoading"
|
||||
placeholder="选择店铺"
|
||||
@visible-change="onShopVisible"
|
||||
>
|
||||
<el-option v-for="shop in shopOptions" :key="shop.id" :value="shop.id" :label="shop.displayName"><div class="shop-option" :title="shop.displayName"><span class="shop-option-name">{{ shop.displayName }}</span><el-tag v-if="!shop.enabled" size="small" type="info" effect="plain">已停用</el-tag></div></el-option>
|
||||
<template #empty><div class="shop-empty"><template v-if="shopOptionsLoading">正在加载店铺…</template><template v-else-if="shopOptionsError">店铺加载失败 <el-button link type="primary" @click.stop="ensureShopOptions">重试</el-button></template><template v-else>暂无店铺</template></div></template>
|
||||
</el-select>
|
||||
</el-form-item>
|
||||
<el-form-item label="订单号"><el-input v-model="query.orderCodesText" type="textarea" :autosize="{ minRows: 1, maxRows: 4 }" resize="none" class="order-codes-input" placeholder="每行一个订单号,最多 100 个" @keydown.ctrl.enter.prevent="search" /></el-form-item>
|
||||
<el-form-item label="解析状态"><el-select v-model="query.parseStatus" clearable placeholder="全部" style="width: 110px"><el-option label="成功" value="success" /><el-option label="失败" value="failed" /></el-select></el-form-item>
|
||||
@@ -405,7 +418,7 @@ export default {
|
||||
paginationTimer: null, loadedPage: 1, loadedPageSize: 200,
|
||||
purchaseDevices: [],
|
||||
purchasePreviewGeneration: 0,
|
||||
shopOptions: [], shopOptionsLoaded: false, shopOptionsPromise: null,
|
||||
shopOptions: [], shopOptionsLoaded: false, shopOptionsLoading: false, shopOptionsError: false, shopOptionsPromise: null,
|
||||
purchaseDialog: { open: false, loading: false, saving: false, ids: [], selectedCount: 0, deviceId: null, items: [], eligibleCount: 0, skippedCount: 0, previewError: '' },
|
||||
purchaseResult: { open: false, items: [], createdCount: 0, failedCount: 0 },
|
||||
specMatchResult: { open: false, items: [], selectedIDs: [], autoConfirmedCount: 0, pendingCount: 0, failedCount: 0, skippedCount: 0 },
|
||||
@@ -413,7 +426,7 @@ export default {
|
||||
imageSearchBatch: this.emptyImageSearchBatch(),
|
||||
collectionBatchData: { ruleId: null, deviceId: null },
|
||||
collectionBatchRules: { ruleId: [{ required: true, message: '请选择采集规则', trigger: 'change' }] },
|
||||
query: { page: 1, pageSize: 200, shopName: '', orderCodesText: '', parseStatus: '', processStage: '', purchaseType: 'pdd', createdAtRange: [] },
|
||||
query: { page: 1, pageSize: 200, shopIds: [], orderCodesText: '', parseStatus: '', processStage: '', purchaseType: 'pdd', createdAtRange: [] },
|
||||
returnMatchByProductId: {},
|
||||
returnMatchLoading: false,
|
||||
returnMatchBatchLoading: false,
|
||||
@@ -490,7 +503,7 @@ export default {
|
||||
const requestOptions = allowNetworkRetry ? { suppressNetworkError: true } : {}
|
||||
try {
|
||||
const [createdFrom = '', createdTo = ''] = this.query.createdAtRange || []
|
||||
const r = await listSybProducts({ page: this.query.page, pageSize: this.query.pageSize, shopName: this.query.shopName.trim(), orderCodes: orderCodes.join(','), parseStatus: this.query.parseStatus, processStage: this.query.processStage, purchaseType: this.query.purchaseType, createdFrom, createdTo }, requestOptions)
|
||||
const r = await listSybProducts({ page: this.query.page, pageSize: this.query.pageSize, shopIds: this.query.shopIds, orderCodes: orderCodes.join(','), parseStatus: this.query.parseStatus, processStage: this.query.processStage, purchaseType: this.query.purchaseType, createdFrom, createdTo }, requestOptions)
|
||||
if (generation !== this.loadGeneration) return
|
||||
this.products = r.data.items
|
||||
this.total = r.data.total
|
||||
@@ -513,7 +526,7 @@ export default {
|
||||
}
|
||||
},
|
||||
search() { this.query.page = 1; this.load() },
|
||||
reset() { this.query = { page: 1, pageSize: 200, shopName: '', orderCodesText: '', parseStatus: '', processStage: '', purchaseType: 'pdd', createdAtRange: [] }; this.load() },
|
||||
reset() { this.query = { page: 1, pageSize: 200, shopIds: [], orderCodesText: '', parseStatus: '', processStage: '', purchaseType: 'pdd', createdAtRange: [] }; this.load() },
|
||||
onPagination() {
|
||||
// Both controls may emit after a size change clamps the old page. Coalesce
|
||||
// those events and keep the user on page one with exactly one list load.
|
||||
@@ -532,22 +545,27 @@ export default {
|
||||
this.query.purchaseType = 'all'
|
||||
}
|
||||
},
|
||||
normalizeShopName(value) { return String(value || '').normalize('NFKC').trim().toLocaleLowerCase() },
|
||||
async ensureShopOptions() {
|
||||
if (this.shopOptionsLoaded) return
|
||||
if (this.shopOptionsPromise) return this.shopOptionsPromise
|
||||
this.shopOptionsPromise = listSybShops({ page: 1, pageSize: 200 }, { suppressNetworkError: true, suppressErrorMessage: true })
|
||||
.then((response) => { this.shopOptions = response.data.items || [] })
|
||||
.catch(() => { this.shopOptions = []; ElMessage.warning('店铺列表加载失败,仍可直接输入店铺名称查询') })
|
||||
.finally(() => { this.shopOptionsLoaded = true; this.shopOptionsPromise = null })
|
||||
this.shopOptionsLoading = true
|
||||
this.shopOptionsError = false
|
||||
this.shopOptionsPromise = (async() => {
|
||||
const options = []
|
||||
for (let page = 1; ; page += 1) {
|
||||
const response = await listSybShops({ page, pageSize: 200 }, { suppressNetworkError: true, suppressErrorMessage: true })
|
||||
options.push(...(response.data.items || []))
|
||||
if (options.length >= response.data.total || !response.data.items?.length) break
|
||||
}
|
||||
this.shopOptions = options
|
||||
this.shopOptionsLoaded = true
|
||||
})().catch(() => {
|
||||
this.shopOptionsError = true
|
||||
ElMessage.warning('店铺列表加载失败,请重试')
|
||||
}).finally(() => { this.shopOptionsLoading = false; this.shopOptionsPromise = null })
|
||||
return this.shopOptionsPromise
|
||||
},
|
||||
async suggestSybShops(value, callback) {
|
||||
await this.ensureShopOptions()
|
||||
const keyword = this.normalizeShopName(value)
|
||||
const matches = keyword ? this.shopOptions.filter(item => this.normalizeShopName(item.displayName).includes(keyword)) : this.shopOptions
|
||||
callback(matches.slice(0, 50))
|
||||
},
|
||||
onShopVisible(visible) { if (visible) this.ensureShopOptions() },
|
||||
normalizedOrderCodes() {
|
||||
const values = [...new Set(this.query.orderCodesText.split(/\r?\n/).map(value => value.trim()).filter(Boolean))]
|
||||
if (values.length > 100) { ElMessage.warning('一次最多查询 100 个订单号'); return null }
|
||||
@@ -958,9 +976,10 @@ export default {
|
||||
.search-row-secondary{justify-content:flex-start}
|
||||
.search-form :deep(.el-form-item){margin-right:0;margin-bottom:12px}
|
||||
.search-form :deep(.el-form-item__content){flex-wrap:nowrap}
|
||||
.shop-input{width:130px}.order-codes-input{width:210px}.unlinked-tag{margin-left:8px}
|
||||
.shop-input{width:210px}.order-codes-input{width:210px}.unlinked-tag{margin-left:8px}
|
||||
.shop-option{display:flex;align-items:center;justify-content:space-between;gap:12px}
|
||||
.shop-option-name{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.shop-empty{padding:8px 12px;color:var(--el-text-color-secondary)}
|
||||
.toolbar-actions :deep(.el-form-item__content){gap:8px}
|
||||
.toolbar-actions :deep(.el-button + .el-button){margin-left:0}
|
||||
.action-button-wrap{display:inline-flex}
|
||||
|
||||
@@ -2,6 +2,28 @@ import { expect, test } from '@playwright/test'
|
||||
|
||||
const sybProductRoute = [{ path: '/goauto-order-workbench', component: 'Layout', menuName: 'GoAutoOrderWorkbench', title: '订单工作台', visible: '0', children: [{ path: '/syb-products', component: '/goauto/syb-products/index', menuName: 'GoAutoSybProducts', title: 'SYB 商品', visible: '0' }] }]
|
||||
|
||||
test('SYB 商品列表超过 10 秒后仍正常显示,不重复请求', async({ page, context }) => {
|
||||
await context.addCookies([{ name: 'Admin-Token', value: 'prototype-test-token', domain: 'localhost', path: '/' }])
|
||||
let listCalls = 0
|
||||
await page.route('**/api/**', async route => {
|
||||
const url = new URL(route.request().url())
|
||||
if (url.pathname.startsWith('/src/api/')) return route.continue()
|
||||
if (url.pathname.endsWith('/api/v1/getinfo')) return route.fulfill({ json: { code: 200, data: { roles: ['admin'], name: '测试管理员', avatar: '', introduction: '', permissions: [] }}})
|
||||
if (url.pathname.endsWith('/api/v1/menurole')) return route.fulfill({ json: { code: 200, data: sybProductRoute }})
|
||||
if (url.pathname.endsWith('/api/admin/v1/syb-products')) {
|
||||
listCalls++
|
||||
await new Promise(resolve => setTimeout(resolve, 12000))
|
||||
return route.fulfill({ json: { code: 200, data: { items: [{ id: 355, orderCode: 'TEST-355', productTitle: '延迟查询成功的测试商品', quantity: 1, parseStatus: 'success' }], total: 1, page: 1, pageSize: 200 }}})
|
||||
}
|
||||
if (url.pathname.endsWith('/api/admin/v1/purchase-tasks/batch-preview')) return route.fulfill({ json: { code: 200, data: { items: [{ sybProductId: 355, eligible: false, processStage: 'return_pending', processStageLabel: '退货待确认' }] }}})
|
||||
return route.fulfill({ json: { code: 200, data: [] }})
|
||||
})
|
||||
await page.goto('/#/syb-products')
|
||||
await expect(page.getByText('延迟查询成功的测试商品')).toBeVisible({ timeout: 20000 })
|
||||
expect(listCalls).toBe(1)
|
||||
await expect(page.getByText(/timeout of 10000ms exceeded/)).toHaveCount(0)
|
||||
})
|
||||
|
||||
test('SYB 商品首次网络失败时静默重试一次并恢复列表', async({ page, context }) => {
|
||||
await context.addCookies([{ name: 'Admin-Token', value: 'prototype-test-token', domain: 'localhost', path: '/' }])
|
||||
let listCalls = 0
|
||||
|
||||
@@ -43,13 +43,13 @@ test('SYB 商品工具栏与列宽按紧凑布局显示', async({ page, context
|
||||
expect(Math.abs((reset?.y || 0) - (purchase?.y || 0))).toBeLessThan(2)
|
||||
expect(purchase?.x || 0).toBeGreaterThan((reset?.x || 0) + (reset?.width || 0))
|
||||
await expect(page.getByRole('button', { name: /创建采购\s*0/ })).toBeDisabled()
|
||||
const shopControl = page.getByPlaceholder('选择或输入店铺')
|
||||
const shopControl = page.getByRole('combobox', { name: '店铺' })
|
||||
const shopInput = await shopControl.boundingBox()
|
||||
const orderInput = await page.getByPlaceholder('每行一个订单号,最多 100 个').boundingBox()
|
||||
expect(shopInput).not.toBeNull(); expect(orderInput).not.toBeNull()
|
||||
expect(shopInput?.x || 0).toBeLessThan(orderInput?.x || 0)
|
||||
|
||||
await shopControl.click()
|
||||
await page.locator('.shop-input').click()
|
||||
await expect(page.getByText('大碼臻選', { exact: true }).last()).toBeVisible()
|
||||
await expect(page.getByText('歷史店鋪', { exact: true }).last()).toBeVisible()
|
||||
await expect(page.getByText('已停用', { exact: true })).toBeVisible()
|
||||
@@ -64,12 +64,16 @@ test('SYB 商品工具栏与列宽按紧凑布局显示', async({ page, context
|
||||
expect(widths[9]).toBeGreaterThanOrEqual(210)
|
||||
expect(widths[11]).toBe(132)
|
||||
|
||||
await shopControl.fill('大碼')
|
||||
await page.locator('.shop-input').click()
|
||||
await page.getByRole('option', { name: '大碼臻選' }).click()
|
||||
await page.locator('.shop-input').click()
|
||||
await page.getByRole('option', { name: /歷史店鋪/ }).click()
|
||||
await page.getByPlaceholder('每行一个订单号,最多 100 个').fill(' SYB001\n\nSYB002\nSYB001 ')
|
||||
await page.getByPlaceholder('每行一个订单号,最多 100 个').press('Control+Enter')
|
||||
await expect.poll(() => listURLs.length).toBeGreaterThan(1)
|
||||
const latest = listURLs.at(-1)
|
||||
expect(latest?.searchParams.get('shopName')).toBe('大碼')
|
||||
expect(latest?.searchParams.getAll('shopIds')).toEqual(['1', '2'])
|
||||
expect(latest?.searchParams.has('shopName')).toBe(false)
|
||||
expect(latest?.searchParams.get('orderCodes')).toBe('SYB001,SYB002')
|
||||
|
||||
await page.locator('.el-form-item').filter({ hasText: '处理阶段' }).locator('.el-select').click()
|
||||
@@ -174,7 +178,7 @@ test('批量 AI 匹配展示混合结果并在关闭后刷新采购候选', asyn
|
||||
await expect(page.getByRole('button', { name: /AI 匹配\s*1/ })).toBeEnabled()
|
||||
})
|
||||
|
||||
test('店铺选项加载失败时仍可输入历史店铺查询', async({ page, context }) => {
|
||||
test('店铺选项加载失败时提示重试且不能输入任意店铺', async({ page, context }) => {
|
||||
await context.addCookies([{ name: 'Admin-Token', value: 'prototype-test-token', domain: 'localhost', path: '/' }])
|
||||
const listURLs: URL[] = []
|
||||
await page.route('**/api/**', async route => {
|
||||
@@ -188,13 +192,44 @@ test('店铺选项加载失败时仍可输入历史店铺查询', async({ page,
|
||||
})
|
||||
|
||||
await page.goto('/#/syb-products')
|
||||
const shopControl = page.getByPlaceholder('选择或输入店铺')
|
||||
await shopControl.click()
|
||||
await expect(page.getByText('店铺列表加载失败,仍可直接输入店铺名称查询', { exact: true })).toBeVisible()
|
||||
const shopControl = page.getByRole('combobox', { name: '店铺' })
|
||||
await page.locator('.shop-input').click()
|
||||
await expect(page.getByRole('tooltip', { name: /店铺加载失败/ })).toBeVisible()
|
||||
await expect(page.getByRole('button', { name: '重试' })).toBeVisible()
|
||||
await shopControl.fill('已删除店铺')
|
||||
await page.getByRole('button', { name: '查询', exact: true }).click()
|
||||
await expect.poll(() => listURLs.length).toBeGreaterThan(1)
|
||||
expect(listURLs.at(-1)?.searchParams.get('shopName')).toBe('已删除店铺')
|
||||
expect(listURLs.at(-1)?.searchParams.has('shopIds')).toBe(false)
|
||||
expect(listURLs.at(-1)?.searchParams.has('shopName')).toBe(false)
|
||||
})
|
||||
|
||||
test('店铺管理超过 200 家时仍可搜索并选择后续页店铺', async({ page, context }) => {
|
||||
await context.addCookies([{ name: 'Admin-Token', value: 'prototype-test-token', domain: 'localhost', path: '/' }])
|
||||
const shopPages: number[] = []
|
||||
const listURLs: URL[] = []
|
||||
await page.route('**/api/**', async route => {
|
||||
const url = new URL(route.request().url())
|
||||
if (url.pathname.startsWith('/src/api/')) return route.continue()
|
||||
if (url.pathname.endsWith('/api/v1/menurole')) return route.fulfill({ json: { code: 200, data: sybProductRoute }})
|
||||
if (url.pathname.endsWith('/api/v1/getinfo')) return route.fulfill({ json: { code: 200, data: { roles: ['admin'], name: '管理员', avatar: '', introduction: '', permissions: [] }}})
|
||||
if (url.pathname.endsWith('/api/admin/v1/syb-shops')) {
|
||||
const currentPage = Number(url.searchParams.get('page'))
|
||||
shopPages.push(currentPage)
|
||||
const start = (currentPage - 1) * 200 + 1
|
||||
const count = currentPage === 1 ? 200 : 1
|
||||
const items = Array.from({ length: count }, (_, index) => ({ id: start + index, displayName: `店铺${start + index}`, enabled: true }))
|
||||
return route.fulfill({ json: { code: 200, data: { items, total: 201, page: currentPage, pageSize: 200 }}})
|
||||
}
|
||||
if (url.pathname.endsWith('/api/admin/v1/syb-products')) { listURLs.push(url); return route.fulfill({ json: { code: 200, data: { items: [], total: 0, page: 1, pageSize: 200 }}}) }
|
||||
return route.fulfill({ json: { code: 200, data: [] }})
|
||||
})
|
||||
await page.goto('/#/syb-products')
|
||||
await page.locator('.shop-input').click()
|
||||
await expect.poll(() => shopPages).toEqual([1, 2])
|
||||
await page.getByRole('combobox', { name: '店铺' }).fill('店铺201')
|
||||
await page.getByRole('option', { name: '店铺201' }).click()
|
||||
await page.getByRole('button', { name: '查询', exact: true }).click()
|
||||
await expect.poll(() => listURLs.at(-1)?.searchParams.getAll('shopIds')).toEqual(['201'])
|
||||
})
|
||||
|
||||
test('PDD 待采集的下一步在 SYB 列表上方打开对应 PDD 商品抽屉', async({ page, context }) => {
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
const { test } = require('node:test')
|
||||
const assert = require('node:assert/strict')
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
|
||||
const source = fs.readFileSync(path.join(__dirname, '../../src/api/goauto/syb-products.js'), 'utf8')
|
||||
const names = [...source.matchAll(/export function (\w+)/g)].map(match => match[1])
|
||||
const load = request => new Function('request', source.replace(/^import .+\n/gm, '').replace(/export function /g, 'function ') + `\nreturn { ${names.join(',')} }`)(request)
|
||||
|
||||
test('search, pagination and page-size changes use the list-only 60-second timeout', () => {
|
||||
const api = load(config => config)
|
||||
for (const params of [
|
||||
{ page: 1, pageSize: 200, shopName: '', processStage: 'return_pending', purchaseType: 'all' },
|
||||
{ page: 2, pageSize: 200 },
|
||||
{ page: 1, pageSize: 500 }
|
||||
]) {
|
||||
const config = api.listSybProducts(params)
|
||||
assert.equal(config.timeout, 60000)
|
||||
assert.equal(config.params, params)
|
||||
assert.equal(config.url, '/api/admin/v1/syb-products')
|
||||
assert.equal(config.method, 'get')
|
||||
}
|
||||
})
|
||||
|
||||
test('existing cancellation and error options are preserved', () => {
|
||||
const controller = new AbortController()
|
||||
const config = load(config => config).listSybProducts({}, { signal: controller.signal, suppressNetworkError: true })
|
||||
assert.equal(config.timeout, 60000)
|
||||
assert.equal(config.signal, controller.signal)
|
||||
assert.equal(config.suppressNetworkError, true)
|
||||
controller.abort()
|
||||
assert.equal(config.signal.aborted, true)
|
||||
})
|
||||
|
||||
test('multi-shop serialization and explicit timeout override survive integration', () => {
|
||||
const api = load(config => config)
|
||||
const config = api.listSybProducts({ shopIds: [1, 2], page: 1 })
|
||||
assert.equal(config.timeout, 60000)
|
||||
assert.equal(config.paramsSerializer.serialize(config.params), 'shopIds=1&shopIds=2&page=1')
|
||||
assert.equal(api.listSybProducts({}, { timeout: 15000 }).timeout, 15000)
|
||||
})
|
||||
|
||||
test('other SYB API functions do not acquire the list timeout; global timeout stays 10 seconds', () => {
|
||||
const api = load(config => config)
|
||||
for (const name of names.filter(name => name !== 'listSybProducts')) {
|
||||
assert.equal(api[name](1, {}).timeout, undefined, name)
|
||||
}
|
||||
const globalRequest = fs.readFileSync(path.join(__dirname, '../../src/utils/request.js'), 'utf8')
|
||||
assert.match(globalRequest, /timeout:\s*10000\b/)
|
||||
})
|
||||
|
||||
test('timeout and cancellation failures propagate without new retries', async () => {
|
||||
for (const code of ['ECONNABORTED', 'ERR_CANCELED']) {
|
||||
let calls = 0
|
||||
const failure = Object.assign(new Error(code), { code })
|
||||
const api = load(() => { calls++; return Promise.reject(failure) })
|
||||
await assert.rejects(api.listSybProducts({}), error => error === failure)
|
||||
assert.equal(calls, 1)
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user