新增(自动发货抖店): 接入异步卡密下单与回调
This commit is contained in:
@@ -76,6 +76,16 @@ ADMIN_DEFAULT_USERS_JSON=[{"username":"admin","password":"dev-admin-123456","rol
|
||||
KAQUAN91_USER_ID=
|
||||
KAQUAN91_SECRET=
|
||||
|
||||
# 自动发货抖店开放接口(默认关闭)
|
||||
AUTO_SHIP_DOUYIN_ENABLED=false
|
||||
AUTO_SHIP_DOUYIN_SECRET=
|
||||
AUTO_SHIP_DOUYIN_VERSION=1.0
|
||||
AUTO_SHIP_DOUYIN_SHOP_ID=auto_ship_douyin
|
||||
AUTO_SHIP_DOUYIN_SHOP_NAME=自动发货抖店
|
||||
AUTO_SHIP_DOUYIN_TIMESTAMP_TOLERANCE_SECONDS=600
|
||||
AUTO_SHIP_DOUYIN_CALLBACK_ALLOWED_ORIGINS=
|
||||
AUTO_SHIP_DOUYIN_CALLBACK_TIMEOUT_MS=5000
|
||||
AUTO_SHIP_DOUYIN_CALLBACK_MAX_ATTEMPTS=12
|
||||
# 半自动履约默认使用 order_site 内置真实 Connector;只有选择 external 时才填写远程地址
|
||||
SEMI_AUTO_DEFAULT_CONNECTOR_MODE=embedded
|
||||
HUYA_BIND_GID=3203
|
||||
|
||||
@@ -143,6 +143,16 @@ CORS_ALLOWED_ORIGINS=https://order.khhao.com,https://worker.khhao.com
|
||||
KAQUAN91_USER_ID=
|
||||
KAQUAN91_SECRET=
|
||||
|
||||
# 自动发货抖店开放接口(默认关闭)
|
||||
AUTO_SHIP_DOUYIN_ENABLED=false
|
||||
AUTO_SHIP_DOUYIN_SECRET=
|
||||
AUTO_SHIP_DOUYIN_VERSION=1.0
|
||||
AUTO_SHIP_DOUYIN_SHOP_ID=auto_ship_douyin
|
||||
AUTO_SHIP_DOUYIN_SHOP_NAME=自动发货抖店
|
||||
AUTO_SHIP_DOUYIN_TIMESTAMP_TOLERANCE_SECONDS=600
|
||||
AUTO_SHIP_DOUYIN_CALLBACK_ALLOWED_ORIGINS=
|
||||
AUTO_SHIP_DOUYIN_CALLBACK_TIMEOUT_MS=5000
|
||||
AUTO_SHIP_DOUYIN_CALLBACK_MAX_ATTEMPTS=12
|
||||
# 半自动履约 Connector(虎牙登录/绑定/CK 注入票据)
|
||||
# 默认使用 order_site 内置真实 Connector;只有切到 external 时才需要填写地址和密钥。
|
||||
SEMI_AUTO_CONNECTOR_BASE_URL=
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
"lint:check": "npm run lint -- --quiet",
|
||||
"lint:fix": "npm run lint -- --fix",
|
||||
"mock:open91": "tsx scripts/mock-open91-order.ts",
|
||||
"e2e:auto-ship-douyin": "tsx scripts/e2e-auto-ship-douyin.ts",
|
||||
"douyin-mashida:set-public-url": "tsx scripts/douyin-mashida-set-public-url.ts",
|
||||
"douyin-mashida:preflight": "tsx scripts/douyin-mashida-preflight.ts",
|
||||
"douyin-mashida:subscribe": "tsx scripts/douyin-mashida-subscribe.ts",
|
||||
|
||||
@@ -0,0 +1,424 @@
|
||||
/**
|
||||
* 自动发货抖店全链路联调脚本。
|
||||
*
|
||||
* 前置:
|
||||
* 1. 使用隔离测试库(库名必须包含 _ctest/_itest/_test);
|
||||
* 2. 已执行全部迁移;
|
||||
* 3. 设置 AUTO_SHIP_DOUYIN_E2E_DATABASE_URL,并与 DATABASE_URL 一致。
|
||||
*
|
||||
* 运行:
|
||||
* AUTO_SHIP_DOUYIN_E2E_DATABASE_URL=postgres://... \
|
||||
* npx tsx scripts/e2e-auto-ship-douyin.ts
|
||||
*
|
||||
* 缺失的外网上游用内存 Mock:
|
||||
* - affiliate-dash 钱包、建单
|
||||
* - 平台回调接收端
|
||||
*/
|
||||
import assert from 'node:assert/strict'
|
||||
import { once } from 'node:events'
|
||||
import crypto from 'node:crypto'
|
||||
import type { AddressInfo } from 'node:net'
|
||||
import type { Server } from 'node:http'
|
||||
|
||||
import { resolveIsolatedIntegrationDatabaseUrl } from '../src/test-support/integration-db-guard.js'
|
||||
|
||||
const databaseUrl = resolveIsolatedIntegrationDatabaseUrl('AUTO_SHIP_DOUYIN_E2E_DATABASE_URL')
|
||||
if (!databaseUrl) {
|
||||
console.error('未设置 AUTO_SHIP_DOUYIN_E2E_DATABASE_URL')
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
process.env.DATABASE_URL = databaseUrl
|
||||
process.env.NODE_ENV = 'test'
|
||||
process.env.AUTO_SHIP_DOUYIN_ENABLED = 'true'
|
||||
process.env.AUTO_SHIP_DOUYIN_SECRET = '12345678901234567890123456789012'
|
||||
process.env.AUTO_SHIP_DOUYIN_CALLBACK_ALLOWED_ORIGINS = 'https://callback.mock'
|
||||
process.env.CLAIM_BASE_URL = 'https://claim.mock/h5'
|
||||
|
||||
const { query, closeDb } = await import('../src/db/client.js')
|
||||
const { createApp } = await import('../src/app.js')
|
||||
const { runtimeConfig } = await import('../src/config/runtime.js')
|
||||
const { createStartupState } = await import('../src/startup/state.js')
|
||||
const { assertAutoShipDouyinConfig } =
|
||||
await import('../src/services/open-auto-ship-douyin/config.js')
|
||||
const { signAutoShipDouyinPayload, signAutoShipDouyinCallbackPayload } =
|
||||
await import('../src/services/open-auto-ship-douyin/crypto.js')
|
||||
const { startAutoShipDouyinCallbackWorker, stopAutoShipDouyinCallbackWorker } =
|
||||
await import('../src/services/open-auto-ship-douyin/callback-outbox-service.js')
|
||||
const { loadAppConfigCacheFromDatabase } =
|
||||
await import('../src/services/config/app-config-store.js')
|
||||
|
||||
const productNo = 'PLATFORM-DOUYIN-E2E-20261124'
|
||||
const internalSku = '10000人气值'
|
||||
const runSuffix = `${Date.now()}`
|
||||
const orderNo = `ASD-E2E-${runSuffix}`
|
||||
const overLimitOrderNo = `ASD-E2E-OVER-${runSuffix}`
|
||||
const unconfiguredOrderNo = `ASD-E2E-UNMAPPED-${runSuffix}`
|
||||
const config = assertAutoShipDouyinConfig()
|
||||
const realFetch = globalThis.fetch.bind(globalThis)
|
||||
const callbackRequests: Array<{ body: Record<string, unknown>; headers: Record<string, string> }> =
|
||||
[]
|
||||
|
||||
globalThis.fetch = async (input, init) => {
|
||||
const url =
|
||||
typeof input === 'string'
|
||||
? input
|
||||
: input instanceof URL
|
||||
? input.toString()
|
||||
: String((input as Request).url || input)
|
||||
const method = String(init?.method || (input as Request)?.method || 'GET').toUpperCase()
|
||||
|
||||
if (url.startsWith('https://affiliate.mock/api/client/v1/wallet')) {
|
||||
return jsonResponse({
|
||||
code: 0,
|
||||
message: 'ok',
|
||||
data: { available_balance: 100000, frozen_balance: 0, currency: 'POINT' },
|
||||
})
|
||||
}
|
||||
|
||||
if (url.startsWith('https://affiliate.mock/api/client/v1/orders') && method === 'POST') {
|
||||
const body = JSON.parse(String(init?.body || '{}')) as Record<string, unknown>
|
||||
const clientOrderNo = String(body.client_order_no || '')
|
||||
return jsonResponse({
|
||||
code: 0,
|
||||
message: 'ok',
|
||||
data: {
|
||||
idempotent: false,
|
||||
order: {
|
||||
order_no: `AD-MOCK-${clientOrderNo}`,
|
||||
client_order_no: clientOrderNo,
|
||||
sku: String(body.sku || ''),
|
||||
quantity: Number(body.quantity || 1),
|
||||
amount: 20,
|
||||
currency: 'POINT',
|
||||
order_status: 'paid',
|
||||
can_ship: true,
|
||||
cannot_ship_reason: '',
|
||||
failure_reason: '',
|
||||
product: { sku: String(body.sku || ''), display_name: '自动发货抖店全链路测试商品' },
|
||||
data: body.data || {},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
if (url.startsWith('https://callback.mock/')) {
|
||||
const body = JSON.parse(String(init?.body || '{}')) as Record<string, unknown>
|
||||
const headers: Record<string, string> = {}
|
||||
const rawHeaders = new Headers(init?.headers || {})
|
||||
rawHeaders.forEach((value, key) => {
|
||||
headers[key] = value
|
||||
})
|
||||
callbackRequests.push({ body, headers })
|
||||
return jsonResponse({ code: 200, message: '请求成功' })
|
||||
}
|
||||
|
||||
return realFetch(input, init)
|
||||
}
|
||||
|
||||
await ensureE2eFixture()
|
||||
await loadAppConfigCacheFromDatabase()
|
||||
|
||||
const startupState = createStartupState()
|
||||
startupState.phase = 'ready'
|
||||
startupState.core.ready = true
|
||||
startupState.core.readyAt = new Date().toISOString()
|
||||
|
||||
const app = createApp({ startupState, isShutdownStarted: () => false, config: runtimeConfig })
|
||||
const server: Server = app.listen(0, '127.0.0.1')
|
||||
await once(server, 'listening')
|
||||
const address = server.address() as AddressInfo
|
||||
const baseUrl = `http://127.0.0.1:${address.port}`
|
||||
startAutoShipDouyinCallbackWorker()
|
||||
|
||||
try {
|
||||
const createBase = {
|
||||
orderNo,
|
||||
productNo,
|
||||
buyNum: 1,
|
||||
maxAmount: '60.0000',
|
||||
callbackUrl: 'https://callback.mock/auto-ship',
|
||||
version: '1.0',
|
||||
}
|
||||
const createBody = signedCreateBody(createBase)
|
||||
const created = await postJson(
|
||||
`${baseUrl}/api/v1/open/auto-ship-douyin/orders/create`,
|
||||
createBody,
|
||||
)
|
||||
assert.equal(created.code, 200)
|
||||
assert.equal(created.data?.orderStatus, 10)
|
||||
assert.ok(String(created.data?.outTradeNo || '').startsWith('OS'))
|
||||
|
||||
const dbOrder = await waitForOrderReady(orderNo)
|
||||
assert.equal(dbOrder.order_status, 'paid')
|
||||
assert.ok(dbOrder.task_count >= 1)
|
||||
assert.ok(dbOrder.claim_token)
|
||||
|
||||
const queryBase = { orderNo, version: '1.0' }
|
||||
const queried = await postJson(
|
||||
`${baseUrl}/api/v1/open/auto-ship-douyin/orders/query`,
|
||||
signedQueryBody(queryBase),
|
||||
)
|
||||
assert.equal(queried.code, 200)
|
||||
assert.equal(queried.data?.orderStatus, 20)
|
||||
assert.equal(queried.data?.failCode, 0)
|
||||
assert.ok(String(queried.data?.cards || '').length > 20)
|
||||
|
||||
const decryptedCards = decryptCards(String(queried.data?.cards || ''), config.secret)
|
||||
assert.ok(Array.isArray(decryptedCards) && decryptedCards.length >= 1)
|
||||
assert.match(String(decryptedCards[0]?.cardNo || ''), /^https:\/\/claim\.mock\/h5\/ASD-E2E-/)
|
||||
|
||||
await waitForCallback()
|
||||
const callback = callbackRequests[0]!
|
||||
assert.equal(callback.body.orderNo, orderNo)
|
||||
assert.equal(callback.body.orderStatus, 20)
|
||||
assert.equal(callback.body.failCode, 0)
|
||||
assert.ok(String(callback.body.cards || '').length > 20)
|
||||
assert.equal(callback.body.sign, signAutoShipDouyinCallbackPayload(callback.body, config))
|
||||
assert.ok(callback.headers['x-event-id'])
|
||||
|
||||
const overLimit = await postJson(
|
||||
`${baseUrl}/api/v1/open/auto-ship-douyin/orders/create`,
|
||||
signedCreateBody({
|
||||
orderNo: overLimitOrderNo,
|
||||
productNo,
|
||||
buyNum: 1,
|
||||
maxAmount: '40.0000',
|
||||
callbackUrl: 'https://callback.mock/over-limit',
|
||||
version: '1.0',
|
||||
}),
|
||||
)
|
||||
assert.equal(overLimit.code, 200)
|
||||
assert.equal(overLimit.data?.orderStatus, 30)
|
||||
assert.equal(overLimit.data?.failCode, 1220)
|
||||
const overLimitTasks = await query<{ count: number }>(
|
||||
'SELECT COUNT(*)::int AS count FROM fulfillment_tasks WHERE platform_order_id = $1',
|
||||
[overLimitOrderNo],
|
||||
)
|
||||
assert.equal(overLimitTasks.rows[0]?.count, 0)
|
||||
|
||||
const unmapped = await postJson(
|
||||
`${baseUrl}/api/v1/open/auto-ship-douyin/orders/create`,
|
||||
signedCreateBody({
|
||||
orderNo: unconfiguredOrderNo,
|
||||
productNo: `UNMAPPED-${runSuffix}`,
|
||||
buyNum: 1,
|
||||
maxAmount: '',
|
||||
callbackUrl: 'https://callback.mock/unmapped',
|
||||
version: '1.0',
|
||||
}),
|
||||
)
|
||||
assert.equal(unmapped.code, 200)
|
||||
assert.equal(unmapped.data?.orderStatus, 10)
|
||||
const pending = await query<{ order_status: string }>(
|
||||
"SELECT order_status FROM orders WHERE provider = 'auto_ship_douyin' AND platform = 'doudian' AND platform_order_id = $1",
|
||||
[unconfiguredOrderNo],
|
||||
)
|
||||
assert.equal(pending.rows[0]?.order_status, 'pending_config')
|
||||
|
||||
console.log(
|
||||
JSON.stringify(
|
||||
{
|
||||
ok: true,
|
||||
orderNo,
|
||||
outTradeNo: created.data.outTradeNo,
|
||||
queryStatus: queried.data.orderStatus,
|
||||
cardsDecrypted: decryptedCards,
|
||||
callbackStatus: callback.body.orderStatus,
|
||||
callbackSignVerified: true,
|
||||
overLimit: { orderStatus: overLimit.data.orderStatus, failCode: overLimit.data.failCode },
|
||||
unmapped: {
|
||||
orderStatus: unmapped.data.orderStatus,
|
||||
dbStatus: pending.rows[0]?.order_status,
|
||||
},
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
)
|
||||
} finally {
|
||||
stopAutoShipDouyinCallbackWorker()
|
||||
globalThis.fetch = realFetch
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()))
|
||||
await closeDb()
|
||||
}
|
||||
|
||||
function signedCreateBody(input: Record<string, unknown>) {
|
||||
const payload = { ...input, timestamp: Math.floor(Date.now() / 1000) }
|
||||
return { ...payload, sign: signAutoShipDouyinPayload(payload, config) }
|
||||
}
|
||||
|
||||
function signedQueryBody(input: Record<string, unknown>) {
|
||||
const payload = { ...input, timestamp: Math.floor(Date.now() / 1000) }
|
||||
return { ...payload, sign: signAutoShipDouyinPayload(payload, config) }
|
||||
}
|
||||
|
||||
async function postJson(url: string, body: Record<string, unknown>) {
|
||||
const response = await realFetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json;charset=utf-8' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
return (await response.json()) as {
|
||||
code: number
|
||||
message: string
|
||||
data?: Record<string, unknown>
|
||||
}
|
||||
}
|
||||
|
||||
function jsonResponse(body: unknown) {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json;charset=utf-8' },
|
||||
})
|
||||
}
|
||||
|
||||
function decryptCards(encrypted: string, secret: string) {
|
||||
const decipher = crypto.createDecipheriv('aes-256-ecb', Buffer.from(secret, 'utf8'), null)
|
||||
decipher.setAutoPadding(true)
|
||||
const text = `${decipher.update(encrypted, 'base64', 'utf8')}${decipher.final('utf8')}`
|
||||
return JSON.parse(text) as Array<Record<string, unknown>>
|
||||
}
|
||||
|
||||
async function waitForOrderReady(platformOrderId: string) {
|
||||
for (let i = 0; i < 50; i += 1) {
|
||||
const result = await query<{
|
||||
order_status: string
|
||||
task_count: number
|
||||
claim_token: string | null
|
||||
}>(
|
||||
`
|
||||
SELECT o.order_status,
|
||||
COUNT(t.id)::int AS task_count,
|
||||
MAX(t.claim_token) AS claim_token
|
||||
FROM orders o
|
||||
LEFT JOIN fulfillment_tasks t ON t.order_id = o.id
|
||||
WHERE o.provider = 'auto_ship_douyin'
|
||||
AND o.platform = 'doudian'
|
||||
AND o.platform_order_id = $1
|
||||
GROUP BY o.id
|
||||
`,
|
||||
[platformOrderId],
|
||||
)
|
||||
const row = result.rows[0]
|
||||
if (row && row.task_count > 0 && String(row.claim_token || '').trim()) return row
|
||||
await sleep(100)
|
||||
}
|
||||
throw new Error(`订单未在预期时间内生成领取任务:${platformOrderId}`)
|
||||
}
|
||||
|
||||
async function waitForCallback() {
|
||||
for (let i = 0; i < 100; i += 1) {
|
||||
if (callbackRequests.length > 0) return
|
||||
await sleep(100)
|
||||
}
|
||||
throw new Error('未在预期时间内收到回调')
|
||||
}
|
||||
|
||||
async function ensureE2eFixture() {
|
||||
await query(
|
||||
`
|
||||
INSERT INTO app_config_entries (config_key, config_json, source_file_path, migrated_from_file, created_at, updated_at)
|
||||
VALUES ('affiliate_dash', $1::jsonb, '', FALSE, NOW(), NOW())
|
||||
ON CONFLICT (config_key) DO UPDATE SET config_json = EXCLUDED.config_json, updated_at = NOW()
|
||||
`,
|
||||
[
|
||||
JSON.stringify({
|
||||
enabled: true,
|
||||
baseUrl: 'https://affiliate.mock',
|
||||
appKey: 'e2e-app-key',
|
||||
appSecret: 'e2e-app-secret',
|
||||
callbackSecret: 'e2e-callback-secret',
|
||||
notifyUrl: '',
|
||||
timeoutMs: 5000,
|
||||
timestampToleranceSeconds: 300,
|
||||
preferredMatchEnabled: true,
|
||||
skuMapping: { [internalSku]: 'e2e_sku' },
|
||||
}),
|
||||
],
|
||||
)
|
||||
|
||||
const sku = await query<{ id: number }>(
|
||||
'SELECT id FROM internal_skus WHERE internal_sku_key = $1 LIMIT 1',
|
||||
[internalSku],
|
||||
)
|
||||
if (!sku.rows[0]) throw new Error(`测试内部 SKU 不存在:${internalSku}`)
|
||||
const internalSkuId = Number(sku.rows[0].id)
|
||||
|
||||
const product = await query<{ id: number }>(
|
||||
`
|
||||
INSERT INTO product_catalog (
|
||||
canonical_sku, canonical_name, category, unit_name, status, attributes_json,
|
||||
created_at, updated_at, internal_sku_id, source_kind
|
||||
) VALUES ($1, $2, '', '件', 'active', '{}'::jsonb, NOW(), NOW(), $3, 'affiliate_dash')
|
||||
ON CONFLICT (canonical_sku) DO UPDATE SET
|
||||
canonical_name = EXCLUDED.canonical_name,
|
||||
internal_sku_id = EXCLUDED.internal_sku_id,
|
||||
source_kind = EXCLUDED.source_kind,
|
||||
status = 'active',
|
||||
updated_at = NOW()
|
||||
RETURNING id
|
||||
`,
|
||||
['aff:auto_ship_douyin_e2e', '自动发货抖店全链路测试商品', internalSkuId],
|
||||
)
|
||||
const productId = Number(product.rows[0]?.id || 0)
|
||||
if (!productId) throw new Error('测试标准商品创建失败')
|
||||
|
||||
await query('DELETE FROM sku_channel_routes WHERE internal_sku_id = $1', [internalSkuId])
|
||||
await query(
|
||||
`
|
||||
INSERT INTO sku_channel_routes (
|
||||
internal_sku_id, channel, route_role, priority, enabled, canonical_product_id,
|
||||
carrier_config_json, source, note, created_at, updated_at
|
||||
) VALUES ($1, 'affiliate_dash', 'primary', 10, TRUE, $2, '{}'::jsonb, 'migration', 'E2E test route', NOW(), NOW())
|
||||
`,
|
||||
[internalSkuId, productId],
|
||||
)
|
||||
|
||||
await query(
|
||||
`
|
||||
INSERT INTO internal_sku_mappings (
|
||||
provider, shop_id, match_type, match_value, internal_sku, priority, enabled,
|
||||
source, note, created_at, updated_at
|
||||
) VALUES ('auto_ship_douyin', 'auto_ship_douyin', 'sku_code', $1, $2, 1, TRUE, 'manual', 'E2E test mapping', NOW(), NOW())
|
||||
ON CONFLICT DO NOTHING
|
||||
`,
|
||||
[productNo, internalSku],
|
||||
)
|
||||
|
||||
await query(
|
||||
`
|
||||
INSERT INTO channel_product_mappings (
|
||||
provider, shop_id, platform_sku_code, platform_sku_name, platform_sku_name_key,
|
||||
canonical_product_id, match_type, quantity_multiplier, confidence, source, enabled,
|
||||
note, created_at, updated_at
|
||||
) VALUES ('auto_ship_douyin', 'auto_ship_douyin', $1, '自动发货抖店全链路测试商品', '', $2,
|
||||
'sku_code', 1, 'manual', 'manual', TRUE, 'E2E test mapping', NOW(), NOW())
|
||||
ON CONFLICT (provider, shop_id, platform_sku_code, match_type, platform_sku_name_key)
|
||||
DO UPDATE SET
|
||||
canonical_product_id = EXCLUDED.canonical_product_id,
|
||||
enabled = TRUE,
|
||||
note = EXCLUDED.note,
|
||||
updated_at = NOW()
|
||||
`,
|
||||
[productNo, productId],
|
||||
)
|
||||
|
||||
await query(
|
||||
`DELETE FROM cost_versions WHERE cost_item_id = 3 AND scope_type = 'product' AND canonical_product_id = $1`,
|
||||
[productId],
|
||||
)
|
||||
await query(
|
||||
`
|
||||
INSERT INTO cost_versions (
|
||||
cost_item_id, scope_type, provider, shop_id, canonical_product_id, amount_fen,
|
||||
rate_bps, effective_from, source, status, change_reason, created_at, updated_at
|
||||
) VALUES (3, 'product', '', '', $1, 5000, 0, '2026-01-01T00:00:00+08:00', 'manual', 'active', 'E2E test cost', NOW(), NOW())
|
||||
`,
|
||||
[productId],
|
||||
)
|
||||
}
|
||||
|
||||
function sleep(ms: number) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import douyinMashidaRouter from './routes/douyin-mashida.js'
|
||||
import douyuFulfillmentRouter from './routes/douyu-fulfillment.js'
|
||||
import kuaishouIndustryRouter from './routes/kuaishou-industry.js'
|
||||
import open91Router from './routes/open-91.js'
|
||||
import openAutoShipDouyinRouter from './routes/open-auto-ship-douyin.js'
|
||||
import pddExtensionRouter from './routes/pdd-extension.js'
|
||||
import platformFulfillmentIntegrationRouter from './routes/platform-fulfillment-integration.js'
|
||||
import redeemRouter from './routes/redeem.js'
|
||||
@@ -117,6 +118,7 @@ export function createApp({ startupState, isShutdownStarted, config }: CreateApp
|
||||
|
||||
app.use('/api/v1/open/affiliate-dash', affiliateDashRouter)
|
||||
app.use('/api/v1/open/91', open91Router)
|
||||
app.use('/api/v1/open/auto-ship-douyin', openAutoShipDouyinRouter)
|
||||
app.use('/api/v1/open/kuaishou-industry', kuaishouIndustryRouter)
|
||||
app.use('/api/integration', platformFulfillmentIntegrationRouter)
|
||||
app.use('/api/v1/redeem', redeemRouter)
|
||||
|
||||
@@ -94,6 +94,17 @@ export function createDefaultRuntimeConfig(projectRoot: string): RuntimeConfig {
|
||||
timestampToleranceSeconds: 600,
|
||||
cardsEncoding: 'aes-256-ecb-base64',
|
||||
},
|
||||
autoShipDouyin: {
|
||||
enabled: false,
|
||||
secret: '',
|
||||
version: '1.0',
|
||||
shopId: 'auto_ship_douyin',
|
||||
shopName: '自动发货抖店',
|
||||
timestampToleranceSeconds: 600,
|
||||
callbackAllowedOrigins: [],
|
||||
callbackTimeoutMs: 5000,
|
||||
callbackMaxAttempts: 12,
|
||||
},
|
||||
kuaishouIndustry: {
|
||||
appKey: '',
|
||||
appSecret: '',
|
||||
|
||||
@@ -80,6 +80,31 @@ export const ENV_OVERRIDES: readonly EnvOverride[] = [
|
||||
'timestampToleranceSeconds',
|
||||
]),
|
||||
stringEnv('KAQUAN91_CARDS_ENCODING', ['platforms', 'ninetyone', 'cardsEncoding']),
|
||||
booleanEnv('AUTO_SHIP_DOUYIN_ENABLED', ['platforms', 'autoShipDouyin', 'enabled']),
|
||||
stringEnv('AUTO_SHIP_DOUYIN_SECRET', ['platforms', 'autoShipDouyin', 'secret']),
|
||||
stringEnv('AUTO_SHIP_DOUYIN_VERSION', ['platforms', 'autoShipDouyin', 'version']),
|
||||
stringEnv('AUTO_SHIP_DOUYIN_SHOP_ID', ['platforms', 'autoShipDouyin', 'shopId']),
|
||||
stringEnv('AUTO_SHIP_DOUYIN_SHOP_NAME', ['platforms', 'autoShipDouyin', 'shopName']),
|
||||
integerEnv('AUTO_SHIP_DOUYIN_TIMESTAMP_TOLERANCE_SECONDS', [
|
||||
'platforms',
|
||||
'autoShipDouyin',
|
||||
'timestampToleranceSeconds',
|
||||
]),
|
||||
corsOriginsEnv('AUTO_SHIP_DOUYIN_CALLBACK_ALLOWED_ORIGINS', [
|
||||
'platforms',
|
||||
'autoShipDouyin',
|
||||
'callbackAllowedOrigins',
|
||||
]),
|
||||
integerEnv('AUTO_SHIP_DOUYIN_CALLBACK_TIMEOUT_MS', [
|
||||
'platforms',
|
||||
'autoShipDouyin',
|
||||
'callbackTimeoutMs',
|
||||
]),
|
||||
integerEnv('AUTO_SHIP_DOUYIN_CALLBACK_MAX_ATTEMPTS', [
|
||||
'platforms',
|
||||
'autoShipDouyin',
|
||||
'callbackMaxAttempts',
|
||||
]),
|
||||
stringEnv('KUASHOU_INDUSTRY_APP_KEY', ['platforms', 'kuaishouIndustry', 'appKey']),
|
||||
stringEnv('KUASHOU_INDUSTRY_APP_SECRET', ['platforms', 'kuaishouIndustry', 'appSecret']),
|
||||
stringEnv('KUASHOU_INDUSTRY_SIGN_SECRET', ['platforms', 'kuaishouIndustry', 'signSecret']),
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
-- 180_auto_ship_douyin_callback.sql
|
||||
--
|
||||
-- 自动发货抖店接口回调扩展:
|
||||
-- 1. 只服务新来源 auto_ship_douyin,不复用 live-hub 的 integration_outbox;
|
||||
-- 2. 下单后先落一条 order_watch 任务,worker 只检查该订单是否已可交付;
|
||||
-- 3. 达到终态后在同一行收敛为 delivery_ready / order_failed,再按退避策略投递平台回调。
|
||||
|
||||
CREATE TABLE IF NOT EXISTS auto_ship_callback_outbox (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
event_id UUID NOT NULL UNIQUE DEFAULT gen_random_uuid(),
|
||||
provider TEXT NOT NULL,
|
||||
platform TEXT NOT NULL,
|
||||
order_id BIGINT NOT NULL REFERENCES orders(id) ON DELETE CASCADE,
|
||||
platform_order_id TEXT NOT NULL,
|
||||
callback_url TEXT NOT NULL,
|
||||
event_type TEXT NOT NULL DEFAULT 'order_watch'
|
||||
CHECK (event_type IN ('order_watch', 'delivery_ready', 'order_failed')),
|
||||
dedupe_key TEXT NOT NULL UNIQUE,
|
||||
payload_json JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
status TEXT NOT NULL DEFAULT 'pending'
|
||||
CHECK (status IN ('pending', 'processing', 'sent', 'dead')),
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
locked_at TIMESTAMPTZ,
|
||||
sent_at TIMESTAMPTZ,
|
||||
last_error TEXT NOT NULL DEFAULT '',
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_auto_ship_callback_outbox_due
|
||||
ON auto_ship_callback_outbox (status, next_attempt_at, id);
|
||||
CREATE INDEX IF NOT EXISTS idx_auto_ship_callback_outbox_order
|
||||
ON auto_ship_callback_outbox (order_id, id DESC);
|
||||
|
||||
COMMENT ON TABLE auto_ship_callback_outbox IS
|
||||
'自动发货抖店平台回调任务;按订单定向检查并持久化重试,不与其他集成目的地混用';
|
||||
COMMENT ON COLUMN auto_ship_callback_outbox.event_type IS
|
||||
'order_watch=等待订单可交付;delivery_ready=已生成领取链接;order_failed=终态失败';
|
||||
@@ -7,6 +7,7 @@ import notificationsRouter from './platform-config/notifications.js'
|
||||
import affiliateDashRouter from './platform-config/affiliate-dash.js'
|
||||
import douyinMashidaRouter from './platform-config/douyin-mashida.js'
|
||||
import pddRouter from './platform-config/pdd.js'
|
||||
import autoShipDouyinRouter from './platform-config/auto-ship-douyin.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
@@ -16,6 +17,7 @@ router.use('/platform-config', notificationsRouter)
|
||||
router.use('/platform-config', ninetyoneRouter)
|
||||
router.use('/platform-config', affiliateDashRouter)
|
||||
router.use('/platform-config', pddRouter)
|
||||
router.use('/platform-config', autoShipDouyinRouter)
|
||||
// 抖音码速达:注册在 requireAdminRoles(['admin']) 之后,自动继承 admin 守卫
|
||||
router.use('/platform-config', douyinMashidaRouter)
|
||||
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
import { Router } from 'express'
|
||||
import {
|
||||
failAdminAutoShipDouyinOrder,
|
||||
getAdminAutoShipDouyinCallbacks,
|
||||
getAdminAutoShipDouyinOrders,
|
||||
retryAdminAutoShipDouyinCallback,
|
||||
retryAdminAutoShipDouyinOrder,
|
||||
} from '../../../services/admin/platform-config/auto-ship-douyin-service.js'
|
||||
import type { AdminEntityRouteParams } from '../../../types/admin/route-inputs.js'
|
||||
import type { JsonRecord } from '../../../types/json.js'
|
||||
import { createJsonHandler } from '../session.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.get(
|
||||
'/auto-ship-douyin/orders',
|
||||
createJsonHandler((req) => getAdminAutoShipDouyinOrders(req.query), {
|
||||
successMessage: 'ok',
|
||||
errorMessage: '读取自动发货抖店订单失败',
|
||||
scope: '[admin/platform-config/auto-ship-douyin/orders]',
|
||||
}),
|
||||
)
|
||||
|
||||
router.post(
|
||||
'/auto-ship-douyin/orders/:id/retry',
|
||||
createJsonHandler(
|
||||
(req) => retryAdminAutoShipDouyinOrder(String((req.params as AdminEntityRouteParams).id || '')),
|
||||
{
|
||||
successMessage: '自动发货抖店订单已重试',
|
||||
errorMessage: '重试自动发货抖店订单失败',
|
||||
scope: '[admin/platform-config/auto-ship-douyin/orders/:id/retry]',
|
||||
audit: (_req, data) => {
|
||||
const result = data as JsonRecord
|
||||
return {
|
||||
action: 'platform_auto_ship_douyin_order_retried',
|
||||
targetType: 'order',
|
||||
targetId: String(result.orderId || '').trim(),
|
||||
data: {
|
||||
orderNo: String(result.orderNo || '').trim(),
|
||||
taskCount: Number(result.taskCount || 0),
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
router.post(
|
||||
'/auto-ship-douyin/orders/:id/fail',
|
||||
createJsonHandler(
|
||||
(req) =>
|
||||
failAdminAutoShipDouyinOrder(
|
||||
String((req.params as AdminEntityRouteParams).id || ''),
|
||||
req.body as JsonRecord,
|
||||
),
|
||||
{
|
||||
successMessage: '自动发货抖店订单已标记失败',
|
||||
errorMessage: '标记自动发货抖店订单失败',
|
||||
scope: '[admin/platform-config/auto-ship-douyin/orders/:id/fail]',
|
||||
audit: (req, data) => {
|
||||
const result = data as JsonRecord
|
||||
return {
|
||||
action: 'platform_auto_ship_douyin_order_failed',
|
||||
targetType: 'order',
|
||||
targetId: String(result.orderId || '').trim(),
|
||||
data: {
|
||||
orderNo: String(result.orderNo || '').trim(),
|
||||
reason: String((req.body as JsonRecord).reason || '').trim(),
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
router.get(
|
||||
'/auto-ship-douyin/callbacks',
|
||||
createJsonHandler((req) => getAdminAutoShipDouyinCallbacks(req.query), {
|
||||
successMessage: 'ok',
|
||||
errorMessage: '读取自动发货抖店回调任务失败',
|
||||
scope: '[admin/platform-config/auto-ship-douyin/callbacks]',
|
||||
}),
|
||||
)
|
||||
|
||||
router.post(
|
||||
'/auto-ship-douyin/callbacks/:id/retry',
|
||||
createJsonHandler(
|
||||
(req) =>
|
||||
retryAdminAutoShipDouyinCallback(String((req.params as AdminEntityRouteParams).id || '')),
|
||||
{
|
||||
successMessage: '回调任务已重新排队',
|
||||
errorMessage: '重试回调任务失败',
|
||||
scope: '[admin/platform-config/auto-ship-douyin/callbacks/:id/retry]',
|
||||
audit: (req, data) => {
|
||||
const result = data as JsonRecord
|
||||
return {
|
||||
action: 'platform_auto_ship_douyin_callback_retried',
|
||||
targetType: 'auto_ship_callback',
|
||||
targetId: String((req.params as AdminEntityRouteParams).id || ''),
|
||||
data: {
|
||||
orderId: String(result?.order_id || '').trim(),
|
||||
orderNo: String(result?.platform_order_id || '').trim(),
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
),
|
||||
)
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,95 @@
|
||||
import { Router } from 'express'
|
||||
import { createRateLimitMiddleware } from '../middleware/rate-limit.js'
|
||||
import { createAutoShipDouyinOrder } from '../services/open-auto-ship-douyin/order-create-service.js'
|
||||
import { queryAutoShipDouyinOrder } from '../services/open-auto-ship-douyin/order-query-service.js'
|
||||
import { buildAutoShipDouyinErrorResponse } from '../services/open-auto-ship-douyin/response.js'
|
||||
import { createRequestId, logIntegration } from '../utils/logger.js'
|
||||
import type { JsonObject } from '../types/json.js'
|
||||
|
||||
const router = Router()
|
||||
const rateLimit = createRateLimitMiddleware({
|
||||
scope: 'auto-ship-douyin',
|
||||
windowMs: 60_000,
|
||||
max: 120,
|
||||
onLimit: (_req, res) => {
|
||||
res.status(200).json(buildAutoShipDouyinErrorResponse('请求过于频繁,请稍后再试', 429))
|
||||
},
|
||||
})
|
||||
|
||||
function resolveErrorCode(error: unknown) {
|
||||
const status =
|
||||
error && typeof error === 'object' && 'statusCode' in error
|
||||
? Number((error as { statusCode?: unknown }).statusCode || 500)
|
||||
: 500
|
||||
if (status === 409) return 409
|
||||
return status >= 500 ? 500 : 400
|
||||
}
|
||||
|
||||
router.post('/orders/create', rateLimit, async (req, res) => {
|
||||
const requestId = createRequestId('auto-ship-douyin')
|
||||
const startedAt = Date.now()
|
||||
const body = (req.body || {}) as JsonObject
|
||||
logIntegration('[auto-ship-douyin/create]', '收到异步卡密采购下单请求', {
|
||||
requestId,
|
||||
ip: req.ip,
|
||||
orderNo: String(body.orderNo || ''),
|
||||
productNo: String(body.productNo || ''),
|
||||
buyNum: Number(body.buyNum || 0),
|
||||
maxAmount: String(body.maxAmount || ''),
|
||||
hasCallbackUrl: Boolean(String(body.callbackUrl || '').trim()),
|
||||
})
|
||||
try {
|
||||
const result = await createAutoShipDouyinOrder(body, { requestId })
|
||||
const data = result.data as JsonObject | null
|
||||
logIntegration('[auto-ship-douyin/create]', '异步卡密采购下单处理完成', {
|
||||
requestId,
|
||||
durationMs: Date.now() - startedAt,
|
||||
orderStatus: data?.orderStatus,
|
||||
outTradeNo: data?.outTradeNo,
|
||||
failCode: data?.failCode,
|
||||
})
|
||||
res.status(200).json(result)
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : '系统错误'
|
||||
logIntegration(
|
||||
'[auto-ship-douyin/create]',
|
||||
'异步卡密采购下单处理失败',
|
||||
{ requestId, durationMs: Date.now() - startedAt, error },
|
||||
{ level: 'error' },
|
||||
)
|
||||
res.status(200).json(buildAutoShipDouyinErrorResponse(message, resolveErrorCode(error)))
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/orders/query', rateLimit, async (req, res) => {
|
||||
const requestId = createRequestId('auto-ship-douyin')
|
||||
const startedAt = Date.now()
|
||||
const body = (req.body || {}) as JsonObject
|
||||
logIntegration('[auto-ship-douyin/query]', '收到订单查询请求', {
|
||||
requestId,
|
||||
ip: req.ip,
|
||||
orderNo: String(body.orderNo || ''),
|
||||
})
|
||||
try {
|
||||
const result = await queryAutoShipDouyinOrder(body, { requestId })
|
||||
const data = result.data as JsonObject | null
|
||||
logIntegration('[auto-ship-douyin/query]', '订单查询处理完成', {
|
||||
requestId,
|
||||
durationMs: Date.now() - startedAt,
|
||||
orderStatus: data?.orderStatus,
|
||||
failCode: data?.failCode,
|
||||
})
|
||||
res.status(200).json(result)
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : '系统错误'
|
||||
logIntegration(
|
||||
'[auto-ship-douyin/query]',
|
||||
'订单查询处理失败',
|
||||
{ requestId, durationMs: Date.now() - startedAt, error },
|
||||
{ level: 'error' },
|
||||
)
|
||||
res.status(200).json(buildAutoShipDouyinErrorResponse(message, resolveErrorCode(error)))
|
||||
}
|
||||
})
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,54 @@
|
||||
import type { JsonObject } from '../../../types/json.js'
|
||||
import {
|
||||
failAutoShipDouyinOrder,
|
||||
listAutoShipDouyinOrders,
|
||||
retryAutoShipDouyinOrder,
|
||||
} from '../../open-auto-ship-douyin/order-service.js'
|
||||
import {
|
||||
listAutoShipDouyinCallbacks,
|
||||
retryAutoShipDouyinCallback,
|
||||
} from '../../open-auto-ship-douyin/callback-outbox-service.js'
|
||||
|
||||
export async function getAdminAutoShipDouyinOrders(query: JsonObject = {}) {
|
||||
return listAutoShipDouyinOrders({
|
||||
page: Number(query.page || 1) || 1,
|
||||
pageSize: Number(query.pageSize || 20) || 20,
|
||||
status: String(query.status || 'pending_config'),
|
||||
})
|
||||
}
|
||||
|
||||
export async function retryAdminAutoShipDouyinOrder(orderId: number | string) {
|
||||
const result = await retryAutoShipDouyinOrder(orderId)
|
||||
return {
|
||||
orderId: Number(result.order?.id || 0),
|
||||
orderNo: String(result.order?.platform_order_id || '').trim(),
|
||||
orderStatus: String(result.order?.order_status || '').trim(),
|
||||
orderItemCount: Array.isArray(result.orderItems) ? result.orderItems.length : 0,
|
||||
taskCount: Array.isArray(result.tasks) ? result.tasks.length : 0,
|
||||
}
|
||||
}
|
||||
|
||||
export async function failAdminAutoShipDouyinOrder(
|
||||
orderId: number | string,
|
||||
payload: JsonObject = {},
|
||||
) {
|
||||
const result = await failAutoShipDouyinOrder(orderId, payload.reason)
|
||||
return {
|
||||
orderId: Number(result.order?.id || 0),
|
||||
orderNo: String(result.order?.platform_order_id || '').trim(),
|
||||
orderStatus: String(result.order?.order_status || '').trim(),
|
||||
taskCount: Array.isArray(result.tasks) ? result.tasks.length : 0,
|
||||
}
|
||||
}
|
||||
|
||||
export async function getAdminAutoShipDouyinCallbacks(query: JsonObject = {}) {
|
||||
return listAutoShipDouyinCallbacks({
|
||||
page: Number(query.page || 1) || 1,
|
||||
pageSize: Number(query.pageSize || 20) || 20,
|
||||
status: String(query.status || 'pending'),
|
||||
})
|
||||
}
|
||||
|
||||
export async function retryAdminAutoShipDouyinCallback(callbackId: number | string) {
|
||||
return retryAutoShipDouyinCallback(callbackId)
|
||||
}
|
||||
@@ -97,7 +97,7 @@ export const COST_VERSION_SOURCES = new Set(['manual', 'upstream_sync', 'import'
|
||||
export const COST_VERSION_STATUSES = new Set(['draft', 'active', 'retired'])
|
||||
export const COST_EXCEPTION_STATUSES = new Set(['open', 'resolved', 'ignored'])
|
||||
export const COST_EXCEPTION_SUBJECT_TYPES = new Set(['order_item', 'work_order', 'manual_case'])
|
||||
export const PROVIDERS = ['91kaquan', 'pdd', 'douyin_mashida']
|
||||
export const PROVIDERS = ['91kaquan', 'pdd', 'douyin_mashida', 'auto_ship_douyin']
|
||||
|
||||
/** 首次把接单模板发单金额落成成本版本时使用的基线时间。 */
|
||||
export const WORK_ORDER_TEMPLATE_COST_BASELINE = '2026-07-10T00:00:00+08:00'
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
/**
|
||||
* 自动发货抖店接入集成测试(需要真实 PostgreSQL)。
|
||||
*
|
||||
* AUTO_SHIP_DOUYIN_TEST_DATABASE_URL=postgres://... \
|
||||
* npx tsx --test src/services/open-auto-ship-douyin/auto-ship-douyin.integration.test.ts
|
||||
*/
|
||||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
|
||||
const TEST_DATABASE_URL = String(process.env.AUTO_SHIP_DOUYIN_TEST_DATABASE_URL || '').trim()
|
||||
|
||||
test(
|
||||
'未配置商品仍落库、进入待补全并创建回调 watch,重复下单不重复建单',
|
||||
{ skip: !TEST_DATABASE_URL ? '未设置 AUTO_SHIP_DOUYIN_TEST_DATABASE_URL' : false },
|
||||
async () => {
|
||||
process.env.DATABASE_URL = TEST_DATABASE_URL
|
||||
process.env.AUTO_SHIP_DOUYIN_ENABLED = 'true'
|
||||
process.env.AUTO_SHIP_DOUYIN_SECRET = '12345678901234567890123456789012'
|
||||
process.env.AUTO_SHIP_DOUYIN_CALLBACK_ALLOWED_ORIGINS = 'https://callback.example.com'
|
||||
|
||||
const { closeDb, query } = await import('../../../db/client.js')
|
||||
const { assertAutoShipDouyinConfig } = await import('./config.js')
|
||||
const { signAutoShipDouyinPayload } = await import('./crypto.js')
|
||||
const { createAutoShipDouyinOrder } = await import('./order-create-service.js')
|
||||
const suffix = `${Date.now()}_${Math.floor(Math.random() * 1_000_000)}`
|
||||
const orderNo = `ASD-IT-${suffix}`
|
||||
let orderId = 0
|
||||
|
||||
try {
|
||||
const config = assertAutoShipDouyinConfig()
|
||||
const timestamp = Math.floor(Date.now() / 1000)
|
||||
const base = {
|
||||
orderNo,
|
||||
productNo: `UNMAPPED-${suffix}`,
|
||||
buyNum: 1,
|
||||
maxAmount: '',
|
||||
callbackUrl: 'https://callback.example.com/hook',
|
||||
timestamp,
|
||||
version: '1.0',
|
||||
}
|
||||
const payload = { ...base, sign: signAutoShipDouyinPayload(base, config) }
|
||||
|
||||
const first = await createAutoShipDouyinOrder(payload)
|
||||
assert.equal(first.data?.orderStatus, 10)
|
||||
|
||||
const orders = await query<{ id: number; order_status: string }>(
|
||||
`SELECT id, order_status FROM orders WHERE provider = 'auto_ship_douyin' AND platform = 'doudian' AND platform_order_id = $1`,
|
||||
[orderNo],
|
||||
)
|
||||
assert.equal(orders.rows.length, 1)
|
||||
orderId = Number(orders.rows[0]!.id)
|
||||
assert.equal(orders.rows[0]!.order_status, 'pending_config')
|
||||
|
||||
const callbacks = await query<{ event_type: string; status: string }>(
|
||||
`SELECT event_type, status FROM auto_ship_callback_outbox WHERE order_id = $1`,
|
||||
[orderId],
|
||||
)
|
||||
assert.equal(callbacks.rows.length, 1)
|
||||
assert.equal(callbacks.rows[0]!.event_type, 'order_watch')
|
||||
assert.equal(callbacks.rows[0]!.status, 'pending')
|
||||
|
||||
const second = await createAutoShipDouyinOrder({
|
||||
...base,
|
||||
timestamp: Math.floor(Date.now() / 1000),
|
||||
sign: signAutoShipDouyinPayload(
|
||||
{ ...base, timestamp: Math.floor(Date.now() / 1000) },
|
||||
config,
|
||||
),
|
||||
})
|
||||
assert.equal(second.data?.orderStatus, 10)
|
||||
const count = await query<{ total: number }>(
|
||||
`SELECT COUNT(*)::int AS total FROM orders WHERE provider = 'auto_ship_douyin' AND platform = 'doudian' AND platform_order_id = $1`,
|
||||
[orderNo],
|
||||
)
|
||||
assert.equal(Number(count.rows[0]?.total || 0), 1)
|
||||
} finally {
|
||||
if (orderId > 0) {
|
||||
await query('DELETE FROM auto_ship_callback_outbox WHERE order_id = $1', [orderId])
|
||||
await query('DELETE FROM order_source_snapshots WHERE order_id = $1', [orderId])
|
||||
await query('DELETE FROM orders WHERE id = $1', [orderId])
|
||||
}
|
||||
await closeDb()
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,396 @@
|
||||
import { query, withTransaction } from '../../db/client.js'
|
||||
import type { OrderRow } from '../../types/repository/rows.js'
|
||||
import { getOrderById } from '../../repositories/order-repo.js'
|
||||
import { logError, logInfo, logWarn } from '../../utils/logger.js'
|
||||
import {
|
||||
AUTO_SHIP_DOUYIN_PLATFORM,
|
||||
AUTO_SHIP_DOUYIN_PROVIDER,
|
||||
assertAutoShipDouyinCallbackUrl,
|
||||
assertAutoShipDouyinConfig,
|
||||
getAutoShipDouyinConfig,
|
||||
} from './config.js'
|
||||
import { encryptAutoShipDouyinCards, signAutoShipDouyinCallbackPayload } from './crypto.js'
|
||||
import { resolveAutoShipDouyinOrderSnapshot } from './order-state-service.js'
|
||||
import { buildAutoShipDouyinOutTradeNo, formatAutoShipDouyinOrderCost } from './response.js'
|
||||
|
||||
type CallbackOutboxRow = {
|
||||
id: string
|
||||
event_id: string
|
||||
event_type: string
|
||||
order_id: string
|
||||
platform_order_id: string
|
||||
callback_url: string
|
||||
payload_json: unknown
|
||||
attempts: number
|
||||
}
|
||||
|
||||
const DEFAULT_INTERVAL_MS = 1000
|
||||
const DEFAULT_BATCH_SIZE = 20
|
||||
const DEFAULT_MAX_ATTEMPTS = 12
|
||||
const REQUEST_TIMEOUT_MS = 5000
|
||||
const PROCESSING_STALE_SECONDS = 120
|
||||
const WAIT_DELIVERY_SECONDS = 5
|
||||
|
||||
let timer: NodeJS.Timeout | null = null
|
||||
let running = false
|
||||
let stopped = true
|
||||
|
||||
export async function ensureAutoShipDouyinCallbackWatch(order: OrderRow, callbackUrl: string) {
|
||||
const normalizedCallbackUrl = assertAutoShipDouyinCallbackUrl(callbackUrl)
|
||||
const dedupeKey = [
|
||||
AUTO_SHIP_DOUYIN_PROVIDER,
|
||||
AUTO_SHIP_DOUYIN_PLATFORM,
|
||||
String(order.platform_order_id || '').trim(),
|
||||
'callback',
|
||||
].join('|')
|
||||
|
||||
await query(
|
||||
`
|
||||
INSERT INTO auto_ship_callback_outbox (
|
||||
provider, platform, order_id, platform_order_id, callback_url,
|
||||
event_type, dedupe_key, status, next_attempt_at, updated_at
|
||||
) VALUES ($1, $2, $3, $4, $5, 'order_watch', $6, 'pending', NOW(), NOW())
|
||||
ON CONFLICT (dedupe_key) DO UPDATE SET
|
||||
callback_url = EXCLUDED.callback_url,
|
||||
status = CASE
|
||||
WHEN auto_ship_callback_outbox.status = 'dead' THEN 'pending'
|
||||
ELSE auto_ship_callback_outbox.status
|
||||
END,
|
||||
next_attempt_at = CASE
|
||||
WHEN auto_ship_callback_outbox.status = 'dead' THEN NOW()
|
||||
ELSE auto_ship_callback_outbox.next_attempt_at
|
||||
END,
|
||||
updated_at = NOW()
|
||||
`,
|
||||
[
|
||||
AUTO_SHIP_DOUYIN_PROVIDER,
|
||||
AUTO_SHIP_DOUYIN_PLATFORM,
|
||||
order.id,
|
||||
order.platform_order_id,
|
||||
normalizedCallbackUrl,
|
||||
dedupeKey,
|
||||
],
|
||||
)
|
||||
}
|
||||
|
||||
export async function resetAutoShipDouyinCallbackWatch(orderId: number) {
|
||||
await query(
|
||||
`
|
||||
UPDATE auto_ship_callback_outbox
|
||||
SET event_type = 'order_watch',
|
||||
payload_json = '{}'::jsonb,
|
||||
status = 'pending',
|
||||
attempts = 0,
|
||||
next_attempt_at = NOW(),
|
||||
locked_at = NULL,
|
||||
sent_at = NULL,
|
||||
last_error = '',
|
||||
updated_at = NOW()
|
||||
WHERE provider = $1 AND platform = $2 AND order_id = $3
|
||||
`,
|
||||
[AUTO_SHIP_DOUYIN_PROVIDER, AUTO_SHIP_DOUYIN_PLATFORM, orderId],
|
||||
)
|
||||
}
|
||||
|
||||
export async function listAutoShipDouyinCallbacks(
|
||||
input: {
|
||||
status?: string
|
||||
page?: number
|
||||
pageSize?: number
|
||||
} = {},
|
||||
) {
|
||||
const page = Math.max(1, Math.trunc(Number(input.page) || 1))
|
||||
const pageSize = Math.min(100, Math.max(1, Math.trunc(Number(input.pageSize) || 20)))
|
||||
const params: unknown[] = [AUTO_SHIP_DOUYIN_PROVIDER, AUTO_SHIP_DOUYIN_PLATFORM]
|
||||
const clauses = ['provider = $1', 'platform = $2']
|
||||
const status = String(input.status || '').trim()
|
||||
if (status && status !== 'all') {
|
||||
params.push(status)
|
||||
clauses.push(`status = $${params.length}`)
|
||||
}
|
||||
const where = clauses.join(' AND ')
|
||||
const count = await query<{ total: number }>(
|
||||
`SELECT COUNT(*)::int AS total FROM auto_ship_callback_outbox WHERE ${where}`,
|
||||
params,
|
||||
)
|
||||
params.push(pageSize, (page - 1) * pageSize)
|
||||
const rows = await query(
|
||||
`
|
||||
SELECT id, event_id, order_id, platform_order_id, event_type, status,
|
||||
attempts, next_attempt_at, sent_at, last_error, created_at, updated_at
|
||||
FROM auto_ship_callback_outbox
|
||||
WHERE ${where}
|
||||
ORDER BY id DESC
|
||||
LIMIT $${params.length - 1} OFFSET $${params.length}
|
||||
`,
|
||||
params,
|
||||
)
|
||||
return {
|
||||
page,
|
||||
pageSize,
|
||||
total: Number(count.rows[0]?.total || 0),
|
||||
items: rows.rows,
|
||||
}
|
||||
}
|
||||
|
||||
export async function retryAutoShipDouyinCallback(idInput: number | string) {
|
||||
const id = Number(idInput)
|
||||
if (!Number.isInteger(id) || id <= 0) {
|
||||
throw new Error('回调任务 ID 无效')
|
||||
}
|
||||
const result = await query(
|
||||
`
|
||||
UPDATE auto_ship_callback_outbox
|
||||
SET status = 'pending',
|
||||
attempts = 0,
|
||||
next_attempt_at = NOW(),
|
||||
locked_at = NULL,
|
||||
last_error = '',
|
||||
updated_at = NOW()
|
||||
WHERE id = $1 AND provider = $2 AND platform = $3
|
||||
RETURNING id, order_id, platform_order_id, event_type, status
|
||||
`,
|
||||
[id, AUTO_SHIP_DOUYIN_PROVIDER, AUTO_SHIP_DOUYIN_PLATFORM],
|
||||
)
|
||||
return result.rows[0] || null
|
||||
}
|
||||
|
||||
export function buildAutoShipDouyinCallbackPayload(
|
||||
order: OrderRow,
|
||||
snapshot: {
|
||||
orderStatus: number
|
||||
failCode: number
|
||||
failReason: string
|
||||
orderCostFen: number | null
|
||||
cardItems: unknown[]
|
||||
},
|
||||
) {
|
||||
const config = assertAutoShipDouyinConfig()
|
||||
const cards =
|
||||
snapshot.orderStatus === 20 ? encryptAutoShipDouyinCards(snapshot.cardItems, config.secret) : ''
|
||||
const payload = {
|
||||
orderNo: String(order.platform_order_id || '').trim(),
|
||||
outTradeNo: buildAutoShipDouyinOutTradeNo(order),
|
||||
orderStatus: snapshot.orderStatus,
|
||||
failCode: snapshot.failCode,
|
||||
failReason: snapshot.failReason,
|
||||
orderCost: formatAutoShipDouyinOrderCost(snapshot.orderCostFen, { trim: true }),
|
||||
cards,
|
||||
timestamp: Math.floor(Date.now() / 1000),
|
||||
}
|
||||
return {
|
||||
...payload,
|
||||
sign: signAutoShipDouyinCallbackPayload(payload, config),
|
||||
}
|
||||
}
|
||||
|
||||
async function claimDueEvents(limit: number): Promise<CallbackOutboxRow[]> {
|
||||
return withTransaction(async (client) => {
|
||||
await client.query(
|
||||
`
|
||||
UPDATE auto_ship_callback_outbox
|
||||
SET status = 'pending', locked_at = NULL, next_attempt_at = NOW()
|
||||
WHERE status = 'processing'
|
||||
AND locked_at < NOW() - ($1 * INTERVAL '1 second')
|
||||
`,
|
||||
[PROCESSING_STALE_SECONDS],
|
||||
)
|
||||
const claimed = await client.query<CallbackOutboxRow>(
|
||||
`
|
||||
SELECT id, event_id, event_type, order_id, platform_order_id, callback_url, payload_json, attempts
|
||||
FROM auto_ship_callback_outbox
|
||||
WHERE status = 'pending' AND next_attempt_at <= NOW()
|
||||
ORDER BY id ASC
|
||||
LIMIT $1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
`,
|
||||
[limit],
|
||||
)
|
||||
const ids = claimed.rows.map((row) => Number(row.id)).filter((id) => id > 0)
|
||||
if (ids.length === 0) return []
|
||||
await client.query(
|
||||
`UPDATE auto_ship_callback_outbox SET status = 'processing', locked_at = NOW() WHERE id = ANY($1::bigint[])`,
|
||||
[ids],
|
||||
)
|
||||
return claimed.rows
|
||||
})
|
||||
}
|
||||
|
||||
async function updateWatchState(row: CallbackOutboxRow) {
|
||||
const order = await getOrderById(Number(row.order_id))
|
||||
if (!order) {
|
||||
await query(
|
||||
`UPDATE auto_ship_callback_outbox SET status = 'dead', last_error = '订单不存在', locked_at = NULL, updated_at = NOW() WHERE id = $1`,
|
||||
[row.id],
|
||||
)
|
||||
return null
|
||||
}
|
||||
const snapshot = await resolveAutoShipDouyinOrderSnapshot(order)
|
||||
if (snapshot.orderStatus === 10) {
|
||||
await query(
|
||||
`
|
||||
UPDATE auto_ship_callback_outbox
|
||||
SET status = 'pending',
|
||||
locked_at = NULL,
|
||||
next_attempt_at = NOW() + ($2 * INTERVAL '1 second'),
|
||||
last_error = 'waiting_delivery',
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[row.id, WAIT_DELIVERY_SECONDS],
|
||||
)
|
||||
return null
|
||||
}
|
||||
const payload = buildAutoShipDouyinCallbackPayload(order, snapshot)
|
||||
const eventType = snapshot.orderStatus === 20 ? 'delivery_ready' : 'order_failed'
|
||||
await query(
|
||||
`
|
||||
UPDATE auto_ship_callback_outbox
|
||||
SET event_type = $2,
|
||||
payload_json = $3::jsonb,
|
||||
status = 'pending',
|
||||
locked_at = NULL,
|
||||
next_attempt_at = NOW(),
|
||||
last_error = '',
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[row.id, eventType, payload],
|
||||
)
|
||||
return payload
|
||||
}
|
||||
|
||||
async function deliverCallback(row: CallbackOutboxRow, payload: unknown) {
|
||||
const config = getAutoShipDouyinConfig()
|
||||
const rawBody = JSON.stringify(payload)
|
||||
const timestamp = String(Math.floor(Date.now() / 1000))
|
||||
const response = await fetch(row.callback_url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json;charset=utf-8',
|
||||
'X-Event-Id': row.event_id,
|
||||
'X-Timestamp': timestamp,
|
||||
},
|
||||
body: rawBody,
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(config.callbackTimeoutMs),
|
||||
})
|
||||
if (!response.ok) {
|
||||
throw new Error(`平台回调返回 HTTP ${response.status}`)
|
||||
}
|
||||
const body = (await response.json().catch(() => null)) as { code?: unknown } | null
|
||||
if (!body || Number(body.code) !== 200) {
|
||||
throw new Error('平台回调未返回 code=200')
|
||||
}
|
||||
}
|
||||
|
||||
async function markSent(id: string) {
|
||||
await query(
|
||||
`UPDATE auto_ship_callback_outbox SET status = 'sent', sent_at = NOW(), locked_at = NULL, last_error = '', updated_at = NOW() WHERE id = $1`,
|
||||
[id],
|
||||
)
|
||||
}
|
||||
|
||||
async function markFailed(row: CallbackOutboxRow, error: unknown) {
|
||||
const attempts = Number(row.attempts || 0) + 1
|
||||
const maxAttempts = Math.max(
|
||||
1,
|
||||
Math.trunc(getAutoShipDouyinConfig().callbackMaxAttempts || DEFAULT_MAX_ATTEMPTS),
|
||||
)
|
||||
const dead = attempts >= maxAttempts
|
||||
const message = (error instanceof Error ? error.message : String(error)).slice(0, 2000)
|
||||
await query(
|
||||
`
|
||||
UPDATE auto_ship_callback_outbox
|
||||
SET status = $2,
|
||||
attempts = $3,
|
||||
locked_at = NULL,
|
||||
next_attempt_at = NOW() + ($4 * INTERVAL '1 second'),
|
||||
last_error = $5,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1
|
||||
`,
|
||||
[
|
||||
row.id,
|
||||
dead ? 'dead' : 'pending',
|
||||
attempts,
|
||||
dead ? 0 : autoShipDouyinCallbackBackoffSeconds(attempts),
|
||||
message,
|
||||
],
|
||||
)
|
||||
if (dead) {
|
||||
logError('[auto-ship-douyin/callback]', '回调超过最大重试次数,已进入 dead', {
|
||||
eventId: row.event_id,
|
||||
orderId: row.order_id,
|
||||
attempts,
|
||||
error: message,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export function autoShipDouyinCallbackBackoffSeconds(attempts: number) {
|
||||
const normalized = Math.max(1, Math.trunc(Number(attempts) || 1))
|
||||
return Math.min(3600, 5 * 2 ** Math.min(normalized - 1, 10))
|
||||
}
|
||||
|
||||
async function publishDueEvents() {
|
||||
const batchSize = envInt('AUTO_SHIP_DOUYIN_CALLBACK_BATCH_SIZE', DEFAULT_BATCH_SIZE, 1, 100)
|
||||
const rows = await claimDueEvents(batchSize)
|
||||
for (const row of rows) {
|
||||
try {
|
||||
let payload = row.payload_json
|
||||
if (row.event_type === 'order_watch') {
|
||||
payload = await updateWatchState(row)
|
||||
if (!payload) continue
|
||||
}
|
||||
await deliverCallback(row, payload)
|
||||
await markSent(row.id)
|
||||
} catch (error) {
|
||||
await markFailed(row, error)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function runLoop() {
|
||||
if (stopped || running) return
|
||||
running = true
|
||||
try {
|
||||
await publishDueEvents()
|
||||
} catch (error) {
|
||||
logWarn('[auto-ship-douyin/callback]', '回调投递轮次失败', { error })
|
||||
} finally {
|
||||
running = false
|
||||
if (!stopped) {
|
||||
timer = setTimeout(
|
||||
() => void runLoop(),
|
||||
envInt('AUTO_SHIP_DOUYIN_CALLBACK_INTERVAL_MS', DEFAULT_INTERVAL_MS, 250, 60_000),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function startAutoShipDouyinCallbackWorker() {
|
||||
if (timer || !stopped) return
|
||||
if (!getAutoShipDouyinConfig().enabled) {
|
||||
logInfo('[auto-ship-douyin/callback]', '接口未启用,回调 worker 保持待命')
|
||||
return
|
||||
}
|
||||
stopped = false
|
||||
logInfo('[auto-ship-douyin/callback]', '回调 worker 已启动')
|
||||
timer = setTimeout(() => void runLoop(), 0)
|
||||
timer.unref?.()
|
||||
}
|
||||
|
||||
export function stopAutoShipDouyinCallbackWorker() {
|
||||
stopped = true
|
||||
if (timer) {
|
||||
clearTimeout(timer)
|
||||
timer = null
|
||||
}
|
||||
}
|
||||
|
||||
function envInt(name: string, fallback: number, min: number, max: number) {
|
||||
const parsed = Number(process.env[name])
|
||||
if (!Number.isFinite(parsed)) return fallback
|
||||
return Math.max(min, Math.min(max, Math.trunc(parsed)))
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import { runtimeConfig } from '../../config/runtime.js'
|
||||
import { createHttpError } from '../../utils/http.js'
|
||||
import type { RuntimeConfig } from '../../types/runtime-config.js'
|
||||
|
||||
export const AUTO_SHIP_DOUYIN_PROVIDER = 'auto_ship_douyin'
|
||||
export const AUTO_SHIP_DOUYIN_PLATFORM = 'doudian'
|
||||
export const AUTO_SHIP_DOUYIN_SUCCESS_MESSAGE = '接口调用成功'
|
||||
export const AUTO_SHIP_DOUYIN_DEFAULT_FAIL_CODE = 1204
|
||||
export const AUTO_SHIP_DOUYIN_COST_EXCEED_FAIL_CODE = 1220
|
||||
|
||||
type AutoShipDouyinRuntimeConfig = RuntimeConfig['platforms']['autoShipDouyin']
|
||||
|
||||
export function getAutoShipDouyinConfig(overrides: Partial<AutoShipDouyinRuntimeConfig> = {}) {
|
||||
const config = {
|
||||
...(runtimeConfig.platforms?.autoShipDouyin || {}),
|
||||
...overrides,
|
||||
}
|
||||
|
||||
return {
|
||||
enabled: Boolean(config.enabled),
|
||||
secret: String(config.secret || '').trim(),
|
||||
version: String(config.version || '1.0').trim() || '1.0',
|
||||
shopId: String(config.shopId || AUTO_SHIP_DOUYIN_PROVIDER).trim() || AUTO_SHIP_DOUYIN_PROVIDER,
|
||||
shopName: String(config.shopName || '自动发货抖店').trim() || '自动发货抖店',
|
||||
timestampToleranceSeconds: Number(config.timestampToleranceSeconds || 600) || 600,
|
||||
callbackAllowedOrigins: Array.isArray(config.callbackAllowedOrigins)
|
||||
? config.callbackAllowedOrigins.map((item) => String(item || '').trim()).filter(Boolean)
|
||||
: [],
|
||||
callbackTimeoutMs: Number(config.callbackTimeoutMs || 5000) || 5000,
|
||||
callbackMaxAttempts: Number(config.callbackMaxAttempts || 12) || 12,
|
||||
}
|
||||
}
|
||||
|
||||
export function assertAutoShipDouyinConfig(overrides: Partial<AutoShipDouyinRuntimeConfig> = {}) {
|
||||
const config = getAutoShipDouyinConfig(overrides)
|
||||
|
||||
if (!config.enabled) {
|
||||
throw createHttpError('自动发货抖店接口未启用', {
|
||||
statusCode: 503,
|
||||
errorCode: 'auto_ship_douyin_disabled',
|
||||
})
|
||||
}
|
||||
|
||||
if (!config.secret) {
|
||||
throw createHttpError('自动发货抖店 secret 未配置', {
|
||||
statusCode: 500,
|
||||
errorCode: 'auto_ship_douyin_missing_secret',
|
||||
})
|
||||
}
|
||||
|
||||
if (config.secret.length !== 32) {
|
||||
throw createHttpError('自动发货抖店 secret 长度必须为 32 个字符', {
|
||||
statusCode: 500,
|
||||
errorCode: 'auto_ship_douyin_invalid_secret_length',
|
||||
})
|
||||
}
|
||||
|
||||
return config
|
||||
}
|
||||
|
||||
export function assertAutoShipDouyinCallbackUrl(
|
||||
callbackUrl: unknown,
|
||||
config = assertAutoShipDouyinConfig(),
|
||||
) {
|
||||
const raw = String(callbackUrl || '').trim()
|
||||
if (!raw) {
|
||||
throw createHttpError('缺少 callbackUrl', {
|
||||
statusCode: 400,
|
||||
errorCode: 'auto_ship_douyin_missing_callback_url',
|
||||
})
|
||||
}
|
||||
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(raw)
|
||||
} catch {
|
||||
throw createHttpError('callbackUrl 格式无效', {
|
||||
statusCode: 400,
|
||||
errorCode: 'auto_ship_douyin_invalid_callback_url',
|
||||
})
|
||||
}
|
||||
|
||||
if (url.protocol !== 'https:') {
|
||||
throw createHttpError('callbackUrl 必须使用 HTTPS', {
|
||||
statusCode: 400,
|
||||
errorCode: 'auto_ship_douyin_insecure_callback_url',
|
||||
})
|
||||
}
|
||||
|
||||
if (config.callbackAllowedOrigins.length === 0) {
|
||||
throw createHttpError('callbackUrl 域名白名单未配置', {
|
||||
statusCode: 500,
|
||||
errorCode: 'auto_ship_douyin_callback_allowlist_missing',
|
||||
})
|
||||
}
|
||||
|
||||
if (!config.callbackAllowedOrigins.includes(url.origin)) {
|
||||
throw createHttpError('callbackUrl 域名不在允许列表内', {
|
||||
statusCode: 400,
|
||||
errorCode: 'auto_ship_douyin_callback_origin_denied',
|
||||
})
|
||||
}
|
||||
|
||||
return url.toString()
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import { parseAmountToFen } from '../../utils/money.js'
|
||||
import { previewAdminCost } from '../cost-center/cost-resolution-service.js'
|
||||
import { resolveInternalSkuMapping } from '../fulfillment/internal-sku-mapping-service.js'
|
||||
import { loadInternalSkuChannelPlans } from '../fulfillment/internal-sku-channel-service.js'
|
||||
import { listOrderItemsByOrderId } from '../../repositories/order-item-repo.js'
|
||||
import { query } from '../../db/client.js'
|
||||
import { AUTO_SHIP_DOUYIN_PROVIDER } from './config.js'
|
||||
|
||||
export type AutoShipDouyinCostPreview = {
|
||||
productMapped: boolean
|
||||
channelConfigured: boolean
|
||||
internalSku: string
|
||||
channel: string
|
||||
totalCostFen: number | null
|
||||
maxAmountFen: number
|
||||
exceedsMaxAmount: boolean
|
||||
reason: string
|
||||
}
|
||||
|
||||
export function parseAutoShipDouyinMaxAmountFen(value: unknown) {
|
||||
const text = String(value ?? '').trim()
|
||||
if (!text) return null
|
||||
return parseAmountToFen(text)
|
||||
}
|
||||
|
||||
export async function previewAutoShipDouyinCreateCost(input: {
|
||||
productNo: string
|
||||
buyNum: number
|
||||
maxAmount?: string
|
||||
shopId?: string
|
||||
}): Promise<AutoShipDouyinCostPreview> {
|
||||
const productNo = String(input.productNo || '').trim()
|
||||
const shopId = String(input.shopId || AUTO_SHIP_DOUYIN_PROVIDER).trim()
|
||||
const maxAmountFen = parseAutoShipDouyinMaxAmountFen(input.maxAmount) ?? 0
|
||||
const mapping = await resolveInternalSkuMapping({
|
||||
provider: AUTO_SHIP_DOUYIN_PROVIDER,
|
||||
shopId,
|
||||
candidates: [{ matchType: 'sku_code', value: productNo }],
|
||||
})
|
||||
|
||||
if (!mapping) {
|
||||
return {
|
||||
productMapped: false,
|
||||
channelConfigured: false,
|
||||
internalSku: '',
|
||||
channel: '',
|
||||
totalCostFen: null,
|
||||
maxAmountFen,
|
||||
exceedsMaxAmount: false,
|
||||
reason: 'product_mapping_missing',
|
||||
}
|
||||
}
|
||||
|
||||
const plans = await loadInternalSkuChannelPlans([mapping.internalSku])
|
||||
const plan = plans.get(mapping.internalSku)
|
||||
const primary = plan?.primary || null
|
||||
if (!primary) {
|
||||
return {
|
||||
productMapped: true,
|
||||
channelConfigured: false,
|
||||
internalSku: mapping.internalSku,
|
||||
channel: '',
|
||||
totalCostFen: null,
|
||||
maxAmountFen,
|
||||
exceedsMaxAmount: false,
|
||||
reason: 'channel_route_missing',
|
||||
}
|
||||
}
|
||||
|
||||
const preview = await previewAdminCost({
|
||||
provider: AUTO_SHIP_DOUYIN_PROVIDER,
|
||||
shopId,
|
||||
skuCode: productNo,
|
||||
skuName: productNo,
|
||||
quantity: Math.max(1, Number(input.buyNum) || 1),
|
||||
channel: primary.channel,
|
||||
canonicalProductId: primary.canonical_product_id ?? undefined,
|
||||
revenueFen: maxAmountFen,
|
||||
})
|
||||
|
||||
if (preview.exceptions.length > 0) {
|
||||
return {
|
||||
productMapped: true,
|
||||
channelConfigured: true,
|
||||
internalSku: mapping.internalSku,
|
||||
channel: primary.channel,
|
||||
totalCostFen: null,
|
||||
maxAmountFen,
|
||||
exceedsMaxAmount: false,
|
||||
reason: preview.exceptions[0]?.reason || 'cost_missing',
|
||||
}
|
||||
}
|
||||
|
||||
const totalCostFen = Math.max(
|
||||
0,
|
||||
Number(preview.totalCostFen || 0) + Number(preview.manualCost?.costFen || 0),
|
||||
)
|
||||
return {
|
||||
productMapped: true,
|
||||
channelConfigured: true,
|
||||
internalSku: mapping.internalSku,
|
||||
channel: primary.channel,
|
||||
totalCostFen,
|
||||
maxAmountFen,
|
||||
exceedsMaxAmount: maxAmountFen > 0 && totalCostFen > maxAmountFen,
|
||||
reason: '',
|
||||
}
|
||||
}
|
||||
|
||||
export async function resolveAutoShipDouyinOrderCostFen(orderId: number | string) {
|
||||
const id = Number(orderId)
|
||||
if (!Number.isFinite(id) || id <= 0) return null
|
||||
|
||||
const snapshotResult = await query<{ total: string; count: number }>(
|
||||
`
|
||||
SELECT COALESCE(SUM(cs.total_amount_fen), 0)::text AS total,
|
||||
COUNT(*)::int AS count
|
||||
FROM cost_snapshots cs
|
||||
JOIN order_items oi ON oi.id = cs.subject_id
|
||||
WHERE oi.order_id = $1
|
||||
AND cs.subject_type = 'order_item'
|
||||
AND cs.superseded_at IS NULL
|
||||
AND cs.reversed_at IS NULL
|
||||
`,
|
||||
[id],
|
||||
)
|
||||
const snapshotCount = Number(snapshotResult.rows[0]?.count || 0)
|
||||
if (snapshotCount > 0) {
|
||||
return Number(snapshotResult.rows[0]?.total || 0)
|
||||
}
|
||||
|
||||
const items = await listOrderItemsByOrderId(id)
|
||||
if (items.length === 0) return null
|
||||
let total = 0
|
||||
for (const item of items) {
|
||||
const preview = await previewAdminCost({ orderItemId: Number(item.id) })
|
||||
if (preview.exceptions.length > 0) return null
|
||||
total += Number(preview.totalCostFen || 0) + Number(preview.manualCost?.costFen || 0)
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
export function shouldRejectAutoShipDouyinMaxAmount(input: {
|
||||
maxAmount?: string
|
||||
totalCostFen: number | null
|
||||
}) {
|
||||
const maxAmountFen = parseAutoShipDouyinMaxAmountFen(input.maxAmount)
|
||||
if (maxAmountFen === null) return false
|
||||
return input.totalCostFen !== null && input.totalCostFen > maxAmountFen
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import crypto from 'node:crypto'
|
||||
import type { JsonObject } from '../../types/json.js'
|
||||
import { createHttpError } from '../../utils/http.js'
|
||||
import { assertAutoShipDouyinConfig } from './config.js'
|
||||
import { normalizeAutoShipDouyinString } from './payload.js'
|
||||
|
||||
export function stringifyAutoShipDouyinSignValue(value: unknown) {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) return String(value)
|
||||
if (typeof value === 'boolean') return value ? 'true' : 'false'
|
||||
if (value == null) return ''
|
||||
return String(value)
|
||||
}
|
||||
|
||||
export function buildAutoShipDouyinSignSource(
|
||||
params: JsonObject = {},
|
||||
{ secret }: { secret: string } = assertAutoShipDouyinConfig(),
|
||||
) {
|
||||
const queryString = Object.entries(params)
|
||||
.filter(([key]) => key !== 'sign')
|
||||
.sort(([left], [right]) => (left === right ? 0 : left < right ? -1 : 1))
|
||||
.map(([key, value]) => `${key}=${stringifyAutoShipDouyinSignValue(value)}`)
|
||||
.join('&')
|
||||
|
||||
return `${secret}${queryString}${secret}`
|
||||
}
|
||||
|
||||
export function signAutoShipDouyinPayload(
|
||||
params: JsonObject = {},
|
||||
config = assertAutoShipDouyinConfig(),
|
||||
) {
|
||||
return crypto
|
||||
.createHash('md5')
|
||||
.update(buildAutoShipDouyinSignSource(params, config), 'utf8')
|
||||
.digest('hex')
|
||||
.toUpperCase()
|
||||
}
|
||||
|
||||
export function verifyAutoShipDouyinSignature(
|
||||
params: JsonObject = {},
|
||||
config = assertAutoShipDouyinConfig(),
|
||||
) {
|
||||
const expected = signAutoShipDouyinPayload(params, config)
|
||||
const actual = normalizeAutoShipDouyinString(params.sign).toUpperCase()
|
||||
if (expected.length !== actual.length) return false
|
||||
return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(actual))
|
||||
}
|
||||
|
||||
export function assertAutoShipDouyinSignature(
|
||||
params: JsonObject = {},
|
||||
config = assertAutoShipDouyinConfig(),
|
||||
) {
|
||||
if (!verifyAutoShipDouyinSignature(params, config)) {
|
||||
throw createHttpError('验签失败', {
|
||||
statusCode: 400,
|
||||
errorCode: 'auto_ship_douyin_invalid_signature',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 回调严格按参考文档参数表:cards 不参与签名。
|
||||
* failCode / failReason 按参考文档 MD5 示例保留在签名源串中。
|
||||
*/
|
||||
export function buildAutoShipDouyinCallbackSignSource(
|
||||
params: JsonObject = {},
|
||||
config = assertAutoShipDouyinConfig(),
|
||||
) {
|
||||
const signable: JsonObject = { ...params }
|
||||
delete signable.sign
|
||||
delete signable.cards
|
||||
return buildAutoShipDouyinSignSource(signable, config)
|
||||
}
|
||||
|
||||
export function signAutoShipDouyinCallbackPayload(
|
||||
params: JsonObject = {},
|
||||
config = assertAutoShipDouyinConfig(),
|
||||
) {
|
||||
return crypto
|
||||
.createHash('md5')
|
||||
.update(buildAutoShipDouyinCallbackSignSource(params, config), 'utf8')
|
||||
.digest('hex')
|
||||
.toUpperCase()
|
||||
}
|
||||
|
||||
export function encryptAutoShipDouyinCards(
|
||||
cards: unknown[] = [],
|
||||
secret = assertAutoShipDouyinConfig().secret,
|
||||
) {
|
||||
const normalizedSecret = normalizeAutoShipDouyinString(secret)
|
||||
if (normalizedSecret.length !== 32) {
|
||||
throw createHttpError('cards 加密密钥长度必须为 32 个字符', {
|
||||
statusCode: 500,
|
||||
errorCode: 'auto_ship_douyin_invalid_cards_secret_length',
|
||||
})
|
||||
}
|
||||
|
||||
const cipher = crypto.createCipheriv('aes-256-ecb', Buffer.from(normalizedSecret, 'utf8'), null)
|
||||
cipher.setAutoPadding(true)
|
||||
const plainText = JSON.stringify(Array.isArray(cards) ? cards : [])
|
||||
return `${cipher.update(plainText, 'utf8', 'base64')}${cipher.final('base64')}`
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
import { findLatestOrderByPlatformOrderId } from '../../repositories/order-repo.js'
|
||||
import { upsertOrderFromSource } from '../order/order-service.js'
|
||||
import { logIntegration } from '../../utils/logger.js'
|
||||
import {
|
||||
AUTO_SHIP_DOUYIN_COST_EXCEED_FAIL_CODE,
|
||||
AUTO_SHIP_DOUYIN_DEFAULT_FAIL_CODE,
|
||||
assertAutoShipDouyinCallbackUrl,
|
||||
assertAutoShipDouyinConfig,
|
||||
} from './config.js'
|
||||
import { assertAutoShipDouyinSignature } from './crypto.js'
|
||||
import {
|
||||
assertAutoShipDouyinCreatePayload,
|
||||
assertAutoShipDouyinTimestamp,
|
||||
normalizeAutoShipDouyinCreatePayload,
|
||||
} from './payload.js'
|
||||
import {
|
||||
buildAutoShipDouyinOutTradeNo,
|
||||
buildAutoShipDouyinSuccessResponse,
|
||||
formatAutoShipDouyinOrderCost,
|
||||
} from './response.js'
|
||||
import {
|
||||
buildAutoShipDouyinSourceEvent,
|
||||
markAutoShipDouyinOrderPendingConfig,
|
||||
upsertAutoShipDouyinPendingOrder,
|
||||
} from './order-service.js'
|
||||
import { ensureAutoShipDouyinCallbackWatch } from './callback-outbox-service.js'
|
||||
import { previewAutoShipDouyinCreateCost } from './cost.js'
|
||||
import type { JsonObject } from '../../types/json.js'
|
||||
import type { OrderRow } from '../../types/repository/rows.js'
|
||||
|
||||
export async function createAutoShipDouyinOrder(
|
||||
payload: JsonObject = {},
|
||||
{ requestId = '' }: { requestId?: string } = {},
|
||||
) {
|
||||
const config = assertAutoShipDouyinConfig()
|
||||
const normalized = normalizeAutoShipDouyinCreatePayload(payload)
|
||||
|
||||
assertAutoShipDouyinCreatePayload(normalized, config)
|
||||
assertAutoShipDouyinTimestamp(normalized.timestamp, config.timestampToleranceSeconds)
|
||||
assertAutoShipDouyinSignature(payload, config)
|
||||
const callbackUrl = assertAutoShipDouyinCallbackUrl(normalized.callbackUrl, config)
|
||||
|
||||
const existing = await findLatestOrderByPlatformOrderId({
|
||||
provider: 'auto_ship_douyin',
|
||||
platform: 'doudian',
|
||||
platformOrderId: normalized.orderNo,
|
||||
})
|
||||
if (existing) {
|
||||
assertSameAutoShipDouyinCreateRequest(existing, normalized)
|
||||
await ensureAutoShipDouyinCallbackWatch(existing, callbackUrl)
|
||||
return buildExistingAutoShipDouyinCreateResponse(existing)
|
||||
}
|
||||
|
||||
const costPreview = await previewAutoShipDouyinCreateCost({
|
||||
productNo: normalized.productNo,
|
||||
buyNum: normalized.buyNum,
|
||||
maxAmount: normalized.maxAmount,
|
||||
shopId: config.shopId,
|
||||
})
|
||||
const hasMaxAmount = Boolean(String(normalized.maxAmount || '').trim())
|
||||
const costUnavailable = costPreview.totalCostFen === null
|
||||
|
||||
if (hasMaxAmount && costUnavailable) {
|
||||
const pending = await upsertAutoShipDouyinPendingOrder(normalized, config, {
|
||||
status: 'pending_config',
|
||||
reason: costPreview.reason,
|
||||
})
|
||||
await ensureAutoShipDouyinCallbackWatch(pending.order, callbackUrl)
|
||||
logIntegration('[auto-ship-douyin/create]', '订单成本未配置,进入待补全', {
|
||||
requestId,
|
||||
orderNo: normalized.orderNo,
|
||||
productNo: normalized.productNo,
|
||||
reason: costPreview.reason,
|
||||
})
|
||||
return buildAutoShipDouyinSuccessResponse({
|
||||
orderNo: normalized.orderNo,
|
||||
outTradeNo: buildAutoShipDouyinOutTradeNo(pending.order),
|
||||
orderStatus: 10,
|
||||
failCode: 0,
|
||||
failReason: '',
|
||||
orderCost: formatAutoShipDouyinOrderCost(0),
|
||||
cards: '',
|
||||
})
|
||||
}
|
||||
|
||||
if (
|
||||
hasMaxAmount &&
|
||||
costPreview.totalCostFen !== null &&
|
||||
costPreview.totalCostFen > Number(costPreview.maxAmountFen)
|
||||
) {
|
||||
const rejected = await upsertAutoShipDouyinPendingOrder(normalized, config, {
|
||||
status: 'rejected_amount',
|
||||
reason: 'max_amount_exceeded',
|
||||
costPreflightFen: costPreview.totalCostFen,
|
||||
})
|
||||
logIntegration('[auto-ship-douyin/create]', '订单成本超过 maxAmount,已拒绝', {
|
||||
requestId,
|
||||
orderNo: normalized.orderNo,
|
||||
productNo: normalized.productNo,
|
||||
totalCostFen: costPreview.totalCostFen,
|
||||
maxAmountFen: costPreview.maxAmountFen,
|
||||
})
|
||||
return buildAutoShipDouyinSuccessResponse({
|
||||
orderNo: normalized.orderNo,
|
||||
outTradeNo: buildAutoShipDouyinOutTradeNo(rejected.order),
|
||||
orderStatus: 30,
|
||||
failCode: AUTO_SHIP_DOUYIN_COST_EXCEED_FAIL_CODE,
|
||||
failReason: '订单金额超出可接受范围',
|
||||
orderCost: formatAutoShipDouyinOrderCost(costPreview.totalCostFen),
|
||||
cards: '',
|
||||
})
|
||||
}
|
||||
|
||||
const sourceEvent = buildAutoShipDouyinSourceEvent(normalized, config, {
|
||||
costPreflightFen: costPreview.totalCostFen,
|
||||
})
|
||||
const result = await upsertOrderFromSource(sourceEvent, { sourceLabel: 'auto-ship-douyin' })
|
||||
if (!result.order) {
|
||||
throw new Error('订单写入失败')
|
||||
}
|
||||
|
||||
if (!Array.isArray(result.tasks) || result.tasks.length === 0) {
|
||||
const pendingOrder = await markAutoShipDouyinOrderPendingConfig(
|
||||
result.order,
|
||||
costPreview.reason || 'fulfillment_not_ready',
|
||||
)
|
||||
const order = pendingOrder || result.order
|
||||
await ensureAutoShipDouyinCallbackWatch(order, callbackUrl)
|
||||
logIntegration('[auto-ship-douyin/create]', '订单等待履约配置', {
|
||||
requestId,
|
||||
orderNo: normalized.orderNo,
|
||||
orderId: order.id,
|
||||
reason: costPreview.reason || 'fulfillment_not_ready',
|
||||
})
|
||||
return buildAutoShipDouyinSuccessResponse({
|
||||
orderNo: normalized.orderNo,
|
||||
outTradeNo: buildAutoShipDouyinOutTradeNo(order),
|
||||
orderStatus: 10,
|
||||
failCode: 0,
|
||||
failReason: '',
|
||||
orderCost: formatAutoShipDouyinOrderCost(costPreview.totalCostFen || 0),
|
||||
cards: '',
|
||||
})
|
||||
}
|
||||
|
||||
await ensureAutoShipDouyinCallbackWatch(result.order, callbackUrl)
|
||||
logIntegration('[auto-ship-douyin/create]', '异步卡密采购订单已受理', {
|
||||
requestId,
|
||||
orderNo: normalized.orderNo,
|
||||
orderId: result.order.id,
|
||||
taskCount: result.tasks.length,
|
||||
totalCostFen: costPreview.totalCostFen,
|
||||
})
|
||||
return buildAutoShipDouyinSuccessResponse({
|
||||
orderNo: normalized.orderNo,
|
||||
outTradeNo: buildAutoShipDouyinOutTradeNo(result.order),
|
||||
orderStatus: 10,
|
||||
failCode: 0,
|
||||
failReason: '',
|
||||
orderCost: formatAutoShipDouyinOrderCost(costPreview.totalCostFen || 0),
|
||||
cards: '',
|
||||
})
|
||||
}
|
||||
|
||||
function buildExistingAutoShipDouyinCreateResponse(order: OrderRow) {
|
||||
const status = String(order.order_status || '').trim()
|
||||
if (status === 'rejected_amount') {
|
||||
return buildAutoShipDouyinSuccessResponse({
|
||||
orderNo: order.platform_order_id,
|
||||
outTradeNo: buildAutoShipDouyinOutTradeNo(order),
|
||||
orderStatus: 30,
|
||||
failCode: AUTO_SHIP_DOUYIN_COST_EXCEED_FAIL_CODE,
|
||||
failReason: '订单金额超出可接受范围',
|
||||
orderCost: formatAutoShipDouyinOrderCost(0),
|
||||
cards: '',
|
||||
})
|
||||
}
|
||||
if (status === 'manual_failed') {
|
||||
return buildAutoShipDouyinSuccessResponse({
|
||||
orderNo: order.platform_order_id,
|
||||
outTradeNo: buildAutoShipDouyinOutTradeNo(order),
|
||||
orderStatus: 30,
|
||||
failCode: AUTO_SHIP_DOUYIN_DEFAULT_FAIL_CODE,
|
||||
failReason: '订单无法履约',
|
||||
orderCost: formatAutoShipDouyinOrderCost(0),
|
||||
cards: '',
|
||||
})
|
||||
}
|
||||
return buildAutoShipDouyinSuccessResponse({
|
||||
orderNo: order.platform_order_id,
|
||||
outTradeNo: buildAutoShipDouyinOutTradeNo(order),
|
||||
orderStatus: 10,
|
||||
failCode: 0,
|
||||
failReason: '',
|
||||
orderCost: formatAutoShipDouyinOrderCost(0),
|
||||
cards: '',
|
||||
})
|
||||
}
|
||||
|
||||
function assertSameAutoShipDouyinCreateRequest(
|
||||
order: OrderRow,
|
||||
normalized: ReturnType<typeof normalizeAutoShipDouyinCreatePayload>,
|
||||
) {
|
||||
let body: JsonObject = {}
|
||||
try {
|
||||
const raw =
|
||||
typeof order.raw_payload_json === 'string'
|
||||
? JSON.parse(order.raw_payload_json)
|
||||
: order.raw_payload_json
|
||||
body = raw && typeof raw === 'object' && !Array.isArray(raw) ? (raw.body as JsonObject) : {}
|
||||
} catch {
|
||||
body = {}
|
||||
}
|
||||
const existingProductNo = String(body?.productNo || '').trim()
|
||||
const existingBuyNum = Number(body?.buyNum || 0)
|
||||
if (
|
||||
(existingProductNo && existingProductNo !== normalized.productNo) ||
|
||||
(existingBuyNum > 0 && existingBuyNum !== normalized.buyNum)
|
||||
) {
|
||||
const error = new Error('同一 orderNo 的商品或数量与首次提交不一致')
|
||||
;(error as Error & { statusCode?: number }).statusCode = 409
|
||||
throw error
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
import { findLatestOrderByPlatformOrderId } from '../../repositories/order-repo.js'
|
||||
import { logIntegration } from '../../utils/logger.js'
|
||||
import { asJsonObject, type JsonObject } from '../../types/json.js'
|
||||
import {
|
||||
AUTO_SHIP_DOUYIN_DEFAULT_FAIL_CODE,
|
||||
AUTO_SHIP_DOUYIN_PLATFORM,
|
||||
AUTO_SHIP_DOUYIN_PROVIDER,
|
||||
assertAutoShipDouyinConfig,
|
||||
} from './config.js'
|
||||
import { assertAutoShipDouyinSignature, encryptAutoShipDouyinCards } from './crypto.js'
|
||||
import {
|
||||
assertAutoShipDouyinQueryPayload,
|
||||
assertAutoShipDouyinTimestamp,
|
||||
normalizeAutoShipDouyinQueryPayload,
|
||||
} from './payload.js'
|
||||
import {
|
||||
buildAutoShipDouyinOutTradeNo,
|
||||
buildAutoShipDouyinSuccessResponse,
|
||||
formatAutoShipDouyinOrderCost,
|
||||
} from './response.js'
|
||||
import { resolveAutoShipDouyinOrderSnapshot } from './order-state-service.js'
|
||||
|
||||
export async function queryAutoShipDouyinOrder(
|
||||
payload: JsonObject = {},
|
||||
{ requestId = '' }: { requestId?: string } = {},
|
||||
) {
|
||||
const config = assertAutoShipDouyinConfig()
|
||||
const normalized = normalizeAutoShipDouyinQueryPayload(payload)
|
||||
|
||||
assertAutoShipDouyinQueryPayload(normalized, config)
|
||||
assertAutoShipDouyinTimestamp(normalized.timestamp, config.timestampToleranceSeconds)
|
||||
assertAutoShipDouyinSignature(payload, config)
|
||||
|
||||
const order = await findLatestOrderByPlatformOrderId({
|
||||
provider: AUTO_SHIP_DOUYIN_PROVIDER,
|
||||
platform: AUTO_SHIP_DOUYIN_PLATFORM,
|
||||
platformOrderId: normalized.orderNo,
|
||||
})
|
||||
|
||||
if (!order) {
|
||||
return buildAutoShipDouyinSuccessResponse({
|
||||
orderNo: normalized.orderNo,
|
||||
outTradeNo: '',
|
||||
orderStatus: 30,
|
||||
failCode: AUTO_SHIP_DOUYIN_DEFAULT_FAIL_CODE,
|
||||
failReason: '订单不存在',
|
||||
})
|
||||
}
|
||||
|
||||
const snapshot = await resolveAutoShipDouyinOrderSnapshot(order)
|
||||
const cards =
|
||||
snapshot.orderStatus === 20 ? encryptAutoShipDouyinCards(snapshot.cardItems, config.secret) : ''
|
||||
|
||||
logIntegration('[auto-ship-douyin/query]', '订单查询已处理', {
|
||||
requestId,
|
||||
orderNo: normalized.orderNo,
|
||||
orderId: order.id,
|
||||
orderStatus: snapshot.orderStatus,
|
||||
taskCount: snapshot.tasks.length,
|
||||
readyTaskCount: snapshot.readyTaskIds.length,
|
||||
})
|
||||
|
||||
return buildAutoShipDouyinSuccessResponse({
|
||||
orderNo: normalized.orderNo,
|
||||
outTradeNo: buildAutoShipDouyinOutTradeNo(order),
|
||||
orderStatus: snapshot.orderStatus,
|
||||
failCode: snapshot.failCode,
|
||||
failReason: snapshot.failReason,
|
||||
orderCost: formatAutoShipDouyinOrderCost(snapshot.orderCostFen || 0),
|
||||
cards,
|
||||
})
|
||||
}
|
||||
|
||||
export function parseAutoShipDouyinOrderPayload(value: unknown): JsonObject {
|
||||
if (!value) return {}
|
||||
if (typeof value === 'object' && !Array.isArray(value)) return value as JsonObject
|
||||
try {
|
||||
return asJsonObject(JSON.parse(String(value)))
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
import {
|
||||
createOrder,
|
||||
findLatestOrderByPlatformOrderId,
|
||||
getOrderById,
|
||||
updateOrder,
|
||||
} from '../../repositories/order-repo.js'
|
||||
import { listOrderItemsByOrderId, replaceOrderItems } from '../../repositories/order-item-repo.js'
|
||||
import { listTasksByOrderId } from '../../repositories/task-repo.js'
|
||||
import { upsertOrderFromSource } from '../order/order-service.js'
|
||||
import { asJsonObject, type JsonObject } from '../../types/json.js'
|
||||
import { parseAmountToFen } from '../../utils/money.js'
|
||||
import { nowIso } from '../../utils/time.js'
|
||||
import { createHttpError } from '../../utils/http.js'
|
||||
import { query } from '../../db/client.js'
|
||||
import { AUTO_SHIP_DOUYIN_PLATFORM, AUTO_SHIP_DOUYIN_PROVIDER } from './config.js'
|
||||
import { buildAutoShipDouyinOutTradeNo } from './response.js'
|
||||
import { resetAutoShipDouyinCallbackWatch } from './callback-outbox-service.js'
|
||||
import { previewAutoShipDouyinCreateCost } from './cost.js'
|
||||
import type { OrderItemRow, OrderRow } from '../../types/repository/rows.js'
|
||||
|
||||
export const AUTO_SHIP_DOUYIN_PENDING_CONFIG_STATUS = 'pending_config'
|
||||
export const AUTO_SHIP_DOUYIN_MANUAL_FAILED_STATUS = 'manual_failed'
|
||||
export const AUTO_SHIP_DOUYIN_REJECTED_AMOUNT_STATUS = 'rejected_amount'
|
||||
|
||||
export function buildAutoShipDouyinSourceEvent(
|
||||
payload: JsonObject = {},
|
||||
config: JsonObject = {},
|
||||
options: { totalAmountFen?: number; costPreflightFen?: number | null } = {},
|
||||
) {
|
||||
const productNo = String(payload.productNo || '').trim()
|
||||
const maxAmountFen = parseAmountToFen(payload.maxAmount)
|
||||
const totalAmountFen =
|
||||
options.totalAmountFen !== undefined
|
||||
? Math.max(0, Number(options.totalAmountFen) || 0)
|
||||
: maxAmountFen > 0
|
||||
? maxAmountFen
|
||||
: 0
|
||||
|
||||
return {
|
||||
provider: AUTO_SHIP_DOUYIN_PROVIDER,
|
||||
platform: AUTO_SHIP_DOUYIN_PLATFORM,
|
||||
shopId: String(config.shopId || AUTO_SHIP_DOUYIN_PROVIDER).trim() || AUTO_SHIP_DOUYIN_PROVIDER,
|
||||
shopName: String(config.shopName || '自动发货抖店').trim() || '自动发货抖店',
|
||||
platformOrderId: String(payload.orderNo || '').trim(),
|
||||
orderStatus: 'paid',
|
||||
payStatus: 'paid',
|
||||
buyerId: '',
|
||||
buyerName: '',
|
||||
receiverContact: '',
|
||||
totalAmount: totalAmountFen,
|
||||
currency: 'CNY',
|
||||
paidAt: nowIso(),
|
||||
rawPayload: {
|
||||
source: AUTO_SHIP_DOUYIN_PROVIDER,
|
||||
body: payload,
|
||||
costPreflightFen: options.costPreflightFen ?? null,
|
||||
receivedAt: nowIso(),
|
||||
},
|
||||
items: [
|
||||
{
|
||||
itemId: productNo,
|
||||
externalItemId: productNo,
|
||||
externalSkuCode: productNo,
|
||||
externalSkuName: productNo,
|
||||
skuCode: productNo,
|
||||
skuName: productNo,
|
||||
quantity: Math.max(1, Number(payload.buyNum) || 1),
|
||||
spec: {
|
||||
source: AUTO_SHIP_DOUYIN_PROVIDER,
|
||||
orderNo: String(payload.orderNo || '').trim(),
|
||||
productNo,
|
||||
maxAmount: String(payload.maxAmount || '').trim(),
|
||||
callbackUrl: String(payload.callbackUrl || '').trim(),
|
||||
},
|
||||
snapshot: {
|
||||
source: AUTO_SHIP_DOUYIN_PROVIDER,
|
||||
orderNo: String(payload.orderNo || '').trim(),
|
||||
productNo,
|
||||
externalItemId: productNo,
|
||||
externalSkuCode: productNo,
|
||||
externalSkuName: productNo,
|
||||
maxAmount: String(payload.maxAmount || '').trim(),
|
||||
maxAmountFen,
|
||||
callbackUrl: String(payload.callbackUrl || '').trim(),
|
||||
costPreflightFen: options.costPreflightFen ?? null,
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
export async function markAutoShipDouyinOrderPendingConfig(order: OrderRow, reason = '') {
|
||||
return updateOrder(order.id, {
|
||||
provider: order.provider,
|
||||
platform: order.platform,
|
||||
shopId: order.shop_id,
|
||||
shopName: order.shop_name,
|
||||
platformOrderId: order.platform_order_id,
|
||||
orderStatus: AUTO_SHIP_DOUYIN_PENDING_CONFIG_STATUS,
|
||||
payStatus: order.pay_status,
|
||||
buyerId: order.buyer_id,
|
||||
buyerName: order.buyer_name,
|
||||
receiverContact: order.receiver_contact,
|
||||
totalAmount: Number(order.total_amount) || 0,
|
||||
currency: order.currency,
|
||||
paidAt: order.paid_at,
|
||||
updatedAt: nowIso(),
|
||||
})
|
||||
}
|
||||
|
||||
export async function upsertAutoShipDouyinPendingOrder(
|
||||
payload: JsonObject = {},
|
||||
config: JsonObject = {},
|
||||
options: {
|
||||
status?: string
|
||||
reason?: string
|
||||
totalAmountFen?: number
|
||||
costPreflightFen?: number | null
|
||||
} = {},
|
||||
) {
|
||||
const event = buildAutoShipDouyinSourceEvent(payload, config, options)
|
||||
const now = nowIso()
|
||||
const existing = await findLatestOrderByPlatformOrderId({
|
||||
provider: event.provider,
|
||||
platform: event.platform,
|
||||
platformOrderId: event.platformOrderId,
|
||||
})
|
||||
const orderPayload = {
|
||||
provider: event.provider,
|
||||
platform: event.platform,
|
||||
shopId: existing?.shop_id || event.shopId,
|
||||
shopName: existing?.shop_name || event.shopName,
|
||||
platformOrderId: event.platformOrderId,
|
||||
orderStatus: String(options.status || AUTO_SHIP_DOUYIN_PENDING_CONFIG_STATUS).trim(),
|
||||
payStatus: 'paid' as const,
|
||||
buyerId: '',
|
||||
buyerName: '',
|
||||
receiverContact: '',
|
||||
totalAmount: Number(event.totalAmount) || 0,
|
||||
currency: 'CNY',
|
||||
paidAt: existing?.paid_at || now,
|
||||
}
|
||||
const order = existing
|
||||
? await updateOrder(existing.id, { ...orderPayload, updatedAt: now })
|
||||
: await createOrder({ ...orderPayload, createdAt: now, updatedAt: now })
|
||||
if (!order) {
|
||||
throw createHttpError('自动发货抖店待处理订单保存失败', {
|
||||
statusCode: 500,
|
||||
errorCode: 'auto_ship_douyin_pending_order_save_failed',
|
||||
})
|
||||
}
|
||||
|
||||
const [item] = event.items
|
||||
if (!item) {
|
||||
throw createHttpError('自动发货抖店订单商品明细为空', { statusCode: 400 })
|
||||
}
|
||||
const orderItems = await replaceOrderItems(order.id, [
|
||||
{
|
||||
skuCode: item.skuCode,
|
||||
skuName: item.skuName,
|
||||
quantity: item.quantity,
|
||||
specJson: JSON.stringify(item.spec || {}),
|
||||
itemSnapshotJson: JSON.stringify(item.snapshot || {}),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
])
|
||||
|
||||
return { order, orderItems, tasks: [] }
|
||||
}
|
||||
|
||||
export async function retryAutoShipDouyinOrder(orderId: number | string) {
|
||||
const order = await getRequiredAutoShipDouyinOrder(orderId)
|
||||
const items = await listOrderItemsByOrderId(order.id)
|
||||
const body = parseJsonObject(parseJsonObject(order.raw_payload_json).body)
|
||||
const costPreview = await previewAutoShipDouyinCreateCost({
|
||||
productNo: String(body.productNo || '').trim(),
|
||||
buyNum: Math.max(1, Number(body.buyNum) || 1),
|
||||
maxAmount: String(body.maxAmount || '').trim(),
|
||||
shopId: order.shop_id || AUTO_SHIP_DOUYIN_PROVIDER,
|
||||
})
|
||||
const hasMaxAmount = Boolean(String(body.maxAmount || '').trim())
|
||||
if (hasMaxAmount && costPreview.totalCostFen === null) {
|
||||
throw createHttpError('订单成本仍未配置,不能重试履约', {
|
||||
statusCode: 409,
|
||||
errorCode: 'auto_ship_douyin_cost_still_unconfigured',
|
||||
})
|
||||
}
|
||||
if (
|
||||
hasMaxAmount &&
|
||||
costPreview.totalCostFen !== null &&
|
||||
costPreview.totalCostFen > Number(costPreview.maxAmountFen)
|
||||
) {
|
||||
await updateOrder(order.id, {
|
||||
provider: order.provider,
|
||||
platform: order.platform,
|
||||
shopId: order.shop_id,
|
||||
shopName: order.shop_name,
|
||||
platformOrderId: order.platform_order_id,
|
||||
orderStatus: AUTO_SHIP_DOUYIN_REJECTED_AMOUNT_STATUS,
|
||||
payStatus: order.pay_status,
|
||||
buyerId: order.buyer_id,
|
||||
buyerName: order.buyer_name,
|
||||
receiverContact: order.receiver_contact,
|
||||
totalAmount: Number(order.total_amount) || 0,
|
||||
currency: order.currency,
|
||||
paidAt: order.paid_at,
|
||||
updatedAt: nowIso(),
|
||||
})
|
||||
await resetAutoShipDouyinCallbackWatch(order.id)
|
||||
throw createHttpError('订单金额超出可接受范围', {
|
||||
statusCode: 409,
|
||||
errorCode: 'auto_ship_douyin_cost_exceeds_max_amount',
|
||||
})
|
||||
}
|
||||
const event = buildAutoShipDouyinSourceEvent(
|
||||
body,
|
||||
{
|
||||
shopId: order.shop_id,
|
||||
shopName: order.shop_name,
|
||||
},
|
||||
{ costPreflightFen: costPreview.totalCostFen },
|
||||
)
|
||||
const result = await upsertOrderFromSource(event, { sourceLabel: 'auto-ship-douyin-admin-retry' })
|
||||
if (!Array.isArray(result.tasks) || result.tasks.length === 0) {
|
||||
throw createHttpError('当前订单仍未命中履约配置,请先补齐商品和渠道映射', {
|
||||
statusCode: 409,
|
||||
errorCode: 'auto_ship_douyin_order_still_unconfigured',
|
||||
})
|
||||
}
|
||||
await updateOrder(order.id, {
|
||||
provider: order.provider,
|
||||
platform: order.platform,
|
||||
shopId: order.shop_id,
|
||||
shopName: order.shop_name,
|
||||
platformOrderId: order.platform_order_id,
|
||||
orderStatus: 'paid',
|
||||
payStatus: order.pay_status,
|
||||
buyerId: order.buyer_id,
|
||||
buyerName: order.buyer_name,
|
||||
receiverContact: order.receiver_contact,
|
||||
totalAmount: Number(order.total_amount) || 0,
|
||||
currency: order.currency,
|
||||
paidAt: order.paid_at,
|
||||
updatedAt: nowIso(),
|
||||
})
|
||||
await resetAutoShipDouyinCallbackWatch(order.id)
|
||||
return { order: result.order, orderItems: result.orderItems, tasks: result.tasks }
|
||||
}
|
||||
|
||||
export async function failAutoShipDouyinOrder(orderId: number | string, _reason = '') {
|
||||
const order = await getRequiredAutoShipDouyinOrder(orderId)
|
||||
const updated = await updateOrder(order.id, {
|
||||
provider: order.provider,
|
||||
platform: order.platform,
|
||||
shopId: order.shop_id,
|
||||
shopName: order.shop_name,
|
||||
platformOrderId: order.platform_order_id,
|
||||
orderStatus: AUTO_SHIP_DOUYIN_MANUAL_FAILED_STATUS,
|
||||
payStatus: order.pay_status,
|
||||
buyerId: order.buyer_id,
|
||||
buyerName: order.buyer_name,
|
||||
receiverContact: order.receiver_contact,
|
||||
totalAmount: Number(order.total_amount) || 0,
|
||||
currency: order.currency,
|
||||
paidAt: order.paid_at,
|
||||
updatedAt: nowIso(),
|
||||
})
|
||||
return {
|
||||
order: updated,
|
||||
orderItems: await listOrderItemsByOrderId(order.id),
|
||||
tasks: await listTasksByOrderId(order.id),
|
||||
}
|
||||
}
|
||||
|
||||
export async function listAutoShipDouyinOrders(
|
||||
input: {
|
||||
page?: number
|
||||
pageSize?: number
|
||||
status?: string
|
||||
} = {},
|
||||
) {
|
||||
const page = Math.max(1, Math.trunc(Number(input.page) || 1))
|
||||
const pageSize = Math.min(100, Math.max(1, Math.trunc(Number(input.pageSize) || 20)))
|
||||
const params: unknown[] = [AUTO_SHIP_DOUYIN_PROVIDER, AUTO_SHIP_DOUYIN_PLATFORM]
|
||||
const clauses = ['provider = $1', 'platform = $2']
|
||||
const status = String(input.status || 'pending_config').trim()
|
||||
if (status && status !== 'all') {
|
||||
params.push(status)
|
||||
clauses.push(`order_status = $${params.length}`)
|
||||
}
|
||||
const where = clauses.join(' AND ')
|
||||
const count = await query<{ total: number }>(
|
||||
`SELECT COUNT(*)::int AS total FROM orders WHERE ${where}`,
|
||||
params,
|
||||
)
|
||||
params.push(pageSize, (page - 1) * pageSize)
|
||||
const rows = await query(
|
||||
`
|
||||
SELECT id, platform_order_id, shop_id, shop_name, order_status, pay_status,
|
||||
total_amount, created_at, updated_at
|
||||
FROM orders
|
||||
WHERE ${where}
|
||||
ORDER BY id DESC
|
||||
LIMIT $${params.length - 1} OFFSET $${params.length}
|
||||
`,
|
||||
params,
|
||||
)
|
||||
return {
|
||||
page,
|
||||
pageSize,
|
||||
total: Number(count.rows[0]?.total || 0),
|
||||
items: rows.rows.map((row) => ({
|
||||
orderId: Number(row.id),
|
||||
orderNo: String(row.platform_order_id || '').trim(),
|
||||
outTradeNo: buildAutoShipDouyinOutTradeNo(row),
|
||||
shopId: String(row.shop_id || '').trim(),
|
||||
shopName: String(row.shop_name || '').trim(),
|
||||
orderStatus: String(row.order_status || '').trim(),
|
||||
payStatus: String(row.pay_status || '').trim(),
|
||||
totalAmount: Number(row.total_amount || 0),
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
export async function getRequiredAutoShipDouyinOrder(orderId: number | string) {
|
||||
const order = await getOrderById(Number(orderId))
|
||||
if (
|
||||
!order ||
|
||||
order.provider !== AUTO_SHIP_DOUYIN_PROVIDER ||
|
||||
order.platform !== AUTO_SHIP_DOUYIN_PLATFORM
|
||||
) {
|
||||
throw createHttpError('自动发货抖店订单不存在', {
|
||||
statusCode: 404,
|
||||
errorCode: 'auto_ship_douyin_order_not_found',
|
||||
})
|
||||
}
|
||||
return order
|
||||
}
|
||||
|
||||
function parseJsonObject(value: unknown): JsonObject {
|
||||
if (!value) return {}
|
||||
if (typeof value === 'object' && !Array.isArray(value)) return value as JsonObject
|
||||
try {
|
||||
return asJsonObject(JSON.parse(String(value || '{}')))
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { OrderRow, TaskRow } from '../../types/repository/rows.js'
|
||||
import { listTasksByOrderId } from '../../repositories/task-repo.js'
|
||||
import { resolveTaskDeliveryLink } from '../fulfillment/delivery-link-service.js'
|
||||
import type { JsonObject } from '../../types/json.js'
|
||||
import { resolveAutoShipDouyinOrderCostFen } from './cost.js'
|
||||
import { buildAutoShipDouyinCardItem, resolveAutoShipDouyinQueryState } from './response.js'
|
||||
|
||||
export type AutoShipDouyinOrderSnapshot = {
|
||||
orderStatus: number
|
||||
failCode: number
|
||||
failReason: string
|
||||
orderCostFen: number | null
|
||||
cardItems: JsonObject[]
|
||||
tasks: TaskRow[]
|
||||
readyTaskIds: number[]
|
||||
}
|
||||
|
||||
export async function resolveAutoShipDouyinOrderSnapshot(
|
||||
order: Pick<OrderRow, 'id' | 'order_status'>,
|
||||
): Promise<AutoShipDouyinOrderSnapshot> {
|
||||
const tasks = await listTasksByOrderId(order.id)
|
||||
const cardItems: JsonObject[] = []
|
||||
const readyTaskIds: number[] = []
|
||||
|
||||
for (const task of tasks) {
|
||||
const deliveryLink = await resolveTaskDeliveryLink(task)
|
||||
const claimUrl = String(deliveryLink?.claimUrl || '').trim()
|
||||
if (!claimUrl) continue
|
||||
readyTaskIds.push(Number(task.id))
|
||||
cardItems.push(
|
||||
buildAutoShipDouyinCardItem({
|
||||
claimUrl,
|
||||
expireTime: deliveryLink?.expireTime || '',
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
const queryState = resolveAutoShipDouyinQueryState({
|
||||
orderStatus: order.order_status,
|
||||
tasks: tasks as unknown as JsonObject[],
|
||||
readyTaskIds,
|
||||
})
|
||||
const orderCostFen =
|
||||
queryState.orderStatus === 20 ? await resolveAutoShipDouyinOrderCostFen(order.id) : null
|
||||
|
||||
return {
|
||||
...queryState,
|
||||
orderCostFen,
|
||||
cardItems,
|
||||
tasks,
|
||||
readyTaskIds,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { createHttpError } from '../../utils/http.js'
|
||||
import type { JsonObject } from '../../types/json.js'
|
||||
import { assertAutoShipDouyinConfig } from './config.js'
|
||||
|
||||
export function normalizeAutoShipDouyinString(value: unknown) {
|
||||
return String(value ?? '').trim()
|
||||
}
|
||||
|
||||
export function normalizeAutoShipDouyinCreatePayload(payload: JsonObject = {}) {
|
||||
return {
|
||||
orderNo: normalizeAutoShipDouyinString(payload.orderNo),
|
||||
productNo: normalizeAutoShipDouyinString(payload.productNo),
|
||||
buyNum: normalizeAutoShipDouyinBuyNum(payload.buyNum),
|
||||
maxAmount: normalizeAutoShipDouyinOptionalAmount(payload.maxAmount),
|
||||
callbackUrl: normalizeAutoShipDouyinString(payload.callbackUrl),
|
||||
timestamp: normalizeAutoShipDouyinTimestamp(payload.timestamp),
|
||||
version: normalizeAutoShipDouyinString(payload.version),
|
||||
sign: normalizeAutoShipDouyinString(payload.sign).toUpperCase(),
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizeAutoShipDouyinQueryPayload(payload: JsonObject = {}) {
|
||||
return {
|
||||
orderNo: normalizeAutoShipDouyinString(payload.orderNo),
|
||||
timestamp: normalizeAutoShipDouyinTimestamp(payload.timestamp),
|
||||
version: normalizeAutoShipDouyinString(payload.version),
|
||||
sign: normalizeAutoShipDouyinString(payload.sign).toUpperCase(),
|
||||
}
|
||||
}
|
||||
|
||||
export function assertAutoShipDouyinCreatePayload(
|
||||
payload: JsonObject,
|
||||
config = assertAutoShipDouyinConfig(),
|
||||
) {
|
||||
if (!payload.orderNo) throw createHttpError('缺少 orderNo', { statusCode: 400 })
|
||||
if (!payload.productNo) throw createHttpError('缺少 productNo', { statusCode: 400 })
|
||||
if (!Number.isInteger(payload.buyNum) || Number(payload.buyNum) <= 0) {
|
||||
throw createHttpError('buyNum 必须是大于 0 的整数', { statusCode: 400 })
|
||||
}
|
||||
if (!payload.callbackUrl) throw createHttpError('缺少 callbackUrl', { statusCode: 400 })
|
||||
assertAutoShipDouyinCommonPayload(payload, config)
|
||||
}
|
||||
|
||||
export function assertAutoShipDouyinQueryPayload(
|
||||
payload: JsonObject,
|
||||
config = assertAutoShipDouyinConfig(),
|
||||
) {
|
||||
if (!payload.orderNo) throw createHttpError('缺少 orderNo', { statusCode: 400 })
|
||||
assertAutoShipDouyinCommonPayload(payload, config)
|
||||
}
|
||||
|
||||
export function assertAutoShipDouyinTimestamp(
|
||||
timestamp: unknown,
|
||||
toleranceSeconds = assertAutoShipDouyinConfig().timestampToleranceSeconds,
|
||||
) {
|
||||
const nowSeconds = Math.floor(Date.now() / 1000)
|
||||
if (Math.abs(nowSeconds - Number(timestamp)) > Math.max(1, Number(toleranceSeconds) || 600)) {
|
||||
throw createHttpError('timestamp 已过期', { statusCode: 400 })
|
||||
}
|
||||
}
|
||||
|
||||
function assertAutoShipDouyinCommonPayload(payload: JsonObject, config: JsonObject) {
|
||||
if (!payload.timestamp) throw createHttpError('缺少 timestamp', { statusCode: 400 })
|
||||
if (!payload.version) throw createHttpError('缺少 version', { statusCode: 400 })
|
||||
if (payload.version !== config.version) {
|
||||
throw createHttpError(`version 不匹配,当前仅支持 ${config.version}`, { statusCode: 400 })
|
||||
}
|
||||
if (!payload.sign) throw createHttpError('缺少 sign', { statusCode: 400 })
|
||||
}
|
||||
|
||||
function normalizeAutoShipDouyinBuyNum(value: unknown) {
|
||||
const parsed = Number(value)
|
||||
return Number.isInteger(parsed) ? parsed : 0
|
||||
}
|
||||
|
||||
function normalizeAutoShipDouyinOptionalAmount(value: unknown) {
|
||||
const normalized = normalizeAutoShipDouyinString(value)
|
||||
if (!normalized) return ''
|
||||
if (!/^\d+(?:\.\d+)?$/.test(normalized)) {
|
||||
throw createHttpError('maxAmount 格式无效', { statusCode: 400 })
|
||||
}
|
||||
return normalized
|
||||
}
|
||||
|
||||
function normalizeAutoShipDouyinTimestamp(value: unknown) {
|
||||
const normalized = normalizeAutoShipDouyinString(value)
|
||||
return /^\d{10}$/.test(normalized) ? Number(normalized) : 0
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
import test from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import {
|
||||
buildAutoShipDouyinCallbackSignSource,
|
||||
buildAutoShipDouyinSignSource,
|
||||
encryptAutoShipDouyinCards,
|
||||
signAutoShipDouyinCallbackPayload,
|
||||
signAutoShipDouyinPayload,
|
||||
} from './crypto.js'
|
||||
import {
|
||||
buildAutoShipDouyinCardItem,
|
||||
formatAutoShipDouyinExpireTime,
|
||||
formatAutoShipDouyinOrderCost,
|
||||
resolveAutoShipDouyinQueryState,
|
||||
} from './response.js'
|
||||
import { shouldRejectAutoShipDouyinMaxAmount } from './cost.js'
|
||||
import { assertAutoShipDouyinCallbackUrl } from './config.js'
|
||||
|
||||
const secret = '12345678901234567890123456789012'
|
||||
const config = {
|
||||
enabled: true,
|
||||
secret,
|
||||
version: '1.0',
|
||||
shopId: 'auto_ship_douyin',
|
||||
shopName: '自动发货抖店',
|
||||
timestampToleranceSeconds: 600,
|
||||
callbackAllowedOrigins: ['https://callback.example.com'],
|
||||
callbackTimeoutMs: 5000,
|
||||
}
|
||||
|
||||
test('auto-ship-douyin incoming signature uses only actual request body fields', () => {
|
||||
const payload = {
|
||||
orderNo: 'ORDER-1',
|
||||
productNo: 'PLATFORM-SKU-1',
|
||||
buyNum: 1,
|
||||
maxAmount: '',
|
||||
callbackUrl: 'https://callback.example.com/hook',
|
||||
timestamp: 1790000000,
|
||||
version: '1.0',
|
||||
}
|
||||
assert.equal(
|
||||
buildAutoShipDouyinSignSource(payload, config),
|
||||
`${secret}buyNum=1&callbackUrl=https://callback.example.com/hook&maxAmount=&orderNo=ORDER-1&productNo=PLATFORM-SKU-1×tamp=1790000000&version=1.0${secret}`,
|
||||
)
|
||||
const sign = signAutoShipDouyinPayload(payload, config)
|
||||
assert.equal(sign.length, 32)
|
||||
})
|
||||
|
||||
test('auto-ship-douyin callback signature excludes cards per reference parameter table', () => {
|
||||
const payload = {
|
||||
orderNo: 'ORDER-1',
|
||||
outTradeNo: 'OS0000000001',
|
||||
orderStatus: 20,
|
||||
failCode: 0,
|
||||
failReason: '',
|
||||
orderCost: '100',
|
||||
cards: 'ENCRYPTED-CARDS-MUST-NOT-BE-SIGNED',
|
||||
timestamp: 1790000000,
|
||||
}
|
||||
const source = buildAutoShipDouyinCallbackSignSource(payload, config)
|
||||
assert.equal(source.includes('cards='), false)
|
||||
assert.equal(
|
||||
source,
|
||||
`${secret}failCode=0&failReason=&orderCost=100&orderNo=ORDER-1&orderStatus=20&outTradeNo=OS0000000001×tamp=1790000000${secret}`,
|
||||
)
|
||||
assert.equal(signAutoShipDouyinCallbackPayload(payload, config).length, 32)
|
||||
})
|
||||
|
||||
test('auto-ship-douyin callback URL must be HTTPS and allowlisted', () => {
|
||||
assert.equal(
|
||||
assertAutoShipDouyinCallbackUrl('https://callback.example.com/hook', config),
|
||||
'https://callback.example.com/hook',
|
||||
)
|
||||
assert.throws(
|
||||
() => assertAutoShipDouyinCallbackUrl('http://callback.example.com/hook', config),
|
||||
/HTTPS/,
|
||||
)
|
||||
assert.throws(
|
||||
() => assertAutoShipDouyinCallbackUrl('https://evil.example.com/hook', config),
|
||||
/允许列表/,
|
||||
)
|
||||
})
|
||||
test('auto-ship-douyin cards encryption matches AES-256-ECB stable sample', () => {
|
||||
const cards = [
|
||||
{
|
||||
cardNo: 'https://example.com/h5/ORDER-1',
|
||||
cardPwd: '',
|
||||
expireTime: '',
|
||||
jumpLink: 'https://example.com/h5/ORDER-1',
|
||||
},
|
||||
]
|
||||
const encrypted = encryptAutoShipDouyinCards(cards, secret)
|
||||
assert.equal(typeof encrypted, 'string')
|
||||
assert.ok(encrypted.length > 20)
|
||||
})
|
||||
|
||||
test('auto-ship-douyin query state returns 20 only when every task has a delivery link', () => {
|
||||
assert.deepEqual(
|
||||
resolveAutoShipDouyinQueryState({
|
||||
orderStatus: 'paid',
|
||||
tasks: [
|
||||
{ id: 1, task_status: 'link_generated' },
|
||||
{ id: 2, task_status: 'link_generated' },
|
||||
],
|
||||
readyTaskIds: [1, 2],
|
||||
}),
|
||||
{ orderStatus: 20, failCode: 0, failReason: '' },
|
||||
)
|
||||
assert.deepEqual(
|
||||
resolveAutoShipDouyinQueryState({
|
||||
orderStatus: 'paid',
|
||||
tasks: [
|
||||
{ id: 1, task_status: 'link_generated' },
|
||||
{ id: 2, task_status: 'link_generated' },
|
||||
],
|
||||
readyTaskIds: [1],
|
||||
}),
|
||||
{ orderStatus: 10, failCode: 0, failReason: '' },
|
||||
)
|
||||
})
|
||||
|
||||
test('auto-ship-douyin manual review is recoverable and reports processing', () => {
|
||||
assert.deepEqual(
|
||||
resolveAutoShipDouyinQueryState({
|
||||
orderStatus: 'paid',
|
||||
tasks: [{ id: 1, task_status: 'manual_review', last_error: '待人工处理' }],
|
||||
readyTaskIds: [],
|
||||
}),
|
||||
{ orderStatus: 10, failCode: 0, failReason: '' },
|
||||
)
|
||||
})
|
||||
|
||||
test('auto-ship-douyin maxAmount compares whole-order cost and treats empty as no cap', () => {
|
||||
assert.equal(shouldRejectAutoShipDouyinMaxAmount({ maxAmount: '', totalCostFen: 99999 }), false)
|
||||
assert.equal(
|
||||
shouldRejectAutoShipDouyinMaxAmount({ maxAmount: '100.00', totalCostFen: 9999 }),
|
||||
false,
|
||||
)
|
||||
assert.equal(
|
||||
shouldRejectAutoShipDouyinMaxAmount({ maxAmount: '100.00', totalCostFen: 10001 }),
|
||||
true,
|
||||
)
|
||||
assert.equal(shouldRejectAutoShipDouyinMaxAmount({ maxAmount: '0', totalCostFen: 1 }), true)
|
||||
})
|
||||
|
||||
test('auto-ship-douyin card and money formatting follow the reference contract', () => {
|
||||
assert.equal(formatAutoShipDouyinOrderCost(10000), '100.0000')
|
||||
assert.equal(formatAutoShipDouyinOrderCost(10000, { trim: true }), '100')
|
||||
assert.equal(formatAutoShipDouyinExpireTime('2026-05-05 12:00:00'), '2026-05-05 12:00:00')
|
||||
assert.deepEqual(
|
||||
buildAutoShipDouyinCardItem({
|
||||
claimUrl: 'https://example.com/h5/ORDER-1',
|
||||
expireTime: '2026-05-05 12:00:00',
|
||||
}),
|
||||
{
|
||||
cardNo: 'https://example.com/h5/ORDER-1',
|
||||
cardPwd: '',
|
||||
expireTime: '2026-05-05 12:00:00',
|
||||
jumpLink: 'https://example.com/h5/ORDER-1',
|
||||
},
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,119 @@
|
||||
import type { JsonObject } from '../../types/json.js'
|
||||
import { isInactiveCarrierTaskStatus } from '../fulfillment/channel-types.js'
|
||||
import { AUTO_SHIP_DOUYIN_DEFAULT_FAIL_CODE, AUTO_SHIP_DOUYIN_SUCCESS_MESSAGE } from './config.js'
|
||||
import { normalizeAutoShipDouyinString } from './payload.js'
|
||||
|
||||
const AUTO_SHIP_DOUYIN_EXPIRE_FORMATTER = new Intl.DateTimeFormat('zh-CN', {
|
||||
timeZone: 'Asia/Shanghai',
|
||||
year: 'numeric',
|
||||
month: '2-digit',
|
||||
day: '2-digit',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
second: '2-digit',
|
||||
hourCycle: 'h23',
|
||||
})
|
||||
export function buildAutoShipDouyinSuccessResponse(
|
||||
data: unknown,
|
||||
message = AUTO_SHIP_DOUYIN_SUCCESS_MESSAGE,
|
||||
) {
|
||||
return { code: 200, message, data }
|
||||
}
|
||||
|
||||
export function buildAutoShipDouyinErrorResponse(message: unknown, code = 500) {
|
||||
return {
|
||||
code,
|
||||
message: normalizeAutoShipDouyinString(message) || '系统错误',
|
||||
data: null,
|
||||
}
|
||||
}
|
||||
|
||||
export function buildAutoShipDouyinOutTradeNo(order: JsonObject) {
|
||||
const orderId = Number(order?.id || 0)
|
||||
return orderId > 0 ? `OS${String(orderId).padStart(10, '0')}` : ''
|
||||
}
|
||||
|
||||
export function formatAutoShipDouyinOrderCost(valueFen: unknown, { trim = false } = {}) {
|
||||
const fen = Number(valueFen)
|
||||
if (!Number.isFinite(fen)) return trim ? '0' : '0.0000'
|
||||
const yuan = Math.max(0, Math.trunc(fen)) / 100
|
||||
if (trim) return String(Number(yuan.toFixed(4)))
|
||||
return yuan.toFixed(4)
|
||||
}
|
||||
|
||||
export function buildAutoShipDouyinCardItem({
|
||||
claimUrl = '',
|
||||
expireTime = '',
|
||||
}: { claimUrl?: unknown; expireTime?: unknown } = {}) {
|
||||
const normalizedClaimUrl = normalizeAutoShipDouyinString(claimUrl)
|
||||
return {
|
||||
cardNo: normalizedClaimUrl,
|
||||
cardPwd: '',
|
||||
expireTime: formatAutoShipDouyinExpireTime(expireTime),
|
||||
jumpLink: normalizedClaimUrl,
|
||||
}
|
||||
}
|
||||
|
||||
export function formatAutoShipDouyinExpireTime(value: unknown = '') {
|
||||
const normalized = normalizeAutoShipDouyinString(value)
|
||||
if (!normalized) return ''
|
||||
if (/^\d{10}$/.test(normalized) || /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(normalized)) {
|
||||
return normalized
|
||||
}
|
||||
const date = value instanceof Date ? value : new Date(normalized)
|
||||
if (Number.isNaN(date.getTime())) return normalized
|
||||
const byType: Record<string, string> = {}
|
||||
for (const part of AUTO_SHIP_DOUYIN_EXPIRE_FORMATTER.formatToParts(date)) {
|
||||
if (part.type !== 'literal') byType[part.type] = part.value
|
||||
}
|
||||
return `${byType.year}-${byType.month}-${byType.day} ${byType.hour}:${byType.minute}:${byType.second}`
|
||||
}
|
||||
export function resolveAutoShipDouyinQueryState({
|
||||
orderStatus = '',
|
||||
tasks = [],
|
||||
readyTaskIds = [],
|
||||
}: {
|
||||
orderStatus?: string
|
||||
tasks?: JsonObject[]
|
||||
readyTaskIds?: unknown[]
|
||||
} = {}) {
|
||||
const normalizedStatus = normalizeAutoShipDouyinString(orderStatus)
|
||||
const normalizedTasks = Array.isArray(tasks) ? tasks : []
|
||||
const readySet = new Set((Array.isArray(readyTaskIds) ? readyTaskIds : []).map(Number))
|
||||
|
||||
if (normalizedStatus === 'manual_failed' || normalizedStatus === 'rejected_amount') {
|
||||
return {
|
||||
orderStatus: 30,
|
||||
failCode: normalizedStatus === 'rejected_amount' ? 1220 : AUTO_SHIP_DOUYIN_DEFAULT_FAIL_CODE,
|
||||
failReason:
|
||||
normalizedStatus === 'rejected_amount' ? '订单金额超出可接受范围' : '订单无法履约',
|
||||
}
|
||||
}
|
||||
|
||||
if (normalizedTasks.length === 0) {
|
||||
return { orderStatus: 10, failCode: 0, failReason: '' }
|
||||
}
|
||||
|
||||
const terminalTask = normalizedTasks.find((task) => {
|
||||
const status = normalizeAutoShipDouyinString(task?.task_status)
|
||||
if (readySet.has(Number(task?.id || 0))) return false
|
||||
if (!isInactiveCarrierTaskStatus(status)) return false
|
||||
return !['manual_review', 'retry_pending'].includes(status)
|
||||
})
|
||||
if (terminalTask) {
|
||||
return {
|
||||
orderStatus: 30,
|
||||
failCode: AUTO_SHIP_DOUYIN_DEFAULT_FAIL_CODE,
|
||||
failReason:
|
||||
normalizeAutoShipDouyinString(terminalTask.last_error) ||
|
||||
normalizeAutoShipDouyinString(terminalTask.result_message) ||
|
||||
'订单无法履约',
|
||||
}
|
||||
}
|
||||
|
||||
if (readySet.size < normalizedTasks.length) {
|
||||
return { orderStatus: 10, failCode: 0, failReason: '' }
|
||||
}
|
||||
|
||||
return { orderStatus: 20, failCode: 0, failReason: '' }
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { runDatabaseMigrations } from '../db/migrate.js'
|
||||
import { startIntegrationOutboxWorker } from '../services/integration/outbox-worker.js'
|
||||
import { startAutoShipDouyinCallbackWorker } from '../services/open-auto-ship-douyin/callback-outbox-service.js'
|
||||
import { ensureAdminUsersBootstrapped } from '../services/admin/admin-auth-service.js'
|
||||
import { ensureFulfillmentCatalogBootstrapped } from '../services/bootstrap/fulfillment-bootstrap-service.js'
|
||||
import { migrateJsonConfigFilesToDatabase } from '../services/config/json-config-migration-service.js'
|
||||
@@ -50,6 +51,7 @@ export async function bootstrapCoreServices(
|
||||
startScheduledJobs()
|
||||
startKuaishouIndustrySendCallbackRetryWorker()
|
||||
startIntegrationOutboxWorker()
|
||||
startAutoShipDouyinCallbackWorker()
|
||||
startDouyuFulfillmentReconciler()
|
||||
startSemiAutoTaskReconciler()
|
||||
startMemoryReporter()
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { Server } from 'node:http'
|
||||
|
||||
import { stopKuaishouIndustrySendCallbackRetryWorker } from '../services/platforms/kuaishou-industry/send-code-service.js'
|
||||
import { stopIntegrationOutboxWorker } from '../services/integration/outbox-worker.js'
|
||||
import { stopAutoShipDouyinCallbackWorker } from '../services/open-auto-ship-douyin/callback-outbox-service.js'
|
||||
import { stopDouyuFulfillmentReconciler } from '../services/douyu-fulfillment/fulfillment-reconciler.js'
|
||||
import { stopSemiAutoTaskReconciler } from '../services/semi-auto/semi-auto-task-reconciler.js'
|
||||
import { stopScheduledJobs } from '../services/scheduler/scheduler-service.js'
|
||||
@@ -32,6 +33,7 @@ export function createShutdownController(
|
||||
stopScheduledJobs()
|
||||
stopKuaishouIndustrySendCallbackRetryWorker()
|
||||
stopIntegrationOutboxWorker()
|
||||
stopAutoShipDouyinCallbackWorker()
|
||||
stopDouyuFulfillmentReconciler()
|
||||
stopSemiAutoTaskReconciler()
|
||||
|
||||
|
||||
@@ -94,6 +94,17 @@ export type RuntimeConfig = {
|
||||
timestampToleranceSeconds: number
|
||||
cardsEncoding: string
|
||||
}
|
||||
autoShipDouyin: {
|
||||
enabled: boolean
|
||||
secret: string
|
||||
version: string
|
||||
shopId: string
|
||||
shopName: string
|
||||
timestampToleranceSeconds: number
|
||||
callbackAllowedOrigins: string[]
|
||||
callbackTimeoutMs: number
|
||||
callbackMaxAttempts: number
|
||||
}
|
||||
kuaishouIndustry: {
|
||||
appKey: string
|
||||
appSecret: string
|
||||
|
||||
@@ -276,6 +276,7 @@ export default function AdminSalesProfitPage() {
|
||||
{ value: '91kaquan', label: '91卡券' },
|
||||
{ value: 'pdd', label: '拼多多' },
|
||||
{ value: 'douyin_mashida', label: '抖音码速达' },
|
||||
{ value: 'auto_ship_douyin', label: '自动发货抖店' },
|
||||
]}
|
||||
/>
|
||||
</Form.Item>
|
||||
|
||||
@@ -160,6 +160,7 @@ export const PROVIDER_LABELS: Record<string, string> = {
|
||||
'91kaquan': '91 卡券(快手)',
|
||||
pdd: '拼多多',
|
||||
douyin_mashida: '抖音码速达',
|
||||
auto_ship_douyin: '自动发货抖店',
|
||||
}
|
||||
|
||||
export const MAPPING_MATCH_TYPE_OPTIONS: Array<{
|
||||
|
||||
@@ -10,6 +10,7 @@ export const adminOrderPlatformSegmentedOptions = [
|
||||
{ label: '全部平台', value: '' },
|
||||
{ label: '快手 / 91卡券', value: 'kuaishou' },
|
||||
{ label: '抖音码速达', value: 'douyin_mashida' },
|
||||
{ label: '自动发货抖店', value: 'auto_ship_douyin' },
|
||||
{ label: '拼多多', value: 'pdd' },
|
||||
{ label: '本地模拟', value: 'mock' },
|
||||
]
|
||||
@@ -18,6 +19,7 @@ export const adminOrderProviderOptions = [
|
||||
{ label: '全部', value: '' },
|
||||
{ label: '快手 / 91卡券', value: 'kuaishou' },
|
||||
{ label: '抖音码速达', value: 'douyin_mashida' },
|
||||
{ label: '自动发货抖店', value: 'auto_ship_douyin' },
|
||||
{ label: '拼多多', value: 'pdd' },
|
||||
{ label: '本地模拟', value: 'mock' },
|
||||
]
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
| [设备认证-dcauth协议](设备认证-dcauth协议.md) | 设备认证协议 |
|
||||
| [affiliate-dash-发货平台](affiliate-dash-发货平台/) | affiliate-dash 对接资料 |
|
||||
| [91卡券](91卡券/) | 91 卡券接口与签名资料 |
|
||||
| [自动发货抖店](auto-ship-douyin/) | 平台商品编码、异步回调与查询兜底接口资料 |
|
||||
| [抖音-码速达](抖音-码速达/) | 抖音码速达接口、消息与接入资料 |
|
||||
| [行业电子凭证](行业电子凭证/) | 快手行业电子凭证协议 |
|
||||
| [发货平台-2](发货平台-2/) | 历史发货平台协议 |
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
# 自动发货抖店接口说明
|
||||
|
||||
## 1. 适用范围
|
||||
|
||||
本接口用于平台服务端向本系统采购卡密类商品。
|
||||
|
||||
- 平台负责售卖和自动发货;
|
||||
- 本系统负责建单、履约、生成领取链接;
|
||||
- 最终交付物是领取链接,不是直充账号或短信验证码;
|
||||
- 平台查询或回调取得链接后,自动把链接作为卡密展示给买家。
|
||||
|
||||
## 2. 接口方向
|
||||
|
||||
```text
|
||||
新平台 -> POST /api/v1/open/auto-ship-douyin/orders/create
|
||||
新平台 -> POST /api/v1/open/auto-ship-douyin/orders/query
|
||||
本系统 -> POST <平台 callbackUrl>
|
||||
```
|
||||
|
||||
## 3. 来源与商品
|
||||
|
||||
- `provider = auto_ship_douyin`
|
||||
- `platform = doudian`
|
||||
- `productNo` 使用平台自己的稳定商品编号;
|
||||
- 平台商品编号必须在我方完成两层精确映射:
|
||||
- `internal_sku_mappings`:决定内部 SKU 和履约路由;
|
||||
- `channel_product_mappings`:决定标准商品和成本。
|
||||
- 未配置商品不丢单,进入待补全队列并返回处理中;
|
||||
- 禁止按商品名称、标题或编码前缀猜测内部 SKU。
|
||||
|
||||
## 4. 卡密形态
|
||||
|
||||
`cards` 解密后为领取链接数组:
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"cardNo": "https://<供货域名>/h5/<订单号>",
|
||||
"cardPwd": "",
|
||||
"expireTime": "",
|
||||
"jumpLink": "https://<供货域名>/h5/<订单号>"
|
||||
}
|
||||
]
|
||||
```
|
||||
|
||||
`buyNum > 1` 时,每个履约单元对应一张 card,当前均返回同一个订单领取链接,领取页按履约单元顺序推进。
|
||||
|
||||
## 5. 状态
|
||||
|
||||
- `10`:已受理,待配置、待履约或待补链接;
|
||||
- `20`:全部履约单元已具备可交付领取链接;
|
||||
- `30`:无法履约、订单不存在或金额超限。
|
||||
|
||||
`20` 表示链接可交付,不表示上游最终兑换完成。
|
||||
@@ -0,0 +1,64 @@
|
||||
# 签名规则
|
||||
|
||||
## 1. 请求签名
|
||||
|
||||
适用的请求:
|
||||
|
||||
- 异步卡密下单;
|
||||
- 查询订单。
|
||||
|
||||
规则:
|
||||
|
||||
1. 商户密钥为 32 位字符串;
|
||||
2. 仅请求 JSON body 中实际传入的字段参与签名;
|
||||
3. 除 `sign` 外,按字段名 ASCII 升序排序;
|
||||
4. 拼接为 `key=value&key=value`,不做 URL 编码;
|
||||
5. 已传入的空字符串参与签名;
|
||||
6. 未传入的可选字段不参与;
|
||||
7. 签名源串前后分别拼接商户密钥;
|
||||
8. 对源串计算 MD5,输出 32 位大写。
|
||||
|
||||
示例:
|
||||
|
||||
```text
|
||||
buyNum=1&callbackUrl=https://callback.example.com/hook&maxAmount=100.0000&orderNo=202611240001&productNo=PLATFORM-SKU-001×tamp=1790000000&version=1.0
|
||||
```
|
||||
|
||||
```text
|
||||
<32位商户密钥>buyNum=1&callbackUrl=https://callback.example.com/hook&maxAmount=100.0000&orderNo=202611240001&productNo=PLATFORM-SKU-001×tamp=1790000000&version=1.0<32位商户密钥>
|
||||
```
|
||||
|
||||
`sign = MD5(签名源串).toUpperCase()`
|
||||
|
||||
`timestamp` 为 10 位秒级 Unix 时间戳,允许误差 600 秒。
|
||||
|
||||
## 2. 回调签名
|
||||
|
||||
回调严格按参考文档参数表执行:**`cards` 不参与签名**。
|
||||
|
||||
参与回调签名的字段:
|
||||
|
||||
```text
|
||||
failCode
|
||||
failReason
|
||||
orderCost
|
||||
orderNo
|
||||
orderStatus
|
||||
outTradeNo
|
||||
timestamp
|
||||
```
|
||||
|
||||
签名源串:
|
||||
|
||||
```text
|
||||
<32位商户密钥>failCode=0&failReason=&orderCost=100&orderNo=202611240001&orderStatus=20&outTradeNo=OS0000012345×tamp=1790000000<32位商户密钥>
|
||||
```
|
||||
|
||||
规则同样为 MD5 后转 32 位大写。
|
||||
|
||||
## 3. 时间与重放
|
||||
|
||||
- 请求时间戳必须在允许窗口内;
|
||||
- 下单接口按 `orderNo` 幂等;
|
||||
- 查询接口无副作用;
|
||||
- 同一 `orderNo` 不允许更换商品或数量后重复提交。
|
||||
@@ -0,0 +1,93 @@
|
||||
# 异步卡密下单
|
||||
|
||||
## 1. 请求
|
||||
|
||||
```text
|
||||
POST https://<供货域名>/api/v1/open/auto-ship-douyin/orders/create
|
||||
Content-Type: application/json;charset=utf-8
|
||||
```
|
||||
|
||||
## 2. 请求参数
|
||||
|
||||
| 参数名 | 必填 | 类型 | 说明 |
|
||||
| ------------- | ---- | ------ | ---------------------------------------------------- |
|
||||
| `orderNo` | 是 | string | 平台订单号,唯一,作为幂等键 |
|
||||
| `productNo` | 是 | string | 平台自己的稳定商品编号 |
|
||||
| `buyNum` | 是 | int | 购买数量,必须大于 0 |
|
||||
| `maxAmount` | 否 | string | 整单最高可接受金额,人民币元,不是单价;为空时不校验 |
|
||||
| `callbackUrl` | 是 | string | 平台异步回调地址,必须为 HTTPS 且域名在白名单内 |
|
||||
| `timestamp` | 是 | long | 10 位秒级时间戳 |
|
||||
| `version` | 是 | string | 固定 `1.0` |
|
||||
| `sign` | 是 | string | MD5 大写签名 |
|
||||
|
||||
## 3. 请求示例
|
||||
|
||||
```json
|
||||
{
|
||||
"orderNo": "202611240001",
|
||||
"productNo": "PLATFORM-SKU-001",
|
||||
"buyNum": 1,
|
||||
"maxAmount": "100.0000",
|
||||
"callbackUrl": "https://callback.example.com/hook",
|
||||
"timestamp": 1790000000,
|
||||
"version": "1.0",
|
||||
"sign": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
|
||||
}
|
||||
```
|
||||
|
||||
## 4. maxAmount 校验
|
||||
|
||||
- 比较对象是本单**整单实际履约成本**;
|
||||
- 使用 `buyNum` 计算整单总成本,不按单价比较;
|
||||
- 成本大于 `maxAmount` 时:
|
||||
- 不创建履约任务;
|
||||
- 不向上游下单;
|
||||
- 返回 `orderStatus = 30`、`failCode = 1220`;
|
||||
- `maxAmount` 为空时不校验金额;
|
||||
- 成本配置缺失时不猜测,订单进入待补全并返回 `orderStatus = 10`。
|
||||
|
||||
## 5. 成功受理响应
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "接口调用成功",
|
||||
"data": {
|
||||
"orderNo": "202611240001",
|
||||
"outTradeNo": "OS0000012345",
|
||||
"orderStatus": 10,
|
||||
"failCode": 0,
|
||||
"failReason": "",
|
||||
"orderCost": "98.0000",
|
||||
"cards": ""
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
下单接口不返回最终卡密,受理成功固定返回 `10`。
|
||||
|
||||
`orderCost` 是本单实际履约成本,不是 `maxAmount`,也不是单价。查询接口按 4 位小数返回;回调通知按参考文档去掉末尾无效零。
|
||||
|
||||
## 6. 金额超限响应
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "接口调用成功",
|
||||
"data": {
|
||||
"orderNo": "202611240001",
|
||||
"outTradeNo": "OS0000012345",
|
||||
"orderStatus": 30,
|
||||
"failCode": 1220,
|
||||
"failReason": "订单金额超出可接受范围",
|
||||
"orderCost": "101.0000",
|
||||
"cards": ""
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 7. 幂等
|
||||
|
||||
- 同一 `orderNo` 且商品、数量一致:返回已有订单状态;
|
||||
- 同一 `orderNo` 但商品或数量变化:返回协议错误 `code = 409`;
|
||||
- 平台超时后必须使用原 `orderNo` 重试。
|
||||
@@ -0,0 +1,80 @@
|
||||
# 查询订单
|
||||
|
||||
## 1. 请求
|
||||
|
||||
```text
|
||||
POST https://<供货域名>/api/v1/open/auto-ship-douyin/orders/query
|
||||
Content-Type: application/json;charset=utf-8
|
||||
```
|
||||
|
||||
| 参数名 | 必填 | 类型 | 说明 |
|
||||
| ----------- | ---- | ------ | ------------------ |
|
||||
| `orderNo` | 是 | string | 下单时的平台订单号 |
|
||||
| `timestamp` | 是 | long | 10 位秒级时间戳 |
|
||||
| `version` | 是 | string | 固定 `1.0` |
|
||||
| `sign` | 是 | string | MD5 大写签名 |
|
||||
|
||||
```json
|
||||
{
|
||||
"orderNo": "202611240001",
|
||||
"timestamp": 1790000060,
|
||||
"version": "1.0",
|
||||
"sign": "YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY"
|
||||
}
|
||||
```
|
||||
|
||||
## 2. 处理中
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "接口调用成功",
|
||||
"data": {
|
||||
"orderNo": "202611240001",
|
||||
"outTradeNo": "OS0000012345",
|
||||
"orderStatus": 10,
|
||||
"failCode": 0,
|
||||
"failReason": "",
|
||||
"orderCost": "0.0000",
|
||||
"cards": ""
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 3. 成功
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "接口调用成功",
|
||||
"data": {
|
||||
"orderNo": "202611240001",
|
||||
"outTradeNo": "OS0000012345",
|
||||
"orderStatus": 20,
|
||||
"failCode": 0,
|
||||
"failReason": "",
|
||||
"orderCost": "98.0000",
|
||||
"cards": "AES加密后的Base64字符串"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 4. 失败
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "接口调用成功",
|
||||
"data": {
|
||||
"orderNo": "202611240001",
|
||||
"outTradeNo": "OS0000012345",
|
||||
"orderStatus": 30,
|
||||
"failCode": 1204,
|
||||
"failReason": "订单无法履约",
|
||||
"orderCost": "0.0000",
|
||||
"cards": ""
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
查询接口始终保留,作为异步回调失败后的补偿查询。
|
||||
@@ -0,0 +1,82 @@
|
||||
# 回调通知
|
||||
|
||||
## 1. 方向
|
||||
|
||||
```text
|
||||
本系统 -> 平台下单时传入的 callbackUrl
|
||||
```
|
||||
|
||||
只回调终态:
|
||||
|
||||
- `orderStatus = 20`:领取链接已可交付;
|
||||
- `orderStatus = 30`:无法履约。
|
||||
|
||||
不回调 `10`。
|
||||
|
||||
## 2. 请求示例
|
||||
|
||||
```json
|
||||
{
|
||||
"orderNo": "202611240001",
|
||||
"outTradeNo": "OS0000012345",
|
||||
"orderStatus": 20,
|
||||
"failCode": 0,
|
||||
"failReason": "",
|
||||
"orderCost": "98",
|
||||
"cards": "AES加密后的Base64字符串",
|
||||
"timestamp": 1790000000,
|
||||
"sign": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
|
||||
}
|
||||
```
|
||||
|
||||
## 3. 签名
|
||||
|
||||
按参考文档参数表,`cards` 不参与签名。
|
||||
|
||||
签名源串:
|
||||
|
||||
```text
|
||||
<32位商户密钥>failCode=0&failReason=&orderCost=98&orderNo=202611240001&orderStatus=20&outTradeNo=OS0000012345×tamp=1790000000<32位商户密钥>
|
||||
```
|
||||
|
||||
`sign = MD5(签名源串).toUpperCase()`
|
||||
|
||||
## 4. 响应
|
||||
|
||||
平台必须返回:
|
||||
|
||||
```json
|
||||
{
|
||||
"code": 200,
|
||||
"message": "请求成功"
|
||||
}
|
||||
```
|
||||
|
||||
HTTP 2xx 且 `code = 200` 视为成功;其余进入重试。
|
||||
|
||||
## 5. 重试
|
||||
|
||||
建议最大 12 次,退避:
|
||||
|
||||
```text
|
||||
5s / 15s / 1m / 5m / 15m / 30m / 1h
|
||||
```
|
||||
|
||||
达到上限后任务标记 `dead`,后台告警并可人工重发。
|
||||
|
||||
## 6. 幂等
|
||||
|
||||
请求头携带:
|
||||
|
||||
```text
|
||||
X-Event-Id: <UUID>
|
||||
```
|
||||
|
||||
平台应按 `X-Event-Id` 去重;没有该头时至少按 `orderNo + orderStatus` 去重。
|
||||
|
||||
## 7. 安全
|
||||
|
||||
- `callbackUrl` 必须为 HTTPS;
|
||||
- 只允许白名单域名;
|
||||
- 回调日志不得记录完整卡密明文;
|
||||
- 商户密钥不得出现在日志中。
|
||||
@@ -0,0 +1,78 @@
|
||||
# 联调与配置
|
||||
|
||||
## 1. 后端配置
|
||||
|
||||
建议环境变量:
|
||||
|
||||
```text
|
||||
AUTO_SHIP_DOUYIN_ENABLED=false
|
||||
AUTO_SHIP_DOUYIN_SECRET=<32位密钥>
|
||||
AUTO_SHIP_DOUYIN_VERSION=1.0
|
||||
AUTO_SHIP_DOUYIN_SHOP_ID=auto_ship_douyin
|
||||
AUTO_SHIP_DOUYIN_SHOP_NAME=自动发货抖店
|
||||
AUTO_SHIP_DOUYIN_TIMESTAMP_TOLERANCE_SECONDS=600
|
||||
AUTO_SHIP_DOUYIN_CALLBACK_ALLOWED_ORIGINS=https://callback.example.com
|
||||
AUTO_SHIP_DOUYIN_CALLBACK_TIMEOUT_MS=5000
|
||||
AUTO_SHIP_DOUYIN_CALLBACK_MAX_ATTEMPTS=12
|
||||
```
|
||||
|
||||
默认关闭,未配置白名单时拒绝下单回调地址。
|
||||
|
||||
## 2. 商品映射
|
||||
|
||||
每个平台商品需要完成:
|
||||
|
||||
1. `internal_sku_mappings`
|
||||
- provider = `auto_ship_douyin`
|
||||
- shop_id = 平台店铺标识
|
||||
- match_type = `sku_code`
|
||||
- match_value = 平台 `productNo`
|
||||
2. `channel_product_mappings`
|
||||
- provider = `auto_ship_douyin`
|
||||
- platform_sku_code = 平台 `productNo`
|
||||
3. SKU 路由与成本版本配置完成。
|
||||
|
||||
缺任一层都进入待补全队列。
|
||||
|
||||
## 3. 后台接口
|
||||
|
||||
```text
|
||||
GET /api/v1/admin/platform-config/auto-ship-douyin/orders
|
||||
POST /api/v1/admin/platform-config/auto-ship-douyin/orders/:id/retry
|
||||
POST /api/v1/admin/platform-config/auto-ship-douyin/orders/:id/fail
|
||||
GET /api/v1/admin/platform-config/auto-ship-douyin/callbacks
|
||||
POST /api/v1/admin/platform-config/auto-ship-douyin/callbacks/:id/retry
|
||||
```
|
||||
|
||||
## 4. 隔离库全链路脚本
|
||||
|
||||
已提供可重复执行的 Mock 全链路脚本:
|
||||
|
||||
```text
|
||||
AUTO_SHIP_DOUYIN_E2E_DATABASE_URL=postgres://.../order_site_auto_ship_e2e_test \
|
||||
npm run e2e:auto-ship-douyin
|
||||
```
|
||||
|
||||
数据库名必须包含 `_ctest / _itest / _test`,脚本会:
|
||||
|
||||
- 复用现有内部 SKU;
|
||||
- 补齐测试商品、路由、成本映射和平台商品映射;
|
||||
- Mock affiliate-dash 钱包与建单;
|
||||
- Mock 平台回调接收端;
|
||||
- 验证下单、履约、查询 20、卡密解密、回调签名、超限 1220 和未配置待补全。
|
||||
|
||||
## 5. 联调清单
|
||||
|
||||
- 正确签名;
|
||||
- 错误签名;
|
||||
- 空 `maxAmount`;
|
||||
- 成本小于、等于、大于 `maxAmount`;
|
||||
- 未配置商品;
|
||||
- 重复下单;
|
||||
- 同单号不同商品;
|
||||
- 单数量和多数量;
|
||||
- 回调 20;
|
||||
- 回调 30;
|
||||
- 回调超时重试;
|
||||
- 平台返回非 `code=200`;
|
||||
- 查询兜底。
|
||||
@@ -3,14 +3,14 @@ type: 权威架构与实施计划
|
||||
description: 订单、内部 SKU、履约路由、履约执行、商品、成本与财务的唯一权威口径及重构计划。
|
||||
tags: [订单, 内部SKU, 履约, 商品, 成本, 财务, 迁移]
|
||||
status: authoritative
|
||||
version: 2.37
|
||||
updated_at: 2026-11-22
|
||||
version: 2.38
|
||||
updated_at: 2026-11-24
|
||||
---
|
||||
|
||||
# 统一订单、履约与财务模型
|
||||
|
||||
> 状态:**唯一权威文档**。
|
||||
> 最后校准:2026-11-22。
|
||||
> 最后校准:2026-11-24。
|
||||
> 生产基线:迁移 `175`(2026-11-19 核对)。
|
||||
> 开发基线:迁移 `179`(仅本地,尚未部署生产)。
|
||||
>
|
||||
@@ -94,7 +94,10 @@ updated_at: 2026-11-22
|
||||
|
||||
负责:
|
||||
|
||||
- 接收 91、快手送码、拼多多、抖音码速达的数据。
|
||||
- 接收 91、快手送码、拼多多、抖音码速达和自动发货抖店的数据。
|
||||
uto_ship_douyin 只是新的订单来源,platform = doudian;它复用现有内部 SKU 映射、渠道路由、履约执行和成本体系,
|
||||
不新增履约渠道。平台商品编号通过 internal_sku_mappings 与 channel_product_mappings 精确映射,
|
||||
未配置时进入待补全,不按名称猜测。接口回调只用于通知交付结果,订单、履约、成本和财务仍以本项目正式表为唯一真源。
|
||||
- 保存平台订单、订单项、原始报文、支付和售后事实。
|
||||
- 保证来源重放幂等。
|
||||
- 将平台商品字段解析为中文内部 SKU。
|
||||
|
||||
Reference in New Issue
Block a user