feat: batch use pending return matches #349

This commit is contained in:
QiuSW
2026-09-29 10:21:28 +08:00
parent a4c7b5e97b
commit 4280115e11
8 changed files with 464 additions and 13 deletions
@@ -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)
}
}
+2 -2
View File
@@ -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 = {}) {
+28 -8
View File
@@ -13,7 +13,7 @@
<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>
<el-form-item label="处理阶段"><el-select v-model="query.processStage" clearable placeholder="全部" style="width: 132px"><el-option v-for="item in processStageOptions" :key="item.value" :label="item.label" :value="item.value" /></el-select></el-form-item>
<el-form-item class="toolbar-actions"><el-button type="primary" :icon="Search" @click="search">查询</el-button><el-button :icon="RefreshLeft" @click="reset">重置</el-button><el-tooltip v-if="canPurchase" :content="aiMatchButtonReason" :disabled="!aiMatchButtonReason" placement="top"><span class="action-button-wrap"><el-button :loading="specMatchLoading" :disabled="purchaseReadinessLoading || specMatchLoading || aiMatchCandidates.length === 0 || aiMatchButtonOverLimit" @click="runBatchSpecMatch">AI 匹配<span class="action-count">{{ aiMatchCandidates.length }}</span></el-button></span></el-tooltip><el-tooltip v-if="canPurchase" :content="imageSearchButtonReason" :disabled="!imageSearchButtonReason" placement="top"><span class="action-button-wrap"><el-button type="success" plain :disabled="imageSearchRows.length === 0 || imageSearchButtonOverLimit" @click="openImageSearchBatch">图搜采集<span class="action-count">{{ imageSearchRows.length }}</span></el-button></span></el-tooltip><el-tooltip v-if="canPurchase" :content="collectionButtonReason" :disabled="!collectionButtonReason" placement="top"><span class="action-button-wrap"><el-button type="primary" :loading="purchaseReadinessLoading" :disabled="purchaseReadinessLoading || specMatchLoading || collectionCandidates.length === 0 || collectionButtonOverLimit" @click="openCollectionBatch">创建采集<span class="action-count action-count-primary">{{ collectionCandidates.length }}</span></el-button></span></el-tooltip><el-tooltip v-if="canPurchase" :content="purchaseButtonReason" :disabled="!purchaseButtonReason" placement="top"><span class="action-button-wrap"><el-button type="primary" :loading="purchaseReadinessLoading" :disabled="purchaseReadinessLoading || specMatchLoading || purchaseCandidates.length === 0 || purchaseButtonOverLimit" @click="openPurchaseBatch">创建采购<span class="action-count action-count-primary">{{ purchaseCandidates.length }}</span></el-button></span></el-tooltip><el-tooltip v-if="canPurchase" :content="returnMatchButtonReason" :disabled="!returnMatchButtonReason" placement="top"><span class="action-button-wrap"><el-button :loading="returnMatchBatchLoading" :disabled="purchaseReadinessLoading || returnMatchBatchLoading || returnCancelBatchLoading || returnTransitionLoading || matchDetail.saving || returnMatchCandidateIds.length === 0 || returnMatchButtonOverLimit" @click="runBatchMatchReturns">匹配退货<span class="action-count">{{ returnMatchCandidateIds.length }}</span></el-button></span></el-tooltip><el-tooltip v-if="canPurchase" :content="returnCancelButtonReason" :disabled="!returnCancelButtonReason" placement="top"><span class="action-button-wrap"><el-button :loading="returnCancelBatchLoading" :disabled="Boolean(returnCancelButtonReason)" @click="runBatchCancelReturns">取消匹配<span class="action-count">{{ returnCancelCandidates.length }}</span></el-button></span></el-tooltip></el-form-item>
<el-form-item class="toolbar-actions"><el-button type="primary" :icon="Search" @click="search">查询</el-button><el-button :icon="RefreshLeft" @click="reset">重置</el-button><el-tooltip v-if="canPurchase" :content="aiMatchButtonReason" :disabled="!aiMatchButtonReason" placement="top"><span class="action-button-wrap"><el-button :loading="specMatchLoading" :disabled="purchaseReadinessLoading || specMatchLoading || aiMatchCandidates.length === 0 || aiMatchButtonOverLimit" @click="runBatchSpecMatch">AI 匹配<span class="action-count">{{ aiMatchCandidates.length }}</span></el-button></span></el-tooltip><el-tooltip v-if="canPurchase" :content="imageSearchButtonReason" :disabled="!imageSearchButtonReason" placement="top"><span class="action-button-wrap"><el-button type="success" plain :disabled="imageSearchRows.length === 0 || imageSearchButtonOverLimit" @click="openImageSearchBatch">图搜采集<span class="action-count">{{ imageSearchRows.length }}</span></el-button></span></el-tooltip><el-tooltip v-if="canPurchase" :content="collectionButtonReason" :disabled="!collectionButtonReason" placement="top"><span class="action-button-wrap"><el-button type="primary" :loading="purchaseReadinessLoading" :disabled="purchaseReadinessLoading || specMatchLoading || collectionCandidates.length === 0 || collectionButtonOverLimit" @click="openCollectionBatch">创建采集<span class="action-count action-count-primary">{{ collectionCandidates.length }}</span></el-button></span></el-tooltip><el-tooltip v-if="canPurchase" :content="purchaseButtonReason" :disabled="!purchaseButtonReason" placement="top"><span class="action-button-wrap"><el-button type="primary" :loading="purchaseReadinessLoading" :disabled="purchaseReadinessLoading || specMatchLoading || purchaseCandidates.length === 0 || purchaseButtonOverLimit" @click="openPurchaseBatch">创建采购<span class="action-count action-count-primary">{{ purchaseCandidates.length }}</span></el-button></span></el-tooltip><el-tooltip v-if="canPurchase" :content="returnMatchButtonReason" :disabled="!returnMatchButtonReason" placement="top"><span class="action-button-wrap"><el-button :loading="returnMatchBatchLoading" :disabled="purchaseReadinessLoading || returnMatchBatchLoading || returnConfirmBatchLoading || returnCancelBatchLoading || returnTransitionLoading || matchDetail.saving || returnMatchCandidateIds.length === 0 || returnMatchButtonOverLimit" @click="runBatchMatchReturns">匹配退货<span class="action-count">{{ returnMatchCandidateIds.length }}</span></el-button></span></el-tooltip><el-tooltip v-if="canPurchase" :content="returnCancelButtonReason" :disabled="!returnCancelButtonReason" placement="top"><span class="action-button-wrap"><el-button :loading="returnCancelBatchLoading" :disabled="Boolean(returnCancelButtonReason)" @click="runBatchCancelReturns">取消匹配<span class="action-count">{{ returnCancelCandidates.length }}</span></el-button></span></el-tooltip><el-tooltip v-if="canPurchase" :content="returnConfirmButtonReason" :disabled="!returnConfirmButtonReason" placement="top"><span class="action-button-wrap"><el-button type="success" plain :loading="returnConfirmBatchLoading" :disabled="Boolean(returnConfirmButtonReason)" @click="runBatchConfirmReturns">使用退货<span class="action-count">{{ returnConfirmCandidates.length }}</span></el-button></span></el-tooltip></el-form-item>
</div>
<div class="search-row search-row-secondary">
<el-form-item label="创建时间"><el-date-picker v-model="query.createdAtRange" type="daterange" value-format="YYYY-MM-DD" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" clearable /></el-form-item>
@@ -72,7 +72,7 @@
<div class="quick-link-actions">
<el-button type="primary" link @click="openMatchDetail(returnMatchByProductId[row.id].id)">查看对比</el-button>
<el-button v-if="canPurchase" type="primary" link @click="openMatchDetail(returnMatchByProductId[row.id].id, true)">备注</el-button>
<el-button v-if="canPurchase" type="danger" link :disabled="returnCancelBatchLoading || returnTransitionLoading || returnMatchBatchLoading || matchDetail.saving" @click="quickCancelMatch(returnMatchByProductId[row.id].id)">取消匹配</el-button>
<el-button v-if="canPurchase" type="danger" link :disabled="returnConfirmBatchLoading || returnCancelBatchLoading || returnTransitionLoading || returnMatchBatchLoading || matchDetail.saving" @click="quickCancelMatch(returnMatchByProductId[row.id].id)">取消匹配</el-button>
</div>
</template>
<span v-else class="muted">未匹配</span>
@@ -209,6 +209,25 @@
<template #footer><el-button type="primary" :disabled="returnCancelBatchLoading" @click="returnCancelResult.open = false">返回列表</el-button></template>
</el-dialog>
<el-dialog v-model="returnConfirmResult.open" :title="returnConfirmBatchLoading ? '正在使用退货' : '批量使用退货结果'" width="820px" :close-on-click-modal="false" :close-on-press-escape="!returnConfirmBatchLoading" :show-close="!returnConfirmBatchLoading">
<div aria-live="polite" class="result-summary">
<span>已处理 {{ returnConfirmResult.processed }} / {{ returnConfirmResult.total }} 条</span>
<span class="success-text">成功 {{ returnConfirmResult.successCount }} 条</span>
<span>跳过 {{ returnConfirmResult.skippedCount }} 条</span>
<span class="danger-text">失败 {{ returnConfirmResult.failedCount }} 条</span>
</div>
<el-progress v-if="returnConfirmBatchLoading" :percentage="returnConfirmResult.total ? Math.round(returnConfirmResult.processed / returnConfirmResult.total * 100) : 0" />
<el-alert v-if="returnConfirmResult.refreshError" :title="returnConfirmResult.refreshError" type="warning" :closable="false" show-icon />
<p class="muted">仅标记已用退货,不修改已有采购任务,也不会自动让 Yeeke 发货。失败项仅在当前页仍为原待确认匹配时保留勾选;离页失败项仍保留在下表。</p>
<el-table :data="returnConfirmResult.items" border size="small" max-height="420" empty-text="正在处理,请稍候">
<el-table-column label="SYB 订单" prop="orderCode" min-width="180" />
<el-table-column label="原匹配编号" prop="matchId" width="100" />
<el-table-column label="结果" width="90"><template #default="{ row }">{{ { success: '成功', skipped: '跳过', failed: '失败' }[row.status] }}</template></el-table-column>
<el-table-column label="说明" prop="reason" min-width="280" />
</el-table>
<template #footer><el-button type="primary" :disabled="returnConfirmBatchLoading" @click="returnConfirmResult.open = false">返回列表</el-button></template>
</el-dialog>
<el-dialog v-model="returnMatchBatchResult.open" title="批量匹配退货结果" width="820px">
<div class="purchase-summary" aria-live="polite">
<span class="success-text">成功匹配 <strong>{{ returnMatchBatchResult.matchedCount }}</strong> 条</span>
@@ -266,7 +285,7 @@
<h3 class="section-title">备注</h3>
<el-input ref="matchRemarkInput" v-model="matchDetail.remarkText" type="textarea" :rows="2" maxlength="500" show-word-limit :disabled="!canPurchase" />
<div class="drawer-actions">
<el-button v-if="canPurchase" :loading="matchDetail.saving" @click="saveMatchRemark">保存备注</el-button>
<el-button v-if="canPurchase" :loading="matchDetail.saving" :disabled="returnConfirmBatchLoading || returnCancelBatchLoading || returnTransitionLoading || returnMatchBatchLoading" @click="saveMatchRemark">保存备注</el-button>
</div>
<h3 class="section-title">操作日志</h3>
<el-table :data="matchDetail.data.logs" border size="small" max-height="220" empty-text="暂无日志">
@@ -279,8 +298,8 @@
</div>
<template #footer>
<el-button @click="matchDetail.open = false">关闭</el-button>
<el-button v-if="canPurchase && matchDetail.data && matchDetail.data.match.status === 'matched'" type="success" :disabled="returnCancelBatchLoading || returnTransitionLoading || returnMatchBatchLoading || matchDetail.saving" @click="confirmMatchDetail">确认</el-button>
<el-button v-if="canPurchase && matchDetail.data && matchDetail.data.match.status !== 'cancelled'" type="danger" :disabled="returnCancelBatchLoading || returnTransitionLoading || returnMatchBatchLoading || matchDetail.saving" @click="cancelMatchDetail">取消匹配</el-button>
<el-button v-if="canPurchase && matchDetail.data && matchDetail.data.match.status === 'matched'" type="success" :disabled="returnConfirmBatchLoading || returnCancelBatchLoading || returnTransitionLoading || returnMatchBatchLoading || matchDetail.saving" @click="confirmMatchDetail">确认</el-button>
<el-button v-if="canPurchase && matchDetail.data && matchDetail.data.match.status !== 'cancelled'" type="danger" :disabled="returnConfirmBatchLoading || returnCancelBatchLoading || returnTransitionLoading || returnMatchBatchLoading || matchDetail.saving" @click="cancelMatchDetail">取消匹配</el-button>
</template>
</el-dialog>
@@ -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 })
@@ -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 }
},
@@ -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 }
}
}
}
+114
View File
@@ -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<number>()
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()
})
+1 -1
View File
@@ -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('<script>')[1].split('</script>')[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 }
+112
View File
@@ -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)
})