From 4280115e11ae26366a27e88818e73f34254ceb35 Mon Sep 17 00:00:00 2001 From: QiuSW <105186638@qq.com> Date: Tue, 29 Sep 2026 10:21:28 +0800 Subject: [PATCH] feat: batch use pending return matches #349 --- .../goauto/returnmatch/confirm_batch_test.go | 103 ++++++++++++++++ web/src/api/goauto/return-matches.js | 4 +- web/src/views/goauto/syb-products/index.vue | 36 ++++-- .../goauto/syb-products/return-cancel.js | 4 +- .../goauto/syb-products/return-confirm.js | 102 ++++++++++++++++ web/tests/e2e/syb-return-confirm.spec.ts | 114 ++++++++++++++++++ web/tests/unit/syb-return-cancel.test.cjs | 2 +- web/tests/unit/syb-return-confirm.test.cjs | 112 +++++++++++++++++ 8 files changed, 464 insertions(+), 13 deletions(-) create mode 100644 server/app/goauto/returnmatch/confirm_batch_test.go create mode 100644 web/src/views/goauto/syb-products/return-confirm.js create mode 100644 web/tests/e2e/syb-return-confirm.spec.ts create mode 100644 web/tests/unit/syb-return-confirm.test.cjs diff --git a/server/app/goauto/returnmatch/confirm_batch_test.go b/server/app/goauto/returnmatch/confirm_batch_test.go new file mode 100644 index 0000000..9c645e9 --- /dev/null +++ b/server/app/goauto/returnmatch/confirm_batch_test.go @@ -0,0 +1,103 @@ +package returnmatch + +import ( + "context" + "errors" + "fmt" + "net/http/httptest" + "testing" + + "github.com/gin-gonic/gin" + jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth" + "go-admin/app/goauto/models" + "gorm.io/gorm" +) + +// #349 reuses the existing single-record transaction; no production batch API. +func TestConfirmBatchExistingHTTPContract(t *testing.T) { + for _, tc := range []struct { + name, status, role string + code int + }{ + {"admin", "matched", "admin", 200}, + {"purchaser", "matched", "purchaser", 200}, + {"after_sales", "matched", "after_sales", 200}, + {"already_confirmed", "confirmed", "after_sales", 409}, + {"cancelled", "cancelled", "purchaser", 409}, + {"forbidden", "matched", "viewer", 403}, + } { + t.Run(tc.name, func(t *testing.T) { + db := testDB(t) + m := seedCancelMatch(t, db, tc.status) + w := httptest.NewRecorder() + c, _ := gin.CreateTestContext(w) + c.Request = httptest.NewRequest("POST", fmt.Sprintf("/return-matches/%d/confirm", m.ID), nil) + c.Params = gin.Params{{Key: "id", Value: fmt.Sprint(m.ID)}} + c.Set("JWT_PAYLOAD", jwt.MapClaims{"rolekey": tc.role, "username": "confirm-tester"}) + Handler{DB: db}.Confirm(c) + if w.Code != tc.code { + t.Fatalf("status=%d body=%s", w.Code, w.Body.String()) + } + var saved models.ReturnMatch + db.First(&saved, m.ID) + var logs int64 + db.Model(&models.ReturnMatchLog{}).Where("match_id = ?", m.ID).Count(&logs) + if tc.code == 200 { + if saved.Status != "confirmed" || saved.ConfirmedBy != "confirm-tester" || saved.ConfirmedAt == nil || saved.ActiveSYBProductID == nil || saved.ActiveYeekeReturnItemID == nil || logs != 1 { + t.Fatalf("confirmation audit or occupancy lost: %+v logs=%d", saved, logs) + } + } else if saved.Status != tc.status || logs != 0 { + t.Fatalf("rejected confirm changed state: %+v logs=%d", saved, logs) + } + }) + } +} + +func TestConfirmBatchOriginalRecordStateChanges(t *testing.T) { + db := testDB(t) + s := NewService(db) + if _, err := s.Confirm(context.Background(), 99999, "tester"); err != gorm.ErrRecordNotFound { + t.Fatalf("missing=%v", err) + } + m := seedCancelMatch(t, db, "matched") + if _, err := s.Cancel(context.Background(), m.ID, "other"); err != nil { + t.Fatal(err) + } + // Simulate a later rematch with the same product/return, but a new identity. + replacement := m + replacement.ID = 0 + replacement.CancelledAt = nil + replacement.CancelledBy = "" + if err := db.Create(&replacement).Error; err != nil { + t.Fatal(err) + } + if _, err := s.Confirm(context.Background(), m.ID, "batch"); err != errStateConflict { + t.Fatalf("stale original=%v", err) + } + if _, err := s.Confirm(context.Background(), replacement.ID, "reviewer"); err != nil { + t.Fatal(err) + } + if _, err := s.Confirm(context.Background(), replacement.ID, "repeat"); err != errStateConflict { + t.Fatalf("duplicate=%v", err) + } +} + +func TestConfirmBatchAuditFailureRollsBack(t *testing.T) { + db := testDB(t) + m := seedCancelMatch(t, db, "matched") + if err := db.Callback().Create().Before("gorm:create").Register("test:reject_confirm_log", func(tx *gorm.DB) { + if tx.Statement.Schema != nil && tx.Statement.Schema.Name == "ReturnMatchLog" { + tx.AddError(errors.New("synthetic audit failure")) + } + }); err != nil { + t.Fatal(err) + } + if _, err := NewService(db).Confirm(context.Background(), m.ID, "tester"); err == nil { + t.Fatal("expected audit failure") + } + var saved models.ReturnMatch + db.First(&saved, m.ID) + if saved.Status != "matched" || saved.ConfirmedAt != nil || saved.ActiveSYBProductID == nil || saved.ActiveYeekeReturnItemID == nil { + t.Fatalf("confirm did not roll back: %+v", saved) + } +} diff --git a/web/src/api/goauto/return-matches.js b/web/src/api/goauto/return-matches.js index 70dcd1d..074ccf1 100644 --- a/web/src/api/goauto/return-matches.js +++ b/web/src/api/goauto/return-matches.js @@ -12,8 +12,8 @@ export function batchMatchReturns(data) { return request({ url: '/api/admin/v1/return-matches/batch-match', method: 'post', data }) } -export function confirmReturnMatch(matchId) { - return request({ url: `/api/admin/v1/return-matches/${matchId}/confirm`, method: 'post' }) +export function confirmReturnMatch(matchId, options = {}) { + return request({ url: `/api/admin/v1/return-matches/${matchId}/confirm`, method: 'post', ...options }) } export function cancelReturnMatch(matchId, data, options = {}) { diff --git a/web/src/views/goauto/syb-products/index.vue b/web/src/views/goauto/syb-products/index.vue index f9e8edb..d0e1517 100644 --- a/web/src/views/goauto/syb-products/index.vue +++ b/web/src/views/goauto/syb-products/index.vue @@ -13,7 +13,7 @@ - 查询重置AI 匹配{{ aiMatchCandidates.length }}图搜采集{{ imageSearchRows.length }}创建采集{{ collectionCandidates.length }}创建采购{{ purchaseCandidates.length }}匹配退货{{ returnMatchCandidateIds.length }}取消匹配{{ returnCancelCandidates.length }} + 查询重置AI 匹配{{ aiMatchCandidates.length }}图搜采集{{ imageSearchRows.length }}创建采集{{ collectionCandidates.length }}创建采购{{ purchaseCandidates.length }}匹配退货{{ returnMatchCandidateIds.length }}取消匹配{{ returnCancelCandidates.length }}使用退货{{ returnConfirmCandidates.length }}
@@ -72,7 +72,7 @@ 未匹配 @@ -209,6 +209,25 @@ + +
+ 已处理 {{ returnConfirmResult.processed }} / {{ returnConfirmResult.total }} 条 + 成功 {{ returnConfirmResult.successCount }} 条 + 跳过 {{ returnConfirmResult.skippedCount }} 条 + 失败 {{ returnConfirmResult.failedCount }} 条 +
+ + +

仅标记已用退货,不修改已有采购任务,也不会自动让 Yeeke 发货。失败项仅在当前页仍为原待确认匹配时保留勾选;离页失败项仍保留在下表。

+ + + + + + + +
+
成功匹配 {{ returnMatchBatchResult.matchedCount }} 条 @@ -266,7 +285,7 @@

备注

- 保存备注 + 保存备注

操作日志

@@ -279,8 +298,8 @@
@@ -344,6 +363,7 @@ import { ElMessage } from 'element-plus' import { Search, RefreshLeft, ArrowDown } from '@element-plus/icons-vue' import quickLink from './quick-link' import returnCancel from './return-cancel' +import returnConfirm from './return-confirm' import { listSybProducts, getSybProduct, reparseSybProduct, correctSybProduct } from '@/api/goauto/syb-products' import { listSybShops } from '@/api/goauto/syb-shops' import { listDevices } from '@/api/goauto/devices' @@ -368,7 +388,7 @@ const RETURN_MATCH_BATCH_MAX = 500 export default { name: 'GoAutoSybProducts', components: { ShopeeProductDetailDrawer, PddProductDetailDrawer }, - mixins: [quickLink, returnCancel], + mixins: [quickLink, returnCancel, returnConfirm], setup() { return { Search, RefreshLeft, ArrowDown } }, data() { return { @@ -638,7 +658,7 @@ export default { }, async runBatchMatchReturns() { const ids = this.returnMatchCandidateIds - if (!ids.length || this.returnMatchBatchLoading || this.returnCancelBatchLoading || this.returnTransitionLoading || this.matchDetail.saving) return + if (!ids.length || this.returnMatchBatchLoading || this.returnConfirmBatchLoading || this.returnCancelBatchLoading || this.returnTransitionLoading || this.matchDetail.saving) return this.returnMatchBatchLoading = true try { const r = await batchMatchReturns({ sybProductIds: ids }) @@ -673,7 +693,7 @@ export default { await this.load() }, async saveMatchRemark() { - if (this.returnCancelBatchLoading || this.returnTransitionLoading || this.returnMatchBatchLoading || this.matchDetail.saving) return + if (this.returnConfirmBatchLoading || this.returnCancelBatchLoading || this.returnTransitionLoading || this.returnMatchBatchLoading || this.matchDetail.saving) return this.matchDetail.saving = true try { await remarkReturnMatch(this.matchDetail.id, { remark: this.matchDetail.remarkText }) diff --git a/web/src/views/goauto/syb-products/return-cancel.js b/web/src/views/goauto/syb-products/return-cancel.js index 83635a6..c894718 100644 --- a/web/src/views/goauto/syb-products/return-cancel.js +++ b/web/src/views/goauto/syb-products/return-cancel.js @@ -18,7 +18,7 @@ export default { returnCancelButtonReason() { if (this.loading || this.purchaseReadinessLoading || this.returnMatchLoading) return '正在读取处理阶段与退货匹配' if (this.returnMatchLoadError) return '退货匹配读取失败,请刷新重试' - if (this.returnCancelBatchLoading || this.returnMatchBatchLoading || this.returnTransitionLoading || this.matchDetail.saving) return '正在处理退货匹配,请稍候' + if (this.returnConfirmBatchLoading || this.returnCancelBatchLoading || this.returnMatchBatchLoading || this.returnTransitionLoading || this.matchDetail.saving) return '正在处理退货匹配,请稍候' if (!this.returnCancelCandidates.length) return '请勾选退货待确认的已匹配商品;已用退货不参与批量取消' return '' } @@ -30,7 +30,7 @@ export default { return this.purchaseReady(row).processStage === 'return_pending' && match?.status === 'matched' && Number(match.id) > 0 }, async runReturnTransition(action) { - if (this.returnCancelBatchLoading || this.returnMatchBatchLoading || this.returnTransitionLoading || this.matchDetail.saving) return + if (this.returnConfirmBatchLoading || this.returnCancelBatchLoading || this.returnMatchBatchLoading || this.returnTransitionLoading || this.matchDetail.saving) return this.returnTransitionLoading = true try { await action() } finally { this.returnTransitionLoading = false } }, diff --git a/web/src/views/goauto/syb-products/return-confirm.js b/web/src/views/goauto/syb-products/return-confirm.js new file mode 100644 index 0000000..2cbc7f1 --- /dev/null +++ b/web/src/views/goauto/syb-products/return-confirm.js @@ -0,0 +1,102 @@ +import { confirmReturnMatch, getReturnMatch } from '@/api/goauto/return-matches' + +const requestOptions = { suppressErrorMessage: true, suppressNetworkError: true } +function isUnauthorized(error) { + return error?.response?.status === 401 || error?.response?.data?.code === 401 || error?.message === 'Unauthorized' +} +const emptyResult = () => ({ open: false, items: [], total: 0, processed: 0, successCount: 0, skippedCount: 0, failedCount: 0, refreshError: '' }) + +export default { + data() { + return { returnConfirmBatchLoading: false, returnConfirmStopped: false, returnConfirmResult: emptyResult() } + }, + computed: { + returnConfirmCandidates() { return this.returnConfirmSnapshot().filter(item => item.eligible) }, + returnConfirmButtonReason() { + if (this.loading || this.purchaseReadinessLoading || this.returnMatchLoading) return '正在读取处理阶段与退货匹配' + if (this.returnMatchLoadError) return '退货匹配读取失败,请刷新重试' + if (this.returnConfirmBatchLoading || this.returnCancelBatchLoading || this.returnMatchBatchLoading || this.returnTransitionLoading || this.matchDetail.saving) return '正在处理退货匹配,请稍候' + if (!this.returnConfirmCandidates.length) return '请勾选当前页退货待确认的已匹配商品;已用退货不参与批量使用' + return '' + } + }, + beforeUnmount() { this.returnConfirmStopped = true }, + methods: { + returnConfirmSnapshot() { + const current = new Set(this.products.map(row => row.id)) + const seen = new Set() + return this.selectedProducts.filter(row => { + if (!current.has(row.id) || seen.has(row.id)) return false + seen.add(row.id); return true + }).map(row => ({ sybProductId: row.id, orderCode: row.orderCode, matchId: this.returnMatchByProductId[row.id]?.id, eligible: this.isReturnCancelCandidate(row) })) + }, + async runBatchConfirmReturns() { + if (!this.canPurchase || this.returnConfirmButtonReason) return + // Freeze original identities before asking. Never follow a later replacement match. + const snapshot = this.returnConfirmSnapshot() + const count = snapshot.filter(item => item.eligible).length + this.returnConfirmBatchLoading = true + try { + try { + await this.$confirm(`确认使用选中的 ${count} 条退货商品?确认后将标记为已用退货,不再创建采购任务。不修改已有采购任务,也不会自动让 Yeeke 发货。`, '使用退货', { type: 'warning', confirmButtonText: '确认使用', cancelButtonText: '返回' }) + } catch { return } + if (this.returnConfirmStopped) return + this.returnConfirmResult = { ...emptyResult(), open: true, total: snapshot.length } + const result = this.returnConfirmResult + let authExpired = false + for (const original of snapshot) { + const item = { ...original, status: 'skipped', reason: '', retryable: false } + if (!original.eligible) item.reason = '非退货待确认的原匹配,跳过' + else if (authExpired || this.returnConfirmStopped) { item.status = 'failed'; item.reason = '登录失效或已离开页面,未继续执行' } else { + try { + const response = await confirmReturnMatch(original.matchId, requestOptions) + if (response === false) throw new Error('Unauthorized') + item.status = 'success'; item.reason = '已用退货;不修改已有采购任务,不自动发货' + } catch (error) { + if (isUnauthorized(error)) { + authExpired = true; item.status = 'failed'; item.reason = '登录失效,请重新登录后检查原匹配' + } else if (error?.response?.status === 409 && error?.response?.data?.code === 'STATE_CONFLICT') { + item.reason = '原匹配已确认或已取消,未重复使用' + } else { + item.status = 'failed' + item.reason = error?.response ? '使用失败,请刷新检查原匹配' : '网络异常,使用结果未确认' + // Unknown write outcomes are recovered by reading only, not by repeating POST. + try { + const response = await getReturnMatch(original.matchId, requestOptions) + if (response === false) throw new Error('Unauthorized') + const match = response.data?.match + const sameOriginal = Number(match?.id) === Number(original.matchId) && Number(match?.sybProductId) === Number(original.sybProductId) + if (sameOriginal && ['confirmed', 'cancelled'].includes(match.status)) { + item.status = 'skipped'; item.reason = `回读原匹配已${match.status === 'confirmed' ? '确认使用' : '取消'},未重复操作` + } else { + item.retryable = sameOriginal && match.status === 'matched' + item.reason += item.retryable ? ';原匹配仍待确认,可手动重试' : ';原匹配无法确认,请刷新检查' + } + } catch (readError) { + if (isUnauthorized(readError)) authExpired = true + item.reason += ';回读失败,请刷新检查,不自动重试' + } + } + } + } + result.items.push(item); result.processed++ + result[`${item.status}Count`]++ + } + if (this.returnConfirmStopped || authExpired) return + const generation = this.loadGeneration + 1 + try { + await this.load(false, true) + if (generation !== this.loadGeneration || this.returnConfirmStopped) return + if (this.returnMatchLoadError || Object.values(this.purchaseReadiness).some(ready => ready.processNextAction === 'refresh')) { + result.refreshError = '刷新处理阶段或退货匹配失败,请刷新列表后重试'; return + } + const failed = new Map(result.items.filter(item => item.status === 'failed' && item.retryable).map(item => [item.sybProductId, item.matchId])) + await this.$nextTick() + if (generation !== this.loadGeneration || this.returnConfirmStopped) return + this.$refs.productTable?.clearSelection() + this.products.filter(row => failed.get(row.id) === this.returnMatchByProductId[row.id]?.id && this.isReturnCancelCandidate(row)).forEach(row => this.$refs.productTable?.toggleRowSelection(row, true)) + } catch { result.refreshError = '列表刷新失败;执行结果已保留,请手动刷新,勿盲目重复使用' } + } finally { this.returnConfirmBatchLoading = false } + } + } +} diff --git a/web/tests/e2e/syb-return-confirm.spec.ts b/web/tests/e2e/syb-return-confirm.spec.ts new file mode 100644 index 0000000..7267d73 --- /dev/null +++ b/web/tests/e2e/syb-return-confirm.spec.ts @@ -0,0 +1,114 @@ +import { expect, test, type Page, type BrowserContext } from '@playwright/test' + +const menus = [{ path: '/workbench', component: 'Layout', menuName: 'Workbench', title: '工作台', visible: '0', children: [{ path: '/syb-products', component: '/goauto/syb-products/index', menuName: 'GoAutoSybProducts', title: 'SYB 商品', visible: '0' }] }] +async function setup(page: Page, context: BrowserContext, mode = 'success', role = 'after_sales') { + await page.setViewportSize({ width: 1920, height: 1080 }) + await context.addCookies([{ name: 'Admin-Token', value: 'isolated-test-token', domain: 'localhost', path: '/' }]) + const writes: number[] = [] + const confirmed = new Set() + const lists: URL[] = [] + await page.route('**/api/**', async route => { + const url = new URL(route.request().url()); const pathname = url.pathname + if (pathname.startsWith('/src/api/')) return route.continue() + const reply = (data: unknown) => route.fulfill({ json: { code: 200, data } }) + if (pathname.endsWith('/api/v1/menurole')) return reply(menus) + if (pathname.endsWith('/api/v1/getinfo')) return reply({ roles: [role], name: '模拟售后', avatar: '', permissions: [] }) + if (pathname.endsWith('/api/admin/v1/syb-products')) { + lists.push(url) + const items = [1, 2, 3, 4].filter(id => url.searchParams.get('processStage') !== 'return_pending' || (id <= 2 && !confirmed.has(id))).map(id => ({ id, orderCode: `MOCK-${id}`, shopeeItemId: String(100 + id), shopeeProductId: 100 + id, imageUrl: '', productTitle: '模拟商品', quantity: 1, parseStatus: 'success' })) + return reply({ items, total: items.length }) + } + if (pathname.endsWith('/purchase-tasks/batch-preview')) return reply({ items: [1, 2, 3, 4].map(id => ({ sybProductId: id, processStage: confirmed.has(id) ? 'return_used' : id <= 2 ? 'return_pending' : id === 3 ? 'return_used' : 'purchase_ready', processStageLabel: confirmed.has(id) ? '已用退货' : id <= 2 ? '退货待确认' : id === 3 ? '已用退货' : '可创建采购', eligible: id === 4, collectionEligible: false, aiMatchEligible: false })) }) + if (pathname.endsWith('/return-matches')) { + if (mode === 'metadata-error') return route.fulfill({ status: 500, json: { code: 'INTERNAL' } }) + return reply({ items: [1, 2, 3].map(id => ({ id: id + 10, sybProductId: id, status: id <= 2 && !confirmed.has(id) ? 'matched' : 'confirmed', variationName: '模拟规格' })) }) + } + if (/\/return-matches\/\d+\/confirm$/.test(pathname)) { + const id = Number(pathname.split('/').at(-2)); writes.push(id) + expect(route.request().method()).toBe('POST') + if (mode === 'readback-confirmed') return route.fulfill({ status: 504, json: { code: 'TIMEOUT' } }) + if (mode === 'partial' && id === 12) return route.fulfill({ status: 500, json: { code: 'INTERNAL', message: '模拟使用失败' } }) + if (mode === 'auth') return route.fulfill({ status: 401, json: { code: 401, message: '模拟登录失效' } }) + if (mode === 'conflict' && id === 12) return route.fulfill({ status: 409, json: { code: 'STATE_CONFLICT' } }) + await new Promise(resolve => setTimeout(resolve, 150)) + confirmed.add(id - 10); return reply({ item: { id, status: 'confirmed' } }) + } + if (/\/return-matches\/\d+$/.test(pathname)) { + const id = Number(pathname.split('/').at(-1)); return reply({ match: { id, sybProductId: id - 10, status: mode === 'readback-confirmed' || confirmed.has(id - 10) ? 'confirmed' : 'matched' }, logs: [] }) + } + return reply({ items: [], total: 0 }) + }) + await page.goto('/#/syb-products') + await expect(page.getByRole('cell', { name: 'MOCK-1', exact: true })).toBeVisible() + return { writes, lists } +} + +test('v2 button order, one confirmation, no write on return, progress and mutual exclusion', async ({ page, context }) => { + const { writes } = await setup(page, context) + const use = page.getByRole('button', { name: /使用退货\s*0/ }) + await expect(use).toBeDisabled() + const toolbar = await page.locator('.toolbar-actions button').allTextContents() + expect(toolbar.findIndex(t => t.includes('匹配退货'))).toBeLessThan(toolbar.findIndex(t => t.includes('取消匹配'))) + expect(toolbar.findIndex(t => t.includes('取消匹配'))).toBeLessThan(toolbar.findIndex(t => t.includes('使用退货'))) + await page.locator('thead .el-checkbox').first().click() + await page.getByRole('button', { name: /使用退货\s*2/ }).click() + await expect(page.getByText(/不会自动让 Yeeke 发货/, { exact: false }).last()).toBeVisible() + await page.getByRole('button', { name: '返回', exact: true }).click() + expect(writes).toEqual([]) + await page.getByRole('button', { name: /使用退货\s*2/ }).click() + await page.getByRole('button', { name: '确认使用', exact: true }).click() + await expect(page.getByRole('button', { name: '返回列表', exact: true })).toBeDisabled() + await expect(page.getByRole('button', { name: /取消匹配\s*2/ }).first()).toBeDisabled() + await expect(page.getByRole('button', { name: '返回列表', exact: true })).toBeEnabled() + expect(writes).toEqual([11, 12]) + await expect(page.getByText('成功 2 条', { exact: true })).toBeVisible() + await expect(page.getByText('跳过 1 条', { exact: true })).toBeVisible() + await page.getByRole('button', { name: '返回列表', exact: true }).click() + await expect(page.getByText('已选择 0 条', { exact: true })).toBeVisible() +}) + +for (const mode of ['partial', 'conflict', 'auth', 'readback-confirmed']) { + test(`${mode}: independent outcomes, failed selection, auth stop and readback without retry`, async ({ page, context }) => { + const { writes } = await setup(page, context, mode) + await page.locator('thead .el-checkbox').first().click() + await page.getByRole('button', { name: /使用退货\s*2/ }).click() + await page.getByRole('button', { name: '确认使用', exact: true }).click() + await expect(page.getByRole('button', { name: '返回列表', exact: true })).toBeEnabled() + expect(writes).toEqual(mode === 'auth' ? [11] : [11, 12]) + const summary = mode === 'auth' ? '失败 2 条' : mode === 'partial' ? '失败 1 条' : mode === 'conflict' ? '跳过 2 条' : '跳过 3 条' + await expect(page.getByText(summary, { exact: true })).toBeVisible() + await page.getByRole('button', { name: '返回列表', exact: true }).click() + if (mode === 'partial') { + await expect(page.getByText('已选择 1 条', { exact: true })).toBeVisible() + await expect(page.getByRole('button', { name: /使用退货\s*1/ })).toBeEnabled() + } + }) +} + +test('metadata load error disables use', async ({ page, context }) => { + await setup(page, context, 'metadata-error') + await page.locator('thead .el-checkbox').first().click() + await expect(page.getByRole('button', { name: /使用退货\s*0/ })).toBeDisabled() +}) + +test('viewer cannot see use button or selection', async ({ page, context }) => { + await setup(page, context, 'success', 'viewer') + await expect(page.getByRole('button', { name: /使用退货/ })).toHaveCount(0) + await expect(page.locator('thead .el-checkbox')).toHaveCount(0) +}) + +test('pending filter and page size retained; used rows disappear', async ({ page, context }) => { + const { lists } = await setup(page, context) + await page.locator('.el-form-item').filter({ hasText: '处理阶段' }).locator('.el-select__wrapper').click() + await page.getByRole('option', { name: '退货待确认', exact: true }).click() + await page.getByRole('button', { name: '查询', exact: true }).click() + await expect(page.getByRole('cell', { name: 'MOCK-4', exact: true })).toHaveCount(0) + await page.locator('thead .el-checkbox').first().click() + await page.getByRole('button', { name: /使用退货\s*2/ }).click() + await page.getByRole('button', { name: '确认使用', exact: true }).click() + await expect(page.getByRole('button', { name: '返回列表', exact: true })).toBeEnabled() + expect(lists.at(-1)?.searchParams.get('processStage')).toBe('return_pending') + expect(lists.at(-1)?.searchParams.get('pageSize')).toBe('200') + await page.getByRole('button', { name: '返回列表', exact: true }).click() + await expect(page.getByText('暂无 SYB 商品明细', { exact: true })).toBeVisible() +}) diff --git a/web/tests/unit/syb-return-cancel.test.cjs b/web/tests/unit/syb-return-cancel.test.cjs index b32f49f..54dc9b5 100644 --- a/web/tests/unit/syb-return-cancel.test.cjs +++ b/web/tests/unit/syb-return-cancel.test.cjs @@ -100,7 +100,7 @@ test('legacy interceptor false/6401 result is auth failure, not cancellation suc test('pending rows can be selected for cancel but never become collection, purchase, image-search or AI candidates', () => { const script = fs.readFileSync(path.join(__dirname, '../../src/views/goauto/syb-products/index.vue'), 'utf8').split('')[0].replace(/import[^\n]+\n/g, '').replace('export default', 'return') - const options = new Function('quickLink', 'returnCancel', 'ShopeeProductDetailDrawer', 'PddProductDetailDrawer', script)({}, {}, {}, {}) + const options = new Function('quickLink', 'returnCancel', 'returnConfirm', 'ShopeeProductDetailDrawer', 'PddProductDetailDrawer', script)({}, {}, {}, {}, {}) const row = { id: 1, shopeeProductId: 11, imageUrl: 'mock-image' } const ready = { processStage: 'return_pending', eligible: true, collectionEligible: true, aiMatchEligible: true, pddProductId: 9 } const vm = { ...options.methods, selectedProducts: [row], purchaseReadiness: { 1: ready }, canPurchase: true } diff --git a/web/tests/unit/syb-return-confirm.test.cjs b/web/tests/unit/syb-return-confirm.test.cjs new file mode 100644 index 0000000..97f08ee --- /dev/null +++ b/web/tests/unit/syb-return-confirm.test.cjs @@ -0,0 +1,112 @@ +const { test } = require('node:test') +const assert = require('node:assert/strict') +const fs = require('node:fs') +const path = require('node:path') +const readOptions = (file, dependencies) => new Function(...Object.keys(dependencies), fs.readFileSync(path.join(__dirname, '../../src/views/goauto/syb-products', file), 'utf8').replace(/import[^\n]+\n/g, '').replace('export default', 'return'))(...Object.values(dependencies)) +const tick = () => new Promise(resolve => setImmediate(resolve)) +function instance(overrides = {}) { + const writes = []; const reads = []; const selected = []; const confirmations = [] + const dependencies = { + confirmReturnMatch: async (id, options) => { writes.push({ id, options }); return { code: 200 } }, + getReturnMatch: async id => { reads.push(id); return { data: { match: { id, sybProductId: id - 10, status: 'matched' } } } }, ...overrides + } + const options = readOptions('return-confirm.js', dependencies) + const cancel = readOptions('return-cancel.js', { cancelReturnMatch: async () => {}, getReturnMatch: dependencies.getReturnMatch }) + const vm = { ...cancel.methods, ...options.methods, ...cancel.data(), ...options.data(), canPurchase: true, loading: false, returnMatchLoading: false, purchaseReadinessLoading: false, matchDetail: {}, loadGeneration: 0, + products: [1, 2, 3].map(id => ({ id, orderCode: `TEST-${id}` })), + purchaseReadiness: { 1: { processStage: 'return_pending' }, 2: { processStage: 'return_pending' }, 3: { processStage: 'return_used' } }, + returnMatchByProductId: { 1: { id: 11, status: 'matched' }, 2: { id: 12, status: 'matched' }, 3: { id: 13, status: 'confirmed' } }, + purchaseReady(row) { return this.purchaseReadiness[row.id] || {} }, + $confirm: async text => { confirmations.push(text) }, $nextTick: async () => {}, + $refs: { productTable: { clearSelection: () => selected.splice(0), toggleRowSelection: row => selected.push(row.id) } }, + load: async function() { this.loadGeneration++ } + } + vm.selectedProducts = [...vm.products] + Object.entries({ ...cancel.computed, ...options.computed }).forEach(([key, fn]) => Object.defineProperty(vm, key, { get: () => fn.call(vm) })) + return { vm, options, writes, reads, selected, confirmations } +} +test('current-page count, deduplication, mixed rows, original confirm API and one confirmation', async () => { + const { vm, writes, confirmations } = instance() + vm.selectedProducts.push(vm.products[0], { id: 99 }) + assert.equal(vm.returnConfirmCandidates.length, 2) + await vm.runBatchConfirmReturns() + assert.deepEqual(writes.map(w => w.id), [11, 12]) + assert.ok(writes.every(w => w.options.suppressErrorMessage && w.options.suppressNetworkError)) + assert.equal(confirmations.length, 1); assert.match(confirmations[0], /2 条/); assert.match(confirmations[0], /不会自动让 Yeeke 发货/) + assert.equal(vm.returnConfirmResult.successCount, 2); assert.equal(vm.returnConfirmResult.skippedCount, 1) + assert.equal(vm.returnConfirmBatchLoading, false) +}) +test('permission, metadata, busy and empty states prohibit writes', async () => { + for (const [key, value] of [['canPurchase', false], ['loading', true], ['returnMatchLoadError', true], ['returnMatchLoading', true], ['purchaseReadinessLoading', true], ['returnTransitionLoading', true], ['returnMatchBatchLoading', true], ['returnCancelBatchLoading', true]]) { + const { vm, writes } = instance(); vm[key] = value; await vm.runBatchConfirmReturns(); assert.equal(writes.length, 0, key) + } + const { vm, writes } = instance(); vm.matchDetail.saving = true; await vm.runBatchConfirmReturns(); assert.equal(writes.length, 0) + vm.matchDetail.saving = false; vm.selectedProducts = []; await vm.runBatchConfirmReturns(); assert.equal(writes.length, 0) +}) +test('return dismisses without a write or result; confirm busy blocks cancel and single transitions', async () => { + const { vm, writes } = instance(); vm.$confirm = async () => { throw new Error('cancel') }; await vm.runBatchConfirmReturns() + assert.equal(writes.length, 0); assert.equal(vm.returnConfirmResult.open, false); assert.equal(vm.returnConfirmBatchLoading, false) + vm.returnConfirmBatchLoading = true; let ran = false + assert.match(vm.returnCancelButtonReason, /正在处理/) + await vm.runReturnTransition(async () => { ran = true }); assert.equal(ran, false) +}) +test('serial, frozen identities and no duplicate execution while waiting', async () => { + let release; const wait = new Promise(resolve => { release = resolve }); const writes = [] + const { vm } = instance({ confirmReturnMatch: async id => { writes.push(id); if (id === 11) await wait } }) + const running = vm.runBatchConfirmReturns(); await tick() + vm.returnMatchByProductId[2].id = 99; vm.selectedProducts = []; await vm.runBatchConfirmReturns() + assert.deepEqual(writes, [11]); release(); await running; assert.deepEqual(writes, [11, 12]) +}) +test('partial business failure keeps only readback-proven current-page failed selection', async () => { + const { vm, selected, reads } = instance({ confirmReturnMatch: async id => { if (id === 12) throw { response: { status: 500 } } } }) + await vm.runBatchConfirmReturns(); assert.equal(vm.returnConfirmResult.failedCount, 1); assert.deepEqual(reads, [12]); assert.deepEqual(selected, [2]) +}) +test('state conflict skips original; neither readback nor replacement write', async () => { + const { vm, reads } = instance({ confirmReturnMatch: async () => { throw { response: { status: 409, data: { code: 'STATE_CONFLICT' } } } } }) + await vm.runBatchConfirmReturns(); assert.equal(vm.returnConfirmResult.skippedCount, 3); assert.equal(reads.length, 0) +}) +for (const status of ['confirmed', 'cancelled', 'matched']) { + test(`unknown outcome reads original ${status} once, never resends`, async () => { + let writes = 0 + const { vm, reads, selected } = instance({ confirmReturnMatch: async () => { writes++; throw new Error('timeout') }, getReturnMatch: async id => { reads.push(id); return { data: { match: { id, sybProductId: id - 10, status } } } } }) + await vm.runBatchConfirmReturns(); assert.equal(writes, 2); assert.deepEqual(reads, [11, 12]) + assert.equal(vm.returnConfirmResult.successCount, 0) + assert.deepEqual(selected, status === 'matched' ? [1, 2] : []) + assert.equal(vm.returnConfirmResult.skippedCount, status === 'matched' ? 1 : 3) + }) +} +test('unreadable/mismatched original never treated as confirmed or retryable', async () => { + for (const getReturnMatch of [async () => { throw new Error('offline') }, async id => ({ data: { match: { id: id + 1, sybProductId: 999, status: 'confirmed' } } })]) { + const { vm, selected } = instance({ confirmReturnMatch: async () => { throw new Error('timeout') }, getReturnMatch }) + await vm.runBatchConfirmReturns(); assert.equal(vm.returnConfirmResult.failedCount, 2); assert.deepEqual(selected, []) + } +}) +for (const response of [false, new Error('Unauthorized'), { response: { status: 401 } }]) { + test(`auth failure/legacy false stops remaining writes (${String(response)})`, async () => { + let writes = 0 + const { vm } = instance({ confirmReturnMatch: async () => { writes++; if (response === false) return false; throw response } }) + await vm.runBatchConfirmReturns(); assert.equal(writes, 1); assert.equal(vm.returnConfirmResult.failedCount, 2); assert.equal(vm.returnConfirmBatchLoading, false) + assert.match(vm.returnConfirmResult.items[1].reason, /未继续执行/) + }) +} +test('login failure during readback stops remaining POSTs', async () => { + let writes = 0 + const { vm } = instance({ confirmReturnMatch: async () => { writes++; throw new Error('timeout') }, getReturnMatch: async () => { throw new Error('Unauthorized') } }) + await vm.runBatchConfirmReturns(); assert.equal(writes, 1); assert.equal(vm.returnConfirmResult.failedCount, 2) +}) +test('new generation, replaced original and vanished failed row cannot restore old selection', async () => { + for (const load of [async function() { this.loadGeneration += 2 }, async function() { this.loadGeneration++; this.products = [] }, async function() { this.loadGeneration++; this.returnMatchByProductId[1].id = 99; this.returnMatchByProductId[2].id = 98 }]) { + const { vm, selected } = instance({ confirmReturnMatch: async () => { throw new Error('timeout') } }); vm.load = load + await vm.runBatchConfirmReturns(); assert.equal(vm.returnConfirmResult.failedCount, 2); assert.deepEqual(selected, []) + } +}) +test('refresh failure keeps completed result and does not write again', async () => { + const { vm, writes } = instance(); vm.load = async () => { throw new Error('offline') }; await vm.runBatchConfirmReturns() + assert.match(vm.returnConfirmResult.refreshError, /刷新失败/); assert.equal(vm.returnConfirmResult.successCount, 2); assert.equal(writes.length, 2) +}) +test('unmount stops remaining writes after in-flight response', async () => { + let release; const wait = new Promise(resolve => { release = resolve }); let writes = 0 + const { vm, options } = instance({ confirmReturnMatch: async () => { writes++; await wait } }) + const running = vm.runBatchConfirmReturns(); await tick(); options.beforeUnmount.call(vm); release(); await running + assert.equal(writes, 1); assert.equal(vm.returnConfirmBatchLoading, false) +})