Compare commits

..
22 changed files with 464 additions and 956 deletions
@@ -1,126 +0,0 @@
package cn.ilapage.goauto.agent.automation
/** Current-capture evidence only. No clicks, historical selection proof, or whole-screen text fallback. */
internal object PurchaseFinalSpecVerifier {
private fun normalize(value: String) = SpecValueNormalizer.normalizeFinalConfirmation(value)
fun verify(snapshot: UiSnapshot, input: PurchaseExecutionInput, diagnostic: (String) -> Unit) {
val config = PurchaseRehearsalExecutor.DEFAULT_COLLECTOR
val byPath = snapshot.nodes.associateBy(SnapshotNode::path)
fun within(node: SnapshotNode, container: SnapshotNode): Boolean {
val visited = mutableSetOf<String>()
var current: SnapshotNode? = node
while (current != null && visited.add(current.path)) {
if (current.path == container.path) return true
current = current.parentPath?.let(byPath::get)
}
return false
}
fun contained(node: SnapshotNode, container: SnapshotNode) =
node.bounds.width > 0 && node.bounds.height > 0 &&
node.bounds.left >= container.bounds.left && node.bounds.right <= container.bounds.right &&
node.bounds.top >= container.bounds.top && node.bounds.bottom <= container.bounds.bottom
val original = PddScreenParser.parse(snapshot, config, input.goodsId, null, forFinalConfirmation = true)
val fullPanel = boundedQuantityPanel(snapshot).takeIf { original.specPanelOpen }
// #331/#335 sheet ancestry, as represented by SpecPanelFixtures.sheet and taskOptionDedupSheet.
// The inner scroll list is not the full sheet: summary and quantity may be its siblings.
val scoped = fullPanel?.let { panel ->
val nodes = snapshot.nodes.filter { node ->
(within(node, panel) && contained(node, panel)) ||
(node.parentPath == null && node.label.isBlank() && !node.clickable)
}
PddScreenParser.parse(snapshot.copy(nodes = nodes), config, input.goodsId, null, forFinalConfirmation = true)
.takeIf { it.specPanelOpen }
}
val optionScope = if (scoped != null) fullPanel else original.specPanelContainer
val dimensions = (scoped ?: original).dimensions.groupBy(VisibleDimension::key).mapValues { (_, groups) ->
val options = groups.flatMap(VisibleDimension::values).filter { option ->
optionScope != null && within(option.node, optionScope) && contained(option.node, optionScope)
}
// A blank clickable wrapper and its single text child may survive optionBlock separately.
// The #331 size fixture exposes exactly the same rectangle for both. Aggregate only a
// same-value ancestor chain with that physical rectangle, never same-label siblings.
options.groupBy { option ->
options.filter { other -> other.node.bounds == option.node.bounds &&
normalize(other.text) == normalize(option.text) && within(option.node, other.node)
}.minBy { it.node.path.length }.node.path
}.values.map { members ->
members.first().let { first -> first.copy(
available = members.all(VisibleSpecValue::available),
node = first.node.copy(
selected = members.any { it.node.selected },
checked = members.any { it.node.checked },
),
) }
}
}
val summaries = scoped?.finalSelectionSummaries.orEmpty().map { raw ->
// Only the anchored recognized prefix and its optional colon are removed.
val trimmed = raw.trim()
val prefix = config.textAliases.selection.selectedPrefixes.firstOrNull(trimmed::startsWith)
val value = if (prefix == null) trimmed else trimmed.removePrefix(prefix).trimStart().let {
if (it.startsWith(':') || it.startsWith(':')) it.drop(1) else it
}
normalize(value)
}.distinct()
val targets = linkedMapOf("color" to normalize(input.mappedColor), "size" to normalize(input.mappedSize))
.filterValues(String::isNotBlank)
fun reject(dimension: String, stage: String, selected: Boolean = false, conflict: Boolean = false): Nothing {
val detail = "finalSpec;dimension=$dimension;stage=$stage;summaryPresent=${if (summaries.isNotEmpty()) 1 else 0};" +
"selectedFound=${if (selected) 1 else 0};conflict=${if (conflict) 1 else 0}"
diagnostic(detail)
throw PurchaseLiveException("PURCHASE_SPEC_NOT_MATCHED", "创建订单前规格复核失败;$detail")
}
if (targets.isEmpty()) reject("none", "missing_target")
val selectedProof = mutableSetOf<String>()
targets.forEach { (dimension, target) ->
val options = dimensions[dimension].orEmpty()
val selected = options.filter { it.node.selected || it.node.checked }
// Parsed text already follows the established UI trailing-price separation contract.
// The final-only normalizer removes no additional content from values, input or summary.
val exact = options.filter { normalize(it.text) == target }
if (selected.any { normalize(it.text) != target }) reject(dimension, "selected_conflict", selected = true, conflict = true)
if (exact.size > 1) reject(dimension, "candidate_collision", selected.isNotEmpty(), conflict = true)
if (exact.any { !it.available }) reject(dimension, "unavailable", selected.isNotEmpty(), conflict = true)
if (exact.any { it.node.selected || it.node.checked }) selectedProof += dimension
}
if (summaries.size > 1) reject(targets.keys.first(), "summary_conflict", selectedProof.isNotEmpty(), conflict = true)
val summary = summaries.singleOrNull()
// Evidence only supports color then size with a space. Do not guess reverse order or comma separators.
val expected = targets.values.joinToString(" ")
if (summary != null && targets.size == 2) {
val colors = (dimensions["color"].orEmpty().map { normalize(it.text) } + targets.getValue("color")).distinct()
val sizes = (dimensions["size"].orEmpty().map { normalize(it.text) } + targets.getValue("size")).distinct()
if (colors.any { color -> sizes.any { size ->
"$color $size" == summary && (color != targets["color"] || size != targets["size"])
} }) reject("color", "composition_ambiguity", selectedProof.isNotEmpty(), conflict = true)
}
targets.keys.forEach { dimension ->
if (dimension !in selectedProof && summary != expected) reject(dimension, "missing_proof")
}
}
/** Existing #335 quantity-ancestor form, retaining identity as well as bounds for summary ownership. */
private fun boundedQuantityPanel(snapshot: UiSnapshot): SnapshotNode? {
val visible = snapshot.nodes.filter(SnapshotNode::visible)
val screenWidth = visible.maxOfOrNull { it.bounds.right } ?: return null
val screenHeight = visible.maxOfOrNull { it.bounds.bottom } ?: return null
val screenArea = screenWidth.toLong() * screenHeight
val byPath = visible.associateBy(SnapshotNode::path)
var current = visible.singleOrNull {
it.enabled && it.className == "android.widget.EditText" && it.label.toIntOrNull()?.let { value -> value > 0 } == true
} ?: return null
var panel: SnapshotNode? = null
val visited = mutableSetOf(current.path)
while (true) {
val parent = current.parentPath?.let(byPath::get) ?: break
if (!visited.add(parent.path)) return null
val area = parent.bounds.width.toLong() * parent.bounds.height
if (area <= 0 || area >= screenArea || parent.parentPath == null) break
panel = parent
current = parent
}
return panel
}
}
@@ -3,6 +3,7 @@ package cn.ilapage.goauto.agent.automation
import java.text.SimpleDateFormat
import java.util.Locale
import java.util.TimeZone
import org.json.JSONObject
data class ShippingAddressProof internal constructor(
internal val expectedAddress: String,
@@ -17,7 +18,28 @@ data class FinalConfirmationEvidence(
val unitPriceCent: Long,
val addressSuffix: String,
val activityName: String,
)
val observedQuantity: Long? = null,
val selectedSummaryPresent: Boolean = false,
val summaryPromptPresent: Boolean = false,
) {
/** Local boundary evidence only; never used in the uploaded purchase result. */
fun toLocalJson(): String = JSONObject()
.put("goodsId", goodsId)
.put("mappedColor", mappedColor)
.put("mappedSize", mappedSize)
.put("targetQuantity", quantity)
.put("observedQuantity", observedQuantity ?: JSONObject.NULL)
.put("selectedSummaryPresent", selectedSummaryPresent)
.put("summaryPromptPresent", summaryPromptPresent)
.put("unitPriceCent", unitPriceCent)
.put("addressSuffix", addressSuffix)
.put("activityName", activityName)
.toString()
}
internal fun observedPurchaseQuantity(snapshot: UiSnapshot): Long? = snapshot.nodes.filter {
it.visible && it.enabled && it.className?.endsWith("EditText") == true && it.label.toLongOrNull() != null
}.singleOrNull()?.label?.toLongOrNull()
data class PurchaseOrderEvidence(val orderNo: String, val submittedAt: String, val pddOrderAmountCent: Long? = null)
data class PurchaseOrderReadFailure(
@@ -315,18 +337,20 @@ class PurchaseLiveAutomation(
val snapshot = driver.capture()
pageProblem(snapshot)
if (snapshot.packageName != PDD_PACKAGE) fail("PURCHASE_CONFIRMATION_LOST", "最终提交前页面已经变化,禁止创建订单")
if (!hasFinalSavedAddressEvidence(snapshot, address.expectedAddress, address.suffix)) {
if (!hasSavedAddressEvidence(snapshot, address.expectedAddress, address.suffix)) {
fail("PURCHASE_ADDRESS_UPDATE_FAILED", "收货地址保存后复核失败,未创建订单")
}
val submit = finalSubmitTargets(snapshot)
if (submit.size != 1) fail("PURCHASE_SUBMIT_TARGET_AMBIGUOUS", "创建订单按钮不是唯一目标,禁止创建订单")
val screen = PddScreenParser.parse(snapshot, PurchaseRehearsalExecutor.DEFAULT_COLLECTOR, input.goodsId, null)
PurchaseFinalSpecVerifier.verify(snapshot, input, panelDiagnostic)
rejectSubmitSelectionPrompt(submit.single())
val price = screen.priceCent ?: fail("RULE_NOT_MATCHED", "创建订单前没有读取到商品单价")
if (price !in input.minUnitPriceCent..input.maxUnitPriceCent) fail("PURCHASE_PRICE_OUT_OF_RANGE", "当前商品单价超出允许范围", price)
val quantities = snapshot.nodes.filter { it.visible && it.enabled && it.className?.endsWith("EditText") == true }.mapNotNull { it.label.toLongOrNull() }
if (quantities.singleOrNull() != input.quantity) fail("PURCHASE_QUANTITY_MISMATCH", "创建订单前数量复核失败")
return FinalConfirmationEvidence(input.goodsId, input.mappedColor, input.mappedSize, input.quantity, price, address.suffix, snapshot.activityName.orEmpty())
val selection = PurchaseSelectionEvidence.observe(snapshot)
return FinalConfirmationEvidence(
input.goodsId, input.mappedColor, input.mappedSize, input.quantity, price, address.suffix, snapshot.activityName.orEmpty(),
observedPurchaseQuantity(snapshot), selection.selectedSummaryPresent, selection.summaryPromptPresent,
)
}
fun submitOrderOnce() {
@@ -337,8 +361,9 @@ class PurchaseLiveAutomation(
if (snapshot.packageName != PDD_PACKAGE || targets.size != 1) {
fail("PURCHASE_SUBMIT_TARGET_AMBIGUOUS", "最终页面或创建订单按钮已变化,禁止创建订单")
}
rejectSubmitSelectionPrompt(targets.single())
submitAttempted = true
when (driver.clickFresh(targets.single())) {
when (driver.clickFresh(targets.single().chosen)) {
FreshActionResult.SUCCESS -> Unit
FreshActionResult.AMBIGUOUS -> fail("PURCHASE_SUBMIT_TARGET_AMBIGUOUS", "创建订单按钮不唯一")
else -> fail("PURCHASE_ORDER_RESULT_UNKNOWN", "创建订单点击结果不明确,请人工检查")
@@ -879,7 +904,24 @@ class PurchaseLiveAutomation(
* (Samsung: only a zero-size text node), fail explicitly (`bottom_row_unlabelled`) —
* never fall back to a higher row.
*/
private fun finalSubmitTargets(snapshot: UiSnapshot): List<SnapshotNode> {
private data class SubmitTarget(val row: SnapshotNode, val chosen: SnapshotNode, val text: String)
internal fun selectionPromptPresent(snapshot: UiSnapshot): Boolean =
PurchaseSelectionEvidence.observe(snapshot).summaryPromptPresent ||
finalSubmitTargets(snapshot).singleOrNull()?.let { isSelectionPrompt(it.text) } == true
private fun isSelectionPrompt(text: String): Boolean =
Regex("^(选择|選擇).+(后|後)[,,](提交订单|提交訂單)$").matches(text.filterNot(Char::isWhitespace))
private fun rejectSubmitSelectionPrompt(target: SubmitTarget) {
if (isSelectionPrompt(target.text)) {
val detail = "finalSpec;stage=selection_prompt"
panelDiagnostic(detail)
fail("PURCHASE_SPEC_NOT_MATCHED", "创建订单前规格复核失败;$detail")
}
}
private fun finalSubmitTargets(snapshot: UiSnapshot): List<SubmitTarget> {
fun hasArea(node: SnapshotNode) = node.bounds.width > 0 && node.bounds.height > 0
val byPath = snapshot.nodes.associateBy { it.path }
fun clickableAncestor(node: SnapshotNode): SnapshotNode? {
@@ -948,7 +990,14 @@ class PurchaseLiveAutomation(
"leafClass=${chosen.className};rowClass=${row.className};w=${row.bounds.width};h=${row.bounds.height};" +
"price=${hasPrice.diagFlag()};legacyMarker=${legacyMarker.diagFlag()};type=${screen.specPanelType}",
)
return listOf(chosen)
// Prompt evidence uses each visible leaf's own label exactly once. A nested
// clickable button is a separate action and cannot supply text for this row.
val text = (listOf(row) + subtreeDescendants(row, snapshot)).filter { node ->
node.visible && node.label.isNotBlank() && clickableAncestor(node)?.path == row.path &&
subtreeDescendants(node, snapshot).none { it.label.isNotBlank() }
}.sortedWith(compareBy<SnapshotNode> { it.bounds.top }.thenBy { it.bounds.left })
.joinToString("") { it.label }
return listOf(SubmitTarget(row, chosen, text))
}
private fun subtreeDescendants(node: SnapshotNode, snapshot: UiSnapshot): List<SnapshotNode> {
@@ -772,6 +772,11 @@ class PurchaseRehearsalExecutor(
val summaryTokenMatched = !token.isNullOrBlank() && SpecValueNormalizer.summaryHasExactToken(screen.selectedSummary, token)
if (!summaryTokenMatched) {
if (screen.selectedSummary == null && proofUsable) {
if (candidates.any { it.available && it.node.visible &&
SpecValueNormalizer.normalizeFinalConfirmation(it.text) == SpecValueNormalizer.normalizeFinalConfirmation(target) &&
!it.node.selected && !it.node.checked }) {
return FinalSpecVerification(false, "target_visible_unselected", false, candidates.size, true, true, matchingNodes.size)
}
return FinalSpecVerification(true, "attempt_selection_state", false, candidates.size, true, true, matchingNodes.size)
}
return FinalSpecVerification(false, "summary_token_missing", false, candidates.size, proofRecorded, proofUsable, matchingNodes.size)
@@ -803,12 +808,15 @@ class PurchaseRehearsalExecutor(
target: String,
proof: ExactSpecSelectionProof?,
): FinalSpecVerification {
var screen = currentScreen(input)
var selectionPromptPresent = false
fun captureScreen() = currentScreen(input) { snapshot -> selectionPromptPresent = hasSelectionPrompt(snapshot) }
var screen = captureScreen()
screen.problem?.let {
return FinalSpecVerification(false, it.code, false, 0, proof != null, false)
}
if (selectionPromptPresent) return FinalSpecVerification(false, "selection_prompt", false, 0, proof != null, false)
var verification = verifyExactSpecSelection(screen, dimension, target, proof)
if (verification.confirmed || verification.targetMatchCount > 0 || verification.reason == "visible_selected_conflict") return verification
if (verification.confirmed || verification.targetMatchCount > 0 || verification.reason in setOf("visible_selected_conflict", "selection_prompt", "target_visible_unselected")) return verification
if (!screen.specPanelOpen) return verification.copy(reason = "relocation_panel_closed", relocationAttempted = true)
var signature = screen.dimensions.joinToString("|") { item ->
@@ -832,7 +840,7 @@ class PurchaseRehearsalExecutor(
}
swipes++
pause(300)
screen = currentScreen(input)
screen = captureScreen()
screen.problem?.let {
return verification.copy(
reason = it.code,
@@ -840,6 +848,9 @@ class PurchaseRehearsalExecutor(
relocationSwipes = swipes,
)
}
if (selectionPromptPresent) {
return verification.copy(confirmed = false, reason = "selection_prompt", relocationAttempted = true, relocationSwipes = swipes)
}
if (!screen.specPanelOpen) {
return verification.copy(
reason = "relocation_panel_closed",
@@ -851,7 +862,7 @@ class PurchaseRehearsalExecutor(
relocationAttempted = true,
relocationSwipes = swipes,
)
if (verification.confirmed || verification.targetMatchCount > 0 || verification.reason == "visible_selected_conflict") return verification
if (verification.confirmed || verification.targetMatchCount > 0 || verification.reason in setOf("visible_selected_conflict", "selection_prompt", "target_visible_unselected")) return verification
val refreshedSignature = screen.dimensions.joinToString("|") { item ->
"${item.key}:${item.values.joinToString(",") { value -> "${value.text}:${value.available}" }}"
}
@@ -1129,6 +1140,9 @@ class PurchaseRehearsalExecutor(
dimension to (normalizedTarget(dimension, rawTarget)
?: return failure(SPEC_SAFE_TARGET_MISSING, "下发规格无法安全规范化"))
}
if (selected.isEmpty() && hasSelectionPrompt(driver.capture())) {
return failure(SPEC_SELECTION_UNCONFIRMED, "最终规格复核未能确认精确选中状态 [reason=selection_prompt]")
}
selected.forEach { (dimension, target) ->
val verification = verifyExactSpecSelectionWithRelocation(input, dimension, target, selectionProofs[dimension])
if (!verification.confirmed) {
@@ -1152,6 +1166,9 @@ class PurchaseRehearsalExecutor(
return null
}
private fun hasSelectionPrompt(snapshot: UiSnapshot): Boolean =
PurchaseLiveAutomation(driver, pause, panelDiagnostic).selectionPromptPresent(snapshot)
private fun hasAllRecordedSelectionProofs(
input: PurchaseExecutionInput,
proofs: Map<String, ExactSpecSelectionProof>,
@@ -1219,8 +1236,9 @@ class PurchaseRehearsalExecutor(
return normalized.takeIf(SpecValueNormalizer::isSafeSize)
}
private fun currentScreen(input: PurchaseExecutionInput): ParsedPddScreen {
private fun currentScreen(input: PurchaseExecutionInput, snapshotObserved: (UiSnapshot) -> Unit = {}): ParsedPddScreen {
val snapshot = driver.capture()
snapshotObserved(snapshot)
val screen = PddScreenParser.parse(snapshot, DEFAULT_COLLECTOR, input.goodsId, null, purchasePanelContext)
purchasePanelContext = if (screen.isPddPackage && screen.problem == null && screen.specPanelOpen) {
screen.specPanelContainer?.let {
@@ -0,0 +1,68 @@
package cn.ilapage.goauto.agent.automation
/** Boolean-only summary observations within the #374 bounded quantity panel. */
internal data class PurchaseSelectionEvidence(
val selectedSummaryPresent: Boolean = false,
val summaryPromptPresent: Boolean = false,
) {
companion object {
fun observe(snapshot: UiSnapshot): PurchaseSelectionEvidence {
val config = PurchaseRehearsalExecutor.DEFAULT_COLLECTOR
val original = PddScreenParser.parse(snapshot, config, "", null)
val panel = boundedQuantityPanel(snapshot).takeIf { original.specPanelOpen }
?: return PurchaseSelectionEvidence()
val byPath = snapshot.nodes.associateBy(SnapshotNode::path)
fun within(node: SnapshotNode): Boolean {
val visited = mutableSetOf<String>()
var current: SnapshotNode? = node
while (current != null && visited.add(current.path)) {
if (current.path == panel.path) return true
current = current.parentPath?.let(byPath::get)
}
return false
}
fun contained(node: SnapshotNode) = node.bounds.width > 0 && node.bounds.height > 0 &&
node.bounds.left >= panel.bounds.left && node.bounds.right <= panel.bounds.right &&
node.bounds.top >= panel.bounds.top && node.bounds.bottom <= panel.bounds.bottom
val nodes = snapshot.nodes.filter { (within(it) && contained(it)) ||
(it.parentPath == null && it.label.isBlank() && !it.clickable) }
val scoped = PddScreenParser.parse(snapshot.copy(nodes = nodes), config, "", null, forFinalConfirmation = true)
if (!scoped.specPanelOpen) return PurchaseSelectionEvidence()
val quantity = nodes.singleOrNull { it.visible && it.enabled && it.className == "android.widget.EditText" && it.label.toIntOrNull()?.let { value -> value > 0 } == true }
val firstOptionTop = scoped.dimensions.flatMap(VisibleDimension::values).minOfOrNull { it.node.bounds.top } ?: Int.MAX_VALUE
val prompt = quantity != null && nodes.any { node ->
node.visible && !node.clickable && node.className?.endsWith("TextView") == true &&
node.bounds.bottom <= minOf(quantity.bounds.top, firstOptionTop) &&
node.label.filterNot(Char::isWhitespace).let { it.startsWith("请选择") || it.startsWith("請選擇") }
}
val selected = scoped.finalSelectionSummaries.any { raw ->
val compact = raw.filterNot(Char::isWhitespace)
config.textAliases.selection.selectedPrefixes.any(compact::startsWith)
}
return PurchaseSelectionEvidence(selected, prompt)
}
/** Retains #374's real ancestry and bounded full sheet, not the inner option list. */
private fun boundedQuantityPanel(snapshot: UiSnapshot): SnapshotNode? {
val visible = snapshot.nodes.filter(SnapshotNode::visible)
val screenWidth = visible.maxOfOrNull { it.bounds.right } ?: return null
val screenHeight = visible.maxOfOrNull { it.bounds.bottom } ?: return null
val screenArea = screenWidth.toLong() * screenHeight
val byPath = visible.associateBy(SnapshotNode::path)
var current = visible.singleOrNull {
it.enabled && it.className == "android.widget.EditText" && it.label.toIntOrNull()?.let { value -> value > 0 } == true
} ?: return null
var panel: SnapshotNode? = null
val visited = mutableSetOf(current.path)
while (true) {
val parent = current.parentPath?.let(byPath::get) ?: break
if (!visited.add(parent.path)) return null
val area = parent.bounds.width.toLong() * parent.bounds.height
if (area <= 0 || area >= screenArea || parent.parentPath == null) break
panel = parent
current = parent
}
return panel
}
}
}
@@ -864,15 +864,7 @@ class AgentForegroundService : Service() {
panelDiagnostic = { evidence -> Log.i("GoAutoPurchasePanel", "task=${task.taskId};$evidence") },
beforeOrderSubmit = { evidence ->
val boundaryRequestId = UUID.randomUUID().toString()
val finalEvidence = JSONObject()
.put("goodsId", evidence.goodsId)
.put("mappedColor", evidence.mappedColor)
.put("mappedSize", evidence.mappedSize)
.put("quantity", evidence.quantity)
.put("unitPriceCent", evidence.unitPriceCent)
.put("addressSuffix", evidence.addressSuffix)
.put("activityName", evidence.activityName)
.toString()
val finalEvidence = evidence.toLocalJson()
purchaseStore.markOrderSubmitStarted(task.taskId, task.taskAttemptId, boundaryRequestId, finalEvidence)
api.markPurchaseOrderSubmitStarted(task.taskId, boundaryRequestId, token)
},
@@ -3,224 +3,171 @@ package cn.ilapage.goauto.agent
import cn.ilapage.goauto.agent.automation.*
import org.junit.Assert.*
import org.junit.Test
import org.json.JSONObject
/** Final capture only; derived from the existing #331/#332 bounded purchase-sheet fixtures. */
/** #376 replaces #374's final value-proof contract. All fixtures are synthetic. */
class PurchaseFinalSpecConfirmationTest {
@Test fun `bracket display variants and offscreen color are proven by full panel summary`() {
val snapshot = sheet("已选 [香槟]RW圆领 L码[105-115斤]", colors = listOf("其他颜色"), sizes = listOf("L码[105-115斤]"))
.selected("size/o0/t")
accepts(snapshot, "【香槟】RW圆领", "L码【105-115斤】")
@Test fun `local final evidence distinguishes target observed quantity and scoped summary flags`() {
val json = JSONObject(check(sheet("已选 黑色 XL"), input().copy(quantity = 2)).toLocalJson())
assertFalse(json.has("quantity"))
assertEquals(2, json.getLong("targetQuantity"))
assertEquals(1, json.getLong("observedQuantity"))
assertTrue(json.getBoolean("selectedSummaryPresent"))
assertFalse(json.getBoolean("summaryPromptPresent"))
val prompt = check(sheet("请 选择:颜色"), input())
assertFalse(prompt.selectedSummaryPresent)
assertTrue(prompt.summaryPromptPresent)
val external = sheet(null).addText("r/outside", "已选 黑色 XL", NodeBounds(20, 400, 800, 460))
assertFalse(check(external, input()).selectedSummaryPresent)
assertFalse(check(sheet("#黑色 XL#"), input()).selectedSummaryPresent)
}
@Test fun `summary above scroll area is accepted for scrollable and non scrollable sheets`() {
for (scrollable in listOf(true, false)) {
accepts(sheet("已选 黑色 XL", scrollable = scrollable))
}
@Test fun `observed quantity is nullable for missing or multiple numeric editors`() {
val single = sheet(null)
assertEquals(1L, observedPurchaseQuantity(single))
assertNull(observedPurchaseQuantity(single.mapNodes { if (it.className == "android.widget.EditText") it.copy(visible = false) else it }))
val quantity = single.nodes.single { it.className == "android.widget.EditText" }
assertNull(observedPurchaseQuantity(single.copy(nodes = single.nodes + quantity.copy(path = "r/second"))))
val evidence = check(single, input()).copy(observedQuantity = null)
val json = JSONObject(evidence.toLocalJson())
assertTrue(json.has("observedQuantity"))
assertTrue(json.isNull("observedQuantity"))
}
@Test fun `checked only exact option and physical parent child duplicates provide selection proof`() {
accepts(sheet(null).selected("color/o0/img", checked = true).selected("size/o0/t", checked = true))
}
@Test fun `selected other color or size overrides matching summary and positive target`() {
rejects(sheet("已选 黑色 XL", colors = listOf("黑色", "白色")).selected("color/o0").selected("color/o1"))
rejects(sheet("已选 黑色 XL", sizes = listOf("XL", "L")).selected("size/o1/t"))
}
@Test fun `selected bracket variants are not a conflict`() {
accepts(sheet("已选 [白色] XL", colors = listOf("[白色]")).selected("color/o0").selected("size/o0/t"), "【白色】")
}
@Test fun `distinct physical identical or normalized target options are collisions`() {
for (colors in listOf(listOf("黑色", "黑色"), listOf("【白色】", "[白色]"))) {
rejects(sheet("已选 ${colors[0]} XL", colors = colors).selected("color/o0"), colors[0])
}
}
@Test fun `explicit unavailable target cannot be rescued by summary`() {
rejects(sheet("已选 黑色 XL").mapNodes { if (it.path.contains("color/o0")) it.copy(enabled = false) else it })
}
@Test fun `all required selected proofs take priority over a single non proving summary`() {
accepts(sheet("已选 其他颜色 其他尺码").selected("color/o0/img").selected("size/o0/t"))
rejects(sheet("已选 白色 L", colors = listOf("黑色", "白色"), sizes = listOf("XL", "L"))
.selected("color/o0/img").selected("size/o0/t")) // Known alternative composition is a conflict.
}
@Test fun `selected options retain established parser separation of trailing display price`() {
accepts(sheet("已选 黑色 XL", colors = listOf("黑色 ¥19.60"), sizes = listOf("XL ¥19.60"))
.selected("color/o0/img").selected("size/o0/t"))
rejects(sheet("已选 黑色 XL", colors = listOf("黑色加绒 ¥19.60")).selected("color/o0/img"))
rejects(sheet("已选 黑色 XL", colors = listOf("黑色 ¥19.60", "黑色 ¥20.00")).selected("color/o0/img"))
}
@Test fun `unselected visible options alone and unrelated title cannot prove selection`() {
rejects(sheet(null).addText("r/title", "示例黑色 XL 商品"))
}
@Test fun `panel external prefixed summary is ignored even at same coordinates`() {
rejects(sheet(null).addText("r/fake", "已选 黑色 XL"))
accepts(sheet("已选 黑色 XL").addText("r/fake", "已选 白色 L"))
}
@Test fun `structural ancestry overrides textual path prefix`() {
rejects(sheet(null).addText("r/sheet/fake", "已选 黑色 XL", parent = "r"))
}
@Test fun `whole summary rejects substring sizes colors extra dimensions quantity and unsupported separators`() {
for (summary in listOf("已选 黑色 XL", "已选 黑色 加绒 L", "已选 黑色 L 2件", "已选 黑色,L", "已选 L 黑色")) {
rejects(sheet(summary, sizes = listOf("L")), size = "L")
}
rejects(sheet("已选 [白色+黑色]超值两件装 XL", colors = emptyList()), "【白色】")
}
@Test fun `known candidates making another full composition reject ambiguous summary`() {
rejects(sheet("已选 黑色 加绒 XL", colors = listOf("黑色", "黑色 加绒"), sizes = listOf("加绒 XL", "XL")), size = "加绒 XL")
rejects(sheet("已选 黑色 加绒 XL", colors = listOf("黑色", "黑色 加绒"), sizes = listOf("加绒 XL", "XL")), color = "黑色 加绒")
}
@Test fun `summary permits invisible color despite another unselected visible color`() {
accepts(sheet("已选 黑色 XL", colors = listOf("白色")))
}
@Test fun `required single dimension must equal whole summary and empty pair is never proof`() {
accepts(sheet("已选 黑色"), size = "")
accepts(sheet("已选 XL"), color = "")
rejects(sheet("已选 黑色 XL"), size = "")
rejects(sheet("已选 黑色 XL"), color = "")
rejects(sheet("已选 黑色 XL"), color = " ", size = "")
}
@Test fun `anchored selected prefix variants preserve internal colons commas and whitespace`() {
for (prefix in listOf("已选", "已选 ", "已选:", "已选: ", " 已选: ")) {
accepts(sheet("$prefix 黑色:加绒,款 XL", colors = emptyList()), color = "黑色:加绒,款")
}
accepts(sheet("已选 黑色 加绒 XL", colors = emptyList()), color = "黑色 加绒")
rejects(sheet("已选 黑色 加绒 XL", colors = emptyList()), color = "黑色加绒")
rejects(sheet("已选 黑色:加绒 XL", colors = emptyList()), color = "黑色加绒")
rejects(sheet("已选::黑色 XL"))
accepts(sheet("已选::黑色 XL", colors = emptyList()), color = ":黑色")
}
@Test fun `conflicting scoped summaries reject even both exact options selected`() {
rejects(sheet("已选 黑色 XL").selected("color/o0").selected("size/o0/t").addText("r/sheet/second", "已选 白色 L"))
accepts(sheet("已选 黑色 XL").addText("r/sheet/second", "已选:黑色 XL"))
}
@Test fun `display normalization is narrow and content preserving`() {
accepts(sheet("已选 [白色](加绒) RW12 XL", colors = emptyList()), color = "〔白色〕(加绒) RW12")
rejects(sheet("已选 白色 RW12 XL", colors = emptyList()), color = "白色 rw12")
rejects(sheet("已选 白色 1 XL", colors = emptyList()), color = "白色 ①")
rejects(sheet("已选 白色 XL", colors = emptyList()), color = "白色 ¥19.6")
}
@Test fun `existing structurally recognized unprefixed summary is usable`() {
accepts(prefixlessSheet())
rejects(sheet("黑色 XL")) // No quantity/header relationship in this fixture.
rejects(sheet(null).addText("r/title", "黑色 XL"))
rejects(prefixlessSheet().addText("r/sheet/body/info/second", "黑色 L"))
}
@Test fun `same dimension groups retain earlier selected conflicts and physical candidates`() {
val base = sheet("已选 黑色 XL").addText("r/sheet/body/list/extra/h", "颜色分类")
.addText("r/sheet/body/list/extra/o", "白色")
.mapNodes { when (it.path) {
"r/sheet/body/list/extra/h" -> it.copy(bounds = NodeBounds(20, 1000, 500, 1040), parentPath = "r/sheet/body/list")
"r/sheet/body/list/extra/o" -> it.copy(bounds = NodeBounds(20, 1045, 500, 1100), parentPath = "r/sheet/body/list", clickable = true, selected = true)
"r/sheet/body/list" -> it.copy(bounds = NodeBounds(0, 980, 1080, 2036))
else -> it
} }
rejects(base)
rejects(base.mapNodes { if (it.path.endsWith("extra/o")) it.copy(text = "黑色") else it })
}
@Test fun `collector default still collapses same raw labels and leaves summary behavior unchanged`() {
val snapshot = sheet("已选 黑色 XL", colors = listOf("黑色", "黑色"))
val config = PurchaseRehearsalExecutor.DEFAULT_COLLECTOR
val regular = PddScreenParser.parse(snapshot, config, "374", null)
val final = PddScreenParser.parse(snapshot, config, "374", null, forFinalConfirmation = true)
assertEquals(1, regular.dimensions.single { it.key == "color" }.values.size)
assertEquals(2, final.dimensions.single { it.key == "color" }.values.size)
assertEquals(regular.selectedSummary, final.selectedSummary)
assertTrue(regular.finalSelectionSummaries.isEmpty())
}
@Test fun `independently bounded selected options survive absent full panel boundary`() {
val snapshot = sheet(null).selected("color/o0/img").selected("size/o0/t")
.mapNodes { if (it.path == "r/sheet") it.copy(bounds = NodeBounds(0, 0, 1080, 2216)) else it }
PurchaseFinalSpecVerifier.verify(snapshot, input()) { fail(it) }
val noSelections = snapshot.mapNodes { it.copy(selected = false, checked = false) }
.addText("r/sheet/fake", "已选 黑色 XL")
try {
PurchaseFinalSpecVerifier.verify(noSelections, input()) {}
fail("unproven full panel must not supply summary")
} catch (failure: PurchaseLiveException) { assertEquals("PURCHASE_SPEC_NOT_MATCHED", failure.code) }
}
@Test fun `price quantity and address checks remain enforced`() {
rejects(sheet("已选 黑色 XL"), expectedCode = "PURCHASE_PRICE_OUT_OF_RANGE", input = input().copy(maxUnitPriceCent = 1))
rejects(sheet("已选 黑色 XL"), expectedCode = "PURCHASE_QUANTITY_MISMATCH", input = input().copy(quantity = 2))
rejects(sheet("已选 黑色 XL").mapNodes { if (it.path == "r/sheet/body/addr/a/detail") it.copy(text = "示例地址") else it }, expectedCode = "PURCHASE_ADDRESS_UPDATE_FAILED")
}
private fun sheet(
summary: String?, colors: List<String> = listOf("黑色"), sizes: List<String> = listOf("XL"), scrollable: Boolean = true,
): UiSnapshot = SpecPanelFixtures.sheet(SpecPanelFixtures.Sheet(colorLabels = colors, sizeLabels = sizes, listScrollable = scrollable))
.mapNodes { when (it.path) {
"r/sheet/body/summary" -> it.copy(text = summary, visible = summary != null)
"r/sheet/body/addr/a/detail" -> it.copy(text = ADDRESS)
else -> it
} }
/** Reuses the info-above-list shape from PddProductDetailCollectorTest.prefixlessPanel. */
private fun prefixlessSheet(): UiSnapshot {
val base = sheet("黑色 XL")
val info = base.nodes.single { it.path == "r/sheet/body/qty" }.copy(
path = "r/sheet/body/info", bounds = NodeBounds(0, 770, 1080, 1000), parentPath = "r/sheet/body",
)
return base.mapNodes { when {
it.path == "r/sheet/body/summary" -> it.copy(path = "r/sheet/body/info/summary", parentPath = info.path)
it.path == "r/sheet/body/qty" -> it.copy(path = "r/sheet/body/info/qty", parentPath = info.path)
it.path.startsWith("r/sheet/body/qty/") -> it.copy(path = it.path.replace("body/qty/", "body/info/qty/"), parentPath = "r/sheet/body/info/qty")
else -> it
} }.let { it.copy(nodes = it.nodes + info) }
}
private fun UiSnapshot.mapNodes(transform: (SnapshotNode) -> SnapshotNode) = copy(nodes = nodes.map(transform))
private fun UiSnapshot.selected(suffix: String, checked: Boolean = false) = mapNodes {
if (it.path.endsWith(suffix)) it.copy(selected = !checked, checked = checked) else it
}
private fun UiSnapshot.addText(path: String, text: String, parent: String = path.substringBeforeLast('/')) = copy(nodes = nodes + SnapshotNode(
path, parent, text, null, null, "android.widget.TextView", NodeBounds(384, 791, 1068, 852),
false, false, false, false, true, true,
))
private fun input(color: String = "黑色", size: String = "XL") = PurchaseExecutionInput(
taskId = 374, executionMode = "live", phase = "purchase", url = "https://mobile.yangkeduo.com/goods.html?goods_id=374",
goodsId = "374", mappedColor = color, mappedSize = size, quantity = 1,
minUnitPriceCent = 1, maxUnitPriceCent = 3000, addressSuffix = "_cg374",
)
private fun check(snapshot: UiSnapshot, input: PurchaseExecutionInput, diagnostics: MutableList<String> = mutableListOf()): FinalConfirmationEvidence {
@Test fun `summary prompt is scoped to visible nonclickable header rather than option or external text`() {
val normal = sheet(null)
val driver = object : PurchaseUiDriver {
override fun capture() = snapshot
override fun clickFresh(target: SnapshotNode): FreshActionResult = error("final confirmation must be read only")
override fun capture() = normal
override fun swipePurchaseIn(target: SnapshotNode, direction: SwipeDirection, durationMs: Long): Boolean = error("unexpected swipe")
override fun clickFresh(target: SnapshotNode): FreshActionResult = error("unexpected click")
override fun tapPurchaseFresh(target: SnapshotNode): FreshActionResult = error("unexpected tap")
override fun inputFresh(target: SnapshotNode, value: String): FreshActionResult = error("unexpected input")
override fun swipePurchase(direction: SwipeDirection, durationMs: Long): Boolean = error("unexpected swipe")
override fun swipePurchaseIn(target: SnapshotNode, direction: SwipeDirection, durationMs: Long): Boolean = error("unexpected scoped swipe")
override fun backPurchase(): Boolean = error("unexpected back")
}
return PurchaseLiveAutomation(driver, pause = { error("unexpected pause") }, panelDiagnostic = diagnostics::add)
.finalConfirmation(input, ShippingAddressProof(ADDRESS, "_cg374"))
}
private fun accepts(snapshot: UiSnapshot, color: String = "黑色", size: String = "XL") {
val diagnostics = mutableListOf<String>()
val result = try { check(snapshot, input(color, size), diagnostics) } catch (failure: PurchaseLiveException) {
throw AssertionError("${failure.code}: ${diagnostics.lastOrNull()}", failure)
val live = PurchaseLiveAutomation(driver, pause = {})
for (prompt in listOf("请选择颜色", "请 选择:颜色", "請選擇: 顏色")) {
assertTrue(live.selectionPromptPresent(sheet(prompt)))
}
assertEquals(color, result.mappedColor)
val summaryBounds = NodeBounds(384, 791, 1068, 852)
for ((index, snapshot) in listOf(
normal.addText("r/external", "请选择颜色", summaryBounds),
normal.addText("r/sheet/fake", "请选择颜色", summaryBounds).mapNodes { if (it.path.endsWith("fake")) it.copy(parentPath = "r") else it },
sheet("请选择颜色").mapNodes { if (it.path.endsWith("body/summary")) it.copy(visible = false) else it },
sheet("请选择颜色").mapNodes { if (it.path.endsWith("body/summary")) it.copy(clickable = true) else it },
normal.addText("r/sheet/body/list/color/o0/prompt", "请选择颜色", NodeBounds(40, 1600, 300, 1640)),
normal.mapNodes { if (it.path.startsWith("r/sheet/body/qty")) it.copy(bounds = it.bounds.copy(top = 1990, bottom = 2020)) else it }
.addText("r/sheet/body/list/color/o0/prompt", "请选择颜色", NodeBounds(40, 1600, 300, 1640)),
sheet("请选择颜色").mapNodes { if (it.path in listOf("r/sheet", "r/sheet/body")) it.copy(bounds = NodeBounds(0, 0, 1080, 2216)) else it },
).withIndex()) {
assertFalse("variant=$index", live.selectionPromptPresent(snapshot))
assertFalse(PurchaseSelectionEvidence.observe(snapshot).summaryPromptPresent)
}
// A missing final button never adds a pre-address failure by itself.
assertFalse(live.selectionPromptPresent(normal.mapNodes { if (it.path.startsWith("r/sheet/submit")) it.copy(visible = false) else it }))
}
private fun rejects(snapshot: UiSnapshot, color: String = "黑色", size: String = "XL", expectedCode: String = "PURCHASE_SPEC_NOT_MATCHED", input: PurchaseExecutionInput = input(color, size)) {
@Test fun `normal button permits missing heading marketing summary and offscreen size`() {
accepts(sheet("#示例活动#" ).mapNodes { if (it.path.endsWith("color/h")) it.copy(visible = false) else it })
accepts(sheet("#示例活动#").mapNodes { if (it.path.contains("list/size")) it.copy(visible = false) else it })
}
@Test fun `normal button permits wrong selected values unavailable targets and collisions`() {
accepts(sheet(null).mapNodes {
when {
it.path.endsWith("color/o0") -> it.copy(selected = true, contentDescription = "白色")
it.path.endsWith("size/o0/t") -> it.copy(selected = true, text = "L")
else -> it
}
})
accepts(sheet("已选 白色 L").mapNodes { if (it.path.contains("color/o0")) it.copy(enabled = false) else it })
accepts(sheet(null).let { it.copy(nodes = it.nodes + it.nodes.filter { n -> n.path.contains("color/o0") }.map { n ->
n.copy(path = n.path.replace("o0", "o1"), parentPath = n.parentPath?.replace("o0", "o1"), bounds = n.bounds.copy(left = 400, right = 700))
}) })
}
@Test fun `normal button permits mismatched quantity and summary prompt`() {
accepts(sheet("请选择:颜色分类 尺码"), input().copy(quantity = 2))
accepts(sheet("請選擇: 顏色 尺碼"))
}
@Test fun `special button rejects simplified traditional whitespace and split prompt`() {
for (prompt in listOf("选择颜色分类及尺码后,提交订单", "選擇顏色及尺碼後,提交訂單", " 选 择 颜色 后 , 提交 订单 ")) {
rejects(sheet("已选 黑色 XL").button(prompt), "PURCHASE_SPEC_NOT_MATCHED")
}
rejects(splitButton(), "PURCHASE_SPEC_NOT_MATCHED")
rejects(splitButton().mapNodes { if (it.path == "r/sheet/submit/l") it.copy(text = "选择颜色后,提交订单") else it }, "PURCHASE_SPEC_NOT_MATCHED")
}
@Test fun `whole match ignores prefix suffix hidden external and independent child fragments`() {
for (label in listOf("提示选择颜色后,提交订单", "选择颜色后,提交订单优惠", "选择颜色提交订单", "提交订单")) accepts(sheet(null).button(label))
accepts(sheet(null).addText("r/outside", "选择颜色后,提交订单", NodeBounds(20, 10, 800, 70)))
accepts(sheet(null).addText("r/sheet/submit/hidden", "选择颜色后,提交订单", NodeBounds(20, 2140, 800, 2170)).mapNodes {
if (it.path.endsWith("hidden")) it.copy(visible = false) else it
})
accepts(sheet(null).mapNodes { when (it.path) {
"r/sheet/submit" -> it.copy(text = "选择颜色后,提交订单")
"r/sheet/submit/l/t" -> it.copy(text = "选择颜色后,提交订单", visible = false)
else -> it
} }) // Do not use a parent's aggregate label when its labelled child is hidden.
accepts(splitButton().mapNodes { if (it.path.endsWith("/first")) it.copy(clickable = true) else it })
accepts(splitButton().mapNodes { if (it.path.endsWith("/first")) it.copy(path = "r/outside", parentPath = "r") else it })
}
@Test fun `address price and missing button still reject without actions`() {
rejects(sheet(null), "PURCHASE_PRICE_OUT_OF_RANGE", input().copy(maxUnitPriceCent = 1))
rejects(sheet(null).mapNodes { if (it.path.endsWith("addr/a/detail")) it.copy(text = "示例地址") else it }, "PURCHASE_ADDRESS_UPDATE_FAILED")
rejects(sheet(null).mapNodes { if (it.path.startsWith("r/sheet/submit")) it.copy(visible = false) else it }, "PURCHASE_SUBMIT_TARGET_AMBIGUOUS")
}
@Test fun `collector opt in retains independent candidates without changing regular parsing`() {
val snapshot = SpecPanelFixtures.sheet(SpecPanelFixtures.Sheet(colorLabels = listOf("黑色", "黑色")))
val config = PurchaseRehearsalExecutor.DEFAULT_COLLECTOR
val regular = PddScreenParser.parse(snapshot, config, "376", null)
val final = PddScreenParser.parse(snapshot, config, "376", null, forFinalConfirmation = true)
assertEquals(1, regular.dimensions.single { it.key == "color" }.values.size)
assertEquals(2, final.dimensions.single { it.key == "color" }.values.size)
assertEquals(regular.selectedSummary, final.selectedSummary)
}
private fun splitButton(): UiSnapshot = sheet(null).button("提交订单").mapNodes {
if (it.path.endsWith("submit/l/t")) it.copy(bounds = NodeBounds(600, 2180, 1000, 2216)) else it
}.addText("r/sheet/submit/l/first", "选择颜色后,", NodeBounds(20, 2180, 590, 2216))
private fun sheet(summary: String?): UiSnapshot = SpecPanelFixtures.sheet(SpecPanelFixtures.Sheet(colorLabels = listOf("黑色"), sizeLabels = listOf("XL")))
.mapNodes { when (it.path) {
"r/sheet/body/summary" -> it.copy(text = summary, visible = summary != null)
"r/sheet/body/addr/a/detail" -> it.copy(text = ADDRESS)
"r/sheet/submit/l/t" -> it.copy(text = "提交订单")
else -> it
} }
private fun UiSnapshot.mapNodes(transform: (SnapshotNode) -> SnapshotNode) = copy(nodes = nodes.map(transform))
private fun UiSnapshot.button(label: String) = mapNodes { if (it.path.endsWith("submit/l/t")) it.copy(text = label) else it }
private fun UiSnapshot.addText(path: String, text: String, bounds: NodeBounds) = copy(nodes = nodes + SnapshotNode(
path, path.substringBeforeLast('/'), text, null, null, "android.widget.TextView", bounds,
false, false, false, false, true, true,
))
private fun input() = PurchaseExecutionInput(
taskId = 376, executionMode = "live", phase = "purchase", url = "https://mobile.yangkeduo.com/goods.html?goods_id=376",
goodsId = "376", mappedColor = "黑色", mappedSize = "XL", quantity = 1,
minUnitPriceCent = 1, maxUnitPriceCent = 3000, addressSuffix = "_cg376",
)
private fun check(snapshot: UiSnapshot, input: PurchaseExecutionInput, diagnostics: MutableList<String> = mutableListOf()): FinalConfirmationEvidence {
val driver = object : PurchaseUiDriver {
override fun capture() = snapshot
override fun backPurchase(): Boolean = error("unexpected back")
override fun tapPurchaseFresh(target: SnapshotNode): FreshActionResult = error("unexpected tap")
override fun clickFresh(target: SnapshotNode): FreshActionResult = error("unexpected click")
override fun inputFresh(target: SnapshotNode, value: String): FreshActionResult = error("unexpected input")
override fun swipePurchase(direction: SwipeDirection, durationMs: Long): Boolean = error("unexpected swipe")
override fun swipePurchaseIn(target: SnapshotNode, direction: SwipeDirection, durationMs: Long): Boolean = error("unexpected scoped swipe")
}
return PurchaseLiveAutomation(driver, pause = { error("unexpected pause") }, panelDiagnostic = diagnostics::add)
.finalConfirmation(input, ShippingAddressProof(ADDRESS, "_cg376"))
}
private fun accepts(snapshot: UiSnapshot, input: PurchaseExecutionInput = input()) {
assertEquals(input.mappedColor, check(snapshot, input).mappedColor)
}
private fun rejects(snapshot: UiSnapshot, expectedCode: String, input: PurchaseExecutionInput = input()) {
val diagnostics = mutableListOf<String>()
try {
check(snapshot, input, diagnostics)
@@ -228,14 +175,11 @@ class PurchaseFinalSpecConfirmationTest {
} catch (failure: PurchaseLiveException) {
assertEquals(expectedCode, failure.code)
if (expectedCode == "PURCHASE_SPEC_NOT_MATCHED") {
val detail = diagnostics.last()
assertTrue(detail, detail.matches(Regex("finalSpec;dimension=(color|size|none);stage=[a-z_]+;summaryPresent=[01];selectedFound=[01];conflict=[01]")))
assertTrue(failure.message.orEmpty(), failure.message.orEmpty().contains(detail))
assertEquals("finalSpec;stage=selection_prompt", diagnostics.last())
assertTrue(failure.message.orEmpty().contains(diagnostics.last()))
assertFalse(failure.message.orEmpty().contains(ADDRESS))
assertFalse(failure.message.orEmpty().contains("黑色"))
assertFalse(failure.message.orEmpty().contains("XL"))
}
}
}
private companion object { const val ADDRESS = "示例区示例路374号_cg374" }
private companion object { const val ADDRESS = "示例区示例路376号_cg376" }
}
@@ -8,6 +8,9 @@ import cn.ilapage.goauto.agent.automation.PurchaseExecutionInput
import cn.ilapage.goauto.agent.automation.PurchaseLiveAutomation
import cn.ilapage.goauto.agent.automation.PurchaseLiveException
import cn.ilapage.goauto.agent.automation.PurchaseRuleParser
import cn.ilapage.goauto.agent.automation.PurchaseRehearsalExecutor
import cn.ilapage.goauto.agent.automation.PurchaseAgentCapabilities
import cn.ilapage.goauto.agent.automation.PurchaseExecutionOutcome
import cn.ilapage.goauto.agent.automation.PurchaseUiDriver
import cn.ilapage.goauto.agent.automation.SnapshotNode
import cn.ilapage.goauto.agent.automation.SwipeDirection
@@ -18,6 +21,105 @@ import org.junit.Assert.assertTrue
import org.junit.Test
class PurchaseLiveAutomationTest {
@Test
fun `pre address summary or button selection prompt stops executor before any address action`() {
for (variant in listOf("summary", "button", "second-dimension", "after-swipe")) {
val result = runPromptBoundary(prePrompt = variant)
assertEquals(variant, "failed", result.outcome.resultType)
assertEquals(variant, "PURCHASE_SPEC_SELECTION_UNCONFIRMED", result.outcome.errorCode)
assertTrue(result.outcome.message, result.outcome.message.contains("reason=selection_prompt"))
assertEquals(variant, 0, result.boundaries)
assertEquals(variant, 0, result.driver.addressPathClicks)
assertEquals(variant, 0, result.driver.inputCount)
assertEquals(variant, 0, result.driver.submitClicks)
assertEquals(variant, if (variant == "after-swipe") 1 else 0, result.preSwipes)
}
}
@Test
fun `final selection prompt is ordinary failure before boundary and unknown after boundary with zero clicks`() {
val before = runPromptBoundary(finalPrompt = true)
assertEquals("failed", before.outcome.resultType)
assertEquals("PURCHASE_SPEC_NOT_MATCHED", before.outcome.errorCode)
assertTrue(before.outcome.message.contains("finalSpec;stage=selection_prompt"))
assertEquals(0, before.boundaries)
assertEquals(0, before.driver.submitClicks)
assertEquals(1, before.driver.inputCount)
val after = runPromptBoundary(boundaryPrompt = true)
assertEquals("order_result_unknown", after.outcome.resultType)
assertEquals("PURCHASE_ORDER_RESULT_UNKNOWN", after.outcome.errorCode)
assertEquals(1, after.boundaries)
assertEquals(0, after.driver.submitClicks)
assertEquals(0, after.driver.scopedSwipes + after.driver.genericSwipes)
}
@Test
fun `post address wrong spec and quantity normal button complete executor once`() {
val result = runPromptBoundary(wrongFinalValues = true)
assertEquals("order_created", result.outcome.resultType)
assertEquals(1, result.boundaries)
assertEquals(1, result.driver.submitClicks)
}
private data class PromptBoundaryResult(val outcome: PurchaseExecutionOutcome, val driver: LiveDriver, val boundaries: Int, val preSwipes: Int)
private fun runPromptBoundary(
prePrompt: String? = null, finalPrompt: Boolean = false, boundaryPrompt: Boolean = false, wrongFinalValues: Boolean = false,
): PromptBoundaryResult {
val addressDriver = LiveDriver()
var step = ""
var boundaries = 0
var verifyCaptures = 0
var preSwipes = 0
val selectedSheet = SpecPanelFixtures.sheet(SpecPanelFixtures.Sheet(colorLabels = listOf("黑色"), sizeLabels = listOf("XL"))).let { sheet ->
sheet.copy(nodes = sheet.nodes.map { when {
it.path.endsWith("body/summary") -> it.copy(text = "已选 黑色 XL")
it.path.endsWith("qty/input") -> it.copy(text = "2")
it.path.endsWith("submit/l/t") -> it.copy(text = "提交订单")
it.path.endsWith("color/o0") || it.path.endsWith("size/o0/t") -> it.copy(selected = true)
else -> it
} })
}
val driver = object : PurchaseUiDriver by addressDriver {
override fun capture(): UiSnapshot {
if (step in listOf("updateShippingAddress", "createOrder", "readOrderResult")) {
val snapshot = addressDriver.capture()
if (step != "createOrder") return snapshot
return snapshot.copy(nodes = snapshot.nodes.map { node -> when {
node.path == "panel/submit" && (finalPrompt || (boundaryPrompt && boundaries > 0)) ->
node.copy(text = "选择颜色分类及尺码后,提交订单")
wrongFinalValues && node.path == "panel/selected" -> node.copy(text = "已选 白色 L")
wrongFinalValues && node.path == "panel/quantity" -> node.copy(text = "9")
else -> node
} })
}
if (step != "verifyOrderSummary") return selectedSheet
verifyCaptures++
return selectedSheet.copy(nodes = selectedSheet.nodes.map { node -> when {
prePrompt == "after-swipe" && node.path.contains("list/color") -> node.copy(visible = false)
prePrompt == "after-swipe" && preSwipes == 0 && node.path.endsWith("body/summary") -> node.copy(text = "已选 白色 XL")
(prePrompt == "summary" || (prePrompt == "after-swipe" && preSwipes > 0)) && node.path.endsWith("body/summary") -> node.copy(text = "请选择:颜色分类")
(prePrompt == "button" || (prePrompt == "second-dimension" && verifyCaptures > 1)) && node.path.endsWith("submit/l/t") ->
node.copy(text = "选择颜色分类及尺码后,提交订单")
else -> node
} })
}
override fun swipePurchaseIn(target: SnapshotNode, direction: SwipeDirection, durationMs: Long): Boolean {
if (step == "verifyOrderSummary") { preSwipes++; return true }
return addressDriver.swipePurchaseIn(target, direction, durationMs)
}
}
val rule = PurchaseRuleParser.parse("""{
"schemaVersion":1,"ruleType":"pddPurchase",
"requiredCapabilities":["purchase.live.v1","purchase.address-update.v1","purchase.order-create.v1"],
"actions":[{"type":"openProduct"},{"type":"verifyProduct"},{"type":"openSpecPanel"},{"type":"selectSpec"},{"type":"setQuantity"},{"type":"verifyUnitPrice"},{"type":"verifyOrderSummary"},{"type":"updateShippingAddress"},{"type":"createOrder"},{"type":"readOrderResult"}]
}""")
val outcome = PurchaseRehearsalExecutor(driver, { error("unexpected open") }, { null }, pause = {},
stepChanged = { step = it }, beforeOrderSubmit = { boundaries++ },
).execute(input().copy(reuseProbeProduct = true), rule, PurchaseAgentCapabilities.supported)
return PromptBoundaryResult(outcome, addressDriver, boundaries, preSwipes)
}
@Test
fun `hint delayed address update preserves fresh payment back budget for late order evidence`() {
val observationDriver = OrderObservationDriver { sample ->
@@ -723,6 +723,31 @@ class PurchaseRehearsalExecutorTest {
assertEquals(1, driver.clicked.count { it == "黑色" })
}
@Test
fun `visible unselected target without summary cannot reuse historical proof`() {
val driver = FakePurchaseDriver(sizes = listOf("L"), hideSelectedSummaryAfterQuantitySet = true, hideSizeSelectedState = true)
val outcome = executor(driver, { driver.browser = true; true }, { null }, pause = {})
.execute(input().copy(mappedSize = "L"), PurchaseRuleParser.parse(rule()), PurchaseAgentCapabilities.supported)
assertEquals("failed", outcome.resultType)
assertEquals("PURCHASE_SPEC_SELECTION_UNCONFIRMED", outcome.errorCode)
assertTrue(outcome.message, outcome.message.contains("reason=target_visible_unselected"))
assertTrue(outcome.message, outcome.message.contains("proofRecorded=true"))
}
@Test
fun `visible unselected normalized target blocks historical proof without relocation`() {
val target = "L【建议105-115斤】"
val driver = FakePurchaseDriver(
sizes = listOf(target), hideSelectedSummaryAfterQuantitySet = true,
finalSizesAfterQuantitySet = listOf("L[建议105-115斤]"),
)
val outcome = executor(driver, { driver.browser = true; true }, { null }, pause = {})
.execute(input().copy(mappedSize = target), PurchaseRuleParser.parse(rule()), PurchaseAgentCapabilities.supported)
assertEquals("PURCHASE_SPEC_SELECTION_UNCONFIRMED", outcome.errorCode)
assertTrue(outcome.message, outcome.message.contains("reason=target_visible_unselected"))
assertFalse(driver.swipeInPaths.contains("scroll"))
}
@Test
fun `final verification keeps current attempt proof when selected panel becomes unclassified`() {
val driver = FakePurchaseDriver(panelBecomesUnknownAfterSizeProof = true)
@@ -502,7 +502,7 @@ class SpecPanelRecognitionTest {
val base = SpecPanelFixtures.sheet(Sheet(submit = "none"))
val snapshot = base.copy(
nodes = base.nodes + listOf(
node("r/real-submit", "选择颜色分类及尺码后,提交订单", NodeBounds(0, 2135, 1080, 2200), clickable = true, parent = "r"),
node("r/real-submit", "提交订单", NodeBounds(0, 2135, 1080, 2200), clickable = true, parent = "r"),
// Zero-*area* (right==left) and lower on screen: must never win despite
// having its own non-blank label and a clickable ancestor.
node("r/decoy", "¥0.0", NodeBounds(500, 2200, 500, 2216), clickable = true, parent = "r"),
@@ -512,7 +512,7 @@ class SpecPanelRecognitionTest {
PurchaseLiveAutomation(driver, pause = {}).submitOrderOnce()
assertEquals(listOf("选择颜色分类及尺码后,提交订单"), driver.clicked)
assertEquals(listOf("提交订单"), driver.clicked)
}
@Test
@@ -196,7 +196,13 @@ class TruncatedSpecCardTest {
var sizeSelected = false
val clicks = mutableListOf<String>()
override fun capture() = if (opened) snapshot.copy(nodes = snapshot.nodes.map { n ->
if (n.path.contains("/size/o")) n.copy(selected = sizeSelected && n.path.startsWith("r/sheet/body/list/size/o2")) else n
when {
n.path.contains("/size/o") -> n.copy(selected = sizeSelected && n.path.startsWith("r/sheet/body/list/size/o2"))
// #376: a completed fake selection must no longer expose PDD's incomplete-selection prompts.
sizeSelected && n.label.startsWith("请选择") -> n.copy(text = "已选 黑色示例长裤【有抽绳】 有口袋不起球 2XL建议130-150斤")
sizeSelected && n.label == "选择颜色分类及尺码后,提交订单" -> n.copy(text = "提交订单")
else -> n
}
}) else SpecPanelFixtures.productDetailPage()
override fun clickFresh(target: SnapshotNode): FreshActionResult {
clicks += target.label
@@ -242,7 +248,12 @@ class TruncatedSpecCardTest {
}
@Test fun `existing final confirmation target first ordering is documented not changed`() {
val screen = parse(sheet(otherSelected = true))
val snapshot = sheet(otherSelected = true).let { sheet -> sheet.copy(nodes = sheet.nodes.map { node -> when {
node.label.startsWith("请选择") -> node.copy(text = "已选 $full $size")
node.label == "选择颜色分类及尺码后,提交订单" -> node.copy(text = "提交订单")
else -> node
} }) }
val screen = parse(snapshot)
val executor = executor(Driver(sheet()))
val immediate = PurchaseRehearsalExecutor::class.java.declaredMethods.single { it.name == "isExactSpecSelected" }
immediate.isAccessible = true
+2 -11
View File
@@ -2,8 +2,8 @@
generated: true (请先修改 Gitea Wiki,禁止直接编辑本文件)
wiki_page: Architecture-and-Code-Map
wiki_url: https://git.ilapage.cn/OPC/goauto/wiki/Architecture-and-Code-Map.-
wiki_revision: 08da88a4f106004cb5f02448260d2fc22a83e9cc
synchronized_at: 2026-10-10T00:59:09Z
wiki_revision: 76854d900b2372ddedd46a2b82b5677d8bf5cb31
synchronized_at: 2026-10-09T07:45:10Z
<!-- gitea-wiki-mirror:end -->
<!-- gitea-wiki-mirror:start -->
@@ -673,12 +673,3 @@ Web 唯一展示位置为“采集采购 → SYB 同步记录”:列表状态
- `PddProductDetailCollector.collectColors` 只基于既有解析帧记录颜色阶段 UP 派发次数、空发现轮次和横向探索三态;不增加抓取、手势或等待。标签及签名只在内存使用,持久化仍为安全聚合。
- 不新增 Server/Web API 字段、服务端迁移或权限;普通结果 payload/missing 与采购探测失败策略未改变。完整遍历与不完整候选拦截仍属 #370 后续待证据实施范围,不能把本地诊断值作为已实现的业务门禁。
- 读取与三态限制见 Troubleshooting;旧版不保证降级打开 v5。JDBC 测试与实际 Android 安装升级分别验收,测试不代替真实竖向颜色采集验证。
## Admin 列表按当前筛选导出全部页(#372,待验收)
实现绑定 `a4a793f`(分支 `feat/372-list-export`,未合并、未发布)。
- 采购管理与 SYB 商品页各增「导出」按钮:`web/src/utils/list-export.js` 先按当前筛选读第 1 页取总数,超过 5000 条不导出,否则逐页读取(采购每页 100、SYB 每页 500)再用 `web/src/vendor/Export2Excel.js`(经 `utils/save-excel.js` 按需加载)生成 xlsx;任一页或批次失败不生成文件;筛选条件以点击时复制的参数为准。无服务端导出接口、无异步导出任务。
- `GET /api/admin/v1/purchase-tasks` 的 `AdminListRequest`(`server/app/goauto/purchase/admin_query.go`)新增可选 `orderSubmittedFrom` / `orderSubmittedTo`(`YYYY-MM-DD`,含首尾两天,按 `order_submitted_at`,UTC+8 与 SYB 创建时间筛选一致);格式错误或起止倒置返回 `INVALID_REQUEST`;无下单时间的任务在设置该筛选时不出现。采购页筛选栏用日期范围选择器。
- `GET /api/admin/v1/return-matches` 的 `returnmatch.ListItem` 新增只读 `yeekeQuantity`(`server/app/goauto/returnmatch/service.go`,来自既有 `yeeke_return_item` join,不参与匹配);该接口原本就支持一次传多个 `sybProductId`,SYB 导出按每批 200 个商品 ID 调用,不逐行请求,且只采用 `matched`/`confirmed` 的匹配。
- 无数据库迁移、无新接口、无新权限;导出按钮不单独鉴权,能打开列表的用户(含采购员)都可导出。
+2 -26
View File
@@ -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: 1c57a8670034fe08420bcac48b58a9c4b2755f23
synchronized_at: 2026-10-10T00:59:12Z
wiki_revision: f8bb75d1fc0b5e8822186c740ac2034fbd562057
synchronized_at: 2026-10-09T09:25:31Z
<!-- gitea-wiki-mirror:end -->
<!-- gitea-wiki-mirror:start -->
@@ -933,27 +933,3 @@ Android 0.9.64 / versionCode 77,源码 `6550b9f`(分支实现,尚未安装
- 不新增分享、OCR/VLM、滑动取证、自动重新选规格或付款;合成测试与 APK 构建不代表真实订单验证。安装、真实采购、合并和发布须按相应授权执行。
验证:19 个相关套件共418项通过,0失败/错误/跳过;Debug APK与release单测源码编译通过。执行器测试模拟提交边界回调,并验证本地JSON序列化;未执行真实SQLite/服务端边界端到端或真实采购验证。不宣称全量Android测试通过(既有图搜返回忙循环用例不在本次回归范围)。
## Android 采购结果明确拒收恢复(#377)
实现位于工单分支 fix/377-rejected-purchase-outbox(实现提交 8b75a95,运行占位与互斥补齐 309dce3);仅 Android,未合并 main、未安装或发布,真机恢复尚待独立授权验证。
- 每轮先发心跳,再在无任务执行锁时恢复中断任务及补传。心跳任务不一致不能挡住拒收收敛;收尾后只额外重发一次心跳。认证错误停止补传,只有最终心跳成功、没有未完成本地任务/待上传结果且收尾正常才领取新任务。不放宽服务端任务身份校验,不修改心跳间隔或离线阈值。
- 只有 HTTP 409 且错误码精确属于 PURCHASE_STATE_CONFLICT、PURCHASE_LEASE_EXPIRED、PURCHASE_RESULT_CONFLICT 才视为明确拒收。未知 409、网络异常、5xx 及认证错误不按拒收处理;缺少 retryable 不构成拒收证据。
- 本地拒收使用 rejected,不伪装 sent。按 outbox 与 task/attempt 归属事务保存,保留原 payload;不再自动补传该条,继续处理后续结果。拒收不触发上传成功或规格探测交接,交接凭证失效。拒收记录不再充当待上传占位;不改变服务端采购结果和原重购停止边界。
- order_created、order_result_unknown 或带订单号的拒收结果在采购页持续提示人工核对。“已核对”只持久隐藏提醒,不删除结果、不调用服务端、不允许再次下单;非订单拒收仍可在设置及任务详情查看。
- goauto_purchase.db v2→v3 只追加拒收时间、白名单错误码及人工核对时间三个可空列,旧结果与记录保持不变;v1 升级仍经过原 v2 追加列。旧版 SQLiteOpenHelper 不保证能打开 v3,不能靠卸载清数据回退,优先使用保留 v3 schema 的修复版本。
- 设置页区分同步中、真实心跳失败、已连接但有拒收;新说明采用固定文案,不展示任意服务端错误消息。本单只修复明确拒收后的持续阻塞,不代表最初心跳中断的原因已查明,历史诊断仍属于 #378。
- 拒收后只在执行锁空闲、当前运行标记属于同一采购任务且本地当前 attempt 已拒收时清理恢复占位,不清除其他采集/采购或新 attempt;手动当前页采集与同步共用既有 working/任务锁门禁。服务停止写 STOPPED,原服务实例的迟到状态更新不覆盖它。
## Admin 列表导出 Excel(#372,待验收)
实现绑定 `a4a793f`,分支 `feat/372-list-export`,未合并、未发布。
- 范围:采购管理和 SYB 商品页的「导出」导出**当前筛选条件下的全部页**,不是只导出当前页;筛选以点击导出时的值为准。总数超过 **5000** 条时提示缩小筛选范围并不导出;任一页读取失败不生成文件;无数据提示且不生成文件。分页读取期间数据变化可能有少量重复或遗漏,以导出时刻近似结果为准。
- 格式:时间 `YYYY-MM-DD HH:mm:ss`(浏览器本地时区);金额单位元,保留两位小数;空值留空;文件名 `采购导出_YYYYMMDD-HHmmss.xlsx`、`SYB商品导出_YYYYMMDD-HHmmss.xlsx`。不导出收货人、地址、账号等个人信息。
- 采购导出列(按顺序):SYB订单号、虾皮商品ID、颜色、尺码(均为 SYB 目标规格快照)、数量、状态(页面同款中文)、PDD单号、下单时间、价格(元)。价格取 `pddOrderAmountCent / 100`,即 Agent 在 PDD 待付款页读到的应付金额;旧版 Agent 或人工补录前为空则留空。要导出成功采购,先把状态筛为「订单已创建」并按需选择下单日期。
- 采购管理新增「下单日期」筛选:含首尾两天,按 `order_submitted_at`,日期边界 UTC+8,与 SYB 商品页创建时间筛选一致;没有下单时间的任务在设置该筛选时不出现。
- SYB 商品导出列(按顺序):SYB订单、虾皮商品ID、SYB颜色、SYB尺码、SYB数量、yeeke颜色、yeeke尺码、yeeke数量、匹配时间。yeeke 颜色/尺码来自该商品有效(`matched` 或 `confirmed`)退货匹配的 `variationName`,按第一个英文或中文逗号拆分,没有逗号时整段放 yeeke 颜色;yeeke 数量为对应退货商品数量;没有有效匹配时 yeeke 列与匹配时间留空。要导出已用退货,先把处理阶段筛为「已用退货」。
- 权限:不新增按钮权限,能打开列表的用户(含采购员)都可导出。
-50
View File
@@ -25,46 +25,6 @@ type AdminListRequest struct {
ShopeeOrderNo string
ShopeeOrderNos []string
PDDOrderNo string
// OrderSubmittedFrom/To are inclusive YYYY-MM-DD days (UTC+8, same as the
// SYB products createdFrom/createdTo filter) over order_submitted_at.
OrderSubmittedFrom string
OrderSubmittedTo string
}
// adminOrderDayLocation matches the SYB products page's createdFrom/createdTo
// day boundary (sybimport.sybStockLocation) so both pages filter the same way.
var adminOrderDayLocation = time.FixedZone("SYB UTC+8", 8*60*60)
// adminOrderSubmittedRange returns [start, endExclusive); a nil bound means
// that side is open. Both days are inclusive for the caller.
func adminOrderSubmittedRange(from, to string) (*time.Time, *time.Time, error) {
from, to = strings.TrimSpace(from), strings.TrimSpace(to)
parse := func(value, label string) (*time.Time, error) {
if value == "" {
return nil, nil
}
parsed, err := time.ParseInLocation("2006-01-02", value, adminOrderDayLocation)
if err != nil {
return nil, fail(CodeInvalidRequest, label+" 必须是 YYYY-MM-DD")
}
return &parsed, nil
}
start, err := parse(from, "orderSubmittedFrom")
if err != nil {
return nil, nil, err
}
endDay, err := parse(to, "orderSubmittedTo")
if err != nil {
return nil, nil, err
}
if start != nil && endDay != nil && start.After(*endDay) {
return nil, nil, fail(CodeInvalidRequest, "orderSubmittedFrom 不能晚于 orderSubmittedTo")
}
if endDay != nil {
end := endDay.AddDate(0, 0, 1)
endDay = &end
}
return start, endDay, nil
}
type AdminTaskItem struct {
@@ -215,17 +175,7 @@ func (s *Service) AdminList(ctx context.Context, req AdminListRequest) (AdminLis
if req.TaskType != "" && req.TaskType != models.PurchaseTaskTypeSYBOrder && req.TaskType != models.PurchaseTaskTypeStock {
return AdminListResponse{}, fail(CodeInvalidRequest, "taskType 无效")
}
submittedFrom, submittedTo, err := adminOrderSubmittedRange(req.OrderSubmittedFrom, req.OrderSubmittedTo)
if err != nil {
return AdminListResponse{}, err
}
query := s.DB.WithContext(ctx).Model(&models.PurchaseTask{})
if submittedFrom != nil {
query = query.Where("order_submitted_at >= ?", *submittedFrom)
}
if submittedTo != nil {
query = query.Where("order_submitted_at < ?", *submittedTo)
}
if req.TaskID > 0 {
query = query.Where("id = ?", req.TaskID)
}
@@ -1,129 +0,0 @@
package purchase
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"github.com/google/uuid"
"go-admin/app/goauto/models"
"go-admin/app/goauto/purchasecontract"
)
// #372: order_submitted_at day filter, inclusive on both ends, UTC+8 days.
func TestAdminOrderSubmittedRange(t *testing.T) {
db := testDB(t)
f := seed(t, db, []string{purchasecontract.CapabilityPurchaseRehearsalV1}, true)
s := testService(db)
base := createAdminQueryTask(t, s, f)
loc := time.FixedZone("UTC+8", 8*3600)
at := func(day string, h, m int) *time.Time {
d, _ := time.ParseInLocation("2006-01-02", day, loc)
v := d.Add(time.Duration(h)*time.Hour + time.Duration(m)*time.Minute)
return &v
}
cases := []struct {
name string
status string
at *time.Time
}{
{"before", models.PurchaseTaskStatusOrderCreated, at("2026-10-01", 23, 59)},
{"first-day-start", models.PurchaseTaskStatusOrderCreated, at("2026-10-02", 0, 0)},
{"middle", models.PurchaseTaskStatusOrderCreated, at("2026-10-03", 12, 0)},
{"last-day-end", models.PurchaseTaskStatusOrderCreated, at("2026-10-04", 23, 59)},
{"after", models.PurchaseTaskStatusOrderCreated, at("2026-10-05", 0, 0)},
{"middle-failed", models.PurchaseTaskStatusFailed, at("2026-10-03", 13, 0)},
{"no-time", models.PurchaseTaskStatusOrderCreated, nil},
}
for _, tc := range cases {
row := base
row.ID = 0
row.CreateRequestID = uuid.NewString()
row.ShopeeOrderNoSnapshot = tc.name
row.Status = tc.status
row.OrderSubmittedAt = tc.at
if err := db.Create(&row).Error; err != nil {
t.Fatal(err)
}
}
names := func(req AdminListRequest) map[string]bool {
t.Helper()
out, err := s.AdminList(context.Background(), req)
if err != nil {
t.Fatal(err)
}
got := map[string]bool{}
for _, item := range out.Items {
got[item.ShopeeOrderNoSnapshot] = true
}
if int(out.Total) != len(got) {
t.Fatalf("total %d != items %d", out.Total, len(got))
}
return got
}
both := names(AdminListRequest{OrderSubmittedFrom: "2026-10-02", OrderSubmittedTo: "2026-10-04"})
if len(both) != 4 || !both["first-day-start"] || !both["middle"] || !both["last-day-end"] || !both["middle-failed"] {
t.Fatalf("both days must be inclusive: %v", both)
}
combined := names(AdminListRequest{OrderSubmittedFrom: "2026-10-02", OrderSubmittedTo: "2026-10-04", Status: models.PurchaseTaskStatusOrderCreated})
if len(combined) != 3 || combined["middle-failed"] {
t.Fatalf("must combine with status: %v", combined)
}
if only := names(AdminListRequest{OrderSubmittedFrom: "2026-10-04"}); len(only) != 2 || !only["last-day-end"] || !only["after"] {
t.Fatalf("from only: %v", only)
}
if only := names(AdminListRequest{OrderSubmittedTo: "2026-10-02"}); len(only) != 2 || !only["before"] || !only["first-day-start"] {
t.Fatalf("to only: %v", only)
}
if one := names(AdminListRequest{OrderSubmittedFrom: "2026-10-03", OrderSubmittedTo: "2026-10-03"}); len(one) != 2 {
t.Fatalf("single day: %v", one)
}
if none := names(AdminListRequest{}); !none["no-time"] {
t.Fatalf("no filter must keep rows without order time: %v", none)
}
}
func TestAdminOrderSubmittedRangeInvalid(t *testing.T) {
gin.SetMode(gin.TestMode)
db := testDB(t)
f := seed(t, db, []string{purchasecontract.CapabilityPurchaseRehearsalV1}, true)
s := testService(db)
createAdminQueryTask(t, s, f)
for _, req := range []AdminListRequest{
{OrderSubmittedFrom: "2026/10/02"},
{OrderSubmittedTo: "10-02"},
{OrderSubmittedFrom: "2026-13-01"},
{OrderSubmittedFrom: "2026-10-05", OrderSubmittedTo: "2026-10-04"},
} {
if _, err := s.AdminList(context.Background(), req); code(err) != CodeInvalidRequest {
t.Fatalf("%+v: expected invalid request, got %v", req, err)
}
}
for _, query := range []string{"orderSubmittedFrom=abc", "orderSubmittedTo=2026-02-30"} {
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Set("JWT_PAYLOAD", jwt.MapClaims{"rolekey": "purchaser"})
c.Request = httptest.NewRequest(http.MethodGet, "/api/admin/v1/purchase-tasks?"+query, nil)
(Handler{DB: db}).AdminList(c)
if !strings.Contains(w.Body.String(), CodeInvalidRequest) {
t.Fatalf("handler accepted %s: %s", query, w.Body.String())
}
}
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Set("JWT_PAYLOAD", jwt.MapClaims{"rolekey": "purchaser"})
c.Request = httptest.NewRequest(http.MethodGet, "/api/admin/v1/purchase-tasks?orderSubmittedFrom=2026-10-01&orderSubmittedTo=2026-10-02", nil)
(Handler{DB: db}).AdminList(c)
var result struct {
Data AdminListResponse `json:"data"`
}
if err := json.Unmarshal(w.Body.Bytes(), &result); err != nil || w.Code != http.StatusOK {
t.Fatalf("valid range: %d %s", w.Code, w.Body.String())
}
}
+4 -6
View File
@@ -52,12 +52,10 @@ func (h Handler) AdminList(c *gin.Context) {
response, err := service.AdminList(c.Request.Context(), AdminListRequest{
Page: page, PageSize: pageSize, TaskID: taskID, SYBProductID: sybProductID,
Status: strings.TrimSpace(c.Query("status")), ExecutionMode: strings.TrimSpace(c.Query("executionMode")),
TaskType: strings.TrimSpace(c.Query("taskType")),
ShopeeOrderNo: strings.TrimSpace(c.Query("shopeeOrderNo")),
ShopeeOrderNos: c.Request.URL.Query()["shopeeOrderNos"],
PDDOrderNo: strings.TrimSpace(c.Query("pddOrderNo")),
OrderSubmittedFrom: c.Query("orderSubmittedFrom"),
OrderSubmittedTo: c.Query("orderSubmittedTo"),
TaskType: strings.TrimSpace(c.Query("taskType")),
ShopeeOrderNo: strings.TrimSpace(c.Query("shopeeOrderNo")),
ShopeeOrderNos: c.Request.URL.Query()["shopeeOrderNos"],
PDDOrderNo: strings.TrimSpace(c.Query("pddOrderNo")),
})
if err != nil {
writeError(c, err)
+5 -11
View File
@@ -495,12 +495,9 @@ type ListFilter struct {
// sn, spec) so it never has to issue a second request per row.
type ListItem struct {
models.ReturnMatch
OrderSN string `json:"orderSn,omitempty"`
Image string `json:"image,omitempty"`
VariationName string `json:"variationName,omitempty"`
// YeekeQuantity is the yeeke return item's own quantity (read-only, #372
// export); it comes from the same join and is never used for matching.
YeekeQuantity int64 `json:"yeekeQuantity"`
OrderSN string `json:"orderSn,omitempty"`
Image string `json:"image,omitempty"`
VariationName string `json:"variationName,omitempty"`
DestroyDeadline *time.Time `json:"destroyDeadline,omitempty"`
// SyncStatus/MissingSince (#338) surface the yeeke return item's own
// current availability ("ok"/"missing") so the SYB products match column
@@ -541,7 +538,6 @@ func (s *Service) List(ctx context.Context, filter ListFilter) ([]ListItem, erro
OrderSN string
Image string
VariationName string
Quantity int64
DestroyDeadLine *time.Time
SyncStatus string
MissingSince *time.Time
@@ -549,7 +545,7 @@ func (s *Service) List(ctx context.Context, filter ListFilter) ([]ListItem, erro
PackageMissingAt *time.Time `gorm:"column:package_missing_since"`
}
if err := s.DB.WithContext(ctx).Table("yeeke_return_item AS i").
Select("i.id AS id, p.order_sn AS order_sn, i.image AS image, i.variation_name AS variation_name, i.quantity AS quantity, p.destroy_dead_line AS destroy_dead_line, "+
Select("i.id AS id, p.order_sn AS order_sn, i.image AS image, i.variation_name AS variation_name, p.destroy_dead_line AS destroy_dead_line, "+
"i.sync_status AS sync_status, i.missing_since AS missing_since, p.sync_status AS package_sync_status, p.missing_since AS package_missing_since").
Joins("JOIN yeeke_return_package AS p ON p.id = i.package_id").
Where("i.id IN ?", returnIDs).
@@ -560,7 +556,6 @@ func (s *Service) List(ctx context.Context, filter ListFilter) ([]ListItem, erro
OrderSN string
Image string
VariationName string
Quantity int64
DestroyDeadLine *time.Time
SyncStatus string
MissingSince *time.Time
@@ -574,14 +569,13 @@ func (s *Service) List(ctx context.Context, filter ListFilter) ([]ListItem, erro
if j.PackageSyncStat != "ok" {
syncStatus, missingSince = j.PackageSyncStat, j.PackageMissingAt
}
byID[j.ID] = extraFields{j.OrderSN, j.Image, j.VariationName, j.Quantity, j.DestroyDeadLine, syncStatus, missingSince}
byID[j.ID] = extraFields{j.OrderSN, j.Image, j.VariationName, j.DestroyDeadLine, syncStatus, missingSince}
}
for i := range items {
if extra, ok := byID[items[i].YeekeReturnItemID]; ok {
items[i].OrderSN = extra.OrderSN
items[i].Image = extra.Image
items[i].VariationName = extra.VariationName
items[i].YeekeQuantity = extra.Quantity
items[i].DestroyDeadline = extra.DestroyDeadLine
items[i].SyncStatus = extra.SyncStatus
items[i].MissingSince = extra.MissingSince
@@ -2,7 +2,6 @@ package returnmatch
import (
"context"
"encoding/json"
"errors"
"fmt"
"strings"
@@ -485,27 +484,3 @@ func TestList_EnrichesWithYeekeReturnDisplayFields(t *testing.T) {
t.Fatalf("expected enriched list item: %+v", items)
}
}
// #372: List exposes the yeeke return item's quantity (read-only export field).
func TestList_ExposesYeekeQuantity(t *testing.T) {
db := testDB(t)
s := NewService(db)
s.Now = func() time.Time { return time.Date(2026, 9, 24, 0, 0, 0, 0, time.UTC) }
syb := seedSYB(t, db, "SYB-Q", 1, "白色", "L", time.Date(2026, 9, 1, 0, 0, 0, 0, time.UTC))
deadline := time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC)
item := seedReturn(t, db, "白色,L", &deadline)
if err := db.Model(&models.YeekeReturnItem{}).Where("id = ?", item.ID).Update("quantity", 3).Error; err != nil {
t.Fatal(err)
}
if resp, err := s.BatchMatch(context.Background(), BatchMatchRequest{SYBProductIDs: []uint64{syb.ID}}); err != nil || resp.MatchedCount != 1 {
t.Fatalf("setup failed: %v %+v", err, resp)
}
items, err := s.List(context.Background(), ListFilter{SYBProductIDs: []uint64{syb.ID}})
if err != nil || len(items) != 1 || items[0].YeekeQuantity != 3 {
t.Fatalf("expected yeekeQuantity 3: %+v %v", items, err)
}
raw, _ := json.Marshal(items[0])
if !strings.Contains(string(raw), `"yeekeQuantity":3`) {
t.Fatalf("json missing yeekeQuantity: %s", raw)
}
}
-136
View File
@@ -1,136 +0,0 @@
// #372: export every page of an admin list (current filters) to xlsx.
// Pure helpers with injected dependencies so they can be unit tested without a
// browser; the pages inject the API calls and the Export2Excel saver.
export const EXPORT_MAX_ROWS = 5000
const pad = (value, width = 2) => String(value).padStart(width, '0')
// YYYY-MM-DD HH:mm:ss in the browser's local time zone; empty for blank/invalid.
export function formatExportTime(value) {
if (!value) return ''
const date = new Date(value)
if (Number.isNaN(date.getTime())) return ''
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`
}
// YYYYMMDD-HHmmss for file names.
export function formatExportStamp(date = new Date()) {
return `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}-${pad(date.getHours())}${pad(date.getMinutes())}${pad(date.getSeconds())}`
}
// Cents -> yuan text with two decimals; null/undefined/'' stay empty.
export function centToYuan(cent) {
if (cent === null || cent === undefined || cent === '') return ''
const value = Number(cent)
if (!Number.isFinite(value)) return ''
const sign = value < 0 ? '-' : ''
const abs = Math.abs(Math.round(value))
return `${sign}${Math.floor(abs / 100)}.${pad(abs % 100)}`
}
// yeeke only has one variation_name ("color,size"); split at the first English
// or Chinese comma. Without a comma the whole text is the color.
export function splitYeekeVariation(name) {
const text = String(name ?? '').trim()
if (!text) return { color: '', size: '' }
const index = text.search(/[,,]/)
if (index < 0) return { color: text, size: '' }
return { color: text.slice(0, index).trim(), size: text.slice(index + 1).trim() }
}
const blank = value => (value === null || value === undefined ? '' : value)
export const PURCHASE_EXPORT_HEADER = ['SYB订单号', '虾皮商品ID', '颜色', '尺码', '数量', '状态', 'PDD单号', '下单时间', '价格(元)']
// statusLabel: the page's own status -> Chinese label function.
export function purchaseExportRow(task, statusLabel = value => value) {
return [
blank(task.shopeeOrderNoSnapshot), blank(task.shopeeItemIdSnapshot), blank(task.targetColorSnapshot), blank(task.targetSizeSnapshot),
blank(task.quantity), task.status ? statusLabel(task.status) : '', blank(task.pddOrderNo),
formatExportTime(task.orderSubmittedAt), centToYuan(task.pddOrderAmountCent)
]
}
export const SYB_PRODUCT_EXPORT_HEADER = ['SYB订单', '虾皮商品ID', 'SYB颜色', 'SYB尺码', 'SYB数量', 'yeeke颜色', 'yeeke尺码', 'yeeke数量', '匹配时间']
export const isActiveReturnMatch = match => Boolean(match) && (match.status === 'matched' || match.status === 'confirmed')
// match: the active (matched/confirmed) return match of this product, or null.
export function sybProductExportRow(product, match) {
const active = isActiveReturnMatch(match) ? match : null
const yeeke = active ? splitYeekeVariation(active.variationName) : { color: '', size: '' }
return [
blank(product.orderCode), blank(product.shopeeItemId), blank(product.targetColor), blank(product.targetSize), blank(product.quantity),
yeeke.color, yeeke.size, active ? blank(active.yeekeQuantity) : '', active ? formatExportTime(active.matchedAt) : ''
]
}
export function exportFailureMessage(result, maxRows = EXPORT_MAX_ROWS) {
switch (result.reason) {
case 'empty': return '当前筛选没有数据,未生成文件'
case 'too_many': return `共 ${result.total} 条,超过 ${maxRows} 条上限,请缩小筛选范围`
case 'page_failed': return `导出失败:第 ${result.page} 页读取失败,未生成文件`
case 'enrich_failed': return '导出失败:匹配信息读取失败,未生成文件'
default: return '导出失败,未生成文件'
}
}
function chunk(items, size) {
const result = []
for (let i = 0; i < items.length; i += size) result.push(items.slice(i, i + size))
return result
}
// Reads page 1 for the total, refuses above maxRows, then reads the remaining
// pages. Any failure returns { ok: false } and nothing is saved.
// fetchPage(page, pageSize) -> { items, total }
// enrich(items) -> decorated items of the same length (optional, per batch)
// mapRow(item) -> array of cells
// save({ header, data, filename }) -> writes the file (only after success)
export async function runListExport({
fetchPage, pageSize, maxRows = EXPORT_MAX_ROWS, enrich = null, enrichBatchSize = 200,
header, mapRow, filename, save, onProgress = () => {}
}) {
let first
try {
first = await fetchPage(1, pageSize)
} catch (error) {
return { ok: false, reason: 'page_failed', page: 1, error }
}
const total = Number(first?.total) || 0
if (total === 0) return { ok: false, reason: 'empty', total: 0 }
if (total > maxRows) return { ok: false, reason: 'too_many', total }
const pages = Math.ceil(total / pageSize)
const enrichSteps = enrich ? Math.ceil(total / enrichBatchSize) : 0
const steps = pages + enrichSteps
let done = 1
onProgress(done, steps)
let items = [...(first.items || [])]
for (let page = 2; page <= pages; page++) {
let response
try {
response = await fetchPage(page, pageSize)
} catch (error) {
return { ok: false, reason: 'page_failed', page, error }
}
items = items.concat(response?.items || [])
onProgress(++done, steps)
}
if (enrich) {
const decorated = []
for (const part of chunk(items, enrichBatchSize)) {
try {
decorated.push(...await enrich(part))
} catch (error) {
return { ok: false, reason: 'enrich_failed', error }
}
onProgress(++done, steps)
}
items = decorated
}
if (items.length === 0) return { ok: false, reason: 'empty', total: 0 }
const data = items.map(mapRow)
await save({ header, data, filename: `${filename}_${formatExportStamp()}` })
return { ok: true, total, rows: data.length }
}
-5
View File
@@ -1,5 +0,0 @@
// Loads the xlsx writer on demand so the list pages do not pull it into their chunk.
export async function saveExcel(file) {
const { export_json_to_excel: exportJsonToExcel } = await import('@/vendor/Export2Excel')
exportJsonToExcel(file)
}
+4 -28
View File
@@ -16,8 +16,7 @@
<el-form-item label="状态"><el-select v-model="query.status" clearable placeholder="全部状态" style="width:160px"><el-option v-for="item in statuses" :key="item.value" :label="item.label" :value="item.value" /></el-select></el-form-item>
<el-form-item label="SYB 商品"><el-input v-model="query.sybProductId" class="syb-input" clearable placeholder="商品 ID" @keyup.enter="search" /></el-form-item>
<el-form-item label="PDD 订单号"><el-input v-model="query.pddOrderNo" class="order-input" clearable placeholder="订单号" @keyup.enter="search" /></el-form-item>
<el-form-item label="下单日期"><el-date-picker v-model="query.orderSubmittedRange" type="daterange" value-format="YYYY-MM-DD" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" clearable style="width:260px" /></el-form-item>
<el-form-item><el-button type="primary" :icon="Search" :disabled="Boolean(orderFilter.error)" @click="search">查询</el-button><el-button :icon="RefreshLeft" @click="reset">重置</el-button><el-button :disabled="exporting || Boolean(orderFilter.error)" @click="exportExcel">{{ exporting ? `导出中 ${exportProgress.done}/${exportProgress.steps}` : '导出' }}</el-button></el-form-item>
<el-form-item><el-button type="primary" :icon="Search" :disabled="Boolean(orderFilter.error)" @click="search">查询</el-button><el-button :icon="RefreshLeft" @click="reset">重置</el-button></el-form-item>
</el-form>
<div class="batch-actions"><span class="selected-copy">已选择 <strong>{{ retrySelection.length }}</strong> 条</span><el-button type="warning" :disabled="retryCandidates.length === 0" :loading="retryDialog.saving" @click="openRetryDialog">重试({{ retryCandidates.length }})</el-button><el-button type="primary" plain :disabled="orderWritebackCandidates.length === 0" :loading="orderWriteback.saving" @click="submitOrderWriteback(orderWritebackCandidates)">批量回填 SYB({{ orderWritebackCandidates.length }})</el-button></div>
@@ -155,8 +154,6 @@ import { ElMessage, ElMessageBox } from 'element-plus'
import { RefreshLeft, Search } from '@element-plus/icons-vue'
import { authorizeRepurchase, cancelPurchaseTask, choosePurchaseMatching, getPurchaseTask, listPurchaseTasks, requeuePurchaseMatching, resolveUnknownPurchaseTask, retryPurchaseTasksBatch, reviewPurchasePayment, selectPurchaseWriteback, writebackPurchaseOrderNumbers } from '@/api/goauto/purchase-tasks'
import { createRequestId } from '@/utils/request-id'
import { saveExcel } from '@/utils/save-excel'
import { EXPORT_MAX_ROWS, PURCHASE_EXPORT_HEADER, exportFailureMessage, purchaseExportRow, runListExport } from '@/utils/list-export'
import { listFailureSnapshots } from '@/api/goauto/purchase-failure-snapshots'
import FailureSnapshotCell from './FailureSnapshotCell.vue'
@@ -172,10 +169,9 @@ export default {
data() {
return {
loading: false, loadError: '', tasks: [], total: 0, statuses: [...statusOptions, { value: 'syb_writeback_succeeded', label: '已回填 SYB' }],
exporting: false, exportProgress: { done: 0, steps: 0 },
detailSession: 0, snapshots: { items: {}, loading: false, error: false },
orderWriteback: { open: false, saving: false, items: [] },
query: { page: 1, pageSize: 20, taskId: '', taskType: '', shopeeOrderNo: '', status: '', executionMode: 'live', sybProductId: '', pddOrderNo: '', orderSubmittedRange: [] },
query: { page: 1, pageSize: 20, taskId: '', taskType: '', shopeeOrderNo: '', status: '', executionMode: 'live', sybProductId: '', pddOrderNo: '' },
detail: { open: false, loading: false, task: null, attempts: [], matching: null },
matchingAction: { saving: false }, matchingDialog: { open: false, saving: false, color: '', size: '' },
retrySelection: [],
@@ -231,34 +227,14 @@ export default {
try { const r = await listPurchaseTasks(this.cleanQuery()); this.tasks = r.data.items || []; this.total = r.data.total || 0; this.retrySelection = []; this.$nextTick(() => this.$refs.taskTable?.clearSelection()) } catch (error) { this.tasks = []; this.total = 0; this.loadError = error?.message || '采购任务加载失败,请稍后重试' } finally { this.loading = false }
},
cleanQuery() {
const params = Object.fromEntries(Object.entries(this.query).filter(([key, value]) => key !== 'shopeeOrderNo' && key !== 'orderSubmittedRange' && value !== ''))
const [orderSubmittedFrom, orderSubmittedTo] = this.query.orderSubmittedRange || []
if (orderSubmittedFrom) params.orderSubmittedFrom = orderSubmittedFrom
if (orderSubmittedTo) params.orderSubmittedTo = orderSubmittedTo
const params = Object.fromEntries(Object.entries(this.query).filter(([key, value]) => key !== 'shopeeOrderNo' && value !== ''))
const values = this.orderFilter.values
if (values.length === 1) params.shopeeOrderNo = values[0]
else if (values.length > 1) params.shopeeOrderNos = values
return params
},
search() { this.query.page = 1; this.load() },
reset() { this.query = { page: 1, pageSize: 20, taskId: '', taskType: '', shopeeOrderNo: '', status: '', executionMode: 'live', sybProductId: '', pddOrderNo: '', orderSubmittedRange: [] }; this.load() },
// #372: export every page of the filters as they are at click time (params are copied once).
async exportExcel() {
if (this.exporting || this.orderFilter.error) return
const filters = this.cleanQuery(); delete filters.page; delete filters.pageSize
this.exporting = true; this.exportProgress = { done: 0, steps: 0 }
try {
const result = await runListExport({
pageSize: 100, maxRows: EXPORT_MAX_ROWS, header: PURCHASE_EXPORT_HEADER, filename: '采购导出',
fetchPage: async(pageNo, size) => { const r = await listPurchaseTasks({ ...filters, page: pageNo, pageSize: size }); return { items: r.data.items || [], total: r.data.total || 0 } },
mapRow: task => purchaseExportRow(task, this.statusLabel),
save: saveExcel,
onProgress: (done, steps) => { this.exportProgress = { done, steps } }
})
if (!result.ok) ElMessage.warning(exportFailureMessage(result, EXPORT_MAX_ROWS))
else ElMessage.success(`已导出 ${result.rows} 条;导出期间数据变化可能有少量差异`)
} catch (error) { ElMessage.error('导出失败,未生成文件') } finally { this.exporting = false }
},
reset() { this.query = { page: 1, pageSize: 20, taskId: '', taskType: '', shopeeOrderNo: '', status: '', executionMode: 'live', sybProductId: '', pddOrderNo: '' }; this.load() },
clearSnapshots() { this.detailSession++; this.snapshots = { items: {}, loading: false, error: false } },
async loadSnapshots() {
if (!this.isSnapshotAdmin || !this.detail.open || !this.detail.task || this.snapshots.loading) return
+1 -33
View File
@@ -26,7 +26,7 @@
<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" @change="onProcessStageChange"><el-option v-for="item in processStageOptions" :key="item.value" :label="item.label" :value="item.value" /></el-select></el-form-item>
<el-form-item label="采购类型"><el-select v-model="query.purchaseType" style="width: 132px"><el-option label="需 PDD 采购" value="pdd" /><el-option label="无需 PDD 采购" value="excluded" /><el-option label="全部" value="all" /></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-button :disabled="exporting" @click="exportExcel">{{ exporting ? `导出中 ${exportProgress.done}/${exportProgress.steps}` : '导出' }}</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>
<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>
@@ -395,8 +395,6 @@ import { createPurchaseTasksBatch, matchPurchaseSpecsBatch, previewPurchaseTasks
import { batchCreateCollectionTasks, batchCreateImageSearchCollectionTasks } from '@/api/goauto/collection-tasks'
import { listCollectionRules } from '@/api/goauto/collection-rules'
import { listReturnMatches, batchMatchReturns, getReturnMatch, confirmReturnMatch, cancelReturnMatch, remarkReturnMatch } from '@/api/goauto/return-matches'
import { saveExcel } from '@/utils/save-excel'
import { EXPORT_MAX_ROWS, SYB_PRODUCT_EXPORT_HEADER, exportFailureMessage, isActiveReturnMatch, runListExport, sybProductExportRow } from '@/utils/list-export'
import { createRequestId } from '@/utils/request-id'
import { readPurchaseDevice, rememberPurchaseDevice } from '@/utils/purchase-device-preference'
import ShopeeProductDetailDrawer from '../shopee-products/ShopeeProductDetailDrawer.vue'
@@ -432,8 +430,6 @@ export default {
collectionBatchData: { ruleId: null, deviceId: null },
collectionBatchRules: { ruleId: [{ required: true, message: '请选择采集规则', trigger: 'change' }] },
query: { page: 1, pageSize: 200, shopIds: [], orderCodesText: '', parseStatus: '', processStage: '', purchaseType: 'pdd', createdAtRange: [] },
exporting: false,
exportProgress: { done: 0, steps: 0 },
returnMatchByProductId: {},
returnMatchLoading: false,
returnMatchBatchLoading: false,
@@ -533,34 +529,6 @@ export default {
}
},
search() { this.query.page = 1; this.load() },
// #372: export every page of the filters as they are at click time (params are copied once);
// return matches are read per batch of product ids, never per row.
async exportExcel() {
if (this.exporting) return
const orderCodes = this.normalizedOrderCodes()
if (orderCodes === null) return
const [createdFrom = '', createdTo = ''] = this.query.createdAtRange || []
const filters = { shopIds: [...this.query.shopIds], orderCodes: orderCodes.join(','), parseStatus: this.query.parseStatus, processStage: this.query.processStage, purchaseType: this.query.purchaseType, createdFrom, createdTo }
this.exporting = true; this.exportProgress = { done: 0, steps: 0 }
try {
const result = await runListExport({
pageSize: 500, maxRows: EXPORT_MAX_ROWS, header: SYB_PRODUCT_EXPORT_HEADER, filename: 'SYB商品导出',
fetchPage: async(page, size) => { const r = await listSybProducts({ ...filters, page, pageSize: size }, { suppressErrorMessage: true }); return { items: r.data.items || [], total: r.data.total || 0 } },
enrichBatchSize: 200,
enrich: async items => {
const r = await listReturnMatches({ sybProductId: items.map(item => item.id) }, { suppressErrorMessage: true })
const byProduct = {}
for (const match of (r.data?.items || [])) if (isActiveReturnMatch(match) && !byProduct[match.sybProductId]) byProduct[match.sybProductId] = match
return items.map(item => ({ item, match: byProduct[item.id] || null }))
},
mapRow: ({ item, match }) => sybProductExportRow(item, match),
save: saveExcel,
onProgress: (done, steps) => { this.exportProgress = { done, steps } }
})
if (!result.ok) ElMessage.warning(exportFailureMessage(result, EXPORT_MAX_ROWS))
else ElMessage.success(`已导出 ${result.rows} 条;导出期间数据变化可能有少量差异`)
} catch (error) { ElMessage.error('导出失败,未生成文件') } finally { this.exporting = false }
},
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
-133
View File
@@ -1,133 +0,0 @@
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/utils/list-export.js'), 'utf8')
const lib = new Function(source.replace(/^export /gm, '') + `
return { EXPORT_MAX_ROWS, formatExportTime, formatExportStamp, centToYuan, splitYeekeVariation, purchaseExportRow, PURCHASE_EXPORT_HEADER,
sybProductExportRow, SYB_PRODUCT_EXPORT_HEADER, exportFailureMessage, runListExport }`)()
test('time and stamp use local time, empty and invalid stay empty', () => {
const date = new Date(2026, 9, 9, 8, 5, 3)
assert.equal(lib.formatExportTime(date.toISOString()), '2026-10-09 08:05:03')
assert.equal(lib.formatExportTime(null), '')
assert.equal(lib.formatExportTime(''), '')
assert.equal(lib.formatExportTime('not a date'), '')
assert.equal(lib.formatExportStamp(date), '20261009-080503')
})
test('cent to yuan keeps two decimals and leaves empty values empty', () => {
assert.equal(lib.centToYuan(12345), '123.45')
assert.equal(lib.centToYuan(5), '0.05')
assert.equal(lib.centToYuan(1000), '10.00')
assert.equal(lib.centToYuan(0), '0.00')
for (const value of [null, undefined, '']) assert.equal(lib.centToYuan(value), '')
})
test('yeeke variation splits at the first English or Chinese comma, none puts all in color', () => {
assert.deepEqual(lib.splitYeekeVariation('白色,L【建議65-75公斤】'), { color: '白色', size: 'L【建議65-75公斤】' })
assert.deepEqual(lib.splitYeekeVariation('黑色+白色,簡約,L'), { color: '黑色+白色', size: '簡約,L' })
assert.deepEqual(lib.splitYeekeVariation('均碼'), { color: '均碼', size: '' })
assert.deepEqual(lib.splitYeekeVariation(''), { color: '', size: '' })
assert.deepEqual(lib.splitYeekeVariation(undefined), { color: '', size: '' })
})
test('purchase row maps columns in order with status label, amount and blanks', () => {
assert.equal(lib.PURCHASE_EXPORT_HEADER.length, 9)
const row = lib.purchaseExportRow({
shopeeOrderNoSnapshot: '001', shopeeItemIdSnapshot: '5020', targetColorSnapshot: '白色', targetSizeSnapshot: 'L', quantity: 2,
status: 'order_created', pddOrderNo: 'PDD-1', orderSubmittedAt: new Date(2026, 9, 9, 1, 2, 3).toISOString(), pddOrderAmountCent: 3990,
receiverName: 'must not leak', address: 'must not leak'
}, value => ({ order_created: '订单已创建' })[value])
assert.deepEqual(row, ['001', '5020', '白色', 'L', 2, '订单已创建', 'PDD-1', '2026-10-09 01:02:03', '39.90'])
assert.deepEqual(lib.purchaseExportRow({ quantity: 1 }), ['', '', '', '', 1, '', '', '', ''])
assert.equal(lib.purchaseExportRow({ shopeeOrderNoSnapshot: 'A', status: 'failed', pddOrderAmountCent: null })[8], '')
})
test('syb product row uses only an active match and ignores cancelled ones', () => {
const product = { orderCode: 'O1', shopeeItemId: '99', targetColor: '白色', targetSize: 'L', quantity: 1 }
const matchedAt = new Date(2026, 9, 9, 9, 0, 0).toISOString()
assert.equal(lib.SYB_PRODUCT_EXPORT_HEADER.length, 9)
assert.deepEqual(lib.sybProductExportRow(product, { status: 'confirmed', variationName: '白色,L', yeekeQuantity: 3, matchedAt }),
['O1', '99', '白色', 'L', 1, '白色', 'L', 3, '2026-10-09 09:00:00'])
assert.deepEqual(lib.sybProductExportRow(product, { status: 'matched', variationName: '均碼', yeekeQuantity: 1, matchedAt }).slice(5, 8), ['均碼', '', 1])
assert.deepEqual(lib.sybProductExportRow(product, { status: 'cancelled', variationName: 'x', yeekeQuantity: 1, matchedAt }), ['O1', '99', '白色', 'L', 1, '', '', '', ''])
assert.deepEqual(lib.sybProductExportRow(product, null), ['O1', '99', '白色', 'L', 1, '', '', '', ''])
})
function harness(total, options = {}) {
const calls = []; const saved = []; const progress = []
const pageSize = options.pageSize || 100
const run = () => lib.runListExport({
pageSize, header: ['id'], filename: '测试', mapRow: item => [item.id],
fetchPage: async (page, size) => {
calls.push(page)
if (options.failPage === page) throw new Error('boom')
const start = (page - 1) * size
return { total, items: Array.from({ length: Math.max(0, Math.min(size, total - start)) }, (_, i) => ({ id: start + i + 1 })) }
},
save: async file => { saved.push(file) }, onProgress: (done, steps) => progress.push([done, steps]), ...options.extra
})
return { run, calls, saved, progress }
}
test('reads every page, reports progress, saves once with a timestamped name', async () => {
const h = harness(250)
const result = await h.run()
assert.deepEqual(result, { ok: true, total: 250, rows: 250 })
assert.deepEqual(h.calls, [1, 2, 3])
assert.deepEqual(h.progress, [[1, 3], [2, 3], [3, 3]])
assert.equal(h.saved.length, 1)
assert.equal(h.saved[0].data.length, 250)
assert.deepEqual(h.saved[0].data[249], [250])
assert.match(h.saved[0].filename, /^测试_\d{8}-\d{6}$/)
})
test('exactly 5000 rows are allowed, 5001 is refused after reading only page 1', async () => {
const ok = harness(5000, { pageSize: 500 })
assert.equal((await ok.run()).ok, true)
assert.equal(ok.calls.length, 10)
const over = harness(5001, { pageSize: 500 })
const result = await over.run()
assert.deepEqual(result, { ok: false, reason: 'too_many', total: 5001 })
assert.deepEqual(over.calls, [1])
assert.equal(over.saved.length, 0)
assert.equal(lib.exportFailureMessage(result), '共 5001 条,超过 5000 条上限,请缩小筛选范围')
})
test('empty result does not save', async () => {
const h = harness(0)
const result = await h.run()
assert.deepEqual(result, { ok: false, reason: 'empty', total: 0 })
assert.equal(h.saved.length, 0)
assert.match(lib.exportFailureMessage(result), /没有数据/)
})
test('a failing page stops the export without saving', async () => {
const h = harness(450, { failPage: 3 })
const result = await h.run()
assert.equal(result.ok, false)
assert.equal(result.reason, 'page_failed')
assert.equal(result.page, 3)
assert.deepEqual(h.calls, [1, 2, 3])
assert.equal(h.saved.length, 0)
assert.equal(lib.exportFailureMessage(result), '导出失败:第 3 页读取失败,未生成文件')
const first = harness(10, { failPage: 1 })
assert.equal((await first.run()).page, 1)
assert.equal(first.saved.length, 0)
})
test('enrich runs per batch (not per row), counts in progress, and a failure saves nothing', async () => {
const batches = []
const h = harness(450, { pageSize: 200, extra: { enrichBatchSize: 200, enrich: async items => { batches.push(items.length); return items.map(item => ({ ...item, id: item.id * 10 })) } } })
const result = await h.run()
assert.equal(result.ok, true)
assert.deepEqual(batches, [200, 200, 50])
assert.deepEqual(h.saved[0].data[0], [10])
assert.deepEqual(h.progress[h.progress.length - 1], [6, 6])
const bad = harness(450, { pageSize: 200, extra: { enrich: async () => { throw new Error('boom') } } })
const failed = await bad.run()
assert.equal(failed.reason, 'enrich_failed')
assert.equal(bad.saved.length, 0)
})