新增(自动发货抖店): 接入异步卡密下单与回调

This commit is contained in:
2026-11-24 17:28:38 +08:00
parent be1b88ac6b
commit 63f020113a
39 changed files with 3179 additions and 5 deletions
+2
View File
@@ -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)
+11
View File
@@ -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: '',
+25
View File
@@ -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&timestamp=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&timestamp=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: '' }
}
+2
View File
@@ -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
View File
@@ -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()
+11
View File
@@ -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