Compare commits

...
Author SHA1 Message Date
QiuSWandClaude Sonnet 5.5 8be6b05b31 fix(android,server): pass final spec check on no pending prompt and record it (#393)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NTDbDcwbDw1TSAcE6wfh2F
2026-10-14 11:24:25 +08:00
QiuSWandClaude Opus 5.5 9f918b05e2 docs: mirror wiki for #391
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NTDbDcwbDw1TSAcE6wfh2F
2026-10-14 10:28:42 +08:00
QiuSWandClaude Opus 5.5 0cb674a88a merge: strip leading # in selected summary and record final spec proof (#391)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NTDbDcwbDw1TSAcE6wfh2F
2026-10-14 10:16:56 +08:00
QiuSWandClaude Sonnet 5.5 f62f071e63 fix(android,server): accept exact selected summary as final spec proof and record it (#391)
Final spec verifier now strips one leading '#'/full-width '#' after the
"已选" prefix and optional colon, so "已选: #颜色 尺码" summaries count as
proof again; verify() returns selected_option/selected_summary. The agent
sends it as optional specProof on order-submit-started; the server stores it
in nullable purchase_task.order_spec_proof (unknown/missing -> NULL, replay
keeps the stored value, claim/start still reject unknown fields).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NTDbDcwbDw1TSAcE6wfh2F
2026-10-14 10:14:23 +08:00
QiuSWandClaude Opus 5.5 ccd650f2e3 docs: mirror wiki for #390 merge
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NTDbDcwbDw1TSAcE6wfh2F
2026-10-14 09:39:48 +08:00
QiuSWandClaude Opus 5.5 5282d65a45 merge: accept near-square purchase scroll panels (#390)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NTDbDcwbDw1TSAcE6wfh2F
2026-10-14 09:28:16 +08:00
QiuSW 0dfe8406c4 docs: sync cancellation and purchase scroll contracts (#389 #390) 2026-10-13 18:05:05 +08:00
QiuSW a3c05a751b fix(android): accept near-square purchase scroll panels (#390) 2026-10-13 18:01:50 +08:00
QiuSWandClaude Opus 5.5 b2285c8394 docs: mirror wiki for #388
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NTDbDcwbDw1TSAcE6wfh2F
2026-10-13 16:27:07 +08:00
QiuSWandClaude Opus 5.5 496bf803f5 merge: accept evidence-complete quick confirmation panel after address save (#388)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NTDbDcwbDw1TSAcE6wfh2F
2026-10-13 16:21:41 +08:00
QiuSWandClaude Sonnet 5.5 0d21ca9881 fix(android): accept evidence-complete quick confirmation panel after address save (#388)
Purchase now accepts a QUICK_CONFIRMATION panel (the order sheet with the
"已选" summary PDD re-renders after returning from the address list) only
when it has the same #331 required evidence as REQUIRED_EVIDENCE (address
entry, payment entry, single quantity input in one container). Applies to
isPurchaseConfirmationPanel and finalSubmitTargets; address suffix,
bottom-row target, blocked words and spec/price/quantity checks unchanged.
Adds a structured, text-free diagnostic to PURCHASE_ADDRESS_SAVE_TIMEOUT
after Back. Agent 0.9.71 (84) -> 0.9.72 (85). Regression tests added.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NTDbDcwbDw1TSAcE6wfh2F
2026-10-13 16:13:20 +08:00
QiuSWandClaude Opus 5.5 00a0c8386d docs: mirror wiki for #387 release
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NTDbDcwbDw1TSAcE6wfh2F
2026-10-13 11:52:23 +08:00
QiuSWandClaude Opus 5.5 5183df306f docs: mirror wiki for collection task cancel by device (#387)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NTDbDcwbDw1TSAcE6wfh2F
2026-10-13 11:23:00 +08:00
QiuSWandClaude Opus 5.5 df6b4a570c merge: 采集任务按设备批量取消,采购员仅可取消本人设备任务 (#387)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NTDbDcwbDw1TSAcE6wfh2F
2026-10-13 11:16:14 +08:00
QiuSWandClaude Sonnet 5.5 fc5d9edfa6 feat(task): 批量取消按设备限定,采购员只能取消本人设备任务 (#387)
- 批量取消新增可选 deviceId;非管理员必填且须为本人设备,否则 INVALID_REQUEST/FORBIDDEN
- 单条取消对非管理员强制设备归属(未指定设备、他人设备一律拒绝),管理员不变
- 新增 FORBIDDEN 错误码(HTTP 403)
- Web:去掉选设备禁用按钮;采购员未选设备点击只提示;数量/预览/提交带 deviceId;弹窗显示设备范围

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-13 11:14:40 +08:00
QiuSWandClaude Opus 5.5 59a483f53a docs: mirror wiki for Agent APK signing per device (#385 #386)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NTDbDcwbDw1TSAcE6wfh2F
2026-10-13 09:38:38 +08:00
QiuSWandClaude Opus 5.5 328afde919 chore(android): bump Agent to 0.9.71 (84) (#385 #386)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NTDbDcwbDw1TSAcE6wfh2F
2026-10-13 09:22:22 +08:00
QiuSWandClaude Opus 5.5 afa03ef3e4 merge: drop diagnostic record lock to avoid deadlock (#386)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NTDbDcwbDw1TSAcE6wfh2F
2026-10-13 09:22:16 +08:00
QiuSWandClaude Opus 5.5 71165b1fe7 fix(android): drop object lock on diagnostic record to avoid deadlock (#386)
AgentDiagnosticStore.record() held the helper monitor (@Synchronized) while
waiting for the SQLite write connection, while failure-snapshot and sync
diagnostic transactions held the connection and re-entered
getWritableDatabase() (same monitor). The inverted lock order deadlocked and
blocked the sync/heartbeat thread forever (seen on purchase device 1).
record() only touches locals inside its own transaction and is called from a
single-thread executor, so the monitor is unnecessary.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NTDbDcwbDw1TSAcE6wfh2F
2026-10-13 09:22:04 +08:00
QiuSWandClaude Opus 5.5 7c0d37b512 merge: pause task claiming when accessibility is not ready (#385)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NTDbDcwbDw1TSAcE6wfh2F
2026-10-13 09:21:50 +08:00
28 changed files with 1454 additions and 52 deletions
+2 -2
View File
@@ -11,8 +11,8 @@ android {
applicationId = "cn.ilapage.goauto.agent"
minSdk = 23
targetSdk = 34
versionCode = 83
versionName = "0.9.70"
versionCode = 88
versionName = "0.9.75"
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
@@ -4,7 +4,7 @@ package cn.ilapage.goauto.agent.automation
internal object PurchaseFinalSpecVerifier {
private fun normalize(value: String) = SpecValueNormalizer.normalizeFinalConfirmation(value)
fun verify(snapshot: UiSnapshot, input: PurchaseExecutionInput, diagnostic: (String) -> Unit) {
fun verify(snapshot: UiSnapshot, input: PurchaseExecutionInput, diagnostic: (String) -> Unit): String {
val config = PurchaseRehearsalExecutor.DEFAULT_COLLECTOR
val byPath = snapshot.nodes.associateBy(SnapshotNode::path)
fun within(node: SnapshotNode, container: SnapshotNode): Boolean {
@@ -61,6 +61,9 @@ internal object PurchaseFinalSpecVerifier {
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
}.trimStart().let {
// #391: 采购1 的摘要写作「已选: #颜色 尺码」;只去掉开头这一个 '#',值内部的不动。
if (it.startsWith('#') || it.startsWith('#')) it.drop(1) else it
}
normalize(value)
}.distinct()
@@ -96,8 +99,36 @@ internal object PurchaseFinalSpecVerifier {
"$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")
// #393: 无「已选」摘要时,若整个窗口没有任何待选提示(「请选择」类前缀),且目标选项不在屏幕上,
// 以「无待选提示」放行该维度。其余拒绝条件不变;依据单独标记供抽查。
val selection = config.textAliases.selection
val pendingPrefixes = selection.summaryPrefixes.filter { it !in selection.selectedPrefixes }
val pendingPrompt = snapshot.nodes.any { node ->
node.visible && listOfNotNull(node.text, node.contentDescription).any { raw ->
val compact = raw.filterNot(Char::isWhitespace)
pendingPrefixes.any { compact.startsWith(it.filterNot(Char::isWhitespace)) }
}
}
var passedByNoPendingPrompt = false
targets.forEach { (dimension, target) ->
if (dimension !in selectedProof && summary != expected) {
val targetVisible = dimensions[dimension].orEmpty().any { normalize(it.text) == target }
if (summaries.isEmpty() && !pendingPrompt && !targetVisible && scoped != null) {
passedByNoPendingPrompt = true
} else {
// 单独一条诊断,保持 finalSpec 拒绝详情格式不变。
diagnostic(
"finalSpecPending;dimension=$dimension;pendingPrompt=${if (pendingPrompt) 1 else 0};" +
"targetVisible=${if (targetVisible) 1 else 0}",
)
reject(dimension, "missing_proof")
}
}
}
return when {
passedByNoPendingPrompt -> PurchaseSpecProof.NO_PENDING_PROMPT
targets.keys.all { it in selectedProof } -> PurchaseSpecProof.SELECTED_OPTION
else -> PurchaseSpecProof.SELECTED_SUMMARY
}
}
@@ -17,8 +17,16 @@ data class FinalConfirmationEvidence(
val unitPriceCent: Long,
val addressSuffix: String,
val activityName: String,
/** #391: 最终规格复核依据,取值见 [PurchaseSpecProof]。 */
val specProof: String = PurchaseSpecProof.SELECTED_OPTION,
)
object PurchaseSpecProof {
const val SELECTED_SUMMARY = "selected_summary"
const val SELECTED_OPTION = "selected_option"
const val NO_PENDING_PROMPT = "no_pending_prompt"
}
data class PurchaseOrderEvidence(val orderNo: String, val submittedAt: String, val pddOrderAmountCent: Long? = null)
data class PurchaseOrderReadFailure(
val code: String,
@@ -321,12 +329,13 @@ class PurchaseLiveAutomation(
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)
val specProof = PurchaseFinalSpecVerifier.verify(snapshot, input, panelDiagnostic)
panelDiagnostic("finalSpecProof=$specProof")
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())
return FinalConfirmationEvidence(input.goodsId, input.mappedColor, input.mappedSize, input.quantity, price, address.suffix, snapshot.activityName.orEmpty(), specProof)
}
fun submitOrderOnce() {
@@ -560,7 +569,11 @@ class PurchaseLiveAutomation(
restoreFinalEvidenceInCurrentPanel(savedEvidence, expected, suffix)
} else {
if (!driver.backPurchase()) fail("PURCHASE_ADDRESS_UPDATE_FAILED", "地址保存后无法返回订单页面,未创建订单")
waitFor("PURCHASE_ADDRESS_SAVE_TIMEOUT", "地址保存后无法返回订单页面,未创建订单") {
waitFor(
"PURCHASE_ADDRESS_SAVE_TIMEOUT",
"地址保存后无法返回订单页面,未创建订单",
diagnostic = { addressSaveBackDiagnostic(it, expected, suffix) },
) {
hasFinalSavedAddressEvidence(it, expected, suffix)
}
}
@@ -612,9 +625,21 @@ class PurchaseLiveAutomation(
private fun isPurchaseConfirmationPanel(snapshot: UiSnapshot): Boolean {
if (snapshot.packageName != PDD_PACKAGE || shippingAddressEditors(snapshot).isNotEmpty()) return false
val screen = PddScreenParser.parse(snapshot, PurchaseRehearsalExecutor.DEFAULT_COLLECTOR, "", null)
return screen.specPanelType in PURCHASE_CONFIRMATION_PANEL_TYPES
return acceptsPurchasePanel(screen)
}
/**
* #388: after an address save PDD may re-render the sheet with the "已选" summary, which the parser
* classifies as QUICK_CONFIRMATION. Accept that type only with the same evidence bar as
* REQUIRED_EVIDENCE (address, payment entry and the single quantity input in one container).
* This only affects panel recognition; address suffix, bottom-row submit target, blocked words
* and spec/price/quantity checks are unchanged.
*/
private fun acceptsPurchasePanel(screen: ParsedPddScreen): Boolean =
screen.specPanelType in PURCHASE_CONFIRMATION_PANEL_TYPES ||
(screen.specPanelType == SpecPanelType.QUICK_CONFIRMATION &&
screen.hasRequiredPanelEvidence && screen.requiredEvidenceSameContainer)
private fun restoreFinalEvidenceInCurrentPanel(
initial: UiSnapshot,
expected: String,
@@ -749,22 +774,39 @@ class PurchaseLiveAutomation(
private fun hasExactTaskSuffix(value: String, suffix: String): Boolean =
Regex("${Regex.escape(suffix)}(?![0-9])").containsMatchIn(normalizeAddressText(value))
private fun waitFor(code: String, message: String, predicate: (UiSnapshot) -> Boolean): UiSnapshot {
private fun waitFor(
code: String,
message: String,
diagnostic: ((UiSnapshot) -> String)? = null,
predicate: (UiSnapshot) -> Boolean,
): UiSnapshot {
var last: UiSnapshot? = null
repeat(50) {
val snapshot = driver.capture()
pageProblem(snapshot)
if (predicate(snapshot)) return snapshot
last = snapshot
pause(200)
}
val sampled = last
if (diagnostic != null && sampled != null) fail(code, "$message [${diagnostic(sampled)}]")
fail(code, message)
}
/** Types, counts and 0/1 flags only; never page text. */
private fun addressSaveBackDiagnostic(snapshot: UiSnapshot, expected: String, suffix: String): String {
val screen = PddScreenParser.parse(snapshot, PurchaseRehearsalExecutor.DEFAULT_COLLECTOR, "", null)
val saved = if (hasSavedAddressEvidence(snapshot, expected, suffix)) 1 else 0
return "stage=address_save_back;type=${screen.specPanelType};${screen.requiredEvidenceSummary()};" +
"saved=$saved;submitTargets=${finalSubmitTargets(snapshot).size}"
}
private fun purchasePanelScrollTargets(snapshot: UiSnapshot): List<SnapshotNode> {
val screenWidth = snapshot.nodes.maxOfOrNull { it.bounds.right }?.coerceAtLeast(1) ?: 1
val screenHeight = snapshot.nodes.maxOfOrNull { it.bounds.bottom }?.coerceAtLeast(1) ?: 1
return snapshot.nodes.filter { node ->
node.visible && node.enabled && node.scrollable &&
node.bounds.height >= node.bounds.width &&
node.bounds.height * 100 >= node.bounds.width * PANEL_SCROLL_MIN_HEIGHT_TO_WIDTH_PERCENT &&
node.bounds.width * 100 >= screenWidth * 60 &&
node.bounds.height * 100 >= screenHeight * 20
}.distinctBy { it.path }
@@ -888,7 +930,7 @@ class PurchaseLiveAutomation(
return current
}
val screen = PddScreenParser.parse(snapshot, PurchaseRehearsalExecutor.DEFAULT_COLLECTOR, "", null)
if (screen.specPanelType !in PURCHASE_CONFIRMATION_PANEL_TYPES) {
if (!acceptsPurchasePanel(screen)) {
panelDiagnostic("bottomSubmit;outcome=not_panel;type=${screen.specPanelType}")
return emptyList()
}
@@ -1120,6 +1162,8 @@ class PurchaseLiveAutomation(
const val SPEC_CONFIRMATION_MAX_SAMPLES = 20
const val SPEC_CONFIRMATION_SAMPLE_INTERVAL_MS = 100L
const val ADDRESS_ENTRY_STABLE_INTERVAL_MS = 200L
// #390: near-square purchase lists can be shorter than their width; exclude flat strips.
const val PANEL_SCROLL_MIN_HEIGHT_TO_WIDTH_PERCENT = 80
const val ADDRESS_CARD_OVERLAP_PERCENT = 70
const val ADDRESS_SEMANTIC_MIN_LENGTH = 4
val ADDRESS_CARD_GENERIC_LABELS = setOf("收货地址", "修改", "默认地址", "默认")
@@ -538,8 +538,10 @@ class AgentApiClient(
return purchaseTask(requireNotNull(request("POST", "/api/agent/v1/purchase-tasks/$taskId/start", payload, token)).getJSONObject("data"))
}
fun markPurchaseOrderSubmitStarted(taskId: Long, requestId: String, token: String): PurchaseAgentTask {
fun markPurchaseOrderSubmitStarted(taskId: Long, requestId: String, token: String, specProof: String? = null): PurchaseAgentTask {
val payload = JSONObject().put("requestId", requestId)
// #391: 可选依据;恢复路径拿不到时不带该字段,服务端存 NULL。
if (!specProof.isNullOrBlank()) payload.put("specProof", specProof)
return purchaseTask(requireNotNull(request("POST", "/api/agent/v1/purchase-tasks/$taskId/order-submit-started", payload, token)).getJSONObject("data"))
}
@@ -166,7 +166,6 @@ class AgentDiagnosticStore(context: Context) : SQLiteOpenHelper(context, DATABAS
}
}
@Synchronized
fun record(event: AgentDiagnosticEvent) {
require(event.taskId > 0)
require(event.taskType in setOf("collection", "purchase"))
@@ -1074,9 +1074,10 @@ class AgentForegroundService : Service() {
.put("unitPriceCent", evidence.unitPriceCent)
.put("addressSuffix", evidence.addressSuffix)
.put("activityName", evidence.activityName)
.put("specProof", evidence.specProof)
.toString()
purchaseStore.markOrderSubmitStarted(task.taskId, task.taskAttemptId, boundaryRequestId, finalEvidence)
api.markPurchaseOrderSubmitStarted(task.taskId, boundaryRequestId, token)
api.markPurchaseOrderSubmitStarted(task.taskId, boundaryRequestId, token, evidence.specProof)
},
).execute(
PurchaseExecutionInput(
@@ -1302,6 +1302,113 @@ class PurchaseLiveAutomationTest {
assertEquals(0, driver.genericSwipes)
}
@Test
fun `near square purchase panel reveals collapsed address with one bounded swipe`() {
assertClippedPanelAddressRevealed(NodeBounds(0, 400, 1080, 1478))
}
@Test
fun `purchase panel accepts exactly eighty percent height to width`() {
assertClippedPanelAddressRevealed(NodeBounds(0, 400, 1080, 1264))
}
private fun assertClippedPanelAddressRevealed(bounds: NodeBounds) {
val driver = LiveDriver(addressClipped = true, clippedPanelBounds = bounds)
val initial = driver.capture()
val collapsedAddress = initial.nodes.single { it.path == "panel/collapsed-address" }
assertEquals(0, collapsedAddress.bounds.height)
assertFalse(collapsedAddress.visible)
assertEquals(2376, initial.nodes.maxOf { it.bounds.bottom })
val proof = PurchaseLiveAutomation(driver, pause = {}).updateShippingAddress("_cg390")
assertTrue(proof.expectedAddress.endsWith("_cg390"))
assertEquals(listOf(Triple(bounds, SwipeDirection.DOWN, 350L)), driver.scopedSwipeRequests)
assertEquals(1, driver.addressPathClicks)
assertEquals(1, driver.inputCount)
assertEquals(0, driver.genericSwipes + driver.submitClicks)
}
@Test
fun `purchase panel rejects height just below eighty percent and flat horizontal strip`() {
for (height in listOf(863, 400)) {
val driver = LiveDriver(addressClipped = true, clippedPanelBounds = NodeBounds(0, 400, 1080, 400 + height))
val error = runCatching { PurchaseLiveAutomation(driver, pause = {}).updateShippingAddress("_cg390") }
.exceptionOrNull() as PurchaseLiveException
assertEquals("PURCHASE_ADDRESS_ENTRY_AMBIGUOUS", error.code)
assertEquals(0, driver.scopedSwipes + driver.genericSwipes + driver.inputCount + driver.submitClicks)
assertTrue(driver.clicked.isEmpty())
}
}
@Test
fun `purchase panel still requires sixty percent screen width and twenty percent screen height`() {
for (bounds in listOf(NodeBounds(0, 400, 647, 1478), NodeBounds(0, 400, 648, 999))) {
val driver = LiveDriver(addressClipped = true, clippedPanelBounds = bounds, clippedScreenHeight = 3000)
val error = runCatching { PurchaseLiveAutomation(driver, pause = {}).updateShippingAddress("_cg390") }
.exceptionOrNull() as PurchaseLiveException
assertEquals("PURCHASE_ADDRESS_ENTRY_AMBIGUOUS", error.code)
assertEquals(0, driver.scopedSwipes + driver.genericSwipes + driver.inputCount + driver.submitClicks)
assertTrue(driver.clicked.isEmpty())
}
}
@Test
fun `two near square purchase panels remain ambiguous without swiping`() {
val driver = LiveDriver(addressClipped = true, duplicatePanels = true, clippedPanelBounds = NodeBounds(0, 400, 1080, 1478))
val error = runCatching { PurchaseLiveAutomation(driver, pause = {}).updateShippingAddress("_cg390") }
.exceptionOrNull() as PurchaseLiveException
assertEquals("PURCHASE_ADDRESS_ENTRY_AMBIGUOUS", error.code)
assertEquals(0, driver.scopedSwipes + driver.genericSwipes + driver.inputCount + driver.submitClicks)
assertTrue(driver.clicked.isEmpty())
}
@Test
fun `near square purchase panel stops after unchanged viewport without address`() {
assertClippedPanelTimeout(viewportChanges = false, expectedSwipes = 2)
}
@Test
fun `near square purchase panel stops within five rounds without address`() {
assertClippedPanelTimeout(viewportChanges = true, expectedSwipes = 4)
}
private fun assertClippedPanelTimeout(viewportChanges: Boolean, expectedSwipes: Int) {
val bounds = NodeBounds(0, 400, 1080, 1478)
val driver = LiveDriver(
addressClipped = true, clippedPanelBounds = bounds,
keepAddressClipped = true, clippedViewportChanges = viewportChanges,
)
val error = runCatching { PurchaseLiveAutomation(driver, pause = {}).updateShippingAddress("_cg390") }
.exceptionOrNull() as PurchaseLiveException
assertEquals("PURCHASE_ADDRESS_PANEL_TIMEOUT", error.code)
assertEquals(List(expectedSwipes) { Triple(bounds, SwipeDirection.DOWN, 350L) }, driver.scopedSwipeRequests)
assertEquals(0, driver.genericSwipes + driver.inputCount + driver.submitClicks)
assertTrue(driver.clicked.isEmpty())
}
@Test
fun `saved address evidence is restored through near square purchase panel`() {
val bounds = NodeBounds(0, 400, 1080, 1478)
val driver = LiveDriver(saveReturnsToSpecPanel = true, clippedPanelBounds = bounds)
val automation = PurchaseLiveAutomation(driver, pause = {})
val proof = automation.updateShippingAddress("_cg390")
val final = automation.finalConfirmation(input().copy(addressSuffix = "_cg390"), proof)
assertEquals("_cg390", final.addressSuffix)
assertEquals(listOf(Triple(bounds, SwipeDirection.DOWN, 350L)), driver.scopedSwipeRequests)
assertEquals(0, driver.backCount + driver.genericSwipes + driver.submitClicks)
}
@Test
fun `ambiguous purchase panels fail without swiping or clicking`() {
val driver = LiveDriver(addressClipped = true, duplicatePanels = true)
@@ -1448,6 +1555,10 @@ class PurchaseLiveAutomationTest {
private class LiveDriver(
private val addressClipped: Boolean = false,
private val duplicatePanels: Boolean = false,
private val clippedPanelBounds: NodeBounds? = null,
private val clippedScreenHeight: Int = 2376,
private val keepAddressClipped: Boolean = false,
private val clippedViewportChanges: Boolean = false,
private val chooserAfterSubmit: Boolean = false,
private val trustedChooser: Boolean = true,
private val splitConfirmationAddress: Boolean = false,
@@ -1480,6 +1591,7 @@ class PurchaseLiveAutomationTest {
val clicked = mutableListOf<String>()
var submitClicks = 0
var scopedSwipes = 0
val scopedSwipeRequests = mutableListOf<Triple<NodeBounds, SwipeDirection, Long>>()
var genericSwipes = 0
var addressTaps = 0
var addressPathClicks = 0
@@ -1500,7 +1612,21 @@ class PurchaseLiveAutomationTest {
postSubmitCaptureCount++
if (pendingPostSubmitPages.isNotEmpty()) page = pendingPostSubmitPages.removeAt(0)
}
val snapshot = currentSnapshot()
val snapshot = currentSnapshot().let { original ->
if (clippedPanelBounds != null && ((page == "confirmation" && !addressVisible) || page == "post-save-spec")) {
original.copy(nodes = original.nodes.map {
when (it.path) {
"root" -> it.copy(bounds = NodeBounds(0, 0, 1080, clippedScreenHeight))
"panel", "panel2" -> it.copy(bounds = clippedPanelBounds)
else -> it
}
} + node("panel/collapsed-address", "138****5678", parentPath = "panel",
bounds = NodeBounds(20, 400, 400, 400)).copy(visible = false) +
node("panel/viewport-marker", "", parentPath = "panel", bounds = NodeBounds(
20, 800 + if (clippedViewportChanges) scopedSwipes else 0, 300, 850,
)))
} else original
}
if (page == "edit" && inputCount == 0) {
initialEditCaptures++
return initialEditFrame(snapshot, initialEditCaptures).also { lastInitialEditSnapshot = it }
@@ -1691,7 +1817,8 @@ class PurchaseLiveAutomationTest {
}
override fun swipePurchaseIn(target: SnapshotNode, direction: SwipeDirection, durationMs: Long): Boolean {
scopedSwipes++
if (target.path == "panel" && direction == SwipeDirection.DOWN) addressVisible = true
scopedSwipeRequests += Triple(target.bounds, direction, durationMs)
if (target.path == "panel" && direction == SwipeDirection.DOWN && !keepAddressClipped) addressVisible = true
if (page == "post-save-spec" && direction == SwipeDirection.DOWN && !savedSpecPanelRecoveryStuck) page = "confirmation"
return true
}
@@ -0,0 +1,130 @@
package cn.ilapage.goauto.agent
import cn.ilapage.goauto.agent.automation.*
import org.junit.Assert.*
import org.junit.Test
/** #393: 无「已选」摘要且无「请选择」时,以无待选提示通过。所有规格与地址均为合成数据。 */
class PurchaseNoPendingPromptProofTest {
// 颜色目标不在屏幕上;尺码目标 XL 可见。
private fun noPrompt(sizeSelected: Boolean = true, extraNode: String? = null): UiSnapshot {
var snapshot = sheet(null, colors = listOf("其他颜色"), sizes = listOf("XL"))
if (sizeSelected) snapshot = snapshot.selected("size/o0/t")
if (extraNode != null) {
val base = snapshot.nodes.first { it.path == "r/sheet/body/summary" }
snapshot = snapshot.copy(nodes = snapshot.nodes + base.copy(path = "r/sheet/body/extra", text = extraNode, visible = true))
}
return snapshot
}
@Test fun `no summary no prompt and offscreen target passes as no_pending_prompt and submits once`() {
val driver = Driver(noPrompt())
val automation = automation(driver)
val evidence = automation.finalConfirmation(input("黑色", "XL"), PROOF)
assertEquals("no_pending_prompt", evidence.specProof)
assertTrue(driver.clicked.isEmpty())
automation.submitOrderOnce()
assertEquals(1, driver.clicked.size)
val error = runCatching { automation.submitOrderOnce() }.exceptionOrNull() as PurchaseLiveException
assertEquals("PURCHASE_SUBMIT_ALREADY_ATTEMPTED", error.code)
assertEquals(1, driver.clicked.size)
}
@Test fun `pending prompt anywhere rejects including traditional`() {
for (text in listOf("请选择 颜色", "请选择: 颜色", " 请 选择颜色", "請選擇 顏色")) {
rejectsMissingProof(noPrompt(extraNode = text), input("黑色", "XL"), text)
}
// 位于摘要节点上的「请选择」同样拒绝
rejectsMissingProof(sheet("请选择 颜色", colors = listOf("其他颜色")).selected("size/o0/t"), input("黑色", "XL"), "summary")
}
@Test fun `target visible but unselected rejects`() {
val snapshot = sheet(null, colors = listOf("黑色"), sizes = listOf("XL")).selected("size/o0/t")
val error = rejects(snapshot, input("黑色", "XL"))
assertTrue(error.message.orEmpty(), error.message.orEmpty().contains("stage=missing_proof"))
}
@Test fun `summary present but different rejects`() {
val snapshot = sheet("已选: 白色 XL", colors = listOf("其他颜色")).selected("size/o0/t")
rejectsMissingProof(snapshot, input("黑色", "XL"), "summary")
}
@Test fun `visible selected option conflicting with target rejects as selected_conflict`() {
val snapshot = sheet(null, colors = listOf("其他颜色"), sizes = listOf("XL")).selected("color/o0/img").selected("size/o0/t")
assertTrue(rejects(snapshot, input("黑色", "XL")).message.orEmpty().contains("stage=selected_conflict"))
}
@Test fun `price and quantity are still enforced after no pending prompt`() {
for ((expected, task) in listOf(
"PURCHASE_QUANTITY_MISMATCH" to input("黑色", "XL").copy(quantity = 2),
"PURCHASE_PRICE_OUT_OF_RANGE" to input("黑色", "XL").copy(maxUnitPriceCent = 1),
)) {
val driver = Driver(noPrompt())
val error = runCatching { automation(driver).finalConfirmation(task, PROOF) }.exceptionOrNull() as PurchaseLiveException
assertEquals(expected, error.code)
assertTrue(driver.clicked.isEmpty())
}
}
@Test fun `391 proofs are unchanged`() {
val selected = sheet(null).selected("color/o0/img").selected("size/o0/t")
assertEquals("selected_option", check(selected, input("黑色", "XL")).specProof)
val summary = sheet("已选: #黑色 XL", colors = listOf("其他颜色"), sizes = listOf("其他尺码"))
assertEquals("selected_summary", check(summary, input("黑色", "XL")).specProof)
}
private fun rejectsMissingProof(snapshot: UiSnapshot, input: PurchaseExecutionInput, label: String) {
val message = rejects(snapshot, input).message.orEmpty()
assertTrue("$label: $message", message.contains("stage=missing_proof"))
}
private fun automation(driver: PurchaseUiDriver, diagnostics: MutableList<String> = mutableListOf()) =
PurchaseLiveAutomation(driver, pause = {}, panelDiagnostic = diagnostics::add)
private fun check(snapshot: UiSnapshot, input: PurchaseExecutionInput, diagnostics: MutableList<String> = mutableListOf()) =
automation(Driver(snapshot), diagnostics).finalConfirmation(input, PROOF)
private fun rejects(snapshot: UiSnapshot, input: PurchaseExecutionInput): PurchaseLiveException {
val driver = Driver(snapshot)
val error = runCatching { automation(driver).finalConfirmation(input, PROOF) }.exceptionOrNull() as PurchaseLiveException
assertEquals("PURCHASE_SPEC_NOT_MATCHED", error.code)
assertTrue(driver.clicked.isEmpty())
return error
}
private fun sheet(
summary: String?, colors: List<String> = listOf("黑色"), sizes: List<String> = listOf("XL"),
): UiSnapshot = SpecPanelFixtures.sheet(SpecPanelFixtures.Sheet(colorLabels = colors, sizeLabels = sizes))
.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
} }
private fun UiSnapshot.mapNodes(transform: (SnapshotNode) -> SnapshotNode) = copy(nodes = nodes.map(transform))
private fun UiSnapshot.selected(suffix: String) = mapNodes {
if (it.path.endsWith(suffix)) it.copy(selected = true) else it
}
private fun input(color: String, size: String) = PurchaseExecutionInput(
taskId = 393, executionMode = "live", phase = "purchase", url = "https://mobile.yangkeduo.com/goods.html?goods_id=393",
goodsId = "393", mappedColor = color, mappedSize = size, quantity = 1,
minUnitPriceCent = 1, maxUnitPriceCent = 3000, addressSuffix = "_cg393",
)
private class Driver(private val snapshot: UiSnapshot) : PurchaseUiDriver {
val clicked = mutableListOf<String>()
override fun capture() = snapshot
override fun clickFresh(target: SnapshotNode): FreshActionResult { clicked += target.path; return FreshActionResult.SUCCESS }
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")
}
private companion object {
const val ADDRESS = "示例区示例路391号_cg393"
val PROOF = ShippingAddressProof(ADDRESS, "_cg393")
}
}
@@ -0,0 +1,260 @@
package cn.ilapage.goauto.agent
import cn.ilapage.goauto.agent.automation.*
import org.junit.Assert.*
import org.junit.Test
/**
* #388: after an address save PDD can show the order sheet with the "已选" summary, which the parser classifies as
* QUICK_CONFIRMATION. Purchase accepts it only with the #331 required evidence in one container. All nodes are
* synthetic (derived from [SpecPanelFixtures.sheet]); addresses and phones are fake.
*/
class PurchaseQuickConfirmationAddressTest {
// 1. Full call chain: finalConfirmation passes and submitOrderOnce clicks once on the bottom row leaf.
@Test fun `evidence complete quick confirmation passes final confirmation and submits once on the bottom row`() {
val panel = quick()
assertQuick(panel)
val driver = StaticDriver(panel)
val automation = automation(driver)
val evidence = automation.finalConfirmation(input(), ShippingAddressProof(ADDRESS, SUFFIX))
assertEquals("黑色", evidence.mappedColor)
assertEquals(1960L, evidence.unitPriceCent)
assertTrue(driver.clicked.isEmpty())
automation.submitOrderOnce()
assertEquals(listOf("r/sheet/submit/l/t"), driver.clicked)
val error = runCatching { automation.submitOrderOnce() }.exceptionOrNull() as PurchaseLiveException
assertEquals("PURCHASE_SUBMIT_ALREADY_ATTEMPTED", error.code)
assertEquals(1, driver.clicked.size)
}
// 2. Chain path 1: save -> address list (non panel) -> one Back -> evidence complete quick panel.
@Test fun `save then address list then one back accepts evidence complete quick confirmation`() {
val driver = FlowDriver(afterSave = "list", afterBack = "quickNew")
assertQuick(driver.quickNew)
val proof = automation(driver).updateShippingAddress(SUFFIX)
assertEquals(ADDRESS, proof.expectedAddress)
assertEquals(1, driver.backCount)
assertEquals(1, driver.saveClicks)
}
// 3. Chain path 2: save lands directly on the evidence complete quick panel; no Back, final_evidence.
@Test fun `save landing directly on evidence complete quick confirmation passes without back`() {
val driver = FlowDriver(afterSave = "quickNew", afterBack = "quickNew")
val diagnostics = mutableListOf<String>()
val proof = automation(driver, diagnostics).updateShippingAddress(SUFFIX)
assertEquals(ADDRESS, proof.expectedAddress)
assertEquals(0, driver.backCount)
assertTrue(diagnostics.toString(), diagnostics.any { it.contains("addressSaveWait;outcome=final_evidence") && it.contains("type=QUICK_CONFIRMATION") })
}
// 4a. Rejected: no address entry (no masked phone) -> panel type not accepted, no target, no click.
@Test fun `quick confirmation without address entry has no submit target`() {
val panel = quick(phone = "测试,示例省示例市")
assertQuick(panel)
assertNoSubmitTarget(panel)
}
// 4b. Rejected: required evidence is not in one panel container.
@Test fun `quick confirmation with evidence in different containers has no submit target`() {
val panel = quick(detachAddress = true)
assertQuick(panel)
assertNoSubmitTarget(panel)
}
// 5. Rejected: bottom row mentions payment method or payment wording.
@Test fun `quick confirmation whose bottom row has payment wording has no submit target`() {
listOf("微信支付 现在买,仅 ¥19.6", "现在买,仅 ¥19.6 立即支付", "先用后付 现在买,仅 ¥19.6").forEach { bottom ->
val panel = quick(bottom = bottom)
assertQuick(panel)
assertNoSubmitTarget(panel)
}
// The alias-only variant must be rejected by the bottom row rule itself.
val aliasError = runCatching { automation(StaticDriver(quick(bottom = "微信支付 现在买,仅 ¥19.6"))).submitOrderOnce() }.exceptionOrNull() as PurchaseLiveException
assertEquals("PURCHASE_SUBMIT_TARGET_AMBIGUOUS", aliasError.code)
}
// 6. Rejected: spec on the panel differs from the task.
@Test fun `quick confirmation with another spec fails final confirmation without clicking`() {
val panel = quick()
assertQuick(panel)
val driver = StaticDriver(panel)
val error = runCatching {
automation(driver).finalConfirmation(input(color = "红色"), ShippingAddressProof(ADDRESS, SUFFIX))
}.exceptionOrNull() as PurchaseLiveException
assertEquals("PURCHASE_SPEC_NOT_MATCHED", error.code)
assertTrue(driver.clicked.isEmpty())
}
// 7. Rejected: unit price outside the allowed range.
@Test fun `quick confirmation with price out of range fails final confirmation without clicking`() {
val panel = quick()
assertQuick(panel)
val driver = StaticDriver(panel)
val error = runCatching {
automation(driver).finalConfirmation(input().copy(maxUnitPriceCent = 1000), ShippingAddressProof(ADDRESS, SUFFIX))
}.exceptionOrNull() as PurchaseLiveException
assertEquals("PURCHASE_PRICE_OUT_OF_RANGE", error.code)
assertTrue(driver.clicked.isEmpty())
}
// 8. Rejected: the task address suffix is not unique on the panel.
@Test fun `quick confirmation with duplicated address suffix still fails`() {
val panel = quick(duplicateAddress = true)
assertQuick(panel)
val driver = StaticDriver(panel)
val error = runCatching {
automation(driver).finalConfirmation(input(), ShippingAddressProof(ADDRESS, SUFFIX))
}.exceptionOrNull() as PurchaseLiveException
assertEquals("PURCHASE_ADDRESS_UPDATE_FAILED", error.code)
assertTrue(driver.clicked.isEmpty())
}
// 9. Diagnostic: still failing after Back carries only structural markers, no page text.
@Test fun `address save back timeout carries structured diagnostic without page text`() {
val driver = FlowDriver(afterSave = "list", afterBack = "quickBlocked")
assertQuick(driver.quickBlocked)
val error = runCatching { automation(driver).updateShippingAddress(SUFFIX) }.exceptionOrNull() as PurchaseLiveException
assertEquals("PURCHASE_ADDRESS_SAVE_TIMEOUT", error.code)
val message = error.message.orEmpty()
assertTrue(message, message.startsWith("地址保存后无法返回订单页面,未创建订单 [stage=address_save_back;type=QUICK_CONFIRMATION;"))
assertTrue(message, message.contains("saved=1;submitTargets=0]"))
assertEquals(1, driver.backCount)
listOf("测试路", "139", "示例", ADDRESS, "微信").forEach { assertFalse("$it in $message", message.contains(it)) }
}
private fun automation(driver: PurchaseUiDriver, diagnostics: MutableList<String> = mutableListOf()) =
PurchaseLiveAutomation(driver, pause = {}, panelDiagnostic = diagnostics::add)
private fun assertQuick(snapshot: UiSnapshot) {
val screen = PddScreenParser.parse(snapshot, PurchaseRehearsalExecutor.DEFAULT_COLLECTOR, "", null)
assertEquals(SpecPanelType.QUICK_CONFIRMATION, screen.specPanelType)
}
private fun assertNoSubmitTarget(panel: UiSnapshot) {
val driver = StaticDriver(panel)
val diagnostics = mutableListOf<String>()
val error = runCatching { automation(driver, diagnostics).submitOrderOnce() }.exceptionOrNull() as PurchaseLiveException
// Payment wording may already stop the page earlier (PAYMENT_FORBIDDEN); either way nothing is clicked.
assertTrue(error.code, error.code in setOf("PURCHASE_SUBMIT_TARGET_AMBIGUOUS", "PURCHASE_PAYMENT_FORBIDDEN"))
assertTrue(driver.clicked.isEmpty())
}
private fun input(color: String = "黑色") = PurchaseExecutionInput(
taskId = 101, executionMode = "live", phase = "purchase", url = "https://mobile.yangkeduo.com/goods.html?goods_id=101",
goodsId = "101", mappedColor = color, mappedSize = "XL", quantity = 1,
minUnitPriceCent = 1, maxUnitPriceCent = 3000, addressSuffix = SUFFIX,
)
/** Quick confirmation panel: summary, close, +/- and input, payment row, address row and a full-width bottom buy row. */
private fun quick(
address: String = ADDRESS,
bottom: String = "现在买,仅 ¥19.6",
phone: String = "测试,${SpecPanelFixtures.FAKE_PHONE},示例省示例市",
detachAddress: Boolean = false,
duplicateAddress: Boolean = false,
): UiSnapshot {
val base = SpecPanelFixtures.sheet(SpecPanelFixtures.Sheet(colorLabels = listOf("黑色"), sizeLabels = listOf("XL")))
val addrPrefix = "r/sheet/body/addr"
val nodes = base.nodes.map { node ->
var n = when (node.path) {
"r/sheet/body/summary" -> node.copy(text = "已选 黑色 XL")
"r/sheet/body/addr/a/detail" -> node.copy(text = address)
"r/sheet/body/addr/a/b/c/phone" -> node.copy(text = phone)
"r/sheet/submit/l/t" -> node.copy(text = bottom)
else -> node
}
if (detachAddress && (n.path == addrPrefix || n.path.startsWith("$addrPrefix/"))) {
n = n.copy(
path = n.path.replaceFirst(addrPrefix, "r/addrwrap/addr"),
parentPath = n.parentPath?.let { if (it == "r/sheet/body") "r/addrwrap" else it.replaceFirst(addrPrefix, "r/addrwrap/addr") },
)
}
n
}.toMutableList()
if (detachAddress) {
nodes += SnapshotNode("r/addrwrap", "r", "", null, null, "android.widget.FrameLayout", NodeBounds(0, 330, 1080, 484), false, false, false, false, true, true)
}
if (duplicateAddress) {
nodes += SnapshotNode("r/sheet/body/dup", "r/sheet/body", address, null, null, "android.widget.TextView", NodeBounds(36, 1000, 1000, 1060), false, false, false, false, true, true)
}
return base.copy(nodes = nodes)
}
private class StaticDriver(private val snapshot: UiSnapshot) : PurchaseUiDriver {
val clicked = mutableListOf<String>()
override fun capture() = snapshot
override fun clickFresh(target: SnapshotNode): FreshActionResult { clicked += target.path; return FreshActionResult.SUCCESS }
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")
}
/** confirmation (old address) -> list -> edit -> save -> [afterSave] -> Back -> [afterBack]. */
private class FlowDriver(private val afterSave: String, private val afterBack: String) : PurchaseUiDriver {
private var page = "quickOld"
private var address = "测试路1号-old"
var backCount = 0
var saveClicks = 0
val quickNew: UiSnapshot get() = quickFor(ADDRESS)
val quickBlocked: UiSnapshot get() = quickFor(ADDRESS, bottom = "微信支付 现在买,仅 ¥19.6")
private fun quickFor(addr: String, bottom: String = "现在买,仅 ¥19.6") =
PurchaseQuickConfirmationAddressTest().quick(address = addr, bottom = bottom)
override fun capture(): UiSnapshot = when (page) {
"quickOld" -> quickFor(address)
"quickNew" -> quickFor(address)
"quickBlocked" -> quickFor(address, bottom = "微信支付 现在买,仅 ¥19.6")
"list" -> snapshot(listOf(
node("title", "收货地址"),
node("modify-parent", "", clickable = true),
node("modify", "修改", parentPath = "modify-parent"),
node("address", address),
))
else -> snapshot(listOf(
node("title", "修改收货地址"),
node("recipient-label", "收货人", bounds = NodeBounds(20, 200, 160, 260)),
node("editor-recipient", "测试收货人", className = "android.widget.EditText", bounds = NodeBounds(180, 190, 900, 270)),
node("phone-label", "手机号", bounds = NodeBounds(20, 300, 160, 360)),
node("editor-phone", "13800000000", className = "android.widget.EditText", bounds = NodeBounds(180, 290, 900, 370)),
node("detail", "详细地址", bounds = NodeBounds(20, 400, 160, 460)),
node("editor-address", address, className = "android.widget.EditText", bounds = NodeBounds(180, 390, 900, 480)),
node("save-parent", "", clickable = true), node("save", "保存", parentPath = "save-parent"),
))
}
override fun clickFresh(target: SnapshotNode): FreshActionResult {
when {
target.label.contains(SpecPanelFixtures.FAKE_PHONE) -> page = "list"
target.label == "修改" -> page = "edit"
target.label == "保存" -> { saveClicks++; page = afterSave }
else -> error("unexpected click ${target.path}")
}
return FreshActionResult.SUCCESS
}
override fun tapPurchaseFresh(target: SnapshotNode): FreshActionResult = error("unexpected tap")
override fun inputFresh(target: SnapshotNode, value: String): FreshActionResult { address = value; return FreshActionResult.SUCCESS }
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 { backCount++; page = afterBack; return true }
private fun snapshot(nodes: List<SnapshotNode>) = UiSnapshot(SpecPanelFixtures.PDD, SpecPanelFixtures.ACTIVITY, nodes)
private fun node(
path: String, text: String, clickable: Boolean = false, className: String = "android.widget.TextView",
bounds: NodeBounds = NodeBounds(0, 0, 500, 100), parentPath: String? = null,
) = SnapshotNode(path, parentPath, text, null, null, className, bounds, clickable, false, false, false, true, true)
}
private companion object {
const val SUFFIX = "_cg101"
const val ADDRESS = "测试路1号_cg101"
}
}
@@ -0,0 +1,152 @@
package cn.ilapage.goauto.agent
import cn.ilapage.goauto.agent.automation.*
import org.junit.Assert.*
import org.junit.Test
/** #391: the final verifier reads "已选: #颜色 尺码" summaries. All specs and addresses are synthetic. */
class PurchaseSelectedSummaryProofTest {
private val offscreen = Pair(listOf("其他颜色"), listOf("其他尺码"))
private fun offscreenSheet(summary: String?) = sheet(summary, colors = offscreen.first, sizes = offscreen.second)
// 1. '#' before the value, off-screen options -> summary proof, one click.
@Test fun `hash prefixed summary with offscreen options passes as selected_summary and submits once`() {
val driver = Driver(offscreenSheet("已选: #黑色[九分]小个子 S 建议80-90斤"))
val automation = automation(driver)
val evidence = automation.finalConfirmation(input("黑色【九分】小个子", "S 建议80-90斤"), PROOF)
assertEquals("selected_summary", evidence.specProof)
assertTrue(driver.clicked.isEmpty())
automation.submitOrderOnce()
assertEquals(1, driver.clicked.size)
val error = runCatching { automation.submitOrderOnce() }.exceptionOrNull() as PurchaseLiveException
assertEquals("PURCHASE_SUBMIT_ALREADY_ATTEMPTED", error.code)
assertEquals(1, driver.clicked.size)
}
// 2. Full-width hash, colon and whitespace variants; summary without '#' unchanged.
@Test fun `hash and colon variants pass and plain summary is unchanged`() {
for (summary in listOf("已选: #黑色 XL", "已选:#黑色 XL", "已选:#黑色 XL", "已选 # 黑色 XL", "已选:黑色 XL", "已选 黑色 XL")) {
assertEquals(summary, "selected_summary", check(offscreenSheet(summary), input("黑色", "XL")).specProof)
}
}
// 3. Only the leading '#' is removed.
@Test fun `inner hash is preserved and double leading hash is not matched`() {
assertEquals("selected_summary", check(offscreenSheet("已选:红色#2 XL"), input("红色#2", "XL")).specProof)
assertEquals("selected_summary", check(offscreenSheet("已选: #红色#2 XL"), input("红色#2", "XL")).specProof)
rejectsMissingProof(offscreenSheet("已选: ##黑色 XL"), input("黑色", "XL"))
}
// 4. Longer color still rejected.
@Test fun `hash summary with longer color is still rejected`() {
rejectsMissingProof(offscreenSheet("已选: #黑色加绒 XL"), input("黑色", "XL"))
}
// 5. Original protections still apply with a '#' summary.
@Test fun `selected conflict and composition ambiguity still reject under hash summary`() {
rejects(sheet("已选: #黑色 XL", colors = listOf("黑色", "白色")).selected("color/o1"), input("黑色", "XL"))
rejects(
sheet("已选: #黑色 加绒 XL", colors = listOf("黑色", "黑色 加绒"), sizes = listOf("加绒 XL", "XL")),
input("黑色", "加绒 XL"),
)
}
// 6. Quantity and price are still checked, with no click.
@Test fun `summary proof still enforces quantity and price without clicking`() {
val snapshot = offscreenSheet("已选: #黑色 XL")
for ((expected, task) in listOf(
"PURCHASE_QUANTITY_MISMATCH" to input("黑色", "XL").copy(quantity = 2),
"PURCHASE_PRICE_OUT_OF_RANGE" to input("黑色", "XL").copy(maxUnitPriceCent = 1),
)) {
val driver = Driver(snapshot)
val error = runCatching { automation(driver).finalConfirmation(task, PROOF) }.exceptionOrNull() as PurchaseLiveException
assertEquals(expected, error.code)
assertTrue(driver.clicked.isEmpty())
}
}
// 7. Selected visible options -> selected_option.
@Test fun `selected visible options pass as selected_option`() {
val snapshot = sheet(null).selected("color/o0/img").selected("size/o0/t")
val diagnostics = mutableListOf<String>()
assertEquals("selected_option", check(snapshot, input("黑色", "XL"), diagnostics).specProof)
assertTrue(diagnostics.toString(), diagnostics.contains("finalSpecProof=selected_option"))
}
// 8. The order-submit-started request carries specProof only when provided.
@Test fun `order submit started request body carries specProof`() {
fun body(specProof: String?): String {
val out = java.io.ByteArrayOutputStream()
val connection = object : java.net.HttpURLConnection(java.net.URL("http://127.0.0.1")) {
override fun connect() {}
override fun disconnect() {}
override fun usingProxy() = false
override fun getOutputStream(): java.io.OutputStream = out
override fun getResponseCode(): Int = 500
override fun getErrorStream(): java.io.InputStream = "{}".byteInputStream()
}
val api = cn.ilapage.goauto.agent.network.AgentApiClient("http://127.0.0.1", connectionFactory = { connection })
runCatching { api.markPurchaseOrderSubmitStarted(1, "req-1", "synthetic", specProof) }
return out.toString(Charsets.UTF_8.name())
}
val withProof = org.json.JSONObject(body("selected_summary"))
assertEquals("req-1", withProof.getString("requestId"))
assertEquals("selected_summary", withProof.getString("specProof"))
assertFalse(org.json.JSONObject(body(null)).has("specProof"))
}
private fun automation(driver: PurchaseUiDriver, diagnostics: MutableList<String> = mutableListOf()) =
PurchaseLiveAutomation(driver, pause = {}, panelDiagnostic = diagnostics::add)
private fun check(snapshot: UiSnapshot, input: PurchaseExecutionInput, diagnostics: MutableList<String> = mutableListOf()) =
automation(Driver(snapshot), diagnostics).finalConfirmation(input, PROOF)
private fun rejects(snapshot: UiSnapshot, input: PurchaseExecutionInput): PurchaseLiveException {
val driver = Driver(snapshot)
val error = runCatching { automation(driver).finalConfirmation(input, PROOF) }.exceptionOrNull() as PurchaseLiveException
assertEquals("PURCHASE_SPEC_NOT_MATCHED", error.code)
assertTrue(driver.clicked.isEmpty())
return error
}
private fun rejectsMissingProof(snapshot: UiSnapshot, input: PurchaseExecutionInput) {
assertTrue(rejects(snapshot, input).message.orEmpty().contains("stage=missing_proof"))
}
private fun sheet(
summary: String?, colors: List<String> = listOf("黑色"), sizes: List<String> = listOf("XL"),
): UiSnapshot = SpecPanelFixtures.sheet(SpecPanelFixtures.Sheet(colorLabels = colors, sizeLabels = sizes))
.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
} }
private fun UiSnapshot.mapNodes(transform: (SnapshotNode) -> SnapshotNode) = copy(nodes = nodes.map(transform))
private fun UiSnapshot.selected(suffix: String) = mapNodes {
if (it.path.endsWith(suffix)) it.copy(selected = true) else it
}
private fun input(color: String, size: String) = PurchaseExecutionInput(
taskId = 391, executionMode = "live", phase = "purchase", url = "https://mobile.yangkeduo.com/goods.html?goods_id=391",
goodsId = "391", mappedColor = color, mappedSize = size, quantity = 1,
minUnitPriceCent = 1, maxUnitPriceCent = 3000, addressSuffix = "_cg391",
)
private class Driver(private val snapshot: UiSnapshot) : PurchaseUiDriver {
val clicked = mutableListOf<String>()
override fun capture() = snapshot
override fun clickFresh(target: SnapshotNode): FreshActionResult { clicked += target.path; return FreshActionResult.SUCCESS }
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")
}
private companion object {
const val ADDRESS = "示例区示例路391号_cg391"
val PROOF = ShippingAddressProof(ADDRESS, "_cg391")
}
}
+3 -2
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: 21d6cb0a4d8829ac2dbc4947e7ef7718f237fd2d
synchronized_at: 2026-10-12T15:15:52Z
wiki_revision: 9575d9a43faa8cc5e814e27e34755c77f97b1e84
synchronized_at: 2026-10-14T02:24:50Z
<!-- gitea-wiki-mirror:end -->
<!-- gitea-wiki-mirror:start -->
@@ -152,6 +152,7 @@ Android Portal/Agent
| Admin 采购任务列表、详情与人工处理 | `web/src/views/goauto/purchase-tasks/`、`web/src/api/goauto/purchase-tasks.js`;创建入口不在本模块 |
| 采购任务创建人与列表筛选(#382) | 迁移 `1791700000000_purchase_task_creator.go` 新增 `purchase_task.created_by`(索引)、`created_source`;`purchase/handler.go` `creatorFromContext` 在 Admin 创建/备货/批量创建与客户端密钥请求时写入,Agent 重试路径 `retry.go` `batchRetryCreate` 写 `agent`;`GET /api/admin/v1/purchase-tasks` 新增 `deviceId`(数字或 `unassigned`)、`createdBy`(数字、`agent`、`unrecorded`),列表/详情返回 `createdBy`、`createdByName`、`createdSource`;`GET /api/admin/v1/purchase-tasks/filter-options`(`admin_query.go`)返回任务中出现过的设备与创建人 |
| SYB 已取消订单拦截(#381) | `purchase/return_match_block.go` `sybCancelled`/`rejectIfSYBCancelled`,错误码 `PURCHASE_SYB_CANCELLED`;拦截点:`service.go` 创建、`batch.go` 预览、`ai_match_eligibility.go`、`collection_eligibility.go`、`task/image_search.go`、`process_stage.go`(阶段 `syb_cancelled`);`returnmatch.participatingStages` 不含该阶段 |
| 最终规格依据标记(#391) | 迁移 `1791800000000_purchase_order_spec_proof.go` 新增可空列 `purchase_task.order_spec_proof`(`models.PurchaseTask.OrderSpecProof`,不进 JSON 输出);`purchase/handler.go` `OrderSubmitStarted` 使用 `OrderSubmitStartedRequest`,`lifecycle.go` `MarkOrderSubmitStartedWithProof` 在标记下单开始时写入;Android `PurchaseFinalSpecVerifier.verify` 返回依据,`FinalConfirmationEvidence.specProof` 经 `AgentApiClient.markPurchaseOrderSubmitStarted` 上报 |
| Admin AI 规格匹配设置 | `web/src/views/goauto/ai-matching-settings/`、`web/src/api/goauto/ai-matching-settings.js`;管理员可查看、维护和测试 Provider(包括内部明文 API Key);采购员菜单硬排除,仍只可通过受控 API 查看启用状态 |
| GoAuto 系统菜单与采购员权限基线 | `server/app/goauto/access/` 统一声明 12 个模块、路由元数据和 Admin API 权限矩阵;迁移 `1787885400000_goauto_menus.go` 幂等维护 `sys_menu`、`sys_menu_api_rule`、采购员默认菜单绑定和 Casbin 固定白名单。`web/src/router/index.js` 只保留公共路由,`web/src/store/modules/permission.js` 在登录时根据 `GET /api/v1/menurole` 返回结果注册业务路由与侧栏;退出、凭据异常和切换角色会清除旧动态路由,未授权深链接回退工作台。菜单可见性与 API 授权彼此独立 |
| Admin 失败采购任务批量重试 | `POST /api/admin/v1/purchase-tasks/batch-retry`;服务端 `server/app/goauto/purchase/retry.go` 负责资格判定、逐项幂等创建与部分成功结果,Admin 页面只允许选择服务端标记可重试的行;不修改 Android Agent |
+55 -4
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: 808db5fb272804ca2320a629efb89cd8deb9cbb9
synchronized_at: 2026-10-12T15:15:56Z
wiki_revision: 178f88e7c58f5ce1d2914dd495df9b45a150996b
synchronized_at: 2026-10-14T02:24:57Z
<!-- gitea-wiki-mirror:end -->
<!-- gitea-wiki-mirror:start -->
@@ -721,6 +721,16 @@ SYB 回填与资料完整性独立:正式SYB任务已有单号且仍关联有
### 采购手机环境前提
执行采购的 Android 手机必须:PDD App 已登录、微信已登录、PDD 已设置默认收货地址、PDD 默认支付方式为微信支付。规格面板的地址与支付证据依赖该前提;不为支付宝等其他支付方式补充识别别名(有意决定)。条件不满足时 Agent 明确失败,不自动登录、不切换支付方式、不填写地址。
## 采购接受证据齐全的快捷确认面板(#388)
实现 `0d21ca9`,合并 `496bf80`(2026-10-13,Android 0.9.72/85);尚未装机,真机采购效果未验证。
- 背景:地址保存后返回的规格面板可能带「已选」摘要和底部「现在买,仅 ¥…」按钮,被面板解析归为 `QUICK_CONFIRMATION`。采购原先只接受 `NORMAL_SCROLLABLE`、`NON_SCROLLABLE_CONFIRMATION`、`ORDER_CONFIRMATION` 和 `REQUIRED_EVIDENCE`,因此地址已保存成功也会以 `PURCHASE_ADDRESS_SAVE_TIMEOUT`「地址保存后无法返回订单页面」失败(14 份失败快照离线回放证实)。
- 规则:采购侧把 `QUICK_CONFIRMATION` 视为可下单面板,**仅当**同时满足 #331 必需证据:收货地址入口、支付方式入口和唯一可用的数量输入框都在同一规格面板容器内(与 `REQUIRED_EVIDENCE` 同一门槛)。缺任何一项仍不接受。
- 该判断用于地址保存后识别面板、最终确认和点击下单前的按钮定位;保存后直接停在证据完整的快捷确认面板时,会按最终证据直接通过,不再按返回键。
- 不变:采集流程中 `QUICK_CONFIRMATION` 的含义和处理;地址后缀须唯一;下单目标仍只能是面板容器内最底部的可点击整行,含支付方式别名或支付字样即拒绝;规格、单价、数量复核和只点击一次下单均不放宽。
- 诊断:按返回键后仍无法确认时,失败提示末尾附 `[stage=address_save_back;type=…;<必需证据摘要>;saved=0|1;submitTargets=N]`,只含类型、计数和 0/1,不含页面文字。
## 管理端售后角色(#341)
- 管理端固定增加 `after_sales`(显示名“售后”)业务角色。售后账号拥有采购员当前权限,并额外可访问“yeeke 退货包裹”和“yeeke 同步记录”两个模块及其接口。
@@ -802,7 +812,7 @@ Android 0.9.64 / versionCode 77,源码 `6550b9f`(分支实现,尚未安装
实现绑定 `d6639a4`;2026-10-05 已合并 main `4567a24`,在线迁移并发布至 122.228.200.167。旧记录保持未获取,随后按既有正常同步范围更新;不新增采购拦截。
- “SYB状态”仅显示来源取消标记:`isCancel=1` 为“已取消”,`0` 为“未取消”,没有有效证据为“未获取”。“未取消”不等于可采购,不表达其他 SYB 业务状态,不由 status/orderStatus、规格解析或 PDD 排除标记推断。
- “SYB状态”仅显示来源取消标记:`isCancel=1/2` 均为“已取消”(#389;仅包含该修复的服务端版本),`0` 为“未取消”,没有有效证据为“未获取”。“未取消”不等于可采购,不表达其他 SYB 业务状态,不由 status/orderStatus、规格解析或 PDD 排除标记推断。
- 正常同步成功取得有效值后覆盖原值,允许由取消变回未取消;失败、字段缺失/null、未知值或空页不改变既有取消状态与取得时间。历史记录不默认未取消。
- 仅更新同步范围内实际导入的明细;超出同步创建日期范围的旧订单保留上次状态,未经同步的显示未获取。此列不是实时核验,列表加载不会请求 SYB。
- 本单严格只做展示:不修改创建、批量、重试、Claim/Start、下单边界、采购资格或任务状态,不自动拦截已取消订单,不影响已存在 PDD 订单或回填事实。后续采购拦截已由 #381 实现(见「SYB 已取消订单不进入 PDD 流程(#381)」)。
@@ -998,7 +1008,7 @@ Android同步诊断不改变#377的心跳→恢复→补传→必要的一次任
合并 main `c5709a0`,2026-10-12 随 `15bab9c` 发布到线上(Server + Web),待业务验收。
- `syb_product.syb_is_cancelled = true`(同步取得 `isCancel=1`)的明细:不能创建采购任务(`PURCHASE_SYB_CANCELLED`「SYB 订单已取消,无需采购」),批量采购预览、AI 规格匹配资格、批量采集资格给出同一原因,图搜采集批量逐项拒绝,不参与退货匹配。NULL(未获取)与 false 不拦截,不推断。
- `syb_product.syb_is_cancelled = true`(包含 #389 的版本同步取得 `isCancel=1/2`;旧版只识别 1)的明细:不能创建采购任务(`PURCHASE_SYB_CANCELLED`「SYB 订单已取消,无需采购」),批量采购预览、AI 规格匹配资格、批量采集资格给出同一原因,图搜采集批量逐项拒绝,不参与退货匹配。NULL(未获取)与 false 不拦截,不推断。
- 处理阶段新增 `syb_cancelled`「已取消」,优先级:已有任务或订单结果 → 退货匹配 → 已取消 → 无需采购(#340)→ 其余;同时被过滤规则标记的行显示「已取消」,创建接口仍拒绝(返回码可能是 `PURCHASE_PDD_EXCLUDED`)。
- 同步照常导入并更新取消状态;订单恢复为未取消后阶段与资格自动恢复。
- 不拦截已存在的采购任务(Claim/Start、下单边界与状态机不变);已下单的已取消明细需人工售后。
@@ -1016,6 +1026,16 @@ Android同步诊断不改变#377的心跳→恢复→补传→必要的一次任
合并 main `15bab9c`,2026-10-12 随发布上线,待业务验收。采集任务页新增「设备」筛选(含已停用设备),使用服务端既有 `deviceId` 参数;选择设备时「取消未开始任务」按钮禁用,因为批量取消接口不支持设备维度,避免取消范围超出当前列表。
## 采集任务按设备批量取消与采购员取消范围(#387)
合并 main `df6b4a5`,待发布和业务验收。取代 #383 中「选择设备时按钮禁用」的规则。
- 「取消未开始的任务」按当前筛选(来源、状态、Goods ID、设备)批量取消待执行任务;选了设备时只取消该设备的任务。
- 采购员必须先在「设备」筛选中选择设备(下拉只含归属本人的设备),未选择时提示并停止,不发请求;服务端同样要求非管理员传 `deviceId`,且设备必须归属当前账号,否则返回 `FORBIDDEN`「只能取消归属自己设备的任务」,不取消任何任务。
- 采购员单条取消也只能取消归属本人设备的任务;未指定设备或他人设备的任务一律拒绝(不区分任务当前状态)。
- 管理员不受归属限制:不选设备时取消筛选范围内全部待执行任务(含未指定设备的任务),也可单条取消任意任务;暂不支持「只取消未指定设备的任务」。
- 「设备归属」指 `agent_device.owner_user_id`,以执行取消时的归属为准。
## 客户端密钥上传 Agent 版本(#384)
合并 main `07800cf`,2026-10-12 发布上线,待业务验收。
@@ -1025,3 +1045,34 @@ Android同步诊断不改变#377的心跳→恢复→补传→必要的一次任
- `release_activate`「设置当前 Agent 版本」:把已上传版本设为当前。设为当前后所有设备启动或手动检查时会提示更新,授权页对此显示风险提示。
- 不开放 APK 下载给客户端 API。上传沿用 Admin 的 Manifest 解析、SHA-256、大小与 versionCode 唯一校验;创建人记为授权该密钥的账号。每次调用写客户端审计,不记录文件内容。
- 设备端安装仍由 Android 系统人工确认;签名与已安装版本不一致的 APK 无法覆盖安装,设为当前前须核对目标设备签名。
## SYB 数值取消标记兼容(#389)
实现绑定 `5f329d231157c62f92e2c1348e57ae7ca561fef3`,工单分支 `fix/389-syb-cancel-enum`;未合并 main、未发布,线上现有明细尚未因此修正。
- 来源货运单列表数值 `isCancel`:0「正常」→ false,1「取消」/2「已取消」→ true;同单明细共用该订单级标记。只接受原有 JSON 数字解码,不将其他非零值、字符串、布尔或缺失/null 当作取消。未知值保留已存状态及同步时间。
- 按用户 2026-10-13 确认,以 SYB 取消标记为准,即使平台 `orderStatus` 仍是待出货、已发货或运送中,1/2 仍表示本系统的已取消;反之,只有平台“申请取消”文字而数值为 0 时不推断取消。前端枚举及整单取消动作可证明 2 的含义,不推测 1 必定由哪个平台生成。
- 已知值随既有同步更新取消状态及取得时间,0 可恢复未取消。#381 的新建/展示期限制沿用,不新增领取/开始/下单边界拦截,不自动停止已有 pending/running 采购任务。日期范围和定时周期不变。
- 线上有界重同步须单独授权;此前在受控环境保留受影响明细原值与时间的最小恢复依据,同步后只读报告新增已取消且仍有未完成任务的明细,由用户决定处理。上述生产数据不写入仓库、工单、Wiki 或消息。
- 回退代码不会自动恢复已经同步的 true;后续纠正须有来源事实及独立授权,不通过一律映射 false 来掩盖错误。
## 采购规格面板近正方形滚动区域(#390)
实现 `a3c05a7`,2026-10-14 合并 main `5282d65`(Agent `0.9.73 / code86`,包含 #388);未安装或发布,真机展开顶部地址区域的效果未验证。
- 仅采购 `PurchaseLiveAutomation.purchasePanelScrollTargets` 的形状条件调整为“高度不小于宽度的 80%”,用于改地址前寻找入口、保存地址后恢复当前面板证据。不是所有纵向滚动容器的通用规则,普通采集器不改。
- 继续要求节点可见、启用、可滚动,宽度至少为视口估算宽度的 60%、高度至少为视口估算高度的 20%,且滚动候选必须唯一。扁平横条、尺寸不足及多候选仍明确失败,不选择最大区域兜底。
- 向下滑动的方向、距离、时长、最多五轮采样和视口不变停止规则保持原样;两个调用点的原有失败路径均保留。地址编辑/保存、规格、金额、提交按钮与一次性下单检查不改,不涉及付款。
- 合成回归与失败现场的只读结构尺寸核对只能证明该几何候选不再被错误排除,不能证明在真实 PDD 页面内滑动一定能展开顶部地址。安装及实际采购须另行授权。
## 最终规格复核的「已选」摘要 `#` 前缀与规格依据标记(#391)
实现 `f62f071`,2026-10-14 合并 main `0cb674a`(Agent `0.9.74 / code87`,含 #388、#390;Server 含迁移 `1791800000000_purchase_order_spec_proof.go`);未发布、未迁移、未安装。
- 改完地址后的最终规格复核(`PurchaseFinalSpecVerifier`)原本就接受面板内的「已选」摘要作为依据:摘要经 `normalizeFinalConfirmation` 后须恰好等于「颜色 尺码」(单空格分隔)。采购1 的摘要写作「已选: #颜色 尺码」,解析时只去掉前缀和一个冒号,多出的 `#` 使比较失败(`stage=missing_proof;summaryPresent=1`)。
- 现在解析时,在去掉前缀和可选冒号之后,再去掉开头的空白和**一个** `#` 或 `#`。值内部的 `#` 不动,连续两个 `#` 只去一个。其他判定不变:只读面板内摘要;选中冲突、候选重复、不可选、组合歧义、摘要冲突照旧拒绝;单价、数量、地址、下单按钮检查照旧。
- 规格依据:每个目标维度都有选中选项作证时记 `selected_option`;至少一个维度只靠摘要通过时记 `selected_summary`。Agent 在 `order-submit-started` 请求中携带 `specProof`,服务端写入 `purchase_task.order_spec_proof`;缺失或未知值存 NULL。中断恢复路径不携带,旧 Agent 为 NULL。
- 抽查:装机试运行一段时间后,只读列出 `order_spec_proof='selected_summary'` 的已下单任务,人工对照 PDD 订单的实际规格,判断有无下错。
- 发布顺序:**先服务端(含迁移)、后 Agent**。服务端严格拒绝未知字段,新 Agent 连旧服务端时 `order-submit-started` 会失败;此时不会下单,但所有采购都会失败。回退顺序相反。
- 采购2 部分面板样式不显示「已选」摘要,这类失败本单不能救回。
+11 -3
View File
@@ -2,8 +2,8 @@
generated: true (请先修改 Gitea Wiki,禁止直接编辑本文件)
wiki_page: Android-Agent-API-Contract
wiki_url: https://git.ilapage.cn/OPC/goauto/wiki/Android-Agent-API-Contract.-
wiki_revision: c05446aecd49fb7234f79f5d5e2df68f244166e9
synchronized_at: 2026-10-12T08:31:57Z
wiki_revision: 3db235ff7d7e9350e129bca499e2da084d4cee42
synchronized_at: 2026-10-14T02:25:49Z
<!-- gitea-wiki-mirror:end -->
<!-- gitea-wiki-mirror:start -->
@@ -250,6 +250,8 @@ POST /api/admin/v1/collection-tasks/batch
GET /api/admin/v1/collection-tasks
GET /api/admin/v1/collection-tasks/{taskId}
POST /api/admin/v1/collection-tasks/{taskId}/reset
POST /api/admin/v1/collection-tasks/{taskId}/cancel
POST /api/admin/v1/collection-tasks/batch-cancel
DELETE /api/admin/v1/collection-tasks/{taskId}
```
@@ -292,6 +294,12 @@ HTTP 200 响应返回 `successCount`、`failureCount` 和按请求顺序排列
`reset` 请求体和失败任务 `DELETE` 请求体均为 `{"requestId":"uuid"}`。只允许删除 `failed`;重置允许 `completed`、`completed_partial`、`failed`。二者均按 `requestId` 幂等。
取消(#297、#298、#387):
- 单条取消 `POST /collection-tasks/{taskId}/cancel`,请求体 `{"requestId":"uuid"}`。只允许取消 `pending` 且未被设备领取(租约未生效)的任务;已取消返回幂等成功;`running` 或其他状态返回 `TASK_STATE_CONFLICT`。
- 批量取消 `POST /collection-tasks/batch-cancel`,请求体字段均可选:`source`、`status`、`goodsId`(与列表筛选同一匹配方式)、`deviceId`。只取消范围内 `pending` 且未被领取的任务,单次最多 500 条;响应 `cancelledCount`、`cancelledIds`、`skipped[{taskId,status}]`、`hasMore`。
- 权限:管理员不受设备归属限制,`deviceId` 可省略(范围含未指定设备的任务)。非管理员(采购员)批量取消必须传 `deviceId`,缺少时 HTTP 422 `INVALID_REQUEST`「请先选择设备」;设备不存在、未归属或归属他人时 HTTP 403 `FORBIDDEN`「只能取消归属自己设备的任务」,不取消任何任务。非管理员单条取消未指定设备或他人设备的任务同样返回 403 `FORBIDDEN`,不区分任务状态。
## Android:注册与心跳
```http
@@ -584,7 +592,7 @@ Admin 列表与详情由 #35 实现;#67 增加 `shopeeOrderNoSnapshot` 的列
| `GET` | `/api/agent/v1/purchase-tasks/next` | 优先返回当前设备的运行任务;存在 `spec_probe_pending` 时返回同一等待任务以阻止其他任务插队,否则返回能力兼容的指定任务或空闲任务 |
| `POST` | `/api/agent/v1/purchase-tasks/{taskId}/claim` | `requestId` 原子领取,并建立设备/可选账号租约 |
| `POST` | `/api/agent/v1/purchase-tasks/{taskId}/start` | 创建不可变 `taskAttemptId` |
| `POST` | `/api/agent/v1/purchase-tasks/{taskId}/order-submit-started` | 创建订单前先落不可逆标记;演练任务和 `spec_probe` attempt 永远拒绝 |
| `POST` | `/api/agent/v1/purchase-tasks/{taskId}/order-submit-started` | 创建订单前先落不可逆标记;演练任务和 `spec_probe` attempt 永远拒绝。请求体 `requestId` 必填;`specProof` 可选(#391),取值 `selected_summary`(最终规格复核凭「已选」摘要)或 `selected_option`(凭选中选项),缺失或未知值存 NULL、不拒绝;同一 `requestId` 重放不改已存值;其他未知字段仍拒绝。`claim`、`start` 不接受 `specProof`。响应不返回该字段 |
| `POST` | `/api/agent/v1/purchase-tasks/{taskId}/result` | 请求体携带 `taskAttemptId` 和 `requestId`;幂等提交演练、规格探测、订单或失败结果 |
自 #215 起,新建 SYB 采购任务不再从 PDD 档案创建持久匹配工作项,也不在首次派发前调用外部 AI;部署前已存在的 `purchase_spec_match_work_item` 继续按原状态兼容处理。新任务首次 `start` 固定得到 `phase=spec_probe`,Android 通过浏览器打开任务链接一次并经既有结果字段回传当次候选;匹配成功后的第二次 `start` 才得到 `phase=purchase` 和服务端固化的精确 PDD 原始标签。连续第二阶段仅在当前 PDD 页面仍有商品页或规格面板强证据时复用首趟页面、不再次打开浏览器链接;手动同任务重试,或当前为 Agent、其他应用及缺少上述强证据时,Android 重新打开任务 `urlSnapshot`。两种路径都不以标题、goodsId 或页面指纹做严格同页校验,仍必须通过 PDD 包名和商品/规格/订单页面结构安全证据。Android 不接收 AI 配置或自由决策权限。
+10 -3
View File
@@ -2,8 +2,8 @@
generated: true (请先修改 Gitea Wiki,禁止直接编辑本文件)
wiki_page: SYB-ERP-Interface-Contract
wiki_url: https://git.ilapage.cn/OPC/goauto/wiki/SYB-ERP-Interface-Contract.-
wiki_revision: 5979a14250c96c3c92348a947c2bc8d3a078c9f4
synchronized_at: 2026-09-29T08:18:40Z
wiki_revision: 3f44b3ed91ff19c592bba4e2dbbef28d971633da
synchronized_at: 2026-10-13T10:03:50Z
<!-- gitea-wiki-mirror:end -->
# 12 顺云宝(SYB)ERP 接口契约
@@ -272,7 +272,7 @@ ID,或某张货运单返回空商品明细,都视为不完整并停止当前
| `shopName` | `<店铺名>` | 蝦皮店铺 |
| `productName` | `純棉上衣` | **只有一个商品名**,一单多商品时不完整 |
| `orderQty` / `detailQty` | `2` / `2` | 商品件数 |
| `isCancel` | `0` | 是否取消 |
| `isCancel` | `0` / `1` / `2` | 订单级取消标记:0 正常,1 取消,2 已取消。包含 #389 的服务端将 1/2 均映射 true、0 映射 false;未知值保留旧值,不从 status/orderStatus 推断。旧版只识别 0/1。 |
| `expCompany` | `蝦皮店到店` | 物流方式 |
| `receiver` / `receiverTel` / `receiverAddr` | — | **收件人信息,属个人数据** |
@@ -709,3 +709,10 @@ POST /am/stock/detail/updateDetailPurchaseCode,无JSON body;query:id=<stoc
客户端每次处理最多一次写请求,并拒绝HTTP重定向重发;超时/连接中断/5xx/损坏响应作为结果未知。无论写响应成功或未知,都须按 stockId + detailId 唯一回读目标;相同单号+pdd才确认为成功,不同已有单号或其他非空平台记冲突且不覆盖。写前为空才写;目标缺失/重复/字段类型异常不得猜测选择。未知且未回读确认时持久化unknown,人工补偿前再次回读,不使用自动写重试。
GoAuto自身通过持久租约串行,但SYB没有CAS证据,无法原子隔离系统外客户端;不能保证任意迟到请求已终止。真实接口写入需另行明确授权;当前验证仅fake/httptest。
### isCancel 枚举核验(#389,2026-10-13)
来源前端 `/sys/js/app.226509c4.js` 的 `cances` 定义 0「正常」、1「取消」、2「已取消」;`/sys/js/stock.b4a33aea.js` 用该枚举渲染状态,整单取消对选中的货运单 ID 设值 2,恢复设值 0,平台取消是另一项可选动作。此次只读核验,没有调用取消或恢复接口。该事实不构成本系统新增调用这些写接口的授权。
经用户确认,GoAuto 的取消判断以该数值为准,不受平台订单/物流文字影响;含 #389 的实现 `5f329d231157c62f92e2c1348e57ae7ca561fef3` 尚未合并发布。字段类型、同步日期范围、数据库及下游 API 不变;来源未知值不覆盖既有状态和时间,不能靠重新同步未知值撤销已写入的 true。
+30 -2
View File
@@ -2,8 +2,8 @@
generated: true (请先修改 Gitea Wiki,禁止直接编辑本文件)
wiki_page: Deployment-and-Operations
wiki_url: https://git.ilapage.cn/OPC/goauto/wiki/Deployment-and-Operations.-
wiki_revision: 7e91eea0ec077f5af813375bdd94d8878e7e16d7
synchronized_at: 2026-10-12T15:16:03Z
wiki_revision: 19eaaa2853544e73f4abc5b788b571377e87296b
synchronized_at: 2026-10-13T03:49:33Z
<!-- gitea-wiki-mirror:end -->
<!-- gitea-wiki-mirror:start -->
@@ -347,6 +347,25 @@ Provider 故障日志只允许记录调用关联 ID、操作类型、耗时、
- 换机生成的调试签名与旧机不同会导致 `INSTALL_FAILED_UPDATE_INCOMPATIBLE`;不可为更新擅自卸载。用户提供的原调试签名已与手机证书核对一致,私有文件位于 `D:/OPC/goauto/debug.keystore`,仅在本地Git排除规则中忽略,绝不提交。应另行私密备份,不能重新生成替代。
- 当前Windows用户级 `C:/Users/Qiu/.gradle/init.d/goauto-debug-signing.gradle` 使用Android Components的 `finalizeDsl`,仅对applicationId `cn.ilapage.goauto.agent` 的debug签名指定原文件;其他项目及release配置不变。普通Gradle调试构建自动生效,文件缺失则明确失败,不退回新签名。更换电脑或GRADLE_USER_HOME时需带入相同私有文件及配置;不要把本机设置当作仓库内或其他电脑已配置。构建后用signingReport与apksigner复核,再以install -r更新。
### Agent 装机签名对照(2026-10-13 核对)
采购机和测试机上已装的 Agent 签名不同,装包前必须按目标设备选对签名:
| 设备 | 序列号 | 已装证书 SHA-256 | 签名文件 |
|---|---|---|---|
| 采购1(PKG110) | `3B65BD02H7F00000` | `bf86d7465c6092be74ce9c4187eb30c9a7d045c3b91891a547e2598429766dec` | `D:/OPC/goauto/debug.keystore`(私有,不提交) |
| 采购2(PLY110) | `3B663A00JW500000` | 同采购1 | 同采购1 |
| 测试机(PLY110) | `3B668T01GF400000` | `3eab2527dc3ce592fe22f2f8cc31e4d0fa07dd1fa54b6209948ea6ce9cd7c4f6` | `C:/Users/Qiu/.android/debug.keystore` |
- 本机 Gradle 调试构建产物已经是采购机签名(由上面的 init 脚本强制),可以直接装采购机;装测试机前需用 apksigner 以测试机签名改签。
- 装包前逐台核对:
- `ro.serialno` 确认目标设备(USB 连接的手机不一定是测试机);
- 用 `pm path` 拉取已装 `base.apk`,比较它与待装 APK 的 `apksigner verify --print-certs`;
- 设备空闲,没有待执行或执行中的任务。
- 签名不一致会报 `INSTALL_FAILED_UPDATE_INCOMPATIBLE`,**不得卸载重装**:卸载会清掉设备凭据和本地采购数据。
- 装完后手动打开 Agent,等待心跳恢复;无障碍显示未连接时,在系统设置中把 GoAuto 关闭后重新打开(#385)。
- 2026-10-13 记录:0.9.71(84,main `328afde`)测试机包 SHA256 `10ad5a2b898230897b15a54f73212ae56a11fcf2f73beffc0392321699d7cf00`,采购1 包 SHA256 `3004cda3784182381e98ce9953cabcdba4017eb535c8578a2b317b3a7303e6ab`,均以 `install -r` 覆盖安装,未卸载。
## Android 商品导航诊断(#373,诊断阶段)
@@ -441,3 +460,12 @@ Server实现 `d84728d`、Android实现 `dbe7e98`,main 合并记录见 #378;
- 按内容验收:`/`、`/login` 新 index,10 项 JS/CSS 200,验证码 200,未登录 Admin 接口 401;`/api/client/v1/agent-app-releases` 的 GET/PUT 无密钥 401;下载路径 404(未开放);日志无 panic/fatal/1146/1054。
- Nginx 9527 vhost `client_max_body_size 100m`,超过 100MB 的 APK 会在到达服务前被拒。
- 回滚:current 切回 `/home/goauto/releases/20261012-15bab9c-381-382-383` 并重启。
## #387 采集任务按设备批量取消发布(2026-10-13)
- 用户授权「先把#387发布到线上」。main `5183df3`(实现 `fc5d9ed`,合并 `df6b4a5`);相对上一线上源码 `07800cf`,Server/Web 只增加 #387 的 6 个文件,无迁移、无配置变化,未做数据库备份。`go test ./app/goauto/task/` 通过;Linux amd64 `CGO_ENABLED=0` 构建、Web `build:prod` 通过。
- 发布目录 `/home/goauto/releases/20261013-5183df3-387`:goauto-server SHA256 `85c307cf2393eaf0d6188217ddf0560d3fead3313b72ce98c1e6bf2e6ea44b23`(运行进程一致),index.html SHA256 `dfd9dadfe28fbdb500aa91ce98611850215ad8b53b908b79200f23b205960ba9`;config 与上一发布 diff 一致,static/temp/var 链接沿用,旧 js/css 哈希资源保留(`cp -rn`);目录 0755,已用 Nginx 运行账号 `www` 验证可读。
- 切换沿用等待脚本(`/root/goauto-switch-387.sh`,复制自 #384 脚本):采集与采购执行中数量连续为 0 后原子切换并重启。11:47:24 开始等待,11:47:41 切换,`goauto.service` active;日志 `/home/goauto/backups/20261013-387-switch.log`。当时有 1 个待执行采购任务,保持原状。
- 按内容验收:`/`、`/login` 返回新 index(含 `id="app"`、无欢迎页),10 项 JS/CSS 与新采集任务页资源均 200,验证码 code=200,未登录访问 `collection-tasks/batch-cancel`、`yeeke-returns` 为业务码 401;重启后日志无 panic/fatal/1146/1054;采购1、采购2 心跳恢复在线(Agent 0.9.71)。
- 未做:线上管理员与采购员账号的功能检查(待用户验收)。
- 回滚:current 原子切回 `/home/goauto/releases/20261012-07800cf-384` 并重启(先确认无执行中任务);无数据库变化。
+9 -2
View File
@@ -24,6 +24,10 @@ const (
PurchaseTaskStatusFailed = "failed"
PurchaseTaskStatusCancelled = "cancelled"
PurchaseOrderSpecProofSelectedSummary = "selected_summary"
PurchaseOrderSpecProofSelectedOption = "selected_option"
PurchaseOrderSpecProofNoPendingPrompt = "no_pending_prompt"
PurchaseAttemptPhaseSpecProbe = "spec_probe"
PurchaseAttemptPhasePurchase = "purchase"
@@ -135,8 +139,11 @@ type PurchaseTask struct {
CreateRequestID string `json:"-" gorm:"size:36;not null;uniqueIndex:ux_purchase_task_create_request_id"`
ClaimRequestID *string `json:"-" gorm:"size:36;uniqueIndex:ux_purchase_task_claim_request_id"`
OrderSubmitRequestID *string `json:"-" gorm:"size:64;uniqueIndex:ux_purchase_task_order_submit_request_id"`
StatusVersion uint64 `json:"statusVersion" gorm:"not null;default:1"`
StatusChangedAt time.Time `json:"statusChangedAt" gorm:"not null"`
// OrderSpecProof 记录下单前最终规格复核的依据(#391):selected_summary=凭「已选」
// 摘要,selected_option=原检查;NULL=旧 Agent 或未提供。仅供人工抽查,不进任何 JSON 输出。
OrderSpecProof *string `json:"-" gorm:"size:32"`
StatusVersion uint64 `json:"statusVersion" gorm:"not null;default:1"`
StatusChangedAt time.Time `json:"statusChangedAt" gorm:"not null"`
PDDOrderNo *string `json:"pddOrderNo" gorm:"size:100;index"`
OrderSubmittedAt *time.Time `json:"orderSubmittedAt"`
+22 -3
View File
@@ -331,9 +331,28 @@ func (h Handler) AgentReset(c *gin.Context) {
c.Header("Cache-Control", "no-store")
c.JSON(http.StatusOK, gin.H{"data": result})
}
func (h Handler) Claim(c *gin.Context) { h.action(c, (*Service).Claim) }
func (h Handler) Start(c *gin.Context) { h.action(c, (*Service).Start) }
func (h Handler) OrderSubmitStarted(c *gin.Context) { h.action(c, (*Service).MarkOrderSubmitStarted) }
func (h Handler) Claim(c *gin.Context) { h.action(c, (*Service).Claim) }
func (h Handler) Start(c *gin.Context) { h.action(c, (*Service).Start) }
func (h Handler) OrderSubmitStarted(c *gin.Context) {
id, ok := pathID(c)
if !ok {
return
}
var req OrderSubmitStartedRequest
if !decode(c, &req) {
return
}
service, serviceOK := h.service(c)
if !serviceOK {
return
}
p, err := service.MarkOrderSubmitStartedWithProof(c.Request.Context(), id, req, bearer(c.GetHeader("Authorization")))
if err != nil {
writeError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"data": p})
}
func (h Handler) Result(c *gin.Context) {
id, ok := pathID(c)
if !ok {
+10
View File
@@ -274,6 +274,12 @@ func purchaseRuleSnapshotHash(snapshot string) string {
}
func (s *Service) MarkOrderSubmitStarted(ctx context.Context, taskID uint64, req ActionRequest, token string) (TaskPayload, error) {
return s.MarkOrderSubmitStartedWithProof(ctx, taskID, OrderSubmitStartedRequest{RequestID: req.RequestID}, token)
}
// MarkOrderSubmitStartedWithProof 在标记下单开始的同一次保存里记录最终规格依据(#391)。
// 依据只认已知枚举,缺失或未知值存 NULL,不影响下单边界标记;重放不改已存值。
func (s *Service) MarkOrderSubmitStartedWithProof(ctx context.Context, taskID uint64, req OrderSubmitStartedRequest, token string) (TaskPayload, error) {
return s.withRunning(ctx, taskID, token, func(tx *gorm.DB, t *models.PurchaseTask, a *models.PurchaseTaskAttempt, d models.AgentDevice) (TaskPayload, error) {
if t.ExecutionMode != models.PurchaseExecutionModeLive {
return TaskPayload{}, fail(CodeStateConflict, "演练任务不能创建订单")
@@ -295,6 +301,10 @@ func (s *Service) MarkOrderSubmitStarted(ctx context.Context, taskID uint64, req
return TaskPayload{}, internal(e)
}
t.OrderSubmitRequestID = &req.RequestID
if proof := req.SpecProof; proof == models.PurchaseOrderSpecProofSelectedSummary || proof == models.PurchaseOrderSpecProofSelectedOption ||
proof == models.PurchaseOrderSpecProofNoPendingPrompt {
t.OrderSpecProof = &proof
}
t.IrreversibleAt = &now
t.StatusVersion++
t.StatusChangedAt = now
@@ -0,0 +1,109 @@
package purchase
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"time"
"go-admin/app/goauto/models"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"gorm.io/gorm"
)
func TestMarkOrderSubmitStartedRecordsSpecProof(t *testing.T) {
for _, tc := range []struct {
name string
proof string
want *string
}{
{"summary", "selected_summary", ptrString("selected_summary")},
{"no pending prompt", "no_pending_prompt", ptrString("no_pending_prompt")},
{"option", "selected_option", ptrString("selected_option")},
{"missing", "", nil},
{"unknown", "something_else", nil},
} {
t.Run(tc.name, func(t *testing.T) {
db := testDB(t)
f := seed(t, db, liveCaps(), true)
s := testService(db)
task, err := createLive(t, s, f)
if err != nil {
t.Fatal(err)
}
startLivePurchaseAfterProbe(t, s, f, task)
reqID := uuid.NewString()
if _, err = s.MarkOrderSubmitStartedWithProof(context.Background(), task.ID, OrderSubmitStartedRequest{RequestID: reqID, SpecProof: tc.proof}, f.token); err != nil {
t.Fatal(err)
}
assertSpecProof(t, db, task.ID, tc.want)
// Same requestId replay with a different proof must not change the stored value.
replay, err := s.MarkOrderSubmitStartedWithProof(context.Background(), task.ID, OrderSubmitStartedRequest{RequestID: reqID, SpecProof: "selected_option"}, f.token)
if err != nil || !replay.Replayed {
t.Fatalf("replay failed: %+v %v", replay, err)
}
assertSpecProof(t, db, task.ID, tc.want)
})
}
}
func TestOrderSubmitStartedHandlerSpecProofAndStrictDecode(t *testing.T) {
db := testDB(t)
f := seed(t, db, liveCaps(), true)
s := testService(db)
task, err := createLive(t, s, f)
if err != nil {
t.Fatal(err)
}
startLivePurchaseAfterProbe(t, s, f, task)
// The handler builds its own service with the real clock; keep the lease valid.
future := time.Now().Add(time.Hour)
if err = db.Session(&gorm.Session{SkipHooks: true}).Model(&models.PurchaseTask{}).Where("id = ?", task.ID).Update("lease_expires_at", future).Error; err != nil {
t.Fatal(err)
}
h := Handler{DB: db}
post := func(fn gin.HandlerFunc, body string) *httptest.ResponseRecorder {
gin.SetMode(gin.TestMode)
w := httptest.NewRecorder()
c, _ := gin.CreateTestContext(w)
c.Params = gin.Params{{Key: "taskId", Value: strconv.FormatUint(task.ID, 10)}}
c.Request = httptest.NewRequest(http.MethodPost, "/", bytes.NewBufferString(body))
c.Request.Header.Set("Authorization", "Bearer "+f.token)
fn(c)
return w
}
// Claim/Start keep rejecting specProof as an unknown field.
for name, fn := range map[string]gin.HandlerFunc{"claim": h.Claim, "start": h.Start} {
if w := post(fn, `{"requestId":"`+uuid.NewString()+`","specProof":"selected_summary"}`); w.Code != http.StatusUnprocessableEntity {
t.Fatalf("%s accepted specProof: %d %s", name, w.Code, w.Body.String())
}
}
// Unknown extra fields are still rejected on order-submit-started.
if w := post(h.OrderSubmitStarted, `{"requestId":"`+uuid.NewString()+`","other":1}`); w.Code != http.StatusUnprocessableEntity {
t.Fatalf("unknown field accepted: %d", w.Code)
}
w := post(h.OrderSubmitStarted, `{"requestId":"`+uuid.NewString()+`","specProof":"selected_summary"}`)
if w.Code != http.StatusOK {
t.Fatalf("order-submit-started failed: %d %s", w.Code, w.Body.String())
}
assertSpecProof(t, db, task.ID, ptrString("selected_summary"))
if bytes.Contains(w.Body.Bytes(), []byte("orderSpecProof")) || bytes.Contains(w.Body.Bytes(), []byte("specProof")) {
t.Fatalf("proof leaked into response: %s", w.Body.String())
}
}
func assertSpecProof(t *testing.T, db *gorm.DB, id uint64, want *string) {
t.Helper()
var saved models.PurchaseTask
if err := db.First(&saved, id).Error; err != nil {
t.Fatal(err)
}
if (saved.OrderSpecProof == nil) != (want == nil) || (want != nil && *saved.OrderSpecProof != *want) {
t.Fatalf("order_spec_proof=%v want %v", saved.OrderSpecProof, want)
}
}
+7
View File
@@ -154,6 +154,13 @@ type ActionRequest struct {
RequestID string `json:"requestId"`
}
// OrderSubmitStartedRequest 只用于 order-submit-started;specProof 可选(#391),
// 领取、开始接口仍用 ActionRequest,不接受该字段。
type OrderSubmitStartedRequest struct {
RequestID string `json:"requestId"`
SpecProof string `json:"specProof,omitempty"`
}
type TaskPayload struct {
TaskID uint64 `json:"taskId"`
TaskAttemptID string `json:"taskAttemptId,omitempty"`
+34 -2
View File
@@ -9,6 +9,7 @@ import (
"strings"
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
)
func (handler Handler) AdminList(c *gin.Context) {
@@ -176,7 +177,7 @@ func (handler Handler) AdminCancel(c *gin.Context) {
if !ok {
return
}
response, err := service.Cancel(c.Request.Context(), id, request)
response, err := service.CancelOwnedBy(c.Request.Context(), id, request, ownerScope(c))
if err != nil {
writeError(c, err)
return
@@ -194,7 +195,7 @@ func (handler Handler) AdminBatchCancel(c *gin.Context) {
if !ok {
return
}
response, err := service.BatchCancel(c.Request.Context(), request)
response, err := service.BatchCancelOwnedBy(c.Request.Context(), request, ownerScope(c))
if err != nil {
writeError(c, err)
return
@@ -202,6 +203,37 @@ func (handler Handler) AdminBatchCancel(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"code": 200, "data": response})
}
// ownerScope 返回取消操作的归属限制:管理员返回 nil(不限制),其他角色返回
// 当前用户 id(取不到时为 0,此时任何设备都不算本人设备)。读取方式与
// device/handler.go 一致(JWT rolekey / identity,#333)。
func ownerScope(c *gin.Context) *uint64 {
if role, _ := jwt.ExtractClaims(c)["rolekey"].(string); role == "admin" {
return nil
}
id := currentUserID(c)
return &id
}
func currentUserID(c *gin.Context) uint64 {
switch id := jwt.ExtractClaims(c)["identity"].(type) {
case float64:
if id > 0 {
return uint64(id)
}
case int:
if id > 0 {
return uint64(id)
}
case int64:
if id > 0 {
return uint64(id)
}
case uint64:
return id
}
return 0
}
func decodeStrict(c *gin.Context, destination any) error {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, 1<<20)
decoder := json.NewDecoder(c.Request.Body)
+64 -5
View File
@@ -13,6 +13,20 @@ import (
const maxBatchCancelItems = 500
const messageNotOwnDevice = "只能取消归属自己设备的任务"
// deviceOwnedBy 判断设备是否归属指定用户;设备为空、不存在或未归属都视为否。
func deviceOwnedBy(db *gorm.DB, deviceID *uint64, ownerUserID uint64) (bool, error) {
if deviceID == nil || *deviceID == 0 || ownerUserID == 0 {
return false, nil
}
var count int64
if err := db.Model(&models.AgentDevice{}).Where("id = ? AND owner_user_id = ?", *deviceID, ownerUserID).Count(&count).Error; err != nil {
return false, internalError(err)
}
return count > 0, nil
}
// CancelResponse describes the outcome of cancelling one pending collection task.
type CancelResponse struct {
TaskID uint64 `json:"taskId"`
@@ -31,6 +45,9 @@ type BatchCancelRequest struct {
// 筛出两条、按钮却取消三十几条——那正是当初放弃「两个固定按钮」、改用
// 「筛选 + 一个按钮」想避免的事(#298)。
GoodsID string `json:"goodsId,omitempty"`
// DeviceID 按设备限定取消范围(#387)。管理员可不传(范围与之前一致,含
// 未指定设备的任务);非管理员必须传,且必须是归属自己的设备。
DeviceID uint64 `json:"deviceId,omitempty"`
}
type BatchCancelSkippedItem struct {
@@ -57,6 +74,13 @@ type BatchCancelResponse struct {
// failure #292 already paid for once. The semantics are "stop what has not
// started, let what is running finish".
func (service *Service) Cancel(ctx context.Context, taskID uint64, request ActionRequest) (CancelResponse, error) {
return service.CancelOwnedBy(ctx, taskID, request, nil)
}
// CancelOwnedBy 与 Cancel 相同,但 ownerUserID 非空时只允许取消归属该用户设备
// 的任务(#387)。未指定设备、设备不存在或归属他人的任务一律返回同一个拒绝,
// 不区分任务当前状态,避免向采购员泄露不属于他的任务信息。
func (service *Service) CancelOwnedBy(ctx context.Context, taskID uint64, request ActionRequest, ownerUserID *uint64) (CancelResponse, error) {
if err := validateAction(taskID, request); err != nil {
return CancelResponse{}, err
}
@@ -69,6 +93,15 @@ func (service *Service) Cancel(ctx context.Context, taskID uint64, request Actio
}
return internalError(err)
}
if ownerUserID != nil {
owned, err := deviceOwnedBy(tx, record.DeviceID, *ownerUserID)
if err != nil {
return err
}
if !owned {
return serviceError(CodeForbidden, messageNotOwnDevice)
}
}
if record.Status == models.TaskStatusCancelled {
response = CancelResponse{TaskID: taskID, Cancelled: true}
return nil
@@ -88,11 +121,15 @@ func (service *Service) Cancel(ctx context.Context, taskID uint64, request Actio
// 只看 status 会把"已被领取、马上要开始"的任务误判成可取消。
// RowsAffected 为 0 说明任务已被领取或状态已变化,取消必须失败。
now := service.Now()
result := tx.Session(&gorm.Session{SkipHooks: true}).Model(&models.CollectionTask{}).
Where("id = ? AND status = ? AND (lease_expires_at IS NULL OR lease_expires_at <= ?)", record.ID, models.TaskStatusPending, now).
Updates(map[string]any{
"status": models.TaskStatusCancelled, "active_slot": nil, "device_run_slot": nil,
})
update := tx.Session(&gorm.Session{SkipHooks: true}).Model(&models.CollectionTask{}).
Where("id = ? AND status = ? AND (lease_expires_at IS NULL OR lease_expires_at <= ?)", record.ID, models.TaskStatusPending, now)
if ownerUserID != nil {
// 上面已校验归属;这里在写入条件里再兜一层,防止校验与更新之间归属变化。
update = update.Where("device_id IN (SELECT id FROM agent_device WHERE owner_user_id = ?)", *ownerUserID)
}
result := update.Updates(map[string]any{
"status": models.TaskStatusCancelled, "active_slot": nil, "device_run_slot": nil,
})
if result.Error != nil {
return internalError(result.Error)
}
@@ -115,6 +152,25 @@ func (service *Service) Cancel(ctx context.Context, taskID uint64, request Actio
// 回滚已经成功取消的其它任务。采购员要的是「能停多少停多少」,而不是全有或
// 全无——批量越大,中途有一条被领走的概率越高。
func (service *Service) BatchCancel(ctx context.Context, request BatchCancelRequest) (BatchCancelResponse, error) {
return service.BatchCancelOwnedBy(ctx, request, nil)
}
// BatchCancelOwnedBy 与 BatchCancel 相同,但 ownerUserID 非空(非管理员)时
// 必须指定 DeviceID,且该设备必须归属 ownerUserID,否则不取消任何任务(#387)。
func (service *Service) BatchCancelOwnedBy(ctx context.Context, request BatchCancelRequest, ownerUserID *uint64) (BatchCancelResponse, error) {
if ownerUserID != nil {
if request.DeviceID == 0 {
return BatchCancelResponse{}, serviceError(device.CodeInvalidRequest, "请先选择设备")
}
deviceID := request.DeviceID
owned, err := deviceOwnedBy(service.DB.WithContext(ctx), &deviceID, *ownerUserID)
if err != nil {
return BatchCancelResponse{}, err
}
if !owned {
return BatchCancelResponse{}, serviceError(CodeForbidden, messageNotOwnDevice)
}
}
source := strings.TrimSpace(request.Source)
if source != "" && source != models.CollectionTaskSourceAdmin && source != models.CollectionTaskSourceAgentCurrentPage && source != models.CollectionTaskSourceImageSearch {
return BatchCancelResponse{}, serviceError(device.CodeInvalidRequest, "source 无效")
@@ -135,6 +191,9 @@ func (service *Service) BatchCancel(ctx context.Context, request BatchCancelRequ
if goodsID := strings.TrimSpace(request.GoodsID); goodsID != "" {
query = query.Where("goods_id_snapshot LIKE ?", "%"+goodsID+"%")
}
if request.DeviceID > 0 {
query = query.Where("device_id = ?", request.DeviceID)
}
var candidates []models.CollectionTask
// 多取一条用于判断范围内是否还有未处理的任务,多出来的那条不参与取消。
if err := query.Order("id ASC").Limit(maxBatchCancelItems + 1).Find(&candidates).Error; err != nil {
+224
View File
@@ -0,0 +1,224 @@
package task
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"go-admin/app/goauto/models"
"github.com/gin-gonic/gin"
jwt "github.com/go-admin-team/go-admin-core/sdk/pkg/jwtauth"
"github.com/google/uuid"
"gorm.io/gorm"
)
// #387:批量取消按设备限定,单条/批量取消对非管理员强制设备归属。
func ownDevice(t *testing.T, db *gorm.DB, name string, owner uint64) models.AgentDevice {
t.Helper()
record, _ := registerTaskDevice(t, db, name)
if owner > 0 {
if err := db.Model(&models.AgentDevice{}).Where("id = ?", record.ID).Update("owner_user_id", owner).Error; err != nil {
t.Fatalf("set owner: %v", err)
}
}
return record
}
func taskStatus(t *testing.T, db *gorm.DB, id uint64) string {
t.Helper()
var stored models.CollectionTask
if err := db.First(&stored, id).Error; err != nil {
t.Fatalf("load task: %v", err)
}
return stored.Status
}
func callCancel(t *testing.T, db *gorm.DB, claims jwt.MapClaims, path string, body any) (*httptest.ResponseRecorder, map[string]any) {
t.Helper()
gin.SetMode(gin.TestMode)
engine := gin.New()
handler := Handler{DB: db}
setClaims := func(c *gin.Context) {
c.Set(jwt.JwtPayloadKey, claims)
c.Set("userId", 0)
c.Next()
}
engine.POST("/batch-cancel", setClaims, handler.AdminBatchCancel)
engine.POST("/:taskId/cancel", setClaims, handler.AdminCancel)
payload, _ := json.Marshal(body)
recorder := httptest.NewRecorder()
engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodPost, path, bytes.NewReader(payload)))
var decoded map[string]any
_ = json.Unmarshal(recorder.Body.Bytes(), &decoded)
return recorder, decoded
}
func purchaser(id float64) jwt.MapClaims {
return jwt.MapClaims{"rolekey": "purchaser", "identity": id}
}
func adminClaims() jwt.MapClaims { return jwt.MapClaims{"rolekey": "admin", "identity": float64(1)} }
func TestBatchCancelWithDeviceIDOnlyCancelsThatDevice(t *testing.T) {
db := openTaskDatabase(t)
service := newTaskService(db)
one := ownDevice(t, db, "one", 3)
two := ownDevice(t, db, "two", 3)
onOne := createTask(t, db, &one.ID)
onTwo := createTask(t, db, &two.ID)
unassigned := createTask(t, db, nil)
response, err := service.BatchCancel(context.Background(), BatchCancelRequest{DeviceID: one.ID})
if err != nil {
t.Fatalf("batch cancel: %v", err)
}
if response.CancelledCount != 1 || response.CancelledIDs[0] != onOne.ID {
t.Fatalf("expected only device one task cancelled, got %+v", response)
}
if taskStatus(t, db, onTwo.ID) != models.TaskStatusPending || taskStatus(t, db, unassigned.ID) != models.TaskStatusPending {
t.Fatalf("other device and unassigned tasks must stay pending")
}
}
func TestBatchCancelWithoutDeviceIDKeepsFullScope(t *testing.T) {
db := openTaskDatabase(t)
service := newTaskService(db)
one := ownDevice(t, db, "one", 3)
createTask(t, db, &one.ID)
createTask(t, db, nil)
response, err := service.BatchCancel(context.Background(), BatchCancelRequest{})
if err != nil {
t.Fatalf("batch cancel: %v", err)
}
if response.CancelledCount != 2 {
t.Fatalf("expected both tasks cancelled including unassigned, got %+v", response)
}
}
func TestBatchCancelPurchaserRequiresDeviceID(t *testing.T) {
db := openTaskDatabase(t)
one := ownDevice(t, db, "one", 3)
record := createTask(t, db, &one.ID)
for _, body := range []map[string]any{{}, {"deviceId": 0}} {
recorder, decoded := callCancel(t, db, purchaser(3), "/batch-cancel", body)
if recorder.Code != http.StatusUnprocessableEntity || decoded["code"] != "INVALID_REQUEST" || decoded["message"] != "请先选择设备" {
t.Fatalf("expected INVALID_REQUEST, got %d %v", recorder.Code, decoded)
}
}
if taskStatus(t, db, record.ID) != models.TaskStatusPending {
t.Fatalf("no task may be cancelled")
}
}
func TestBatchCancelPurchaserOwnDeviceSucceeds(t *testing.T) {
db := openTaskDatabase(t)
own := ownDevice(t, db, "own", 3)
other := ownDevice(t, db, "other", 4)
mine := createTask(t, db, &own.ID)
theirs := createTask(t, db, &other.ID)
recorder, _ := callCancel(t, db, purchaser(3), "/batch-cancel", map[string]any{"deviceId": own.ID})
if recorder.Code != http.StatusOK {
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
if taskStatus(t, db, mine.ID) != models.TaskStatusCancelled || taskStatus(t, db, theirs.ID) != models.TaskStatusPending {
t.Fatalf("expected only own device task cancelled")
}
}
func TestBatchCancelPurchaserRejectsForeignUnownedAndMissingDevices(t *testing.T) {
db := openTaskDatabase(t)
foreign := ownDevice(t, db, "foreign", 4)
unowned := ownDevice(t, db, "unowned", 0)
foreignTask := createTask(t, db, &foreign.ID)
unownedTask := createTask(t, db, &unowned.ID)
for name, id := range map[string]uint64{"foreign": foreign.ID, "unowned": unowned.ID, "missing": 999999} {
recorder, decoded := callCancel(t, db, purchaser(3), "/batch-cancel", map[string]any{"deviceId": id})
if recorder.Code != http.StatusForbidden || decoded["code"] != "FORBIDDEN" {
t.Fatalf("%s: expected 403 FORBIDDEN, got %d %v", name, recorder.Code, decoded)
}
}
if taskStatus(t, db, foreignTask.ID) != models.TaskStatusPending || taskStatus(t, db, unownedTask.ID) != models.TaskStatusPending {
t.Fatalf("rejected requests must not cancel anything")
}
}
func TestBatchCancelMissingIdentityIsRejected(t *testing.T) {
db := openTaskDatabase(t)
unowned := ownDevice(t, db, "unowned", 0)
record := createTask(t, db, &unowned.ID)
recorder, _ := callCancel(t, db, jwt.MapClaims{"rolekey": "purchaser"}, "/batch-cancel", map[string]any{"deviceId": unowned.ID})
if recorder.Code != http.StatusForbidden || taskStatus(t, db, record.ID) != models.TaskStatusPending {
t.Fatalf("expected rejection, got %d", recorder.Code)
}
}
func TestBatchCancelAdminAnyDeviceAndUnassigned(t *testing.T) {
db := openTaskDatabase(t)
foreign := ownDevice(t, db, "foreign", 4)
onForeign := createTask(t, db, &foreign.ID)
unassigned := createTask(t, db, nil)
recorder, _ := callCancel(t, db, adminClaims(), "/batch-cancel", map[string]any{"deviceId": foreign.ID})
if recorder.Code != http.StatusOK || taskStatus(t, db, onForeign.ID) != models.TaskStatusCancelled || taskStatus(t, db, unassigned.ID) != models.TaskStatusPending {
t.Fatalf("admin with deviceId should cancel only that device, code=%d", recorder.Code)
}
recorder, _ = callCancel(t, db, adminClaims(), "/batch-cancel", map[string]any{})
if recorder.Code != http.StatusOK || taskStatus(t, db, unassigned.ID) != models.TaskStatusCancelled {
t.Fatalf("admin without deviceId should cancel unassigned tasks, code=%d", recorder.Code)
}
}
func TestSingleCancelPurchaserOwnership(t *testing.T) {
db := openTaskDatabase(t)
own := ownDevice(t, db, "own", 3)
foreign := ownDevice(t, db, "foreign", 4)
mine := createTask(t, db, &own.ID)
theirs := createTask(t, db, &foreign.ID)
unassigned := createTask(t, db, nil)
body := map[string]any{"requestId": uuid.NewString()}
for name, id := range map[string]uint64{"foreign": theirs.ID, "unassigned": unassigned.ID} {
recorder, decoded := callCancel(t, db, purchaser(3), fmt.Sprintf("/%d/cancel", id), body)
if recorder.Code != http.StatusForbidden || decoded["code"] != "FORBIDDEN" {
t.Fatalf("%s: expected 403, got %d %v", name, recorder.Code, decoded)
}
if taskStatus(t, db, id) != models.TaskStatusPending {
t.Fatalf("%s: status must be unchanged", name)
}
}
recorder, _ := callCancel(t, db, purchaser(3), fmt.Sprintf("/%d/cancel", mine.ID), body)
if recorder.Code != http.StatusOK || taskStatus(t, db, mine.ID) != models.TaskStatusCancelled {
t.Fatalf("own device task should cancel, code=%d body=%s", recorder.Code, recorder.Body.String())
}
// 他人设备上已取消的任务也不能通过幂等分支探测。
if _, err := newTaskService(db).Cancel(context.Background(), theirs.ID, ActionRequest{RequestID: uuid.NewString()}); err != nil {
t.Fatalf("seed: %v", err)
}
recorder, _ = callCancel(t, db, purchaser(3), fmt.Sprintf("/%d/cancel", theirs.ID), body)
if recorder.Code != http.StatusForbidden {
t.Fatalf("foreign cancelled task must still be forbidden, got %d", recorder.Code)
}
}
func TestSingleCancelAdminUnaffected(t *testing.T) {
db := openTaskDatabase(t)
foreign := ownDevice(t, db, "foreign", 4)
theirs := createTask(t, db, &foreign.ID)
unassigned := createTask(t, db, nil)
for _, id := range []uint64{theirs.ID, unassigned.ID} {
recorder, _ := callCancel(t, db, adminClaims(), fmt.Sprintf("/%d/cancel", id), map[string]any{"requestId": uuid.NewString()})
if recorder.Code != http.StatusOK || taskStatus(t, db, id) != models.TaskStatusCancelled {
t.Fatalf("admin cancel of %d failed: %d", id, recorder.Code)
}
}
}
+1 -1
View File
@@ -317,7 +317,7 @@ func writeError(context *gin.Context, err error) {
status = http.StatusUnprocessableEntity
case device.CodeTokenInvalid:
status = http.StatusUnauthorized
case device.CodeDeviceDisabled:
case device.CodeDeviceDisabled, CodeForbidden:
status = http.StatusForbidden
case CodeTaskNotFound:
status = http.StatusNotFound
+1
View File
@@ -20,6 +20,7 @@ const (
DefaultLeaseDuration = 2 * time.Minute
DefaultTaskTimeout = 120
CodeForbidden = "FORBIDDEN"
CodeTaskNotFound = "TASK_NOT_FOUND"
CodeTaskAlreadyClaimed = "TASK_ALREADY_CLAIMED"
CodeTaskAssignedOther = "TASK_ASSIGNED_OTHER_DEVICE"
@@ -0,0 +1,29 @@
package version_local
import (
"runtime"
"go-admin/app/goauto/models"
"go-admin/cmd/migrate/migration"
common "go-admin/common/models"
"gorm.io/gorm"
)
func init() {
_, file, _, _ := runtime.Caller(0)
migration.Migrate.SetVersion(migration.GetFilename(file), MigratePurchaseOrderSpecProof)
}
// MigratePurchaseOrderSpecProof only adds the nullable #391 order_spec_proof
// column to purchase_task. Existing rows are not rewritten. The step is
// guarded so a partial run can be re-run safely.
func MigratePurchaseOrderSpecProof(db *gorm.DB, version string) error {
m := db.Migrator()
if !m.HasColumn(&models.PurchaseTask{}, "OrderSpecProof") {
if err := m.AddColumn(&models.PurchaseTask{}, "OrderSpecProof"); err != nil {
return err
}
}
return db.Where("version = ?", version).FirstOrCreate(&common.Migration{Version: version}).Error
}
@@ -0,0 +1,53 @@
package version_local
import (
"testing"
"go-admin/app/goauto/models"
common "go-admin/common/models"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)
func TestMigratePurchaseOrderSpecProofAddsNullableColumnAndIsIdempotent(t *testing.T) {
db, err := gorm.Open(sqlite.Open(":memory:"), &gorm.Config{Logger: logger.Default.LogMode(logger.Silent)})
if err != nil {
t.Fatal(err)
}
conn, _ := db.DB()
defer conn.Close()
if err = db.AutoMigrate(&common.Migration{}); err != nil {
t.Fatal(err)
}
if err = db.Exec("CREATE TABLE purchase_task (id integer primary key, status text NOT NULL)").Error; err != nil {
t.Fatal(err)
}
if err = db.Exec("INSERT INTO purchase_task(id,status) VALUES(1,'failed')").Error; err != nil {
t.Fatal(err)
}
for i := 0; i < 2; i++ {
if err = MigratePurchaseOrderSpecProof(db, "test_391"); err != nil {
t.Fatal(err)
}
}
if !db.Migrator().HasColumn(&models.PurchaseTask{}, "OrderSpecProof") {
t.Fatal("missing order_spec_proof column")
}
var row struct {
Status string
OrderSpecProof *string
}
if err = db.Table("purchase_task").Select("status, order_spec_proof").Where("id = 1").Scan(&row).Error; err != nil {
t.Fatal(err)
}
if row.Status != "failed" || row.OrderSpecProof != nil {
t.Fatalf("legacy row changed: %+v", row)
}
var count int64
db.Model(&common.Migration{}).Where("version = ?", "test_391").Count(&count)
if count != 1 {
t.Fatal("version not idempotent")
}
}
@@ -14,7 +14,7 @@
<el-form-item>
<el-button type="primary" :icon="Search" @click="handleQuery">查询</el-button>
<el-button :icon="RefreshLeft" @click="resetQuery">重置</el-button>
<el-button type="danger" plain :loading="cancelBatch.loading" :disabled="pendingCancelCount === 0" @click="openCancelBatch">取消未开始的任务<span class="action-count">{{ pendingCancelCount }}</span></el-button>
<el-button type="danger" plain :loading="cancelBatch.loading" :disabled="!cancelNeedsDevice && pendingCancelCount === 0" @click="openCancelBatch">取消未开始的任务<span v-if="!cancelNeedsDevice" class="action-count">{{ pendingCancelCount }}</span></el-button>
</el-form-item>
</el-form>
<el-table v-loading="loading" :data="tasks" border stripe empty-text="暂无采集任务">
@@ -47,7 +47,7 @@
<el-dialog v-model="cancelBatch.open" title="取消未开始的任务" width="680px" :close-on-click-modal="false">
<el-alert
:title="`将取消整个筛选条件(来源:${sourceLabel(query.source) || '全部'};状态:${statusLabel(query.status) || '全部'};Goods ID:${query.goodsId || '全部'})下所有待执行任务,不只是当前页。`"
:title="`将取消${cancelDeviceLabel}上、整个筛选条件(来源:${sourceLabel(query.source) || '全部'};状态:${statusLabel(query.status) || '全部'};Goods ID:${query.goodsId || '全部'})下的所有待执行任务,不只是当前页。`"
type="warning" :closable="false" show-icon class="dialog-alert" />
<div v-loading="cancelBatch.previewLoading">
<p>共 {{ cancelBatch.previewTotal }} 个待执行任务将被取消{{ cancelBatch.previewTotal > cancelBatch.preview.length ? `(仅列出前 ${cancelBatch.preview.length} 个)` : '' }}:</p>
@@ -114,6 +114,16 @@ export default {
cancelBatch: { open: false, previewLoading: false, submitting: false, preview: [], previewTotal: 0 }
}
},
computed: {
isAdmin() { return (this.$store.getters.roles || []).includes('admin') },
// #387:采购员未选设备时不能批量取消(服务端同样拒绝);管理员不受限。
cancelNeedsDevice() { return !this.isAdmin && !this.query.deviceId },
cancelDeviceLabel() {
if (!this.query.deviceId) return '全部设备(含未指定设备)'
const found = this.deviceFilterOptions.find(item => item.id === this.query.deviceId)
return `设备「${found ? found.name : this.query.deviceId}」`
}
},
created() { this.getList(); this.refreshPendingCancelCount(); this.loadDeviceFilterOptions() },
watch: {
// `[必须]` 取消范围必须与眼前的列表一致,三个筛选项都要联动。少了 Goods ID
@@ -135,20 +145,21 @@ export default {
// 取消范围只对「状态筛选为空或恰好是待执行」才有意义:其它状态下这个筛选
// 条件里不可能存在待执行任务,角标应该直接显示 0 并禁用按钮,而不是拿一个
// 与实际可取消数量无关的数字误导采购员。
// 批量取消接口不支持设备维度;选了设备筛选时禁用,避免取消范围超出眼前列表。
cancelScopeStatus() { if (this.query.deviceId) return null; return this.query.status === '' || this.query.status === 'pending' ? 'pending' : null },
// #387:设备维度也参与取消范围;采购员必须先选设备,且服务端只允许取消本人设备的任务。
cancelScopeStatus() { return this.query.status === '' || this.query.status === 'pending' ? 'pending' : null },
async refreshPendingCancelCount() {
const status = this.cancelScopeStatus()
if (!status) { this.pendingCancelCount = 0; return }
const r = await listCollectionTasks({ page: 1, pageSize: 1, status, source: this.query.source || undefined, goodsId: this.query.goodsId || undefined })
if (!status || this.cancelNeedsDevice) { this.pendingCancelCount = 0; return }
const r = await listCollectionTasks({ page: 1, pageSize: 1, status, deviceId: this.query.deviceId || undefined, source: this.query.source || undefined, goodsId: this.query.goodsId || undefined })
this.pendingCancelCount = r.data.total
},
async openCancelBatch() {
if (this.cancelNeedsDevice) { ElMessage.warning('请先在「设备」筛选中选择要取消任务的设备'); return }
const status = this.cancelScopeStatus()
if (!status) return
this.cancelBatch = { open: true, previewLoading: true, submitting: false, preview: [], previewTotal: 0 }
try {
const r = await listCollectionTasks({ page: 1, pageSize: 50, status, source: this.query.source || undefined, goodsId: this.query.goodsId || undefined })
const r = await listCollectionTasks({ page: 1, pageSize: 50, status, deviceId: this.query.deviceId || undefined, source: this.query.source || undefined, goodsId: this.query.goodsId || undefined })
this.cancelBatch.preview = r.data.items
this.cancelBatch.previewTotal = r.data.total
} finally { this.cancelBatch.previewLoading = false }
@@ -158,7 +169,7 @@ export default {
if (!status) return
this.cancelBatch.submitting = true
try {
const response = await batchCancelCollectionTasks({ source: this.query.source || undefined, status, goodsId: this.query.goodsId || undefined })
const response = await batchCancelCollectionTasks({ source: this.query.source || undefined, status, deviceId: this.query.deviceId || undefined, goodsId: this.query.goodsId || undefined })
const skippedText = response.data.skipped?.length ? `,${response.data.skipped.length} 个因执行中或已被设备领取而跳过(任务号:${response.data.skipped.map(item => item.taskId).join('、')})` : ''
ElMessage.success(`已取消 ${response.data.cancelledCount} 个任务${skippedText}`)
if (response.data.hasMore) {