修复自动发货bug

This commit is contained in:
yml
2026-04-14 17:30:36 +08:00
parent bb47d168a9
commit 9f6f67c8a8
14 changed files with 366 additions and 253 deletions
-7
View File
@@ -55,13 +55,6 @@ module.exports = {
enabled: true,
endpoint: 'https://gw-api.agiso.com/aldsIdle/Order/DummySend',
apiVersion: '1',
aldsType: 1,
ignoreAldsLog: false,
ignoreBlackList: false,
ignoreOnOff: false,
ignoreRefundCheck: false,
ignoreRestricted: false,
ignoreTradeStatusCheck: false,
},
messaging: {
enabled: false,
+2 -1
View File
@@ -6,11 +6,12 @@
"scripts": {
"browser:install": "playwright install chromium",
"browser:install:linux": "playwright install --with-deps chromium",
"agiso:auto-delivery:test": "node scripts/test-agiso-auto-delivery.js",
"cleanup:dev-data": "node scripts/cleanup-dev-data.js",
"seed:dev-data": "node scripts/seed-dev-data.js",
"db:migrate": "node src/db/migrate.js",
"dev": "node --watch-path=src --watch-path=config --watch-preserve-output src/index.js",
"test": "node --test",
"test": "node --test $(find src -name '*.test.js' -print)",
"typecheck": "tsc -p tsconfig.json --noEmit",
"start": "node src/index.js"
},
@@ -0,0 +1,288 @@
#!/usr/bin/env node
import crypto from 'node:crypto'
import process from 'node:process'
import { fileURLToPath } from 'node:url'
import { setTimeout as sleep } from 'node:timers/promises'
import { query, closeDb } from '../src/db/client.js'
import { parseJsonObject } from '../src/utils/json.js'
import { getAgisoShopConfig } from '../src/services/platforms/agiso/shop-config-service.js'
import { queryAgisoXianyuOrderDetail } from '../src/services/platforms/agiso/xianyu/order-detail-service.js'
const DEFAULT_DUMMY_ENDPOINT = 'https://gw-api.agiso.com/aldsIdle/Order/DummySend'
const DEFAULT_POLL_SECONDS = [0, 3, 10]
async function main() {
const options = parseArgs(process.argv.slice(2))
if (options.help || !options.orderId) {
printHelp()
process.exit(options.help ? 0 : 1)
}
const orderRecord = await resolveOrderRecord(options)
const shopId = orderRecord?.shop_id || options.shopId
const shopConfig = getAgisoShopConfig(shopId) || {}
const accessToken = String(shopConfig.accessToken || '').trim()
const appSecret = String(shopConfig.appSecret || process.env.AGISO_APP_SECRET || '').trim()
if (!shopId) {
throw new Error('未提供 shopId,且数据库中也没有查到该订单对应的店铺')
}
if (!accessToken) {
throw new Error(`店铺 ${shopId} 缺少 accessToken 配置,请检查 apps/backend/data/agiso-shops.json`)
}
if (!appSecret) {
throw new Error('缺少 AGISO_APP_SECRET 或店铺级 appSecret 配置')
}
printJson('测试输入', {
orderId: options.orderId,
shopId,
pollSeconds: options.pollSeconds,
orderRecord: orderRecord
? {
id: Number(orderRecord.id || 0) || null,
platformOrderId: String(orderRecord.platform_order_id || '').trim(),
orderStatus: String(orderRecord.order_status || '').trim(),
payStatus: String(orderRecord.pay_status || '').trim(),
provider: String(orderRecord.provider || '').trim(),
platform: String(orderRecord.platform || '').trim(),
}
: null,
})
const beforeDetail = await queryAgisoXianyuOrderDetail({
shopId,
platformOrderId: options.orderId,
requestId: `diag-before-${Date.now()}`,
})
printJson('调用前订单详情', summarizeDetail(beforeDetail))
const result = await executeRequest({
platformOrderId: options.orderId,
accessToken,
appSecret,
})
printJson('接口响应 更新发货状态 DummySend', result)
for (const seconds of options.pollSeconds) {
if (seconds > 0) {
await sleep(seconds * 1000)
}
const detail = await queryAgisoXianyuOrderDetail({
shopId,
platformOrderId: options.orderId,
requestId: `diag-after-${seconds}s-${Date.now()}`,
})
printJson(`调用后订单详情 +${seconds}s`, summarizeDetail(detail))
}
}
function parseArgs(argv) {
const output = {
orderId: '',
shopId: '',
pollSeconds: [...DEFAULT_POLL_SECONDS],
help: false,
}
for (let index = 0; index < argv.length; index += 1) {
const current = String(argv[index] || '').trim()
if (!current) {
continue
}
if (!current.startsWith('--')) {
if (!output.orderId) {
output.orderId = current
continue
}
throw new Error(`无法识别的参数:${current}`)
}
if (current === '--help') {
output.help = true
continue
}
const [rawKey, inlineValue = ''] = current.split('=', 2)
const key = rawKey.slice(2)
const nextValue = inlineValue || argv[index + 1] || ''
const shouldConsumeNext = !inlineValue && argv[index + 1] && !String(argv[index + 1]).startsWith('--')
switch (key) {
case 'shop-id':
output.shopId = String(nextValue || '').trim()
break
case 'poll':
output.pollSeconds = parsePollSeconds(nextValue)
break
default:
throw new Error(`无法识别的参数:${current}`)
}
if (shouldConsumeNext) {
index += 1
}
}
return output
}
function parsePollSeconds(value) {
const normalized = String(value || '').trim()
if (!normalized) {
return [...DEFAULT_POLL_SECONDS]
}
const parsed = normalized
.split(',')
.map((item) => Number(String(item || '').trim()))
.filter((item) => Number.isFinite(item) && item >= 0)
.map((item) => Math.floor(item))
if (parsed.length === 0) {
throw new Error(`poll 参数格式无效:${value}`)
}
return parsed
}
async function resolveOrderRecord(options) {
const explicitShopId = String(options.shopId || '').trim()
if (explicitShopId) {
const result = await query(
`
SELECT *
FROM orders
WHERE provider = 'agiso'
AND platform = 'xianyu'
AND shop_id = $1
AND platform_order_id = $2
ORDER BY id DESC
LIMIT 1
`,
[explicitShopId, options.orderId],
)
return result.rows[0] || null
}
const result = await query(
`
SELECT *
FROM orders
WHERE provider = 'agiso'
AND platform = 'xianyu'
AND platform_order_id = $1
ORDER BY id DESC
LIMIT 2
`,
[options.orderId],
)
if (result.rows.length > 1) {
throw new Error(`数据库里命中多条同订单号记录,请显式传入 --shop-id。订单号:${options.orderId}`)
}
return result.rows[0] || null
}
async function executeRequest(context) {
const timestamp = String(Math.floor(Date.now() / 1000))
const requestBody = buildDummySendBody(context, timestamp)
const response = await fetch(DEFAULT_DUMMY_ENDPOINT, {
method: 'POST',
headers: {
Authorization: `Bearer ${context.accessToken}`,
ApiVersion: '1',
'content-type': 'application/x-www-form-urlencoded; charset=utf-8',
},
body: new URLSearchParams(requestBody).toString(),
})
const rawText = await response.text()
const payload = parseJsonObject(rawText, { preserveLargeIntegers: true })
return {
endpoint: DEFAULT_DUMMY_ENDPOINT,
status: response.status,
requestBody,
response: payload,
rawText,
}
}
function buildDummySendBody(context, timestamp) {
const payload = {
tid: context.platformOrderId,
timestamp,
}
payload.sign = generateSign(payload, context.appSecret)
return payload
}
function generateSign(params, appSecret) {
let raw = String(appSecret || '').trim()
for (const [key, value] of Object.entries(params).sort(([left], [right]) => left.localeCompare(right))) {
raw += `${key}${value}`
}
raw += String(appSecret || '').trim()
return crypto.createHash('md5').update(raw, 'utf8').digest('hex').toLowerCase()
}
function summarizeDetail(detailResult) {
return {
success: Boolean(detailResult?.success),
reason: String(detailResult?.reason || '').trim(),
errorMessage: String(detailResult?.errorMessage || '').trim(),
responseStatus: Number(detailResult?.responseStatus || 0),
shipped: Boolean(detailResult?.shipped),
shipTime: Number(detailResult?.shipTime || 0),
orderStatus: Number(detailResult?.orderStatus || 0),
bizOrderId: String(detailResult?.detailPayload?.biz_order_id || '').trim(),
sellerNick: String(detailResult?.detailPayload?.seller_nick || '').trim(),
buyerNick: String(detailResult?.detailPayload?.buyer_nick || '').trim(),
sku: String(detailResult?.detailPayload?.sku || '').trim(),
itemTitle: String(detailResult?.detailPayload?.item?.title || '').trim(),
}
}
function printJson(title, value) {
process.stdout.write(`\n=== ${title} ===\n`)
process.stdout.write(`${JSON.stringify(value, null, 2)}\n`)
}
function printHelp() {
process.stdout.write(`用法:
node scripts/test-agiso-auto-delivery.js <订单号> [--shop-id <店铺ID>] [--poll 0,3,10]
说明:
1. 该脚本只测试正确的发货接口 DummySend。
2. 会先查 Order/Detail,再调用 DummySend,再按 poll 秒数轮询发货状态。
示例:
node scripts/test-agiso-auto-delivery.js 4502285714045005830
node scripts/test-agiso-auto-delivery.js 4502285714045005830 --poll 0,5,15
node scripts/test-agiso-auto-delivery.js 4502285714045005830 --shop-id 2209880145223
`)
}
const isNodeTestRunner = Array.isArray(process.execArgv) && process.execArgv.includes('--test')
const isDirectRun = !isNodeTestRunner && process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]
if (isDirectRun) {
main()
.catch((error) => {
process.stderr.write(`${error instanceof Error ? error.stack || error.message : String(error)}\n`)
process.exitCode = 1
})
.finally(async () => {
await closeDb()
})
}
-19
View File
@@ -215,25 +215,6 @@ function applyEnvOverrides(baseConfig) {
nextConfig.platforms.agiso.autoDelivery.apiVersion = agisoAutoDeliveryApiVersion
}
const agisoAutoDeliveryAldsType = parseInteger(process.env.AGISO_AUTO_DELIVERY_ALDS_TYPE)
if (agisoAutoDeliveryAldsType !== null) {
nextConfig.platforms.agiso.autoDelivery.aldsType = agisoAutoDeliveryAldsType
}
for (const [envKey, configKey] of [
['AGISO_AUTO_DELIVERY_IGNORE_ALDS_LOG', 'ignoreAldsLog'],
['AGISO_AUTO_DELIVERY_IGNORE_BLACK_LIST', 'ignoreBlackList'],
['AGISO_AUTO_DELIVERY_IGNORE_ON_OFF', 'ignoreOnOff'],
['AGISO_AUTO_DELIVERY_IGNORE_REFUND_CHECK', 'ignoreRefundCheck'],
['AGISO_AUTO_DELIVERY_IGNORE_RESTRICTED', 'ignoreRestricted'],
['AGISO_AUTO_DELIVERY_IGNORE_TRADE_STATUS_CHECK', 'ignoreTradeStatusCheck'],
]) {
const parsed = parseBoolean(process.env[envKey])
if (parsed !== null) {
nextConfig.platforms.agiso.autoDelivery[configKey] = parsed
}
}
const agisoMessageAppSecret = String(process.env.AGISO_MESSAGE_APP_SECRET || '').trim()
if (agisoMessageAppSecret) {
nextConfig.platforms.agiso.messaging.appSecret = agisoMessageAppSecret
@@ -306,7 +306,6 @@ export function buildOrderAgisoAutoDeliverySummary(order, tasks = []) {
responseStatus: 0,
errorMessage: '',
requestId: '',
aldsType: null,
updatedAt: null,
sourceTaskId: null,
sourceTaskNo: '',
@@ -409,7 +408,6 @@ function mapAgisoAutoDeliveryContext(value) {
responseStatus: Number(value.responseStatus || 0),
errorMessage: String(value.errorMessage || '').trim(),
requestId: String(value.requestId || '').trim(),
aldsType: Number(value.aldsType || 0) || null,
updatedAt: value.updatedAt || null,
}
}
@@ -10,6 +10,8 @@ import { parseJsonObject } from '../../../../utils/json.js'
import { logWebhook } from '../../../../utils/logger.js'
import { nowIso } from '../../../../utils/time.js'
const AGISO_DUMMY_SEND_ENDPOINT = 'https://gw-api.agiso.com/aldsIdle/Order/DummySend'
/**
* @typedef {{
* order?: Record<string, any> | null
@@ -82,15 +84,8 @@ export async function ensureAgisoXianyuAutoDeliveryForDeliveredTask({
apiVersion: config.apiVersion,
})
const requestBody = buildRequestBody({
tids: String(order.platform_order_id || '').trim(),
platformOrderId: String(order.platform_order_id || '').trim(),
appSecret: config.appSecret,
aldsType: config.aldsType,
ignoreAldsLog: config.ignoreAldsLog,
ignoreBlackList: config.ignoreBlackList,
ignoreOnOff: config.ignoreOnOff,
ignoreRefundCheck: config.ignoreRefundCheck,
ignoreRestricted: config.ignoreRestricted,
ignoreTradeStatusCheck: config.ignoreTradeStatusCheck,
})
logWebhook('[agiso/xianyu/auto-delivery]', '开始执行 Agiso 咸鱼自动发货', {
@@ -100,7 +95,6 @@ export async function ensureAgisoXianyuAutoDeliveryForDeliveredTask({
shopId: order.shop_id,
platformOrderId: order.platform_order_id,
endpoint: config.endpoint,
aldsType: config.aldsType,
})
try {
@@ -116,7 +110,7 @@ export async function ensureAgisoXianyuAutoDeliveryForDeliveredTask({
if (success) {
const requestId = String(parsed?.RequestId || '').trim()
// DummySend 接口返回成功后,再查一次 Order/Detail 确认订单真的进入已发货状态 meow~
// 发货接口返回成功后,再查一次 Order/Detail 确认订单真的进入已发货状态 meow~
const confirmResult = await confirmAgisoXianyuAutoDeliveryShipped({
shopId: order.shop_id,
platformOrderId: order.platform_order_id,
@@ -144,10 +138,9 @@ export async function ensureAgisoXianyuAutoDeliveryForDeliveredTask({
order,
responseStatus: response.status,
response: parsed,
errorMessage: `接口返回成功,但订单状态未确认进入已发货 (orderStatus=${confirmResult.orderStatus}, shipTime=${confirmResult.shipTime})`,
errorMessage: `Agiso 发货状态更新接口已受理,但订单仍未进入已发货,请检查该订单是否允许无物流发货 (orderStatus=${confirmResult.orderStatus}, shipTime=${confirmResult.shipTime})`,
detail: {
requestId,
aldsType: config.aldsType,
confirmOrderStatus: confirmResult.orderStatus,
confirmShipTime: confirmResult.shipTime,
},
@@ -175,7 +168,6 @@ export async function ensureAgisoXianyuAutoDeliveryForDeliveredTask({
response: parsed,
detail: {
requestId,
aldsType: config.aldsType,
confirmOrderStatus: confirmResult.orderStatus,
confirmShipTime: confirmResult.shipTime,
},
@@ -250,17 +242,10 @@ function resolveAgisoXianyuAutoDeliveryConfig(order) {
return {
enabled: normalizeBooleanLike(baseConfig.enabled, true),
endpoint: String(baseConfig.endpoint || '').trim(),
endpoint: resolveAgisoAutoDeliveryEndpoint(baseConfig.endpoint),
apiVersion: String(baseConfig.apiVersion || shopConfig.apiVersion || '1').trim() || '1',
appSecret: String(shopConfig.appSecret || runtimeConfig.platforms?.agiso?.appSecret || '').trim(),
accessToken: String(shopConfig.accessToken || '').trim(),
aldsType: normalizePositiveInteger(baseConfig.aldsType, 1),
ignoreAldsLog: normalizeBooleanLike(baseConfig.ignoreAldsLog, false),
ignoreBlackList: normalizeBooleanLike(baseConfig.ignoreBlackList, false),
ignoreOnOff: normalizeBooleanLike(baseConfig.ignoreOnOff, false),
ignoreRefundCheck: normalizeBooleanLike(baseConfig.ignoreRefundCheck, false),
ignoreRestricted: normalizeBooleanLike(baseConfig.ignoreRestricted, false),
ignoreTradeStatusCheck: normalizeBooleanLike(baseConfig.ignoreTradeStatusCheck, false),
}
}
@@ -272,26 +257,9 @@ function buildRequestHeaders({ accessToken, apiVersion }) {
}
}
function buildRequestBody({
tids,
appSecret,
aldsType,
ignoreAldsLog,
ignoreBlackList,
ignoreOnOff,
ignoreRefundCheck,
ignoreRestricted,
ignoreTradeStatusCheck,
}) {
function buildRequestBody({ platformOrderId, appSecret }) {
const payload = {
tids: String(tids || '').trim(),
aldsType: String(normalizePositiveInteger(aldsType, 1)),
ignoreAldsLog: String(Boolean(ignoreAldsLog)),
ignoreBlackList: String(Boolean(ignoreBlackList)),
ignoreOnOff: String(Boolean(ignoreOnOff)),
ignoreRefundCheck: String(Boolean(ignoreRefundCheck)),
ignoreRestricted: String(Boolean(ignoreRestricted)),
ignoreTradeStatusCheck: String(Boolean(ignoreTradeStatusCheck)),
tid: String(platformOrderId || '').trim(),
timestamp: String(Math.floor(Date.now() / 1000)),
}
@@ -350,6 +318,10 @@ export function resolveAgisoAutoDeliveryErrorMessage(payload, rawText, statusCod
return text || `Agiso 咸鱼自动发货失败,HTTP ${statusCode}`
}
export function resolveAgisoAutoDeliveryEndpoint(value) {
return AGISO_DUMMY_SEND_ENDPOINT
}
async function persistAgisoAutoDeliveryResult(task, {
status,
trigger,
@@ -428,15 +400,6 @@ function isAgisoXianyuOrder(order) {
&& Number(order?.id || 0) > 0
}
function normalizePositiveInteger(value, fallbackValue) {
const parsed = Number(value)
if (Number.isFinite(parsed) && parsed > 0) {
return Math.floor(parsed)
}
return fallbackValue
}
function normalizeBooleanLike(value, fallbackValue) {
if (typeof value === 'boolean') {
return value
@@ -463,7 +426,7 @@ function isPlainObject(value) {
}
/**
* DummySend 返回成功后,再查一次 Order/Detail 确认订单是否真的进入已发货状态 meow~
* 发货接口返回成功后,再查一次 Order/Detail 确认订单是否真的进入已发货状态 meow~
* 只有 ship_time > 0 或 orderStatus >= 3 才算发货确认通过
*/
async function confirmAgisoXianyuAutoDeliveryShipped({ shopId = '', platformOrderId = '', requestId = '' } = {}) {
@@ -5,6 +5,7 @@ import {
hasAgisoAutoDeliverySucceeded,
isOrderReadyForAgisoAutoDelivery,
isAgisoAutoDeliverySuccess,
resolveAgisoAutoDeliveryEndpoint,
resolveAgisoAutoDeliveryErrorMessage,
} from './auto-delivery-service.js'
@@ -58,3 +59,15 @@ test('resolveAgisoAutoDeliveryErrorMessage prefers structured payload message be
'fallback raw body',
)
})
test('resolveAgisoAutoDeliveryEndpoint falls back to DummySend', () => {
assert.equal(
resolveAgisoAutoDeliveryEndpoint(''),
'https://gw-api.agiso.com/aldsIdle/Order/DummySend',
)
assert.equal(
resolveAgisoAutoDeliveryEndpoint('https://gw-api.agiso.com/aldsIdle/Order/DummySend'),
'https://gw-api.agiso.com/aldsIdle/Order/DummySend',
)
})
@@ -21,7 +21,6 @@ export {}
* responseStatus: number
* errorMessage: string
* requestId: string
* aldsType: number | null
* updatedAt: string | null
* }} AdminAgisoAutoDeliveryStatus
*/
-7
View File
@@ -76,13 +76,6 @@ export {}
* enabled: boolean
* endpoint: string
* apiVersion: string
* aldsType: number
* ignoreAldsLog: boolean
* ignoreBlackList: boolean
* ignoreOnOff: boolean
* ignoreRefundCheck: boolean
* ignoreRestricted: boolean
* ignoreTradeStatusCheck: boolean
* }
* messaging: {
* enabled: boolean
-1
View File
@@ -174,7 +174,6 @@ export interface AdminAgisoAutoDeliveryStatus {
responseStatus: number
errorMessage: string
requestId: string
aldsType: number | null
updatedAt: string | null
}
@@ -159,7 +159,6 @@ function formatTaskEventPayload(payload: Record<string, unknown>) {
payload.reason ? `原因 ${payload.reason}` : '',
payload.responseStatus ? `HTTP ${payload.responseStatus}` : '',
payload.requestId ? `请求 ${payload.requestId}` : '',
payload.aldsType ? `发货类型 ${payload.aldsType}` : '',
payload.errorMessage ? `错误 ${payload.errorMessage}` : '',
].filter(Boolean)
@@ -442,7 +441,6 @@ onBeforeUnmount(clearScreenshotPreview)
<p v-if="detail.task.agisoAutoDelivery?.reason">原因{{ formatAutoDeliveryReason(detail.task.agisoAutoDelivery.reason) }}</p>
<p v-if="detail.task.agisoAutoDelivery?.responseStatus">HTTP{{ detail.task.agisoAutoDelivery.responseStatus }}</p>
<p v-if="detail.task.agisoAutoDelivery?.requestId">请求 ID{{ detail.task.agisoAutoDelivery.requestId }}</p>
<p v-if="detail.task.agisoAutoDelivery?.aldsType">发货类型{{ detail.task.agisoAutoDelivery.aldsType }}</p>
</div>
</section>