feat: 支持第三方卡券收到订单后自动核销

This commit is contained in:
yml2213
2026-11-05 15:19:39 +08:00
parent 1df88cc639
commit 92ceb9697b
11 changed files with 323 additions and 30 deletions
@@ -88,6 +88,15 @@ type VoucherConsumeScheduleTarget = {
voucherCount: number
}
type VoucherOrderItemTargetRow = {
id: number
order_id: number
provider: string
platform: string
platform_order_id: string
fulfillment_channel: string
}
const RETRY_DELAYS_SECONDS = [10, 30, 60, 300, 600, 900, 1800]
const PROCESSING_LOCK_SECONDS = 120
@@ -152,6 +161,140 @@ export async function scheduleVoucherConsumeForWorkOrder(
})
}
/**
* Schedule after an order item has a fulfillment channel.
*
* The platform voucher may not exist yet when this runs. The queued job resolves
* the voucher again at execution time and retries while the incoming voucher is
* still being created or synchronized.
*/
export async function scheduleVoucherConsumeForOrderItems(
orderItemIds: number[],
event: VoucherConsumeEvent,
): Promise<{ targetCount: number; queuedCount: number; jobIds: number[] }> {
const ids = [...new Set(orderItemIds.map(Number).filter((id) => Number.isInteger(id) && id > 0))]
if (ids.length === 0) {
return { targetCount: 0, queuedCount: 0, jobIds: [] }
}
const rows = await query<VoucherOrderItemTargetRow>(
`
SELECT
oi.id,
oi.order_id,
oi.fulfillment_channel,
o.provider,
o.platform,
o.platform_order_id
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
WHERE oi.id = ANY($1::bigint[])
AND oi.fulfillment_status = 'assigned'
`,
[ids],
)
const policy = getVoucherConsumePolicy()
const targets: Array<{
provider: VoucherConsumeProvider
channel: VoucherConsumeChannel
trigger_event: VoucherConsumeEvent
target_key: string
platform_order_id: string
order_id: number
order_item_id: number
due_at: string
}> = []
for (const row of rows.rows) {
const provider = resolveVoucherProviderFromFields(row.provider, row.platform)
const channel = normalizeVoucherChannel(row.fulfillment_channel)
if (!provider || !channel) continue
const resolved = resolveVoucherConsumePolicy({
provider,
channel,
event,
policy,
})
if (!resolved.enabled) continue
targets.push({
provider,
channel,
trigger_event: event,
target_key: buildVoucherConsumeTargetKey(row.id, `order_item:${row.id}`),
platform_order_id: String(row.platform_order_id || '').trim(),
order_id: Number(row.order_id),
order_item_id: Number(row.id),
due_at: new Date(Date.now() + resolved.delaySeconds * 1000).toISOString(),
})
}
if (targets.length === 0) {
return { targetCount: 0, queuedCount: 0, jobIds: [] }
}
const inserted = await query<{ id: number }>(
`
INSERT INTO voucher_consume_jobs (
provider,
channel,
trigger_event,
target_key,
platform_order_id,
order_id,
order_item_id,
due_at,
status,
attempt_count,
max_attempts,
updated_at
)
SELECT
target.provider,
target.channel,
target.trigger_event,
target.target_key,
target.platform_order_id,
target.order_id,
target.order_item_id,
target.due_at,
'pending',
0,
8,
NOW()
FROM jsonb_to_recordset($1::jsonb) AS target(
provider text,
channel text,
trigger_event text,
target_key text,
platform_order_id text,
order_id bigint,
order_item_id bigint,
due_at timestamptz
)
ON CONFLICT (provider, target_key)
WHERE status IN ('pending', 'processing', 'succeeded')
DO NOTHING
RETURNING id
`,
[JSON.stringify(targets)],
)
logIntegration('[voucher-consume/queue]', '订单渠道确定后批量安排核销', {
event,
targetCount: targets.length,
queuedCount: inserted.rowCount || 0,
jobIds: inserted.rows.map((row) => Number(row.id)),
})
return {
targetCount: targets.length,
queuedCount: inserted.rowCount || 0,
jobIds: inserted.rows.map((row) => Number(row.id)),
}
}
async function scheduleVoucherConsumeTarget(
target: Omit<VoucherConsumeScheduleTarget, 'voucherCodes' | 'voucherCount'>,
): Promise<VoucherConsumeScheduleResult> {
@@ -688,11 +831,18 @@ async function failVoucherConsumeJob(job: VoucherConsumeJobRow, error: unknown,
}
function resolveVoucherProvider(order: OrderRow): VoucherConsumeProvider | null {
if (isDouyinMashidaProvider(order.provider)) {
return resolveVoucherProviderFromFields(order.provider, order.platform)
}
function resolveVoucherProviderFromFields(
orderProvider: unknown,
orderPlatform: unknown,
): VoucherConsumeProvider | null {
if (isDouyinMashidaProvider(orderProvider)) {
return 'douyin_mashida'
}
const provider = String(order.provider || '').trim()
const platform = String(order.platform || '').trim()
const provider = String(orderProvider || '').trim()
const platform = String(orderPlatform || '').trim()
if (
[OPEN_91_PROVIDER, 'open_91', '91'].includes(provider) ||
[OPEN_91_PLATFORM, 'kuaishou'].includes(platform)
@@ -702,6 +852,19 @@ function resolveVoucherProvider(order: OrderRow): VoucherConsumeProvider | null
return null
}
function normalizeVoucherChannel(value: unknown): VoucherConsumeChannel | null {
const channel = String(value || '').trim()
if (
channel === 'affiliate_dash' ||
channel === 'work_order' ||
channel === 'manual' ||
channel === 'third_party_voucher'
) {
return channel
}
return null
}
function resolveTaskVoucherChannel(
task: Pick<TaskRow, 'executor_key'>,
orderItem: OrderItemRow | null,
@@ -717,16 +880,7 @@ function resolveTaskVoucherChannel(
return 'manual'
}
const channel = String(orderItem?.fulfillment_channel || '').trim()
if (
channel === 'affiliate_dash' ||
channel === 'work_order' ||
channel === 'manual' ||
channel === 'third_party_voucher'
) {
return channel
}
return null
return normalizeVoucherChannel(orderItem?.fulfillment_channel)
}
function buildVoucherConsumeTargetKey(orderItemId: unknown, fallback: string): string {