彻底重构-3
This commit is contained in:
@@ -1,11 +1,16 @@
|
||||
import { createTask, listTasksByOrderId, updateTask } from '../../repositories/task-repo.js'
|
||||
import {
|
||||
getFulfillmentProfileByKey,
|
||||
listFulfillmentProfileRequirements,
|
||||
resolveFulfillmentBinding,
|
||||
} from '../../repositories/fulfillment-profile-repo.js'
|
||||
import { reserveCdkForTask } from './cdk-service.js'
|
||||
import { createTaskClaimToken } from '../claim/claim-service.js'
|
||||
import { nowIso } from '../../utils/time.js'
|
||||
import { randomId } from '../../utils/random.js'
|
||||
|
||||
export function syncDeliveryTasksForOrder(order, orderItems) {
|
||||
const existingTasks = listTasksByOrderId(order.id)
|
||||
export async function syncDeliveryTasksForOrder(order, orderItems) {
|
||||
const existingTasks = await listTasksByOrderId(order.id)
|
||||
|
||||
if (existingTasks.length > 0) {
|
||||
if (order.pay_status !== 'paid') {
|
||||
@@ -13,47 +18,72 @@ export function syncDeliveryTasksForOrder(order, orderItems) {
|
||||
}
|
||||
|
||||
const itemMap = new Map(orderItems.map((item) => [item.id, item]))
|
||||
return existingTasks.map((task) => preparePaidTask({
|
||||
return Promise.all(existingTasks.map((task) => preparePaidTask({
|
||||
...task,
|
||||
skuCode: itemMap.get(task.order_item_id)?.sku_code || '',
|
||||
skuName: itemMap.get(task.order_item_id)?.sku_name || '',
|
||||
}))
|
||||
})))
|
||||
}
|
||||
|
||||
const tasks = []
|
||||
|
||||
for (const item of orderItems) {
|
||||
const binding = await resolveFulfillmentBinding({
|
||||
skuCode: item.sku_code,
|
||||
provider: order.provider,
|
||||
platform: order.platform,
|
||||
shopId: order.shop_id,
|
||||
})
|
||||
const profile = binding || await getFulfillmentProfileByKey('manual_review')
|
||||
if (!profile) {
|
||||
continue
|
||||
}
|
||||
const requirements = await listFulfillmentProfileRequirements(profile.profile_id || profile.id)
|
||||
const primaryRequirement = requirements.find((requirement) => requirement.is_required !== false) || requirements[0] || null
|
||||
const quantity = Math.max(1, Number(item.quantity || 1))
|
||||
|
||||
for (let index = 0; index < quantity; index += 1) {
|
||||
const createdAt = nowIso()
|
||||
const initialStatus = order.pay_status === 'paid' ? 'paid' : 'pending_payment'
|
||||
const initialStatus = order.pay_status === 'paid'
|
||||
? resolvePaidTaskStatus(profile)
|
||||
: 'pending_payment'
|
||||
|
||||
const task = createTask({
|
||||
const task = await createTask({
|
||||
orderId: order.id,
|
||||
orderItemId: item.id,
|
||||
unitIndex: index + 1,
|
||||
provider: order.provider,
|
||||
platform: order.platform,
|
||||
shopId: order.shop_id,
|
||||
shopName: order.shop_name,
|
||||
platformOrderId: order.platform_order_id,
|
||||
taskNo: randomId('DT'),
|
||||
profileId: Number(profile.profile_id || profile.id),
|
||||
executorKey: String(profile.executor_key || 'manual_dispatch'),
|
||||
taskStatus: initialStatus,
|
||||
loginType: '',
|
||||
claimTokenId: null,
|
||||
reservedCdkId: null,
|
||||
browserSessionId: '',
|
||||
nickname: '',
|
||||
roleId: '',
|
||||
roleName: '',
|
||||
area: '',
|
||||
partitionName: '',
|
||||
inventoryStatus: profile.requires_claim ? 'pending' : 'not_required',
|
||||
deliveryStatus: initialStatus === 'redeemed' ? 'delivered' : 'pending',
|
||||
resultCode: '',
|
||||
resultMessage: '',
|
||||
screenshotPath: '',
|
||||
artifactsJson: '{}',
|
||||
claimToken: '',
|
||||
claimExpiresAt: null,
|
||||
automationMode: profile.auto_dispatch ? 'automatic' : 'manual',
|
||||
requiresClaim: Boolean(profile.requires_claim),
|
||||
userActionStatus: profile.requires_claim ? 'pending_claim' : 'not_required',
|
||||
attemptCount: 0,
|
||||
lastError: '',
|
||||
retryCount: 0,
|
||||
expiresAt: null,
|
||||
claimedAt: null,
|
||||
roleConfirmedAt: null,
|
||||
redeemedAt: null,
|
||||
contextJson: JSON.stringify({
|
||||
profileKey: String(profile.profile_key || ''),
|
||||
profileName: String(profile.profile_name || profile.name || ''),
|
||||
skuCode: item.sku_code,
|
||||
skuName: item.sku_name,
|
||||
primaryRequirement: primaryRequirement
|
||||
? {
|
||||
roleKey: String(primaryRequirement.role_key || primaryRequirement.roleKey || 'primary_code'),
|
||||
credentialType: String(primaryRequirement.credential_type || primaryRequirement.credentialType || 'tencent_code'),
|
||||
}
|
||||
: null,
|
||||
}),
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
})
|
||||
@@ -70,16 +100,28 @@ export function syncDeliveryTasksForOrder(order, orderItems) {
|
||||
return tasks
|
||||
}
|
||||
|
||||
return tasks.map((task) => preparePaidTask(task))
|
||||
return Promise.all(tasks.map((task) => preparePaidTask(task)))
|
||||
}
|
||||
|
||||
function preparePaidTask(task) {
|
||||
async function preparePaidTask(task) {
|
||||
const now = nowIso()
|
||||
const taskContext = parseTaskContext(task)
|
||||
const primaryRequirement = taskContext.primaryRequirement || null
|
||||
|
||||
if (['link_generated', 'claimed', 'role_confirmed', 'redeeming', 'redeemed'].includes(task.task_status)) {
|
||||
return task
|
||||
}
|
||||
|
||||
if (!task.requires_claim || String(task.executor_key || '').trim() === 'manual_dispatch') {
|
||||
return updateTask(task.id, {
|
||||
task_status: 'manual_review',
|
||||
inventory_status: 'not_required',
|
||||
user_action_status: 'not_required',
|
||||
last_error: task.last_error || '当前任务需要人工履约处理',
|
||||
updated_at: now,
|
||||
})
|
||||
}
|
||||
|
||||
if (!task.skuCode) {
|
||||
return updateTask(task.id, {
|
||||
task_status: 'manual_review',
|
||||
@@ -88,7 +130,7 @@ function preparePaidTask(task) {
|
||||
})
|
||||
}
|
||||
|
||||
if (task.reserved_cdk_id && task.claim_token_id) {
|
||||
if (task.primary_inventory_item_id && task.primary_claim_token_id) {
|
||||
return updateTask(task.id, {
|
||||
task_status: 'link_generated',
|
||||
last_error: '',
|
||||
@@ -96,24 +138,59 @@ function preparePaidTask(task) {
|
||||
})
|
||||
}
|
||||
|
||||
const reserved = reserveCdkForTask(task.skuCode, task.id)
|
||||
if (!primaryRequirement?.credentialType) {
|
||||
return updateTask(task.id, {
|
||||
task_status: 'manual_review',
|
||||
last_error: '履约档案未配置库存要求,无法自动分配库存',
|
||||
updated_at: now,
|
||||
})
|
||||
}
|
||||
|
||||
const reserved = await reserveCdkForTask({
|
||||
skuCode: task.skuCode,
|
||||
taskId: task.id,
|
||||
credentialType: primaryRequirement.credentialType,
|
||||
roleKey: primaryRequirement.roleKey || 'primary_code',
|
||||
})
|
||||
|
||||
if (!reserved) {
|
||||
return updateTask(task.id, {
|
||||
task_status: 'waiting_inventory',
|
||||
inventory_status: 'pending',
|
||||
last_error: '库存不足,等待可用 CDK',
|
||||
updated_at: now,
|
||||
})
|
||||
}
|
||||
|
||||
const claimToken = createTaskClaimToken(task.id)
|
||||
const claimToken = await createTaskClaimToken(task.id)
|
||||
|
||||
return updateTask(task.id, {
|
||||
task_status: 'link_generated',
|
||||
reserved_cdk_id: reserved.id,
|
||||
claim_token_id: claimToken.id,
|
||||
inventory_status: 'reserved',
|
||||
claim_token: claimToken.token,
|
||||
claim_expires_at: claimToken.expired_at,
|
||||
user_action_status: 'pending_claim',
|
||||
last_error: '',
|
||||
expires_at: claimToken.expired_at,
|
||||
updated_at: now,
|
||||
})
|
||||
}
|
||||
|
||||
function resolvePaidTaskStatus(profile) {
|
||||
if (Boolean(profile?.requires_claim)) {
|
||||
return 'paid'
|
||||
}
|
||||
|
||||
if (String(profile?.executor_key || '').trim() === 'manual_dispatch') {
|
||||
return 'manual_review'
|
||||
}
|
||||
|
||||
return 'paid'
|
||||
}
|
||||
|
||||
function parseTaskContext(task) {
|
||||
try {
|
||||
return JSON.parse(String(task?.context_json || '{}'))
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,222 +0,0 @@
|
||||
import { getDb, runInTransaction } from '../../db/client.js'
|
||||
import { listOrderItemsByOrderId, replaceOrderItems } from '../../repositories/order-item-repo.js'
|
||||
import { enrichAgisoXianyuTradeOrder } from '../platforms/agiso/xianyu/order-detail-service.js'
|
||||
import { logInfo } from '../../utils/logger.js'
|
||||
import { nowIso } from '../../utils/time.js'
|
||||
import { parseJsonObject } from '../../utils/json.js'
|
||||
|
||||
export async function repairAgisoOrderData() {
|
||||
const rows = getDb().prepare(`
|
||||
SELECT
|
||||
o.id,
|
||||
o.provider,
|
||||
o.platform,
|
||||
o.shop_id,
|
||||
o.shop_name,
|
||||
o.platform_order_id,
|
||||
o.total_amount,
|
||||
o.raw_payload_json,
|
||||
o.paid_at,
|
||||
o.buyer_id,
|
||||
o.buyer_name,
|
||||
o.receiver_contact,
|
||||
(
|
||||
SELECT we.body_json
|
||||
FROM webhook_events we
|
||||
WHERE we.related_order_id = o.id
|
||||
ORDER BY we.id DESC
|
||||
LIMIT 1
|
||||
) AS latest_body_json
|
||||
FROM orders o
|
||||
WHERE o.provider = 'agiso' AND o.platform = 'xianyu'
|
||||
ORDER BY o.id ASC
|
||||
`).all()
|
||||
|
||||
if (rows.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
let repairedOrderIdCount = 0
|
||||
let repairedAmountCount = 0
|
||||
let repairedOrderItemCount = 0
|
||||
|
||||
for (const row of rows) {
|
||||
const latestRequestBody = parseJsonObject(row.latest_body_json)
|
||||
const rawJson = String(latestRequestBody.json || '').trim()
|
||||
const webhookPayload = rawJson ? parseJsonObject(rawJson, { preserveLargeIntegers: true }) : {}
|
||||
const rawPayload = parseJsonObject(row.raw_payload_json, { preserveLargeIntegers: true })
|
||||
const expectedOrderId = pickFirstNonEmpty([
|
||||
webhookPayload.biz_order_id,
|
||||
webhookPayload.order_id,
|
||||
webhookPayload.orderId,
|
||||
rawPayload.biz_order_id,
|
||||
rawPayload.order_id,
|
||||
rawPayload.orderId,
|
||||
])
|
||||
|
||||
const parsed = {
|
||||
provider: row.provider,
|
||||
platform: row.platform,
|
||||
shopId: String(row.shop_id || '').trim(),
|
||||
shopName: String(row.shop_name || '').trim(),
|
||||
platformOrderId: expectedOrderId || String(row.platform_order_id || '').trim(),
|
||||
totalAmount: Number(row.total_amount || 0),
|
||||
buyerId: pickFirstNonEmpty([rawPayload.buyer_id, rawPayload.buyerId, rawPayload.BuyerId, row.buyer_id]),
|
||||
buyerName: pickFirstNonEmpty([rawPayload.buyer_name, rawPayload.buyerName, rawPayload.BuyerName, row.buyer_name]),
|
||||
receiverContact: pickFirstNonEmpty([
|
||||
rawPayload.receiver_contact,
|
||||
rawPayload.receiverContact,
|
||||
rawPayload.receiver_mobile,
|
||||
rawPayload.receiverMobile,
|
||||
rawPayload.mobile,
|
||||
rawPayload.phone,
|
||||
row.receiver_contact,
|
||||
]),
|
||||
paidAt: row.paid_at,
|
||||
rawPayload: Object.keys(webhookPayload).length > 0 ? webhookPayload : rawPayload,
|
||||
items: [],
|
||||
}
|
||||
|
||||
const detailResult = await enrichAgisoXianyuTradeOrder(parsed, {
|
||||
requestId: `repair-order-${row.id}`,
|
||||
})
|
||||
|
||||
const nextOrderId = pickFirstNonEmpty([
|
||||
detailResult.parsed.platformOrderId,
|
||||
expectedOrderId,
|
||||
row.platform_order_id,
|
||||
])
|
||||
const nextAmount = Number(detailResult.parsed.totalAmount || 0)
|
||||
const nextRawPayloadJson = JSON.stringify(detailResult.parsed.rawPayload || rawPayload || {})
|
||||
const nextShopName = pickFirstNonEmpty([detailResult.parsed.shopName, row.shop_name])
|
||||
const nextBuyerId = pickFirstNonEmpty([detailResult.parsed.buyerId, row.buyer_id])
|
||||
const nextBuyerName = pickFirstNonEmpty([detailResult.parsed.buyerName, row.buyer_name])
|
||||
const nextReceiverContact = pickFirstNonEmpty([detailResult.parsed.receiverContact, row.receiver_contact])
|
||||
const nextPaidAt = detailResult.parsed.paidAt || row.paid_at
|
||||
const currentOrderItems = listOrderItemsByOrderId(row.id)
|
||||
const repairedItems = Array.isArray(detailResult.parsed.items) ? detailResult.parsed.items : []
|
||||
const shouldRepairOrderItems = repairedItems.length > 0
|
||||
&& (currentOrderItems.length === 0 || currentOrderItems.length === repairedItems.length)
|
||||
&& hasOrderItemChanges(currentOrderItems, repairedItems)
|
||||
|
||||
const orderIdChanged = nextOrderId && nextOrderId !== String(row.platform_order_id || '')
|
||||
const amountChanged = nextAmount > 0 && nextAmount !== Number(row.total_amount || 0)
|
||||
const payloadChanged = nextRawPayloadJson !== String(row.raw_payload_json || '{}')
|
||||
const metadataChanged = nextShopName !== String(row.shop_name || '')
|
||||
|| nextBuyerId !== String(row.buyer_id || '')
|
||||
|| nextBuyerName !== String(row.buyer_name || '')
|
||||
|| nextReceiverContact !== String(row.receiver_contact || '')
|
||||
|| nextPaidAt !== row.paid_at
|
||||
|
||||
if (!orderIdChanged && !amountChanged && !payloadChanged && !metadataChanged && !shouldRepairOrderItems) {
|
||||
continue
|
||||
}
|
||||
|
||||
runInTransaction((db) => {
|
||||
db.prepare(`
|
||||
UPDATE orders
|
||||
SET
|
||||
shop_name = ?,
|
||||
platform_order_id = ?,
|
||||
buyer_id = ?,
|
||||
buyer_name = ?,
|
||||
receiver_contact = ?,
|
||||
total_amount = ?,
|
||||
raw_payload_json = ?,
|
||||
paid_at = ?,
|
||||
updated_at = ?
|
||||
WHERE id = ?
|
||||
`).run(
|
||||
nextShopName,
|
||||
nextOrderId,
|
||||
nextBuyerId,
|
||||
nextBuyerName,
|
||||
nextReceiverContact,
|
||||
nextAmount,
|
||||
nextRawPayloadJson,
|
||||
nextPaidAt,
|
||||
nowIso(),
|
||||
row.id,
|
||||
)
|
||||
|
||||
if (shouldRepairOrderItems) {
|
||||
const itemNow = nowIso()
|
||||
replaceOrderItems(
|
||||
row.id,
|
||||
repairedItems.map((item) => ({
|
||||
skuCode: item.skuCode,
|
||||
skuName: item.skuName,
|
||||
quantity: item.quantity,
|
||||
specJson: JSON.stringify(item.spec || {}),
|
||||
deliveryMode: 'claim_link',
|
||||
createdAt: itemNow,
|
||||
updatedAt: itemNow,
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
if (orderIdChanged) {
|
||||
db.prepare('UPDATE delivery_tasks SET platform_order_id = ? WHERE order_id = ?').run(nextOrderId, row.id)
|
||||
db.prepare(`
|
||||
UPDATE message_deliveries
|
||||
SET
|
||||
platform_order_id = ?,
|
||||
recipient_key = CASE
|
||||
WHEN recipient_key = ? THEN ?
|
||||
ELSE recipient_key
|
||||
END,
|
||||
updated_at = ?
|
||||
WHERE order_id = ?
|
||||
`).run(nextOrderId, row.platform_order_id, nextOrderId, nowIso(), row.id)
|
||||
}
|
||||
})
|
||||
|
||||
if (orderIdChanged) {
|
||||
repairedOrderIdCount += 1
|
||||
}
|
||||
|
||||
if (amountChanged) {
|
||||
repairedAmountCount += 1
|
||||
}
|
||||
|
||||
if (shouldRepairOrderItems) {
|
||||
repairedOrderItemCount += 1
|
||||
}
|
||||
}
|
||||
|
||||
if (repairedOrderIdCount > 0 || repairedAmountCount > 0 || repairedOrderItemCount > 0) {
|
||||
logInfo('[startup]', '已自动修复历史 Agiso 咸鱼订单数据', {
|
||||
repairedOrderIdCount,
|
||||
repairedAmountCount,
|
||||
repairedOrderItemCount,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function hasOrderItemChanges(currentItems, repairedItems) {
|
||||
if (!Array.isArray(currentItems) || !Array.isArray(repairedItems) || currentItems.length !== repairedItems.length) {
|
||||
return repairedItems.length > 0
|
||||
}
|
||||
|
||||
return repairedItems.some((item, index) => {
|
||||
const current = currentItems[index]
|
||||
const currentSpec = parseJsonObject(current?.spec_json, { preserveLargeIntegers: true })
|
||||
const nextSpec = item?.spec || {}
|
||||
|
||||
return String(current?.sku_code || '').trim() !== String(item?.skuCode || '').trim()
|
||||
|| String(current?.sku_name || '').trim() !== String(item?.skuName || '').trim()
|
||||
|| Number(current?.quantity || 0) !== Number(item?.quantity || 0)
|
||||
|| JSON.stringify(currentSpec) !== JSON.stringify(nextSpec)
|
||||
})
|
||||
}
|
||||
|
||||
function pickFirstNonEmpty(values) {
|
||||
for (const value of values) {
|
||||
const normalized = String(value || '').trim()
|
||||
if (normalized) {
|
||||
return normalized
|
||||
}
|
||||
}
|
||||
|
||||
return ''
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import { logWebhook } from '../../utils/logger.js'
|
||||
|
||||
export async function upsertOrderFromWebhook(event) {
|
||||
const now = nowIso()
|
||||
const existing = findOrderByPlatformOrderId({
|
||||
const existing = await findOrderByPlatformOrderId({
|
||||
provider: event.provider,
|
||||
platform: event.platform,
|
||||
shopId: event.shopId,
|
||||
@@ -43,30 +43,30 @@ export async function upsertOrderFromWebhook(event) {
|
||||
}
|
||||
|
||||
const order = existing
|
||||
? updateOrder(existing.id, {
|
||||
? await updateOrder(existing.id, {
|
||||
...basePayload,
|
||||
updatedAt: now,
|
||||
})
|
||||
: createOrder({
|
||||
: await createOrder({
|
||||
...basePayload,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})
|
||||
|
||||
const orderItems = replaceOrderItems(
|
||||
const orderItems = await replaceOrderItems(
|
||||
order.id,
|
||||
event.items.map((item) => ({
|
||||
skuCode: item.skuCode,
|
||||
skuName: item.skuName,
|
||||
quantity: item.quantity,
|
||||
specJson: JSON.stringify(item.spec || {}),
|
||||
deliveryMode: 'claim_link',
|
||||
itemSnapshotJson: JSON.stringify(item.snapshot || item.spec || {}),
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
})),
|
||||
)
|
||||
|
||||
const tasks = syncDeliveryTasksForOrder(order, orderItems)
|
||||
const tasks = await syncDeliveryTasksForOrder(order, orderItems)
|
||||
const messageDeliveries = []
|
||||
|
||||
logWebhook('[order-service]', 'Webhook 订单 upsert 完成', {
|
||||
@@ -85,12 +85,12 @@ export async function upsertOrderFromWebhook(event) {
|
||||
event.provider !== 'agiso'
|
||||
|| event.platform !== 'xianyu'
|
||||
|| String(task.task_status || '') !== 'link_generated'
|
||||
|| !task.claim_token_id
|
||||
|| !task.primary_claim_token_id
|
||||
) {
|
||||
continue
|
||||
}
|
||||
|
||||
const claimToken = getClaimTokenById(task.claim_token_id)
|
||||
const claimToken = await getClaimTokenById(task.primary_claim_token_id)
|
||||
if (!claimToken) {
|
||||
continue
|
||||
}
|
||||
|
||||
@@ -741,23 +741,8 @@ function normalizeProviderDateTime(value) {
|
||||
}
|
||||
|
||||
function resolveSkuCode(rawKey) {
|
||||
const mappings = runtimeConfig.orders.skuMappings
|
||||
const candidates = Array.isArray(rawKey) ? rawKey : [rawKey]
|
||||
|
||||
if (mappings && typeof mappings === 'object') {
|
||||
for (const candidate of candidates) {
|
||||
const normalizedCandidate = String(candidate || '').trim()
|
||||
if (!normalizedCandidate) {
|
||||
continue
|
||||
}
|
||||
|
||||
const direct = mappings[normalizedCandidate]
|
||||
if (typeof direct === 'string' && direct.trim()) {
|
||||
return direct.trim()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const candidate of candidates) {
|
||||
if (typeof candidate === 'string' && candidate.trim()) {
|
||||
return candidate.trim()
|
||||
|
||||
Reference in New Issue
Block a user