彻底重构-3
This commit is contained in:
@@ -22,7 +22,6 @@ TENCENT_SESSION_DEBUG=false
|
||||
ADMIN_SESSION_SECRET=dev-local-session-secret
|
||||
ADMIN_DEFAULT_USERS_JSON=[{"username":"admin","password":"dev-admin-123456","role":"admin"},{"username":"operator","password":"dev-operator-123456","role":"operator"}]
|
||||
|
||||
ORDER_SKU_MAPPINGS_JSON={"32768":"dnf-cdk-a","dnf-cdk-a":"dnf-cdk-a"}
|
||||
ORDER_FULFILLMENT_BINDINGS_JSON=[]
|
||||
|
||||
AGISO_APP_SECRET=
|
||||
|
||||
@@ -20,7 +20,6 @@ TENCENT_SESSION_DEBUG=false
|
||||
ADMIN_SESSION_SECRET=replace-with-a-long-random-secret
|
||||
ADMIN_DEFAULT_USERS_JSON=[{"username":"admin","password":"replace-with-strong-admin-password","role":"admin"},{"username":"operator","password":"replace-with-strong-operator-password","role":"operator"}]
|
||||
|
||||
ORDER_SKU_MAPPINGS_JSON={"32768":"dnf-cdk-a","dnf-cdk-a":"dnf-cdk-a"}
|
||||
ORDER_FULFILLMENT_BINDINGS_JSON=[]
|
||||
|
||||
AGISO_APP_SECRET=
|
||||
|
||||
@@ -53,23 +53,27 @@ docker compose -f docker-compose.dev.yml up -d --build
|
||||
|
||||
开发版 Compose 现在是热更新模式:
|
||||
|
||||
- `postgres` 容器提供 PostgreSQL
|
||||
- 后端源码挂载到容器里,运行 `npm run dev`
|
||||
- 前端源码挂载到容器里,运行 `vite`
|
||||
- Caddy 只负责把 `80/443` 反代到前后端容器
|
||||
|
||||
通常只有首次启动、改 Dockerfile、改系统依赖时才需要 `--build`。
|
||||
|
||||
开发版 Compose 会把后端数据目录直接挂载到:
|
||||
开发版 Compose 会把后端运行产物目录直接挂载到:
|
||||
|
||||
- [apps/backend/data](/Users/yml/codes/order-site-workspace/apps/backend/data)
|
||||
|
||||
这样本地可以直接看到:
|
||||
|
||||
- SQLite 数据库
|
||||
- `data/logs/*.log`
|
||||
- 浏览器会话产物
|
||||
- 截图和证明文件
|
||||
|
||||
PostgreSQL 数据则保存在 Docker volume 里:
|
||||
|
||||
- `postgres_dev_data`
|
||||
|
||||
当前 Dockerfile 已默认针对国内服务器优化以下下载源:
|
||||
|
||||
- Debian `apt` 使用腾讯云镜像
|
||||
@@ -97,6 +101,7 @@ docker compose build \
|
||||
- 改后端 `src/`:容器内自动热重启
|
||||
- 改前端 `src/`:Vite 自动热更新
|
||||
- 改 OCR Python:后端下次调用时直接走挂载后的最新源码
|
||||
- 改数据库 schema:后端启动时会自动执行 migration
|
||||
|
||||
详细文档:
|
||||
|
||||
|
||||
@@ -108,6 +108,7 @@ npm run start
|
||||
|
||||
当前 `docker-compose.dev.yml` 已切到源码挂载模式:
|
||||
|
||||
- `postgres` 容器提供开发库,后端通过 `DATABASE_URL` 连接
|
||||
- 后端容器启动时执行 `npm install` 和 `npm run dev`
|
||||
- OCR 子服务会在容器里执行 `pip install -e /app/subservices/ocr-worker`
|
||||
- 所以平时改 `src/`、改 OCR Python、改 `.env`,一般都不需要重建镜像
|
||||
|
||||
@@ -35,7 +35,6 @@ module.exports = {
|
||||
orders: {
|
||||
claimBaseUrl: 'http://127.0.0.1:5173/#/claim',
|
||||
tokenTtlHours: 24,
|
||||
skuMappings: {},
|
||||
fulfillmentBindings: [],
|
||||
},
|
||||
|
||||
|
||||
@@ -1,21 +1,22 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import fs from 'node:fs'
|
||||
import path from 'node:path'
|
||||
import process from 'node:process'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { DatabaseSync } from 'node:sqlite'
|
||||
|
||||
const CURRENT_DIR = path.dirname(fileURLToPath(import.meta.url))
|
||||
const PROJECT_ROOT = path.resolve(CURRENT_DIR, '..')
|
||||
const DEFAULT_DB_PATH = path.join(PROJECT_ROOT, 'data', 'order-site.db')
|
||||
import { closeDb, query } from '../src/db/client.js'
|
||||
import { runtimeConfig } from '../src/config/runtime.js'
|
||||
|
||||
const PRESETS = {
|
||||
'codex-debug': {
|
||||
platformOrderIds: ['DEBUG-ORDER-001', '2067719225654999', '2067719225655000', '2067719225655001'],
|
||||
shopIds: ['debug-shop', 'shop-10001', 'shop-10002', 'shop-10003'],
|
||||
},
|
||||
}
|
||||
const RESET_TABLES = [
|
||||
'message_deliveries',
|
||||
'tencent_browser_contexts',
|
||||
'task_events',
|
||||
'claim_tokens',
|
||||
'task_inventory_bindings',
|
||||
'fulfillment_tasks',
|
||||
'order_items',
|
||||
'orders',
|
||||
'webhook_events',
|
||||
'inventory_items',
|
||||
]
|
||||
|
||||
const options = parseArgs(process.argv.slice(2))
|
||||
|
||||
@@ -24,437 +25,74 @@ if (options.help) {
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
const preset = options.preset ? PRESETS[options.preset] : null
|
||||
if (options.preset && !preset) {
|
||||
console.error(`未知 preset: ${options.preset}`)
|
||||
printHelp()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const selectors = {
|
||||
provider: options.provider,
|
||||
platform: options.platform,
|
||||
orderIds: normalizeNumberList(options.orderIds),
|
||||
platformOrderIds: uniqueList([...(preset?.platformOrderIds || []), ...options.platformOrderIds]),
|
||||
shopIds: uniqueList([...(preset?.shopIds || []), ...options.shopIds]),
|
||||
shopNames: uniqueList(options.shopNames),
|
||||
}
|
||||
|
||||
if (!hasAnySelector(selectors)) {
|
||||
console.error('至少需要一个筛选条件,或使用 --preset codex-debug')
|
||||
printHelp()
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
const dbPath = resolveDbPath(options.dbPath)
|
||||
const db = new DatabaseSync(dbPath)
|
||||
db.exec('PRAGMA foreign_keys = ON;')
|
||||
db.exec('PRAGMA busy_timeout = 3000;')
|
||||
|
||||
const matched = collectMatches(db, selectors)
|
||||
|
||||
printSummary(dbPath, selectors, matched, options.apply)
|
||||
|
||||
if (!options.apply) {
|
||||
console.log('\n当前为预览模式。确认后追加 `--apply` 执行删除。')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
db.exec('BEGIN')
|
||||
|
||||
try {
|
||||
deleteByIds(db, 'message_deliveries', matched.messageDeliveryIds)
|
||||
deleteByIds(db, 'webhook_events', matched.webhookEventIds)
|
||||
deleteByIds(db, 'orders', matched.orderIds)
|
||||
db.exec('COMMIT')
|
||||
console.log('\n清理完成。若后台服务正在运行,建议重启一次 backend 容器,确保管理后台视图立即刷新。')
|
||||
const counts = await collectCounts()
|
||||
|
||||
printSummary(counts)
|
||||
|
||||
if (!options.apply) {
|
||||
console.log('\n当前为预览模式。确认后追加 `--apply` 执行清库。')
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
await query(`TRUNCATE TABLE ${RESET_TABLES.join(', ')} RESTART IDENTITY CASCADE`)
|
||||
|
||||
console.log('\n已清空测试业务数据。')
|
||||
console.log('保留内容:fulfillment profiles/bindings、admin users、配置文件。')
|
||||
} catch (error) {
|
||||
db.exec('ROLLBACK')
|
||||
console.error('\n清理失败:', error instanceof Error ? error.message : String(error || '未知错误'))
|
||||
process.exit(1)
|
||||
process.exitCode = 1
|
||||
} finally {
|
||||
await closeDb()
|
||||
}
|
||||
|
||||
function collectMatches(db, selectors) {
|
||||
const orderWhere = buildOrderWhere(selectors)
|
||||
const orders = db.prepare(`
|
||||
SELECT id, provider, platform, shop_id, shop_name, platform_order_id
|
||||
FROM orders
|
||||
${orderWhere.sql}
|
||||
ORDER BY id DESC
|
||||
`).all(...orderWhere.params)
|
||||
async function collectCounts() {
|
||||
const output = []
|
||||
|
||||
const orderIds = orders.map((item) => Number(item.id))
|
||||
const taskIds = orderIds.length > 0
|
||||
? db.prepare(`
|
||||
SELECT id
|
||||
FROM delivery_tasks
|
||||
WHERE order_id IN (${placeholders(orderIds.length)})
|
||||
ORDER BY id DESC
|
||||
`).all(...orderIds).map((item) => Number(item.id))
|
||||
: []
|
||||
|
||||
const webhookWhere = buildWebhookWhere(selectors, orderIds)
|
||||
const webhookEvents = db.prepare(`
|
||||
SELECT id, provider, platform, shop_id, shop_name, event_type, event_key, related_order_id
|
||||
FROM webhook_events
|
||||
${webhookWhere.sql}
|
||||
ORDER BY id DESC
|
||||
`).all(...webhookWhere.params)
|
||||
|
||||
const messageWhere = buildMessageWhere(selectors, orderIds, taskIds)
|
||||
const messageDeliveries = db.prepare(`
|
||||
SELECT id, provider, platform, shop_id, shop_name, platform_order_id, status
|
||||
FROM message_deliveries
|
||||
${messageWhere.sql}
|
||||
ORDER BY id DESC
|
||||
`).all(...messageWhere.params)
|
||||
|
||||
return {
|
||||
orders,
|
||||
orderIds,
|
||||
taskIds,
|
||||
webhookEvents,
|
||||
webhookEventIds: webhookEvents.map((item) => Number(item.id)),
|
||||
messageDeliveries,
|
||||
messageDeliveryIds: messageDeliveries.map((item) => Number(item.id)),
|
||||
}
|
||||
}
|
||||
|
||||
function buildOrderWhere(selectors) {
|
||||
const baseFilters = []
|
||||
const matchFilters = []
|
||||
const params = []
|
||||
const matchParams = []
|
||||
|
||||
if (selectors.provider) {
|
||||
baseFilters.push('provider = ?')
|
||||
params.push(selectors.provider)
|
||||
}
|
||||
|
||||
if (selectors.platform) {
|
||||
baseFilters.push('platform = ?')
|
||||
params.push(selectors.platform)
|
||||
}
|
||||
|
||||
if (selectors.orderIds.length > 0) {
|
||||
matchFilters.push(`id IN (${placeholders(selectors.orderIds.length)})`)
|
||||
matchParams.push(...selectors.orderIds)
|
||||
}
|
||||
|
||||
if (selectors.platformOrderIds.length > 0) {
|
||||
matchFilters.push(`platform_order_id IN (${placeholders(selectors.platformOrderIds.length)})`)
|
||||
matchParams.push(...selectors.platformOrderIds)
|
||||
}
|
||||
|
||||
if (selectors.shopIds.length > 0) {
|
||||
matchFilters.push(`shop_id IN (${placeholders(selectors.shopIds.length)})`)
|
||||
matchParams.push(...selectors.shopIds)
|
||||
}
|
||||
|
||||
if (selectors.shopNames.length > 0) {
|
||||
matchFilters.push(`shop_name IN (${placeholders(selectors.shopNames.length)})`)
|
||||
matchParams.push(...selectors.shopNames)
|
||||
}
|
||||
|
||||
const filters = [...baseFilters]
|
||||
if (matchFilters.length > 0) {
|
||||
filters.push(`(${matchFilters.join(' OR ')})`)
|
||||
params.push(...matchParams)
|
||||
}
|
||||
|
||||
return {
|
||||
sql: filters.length > 0 ? `WHERE ${filters.join(' AND ')}` : '',
|
||||
params,
|
||||
}
|
||||
}
|
||||
|
||||
function buildWebhookWhere(selectors, orderIds) {
|
||||
const baseFilters = []
|
||||
const matchFilters = []
|
||||
const params = []
|
||||
const matchParams = []
|
||||
|
||||
if (selectors.provider) {
|
||||
baseFilters.push('provider = ?')
|
||||
params.push(selectors.provider)
|
||||
}
|
||||
|
||||
if (selectors.platform) {
|
||||
baseFilters.push('platform = ?')
|
||||
params.push(selectors.platform)
|
||||
}
|
||||
|
||||
if (orderIds.length > 0) {
|
||||
matchFilters.push(`related_order_id IN (${placeholders(orderIds.length)})`)
|
||||
matchParams.push(...orderIds)
|
||||
}
|
||||
|
||||
if (selectors.shopIds.length > 0) {
|
||||
matchFilters.push(`shop_id IN (${placeholders(selectors.shopIds.length)})`)
|
||||
matchParams.push(...selectors.shopIds)
|
||||
}
|
||||
|
||||
if (selectors.shopNames.length > 0) {
|
||||
matchFilters.push(`shop_name IN (${placeholders(selectors.shopNames.length)})`)
|
||||
matchParams.push(...selectors.shopNames)
|
||||
}
|
||||
|
||||
if (selectors.platformOrderIds.length > 0) {
|
||||
const eventKeyFilters = selectors.platformOrderIds.map(() => 'event_key LIKE ?').join(' OR ')
|
||||
const bodyFilters = selectors.platformOrderIds.map(() => 'body_json LIKE ?').join(' OR ')
|
||||
matchFilters.push(`(${eventKeyFilters})`)
|
||||
matchParams.push(...selectors.platformOrderIds.map((item) => `%${item}%`))
|
||||
matchFilters.push(`(${bodyFilters})`)
|
||||
matchParams.push(...selectors.platformOrderIds.map((item) => `%${item}%`))
|
||||
}
|
||||
|
||||
const filters = [...baseFilters]
|
||||
if (matchFilters.length > 0) {
|
||||
filters.push(`(${matchFilters.join(' OR ')})`)
|
||||
params.push(...matchParams)
|
||||
}
|
||||
|
||||
return {
|
||||
sql: filters.length > 0 ? `WHERE ${filters.join(' AND ')}` : '',
|
||||
params,
|
||||
}
|
||||
}
|
||||
|
||||
function buildMessageWhere(selectors, orderIds, taskIds) {
|
||||
const baseFilters = []
|
||||
const matchFilters = []
|
||||
const params = []
|
||||
const matchParams = []
|
||||
|
||||
if (selectors.provider) {
|
||||
baseFilters.push('provider = ?')
|
||||
params.push(selectors.provider)
|
||||
}
|
||||
|
||||
if (selectors.platform) {
|
||||
baseFilters.push('platform = ?')
|
||||
params.push(selectors.platform)
|
||||
}
|
||||
|
||||
if (orderIds.length > 0) {
|
||||
matchFilters.push(`order_id IN (${placeholders(orderIds.length)})`)
|
||||
matchParams.push(...orderIds)
|
||||
}
|
||||
|
||||
if (taskIds.length > 0) {
|
||||
matchFilters.push(`task_id IN (${placeholders(taskIds.length)})`)
|
||||
matchParams.push(...taskIds)
|
||||
}
|
||||
|
||||
if (selectors.shopIds.length > 0) {
|
||||
matchFilters.push(`shop_id IN (${placeholders(selectors.shopIds.length)})`)
|
||||
matchParams.push(...selectors.shopIds)
|
||||
}
|
||||
|
||||
if (selectors.shopNames.length > 0) {
|
||||
matchFilters.push(`shop_name IN (${placeholders(selectors.shopNames.length)})`)
|
||||
matchParams.push(...selectors.shopNames)
|
||||
}
|
||||
|
||||
if (selectors.platformOrderIds.length > 0) {
|
||||
matchFilters.push(`platform_order_id IN (${placeholders(selectors.platformOrderIds.length)})`)
|
||||
matchParams.push(...selectors.platformOrderIds)
|
||||
}
|
||||
|
||||
const filters = [...baseFilters]
|
||||
if (matchFilters.length > 0) {
|
||||
filters.push(`(${matchFilters.join(' OR ')})`)
|
||||
params.push(...matchParams)
|
||||
}
|
||||
|
||||
return {
|
||||
sql: filters.length > 0 ? `WHERE ${filters.join(' AND ')}` : '',
|
||||
params,
|
||||
}
|
||||
}
|
||||
|
||||
function deleteByIds(db, tableName, ids) {
|
||||
if (!Array.isArray(ids) || ids.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
db.prepare(`DELETE FROM ${tableName} WHERE id IN (${placeholders(ids.length)})`).run(...ids)
|
||||
}
|
||||
|
||||
function resolveDbPath(overridePath) {
|
||||
const candidates = [
|
||||
String(overridePath || '').trim(),
|
||||
DEFAULT_DB_PATH,
|
||||
].filter(Boolean)
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const resolved = path.resolve(candidate)
|
||||
if (fs.existsSync(resolved)) {
|
||||
return resolved
|
||||
}
|
||||
}
|
||||
|
||||
console.error(`未找到数据库文件。默认查找路径: ${DEFAULT_DB_PATH}`)
|
||||
console.error('可使用 `--db-path <path>` 手动指定。')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
function parseArgs(argv) {
|
||||
const output = {
|
||||
help: false,
|
||||
apply: false,
|
||||
dbPath: '',
|
||||
preset: '',
|
||||
provider: '',
|
||||
platform: '',
|
||||
orderIds: [],
|
||||
platformOrderIds: [],
|
||||
shopIds: [],
|
||||
shopNames: [],
|
||||
}
|
||||
|
||||
for (let index = 0; index < argv.length; index += 1) {
|
||||
const current = String(argv[index] || '').trim()
|
||||
|
||||
if (!current) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (current === '--help' || current === '-h') {
|
||||
output.help = true
|
||||
continue
|
||||
}
|
||||
|
||||
if (current === '--apply') {
|
||||
output.apply = true
|
||||
continue
|
||||
}
|
||||
|
||||
if (current === '--db-path') {
|
||||
output.dbPath = String(argv[index + 1] || '').trim()
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
|
||||
if (current === '--preset') {
|
||||
output.preset = String(argv[index + 1] || '').trim()
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
|
||||
if (current === '--provider') {
|
||||
output.provider = String(argv[index + 1] || '').trim()
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
|
||||
if (current === '--platform') {
|
||||
output.platform = String(argv[index + 1] || '').trim()
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
|
||||
if (current === '--order-id') {
|
||||
output.orderIds.push(String(argv[index + 1] || '').trim())
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
|
||||
if (current === '--platform-order-id') {
|
||||
output.platformOrderIds.push(String(argv[index + 1] || '').trim())
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
|
||||
if (current === '--shop-id') {
|
||||
output.shopIds.push(String(argv[index + 1] || '').trim())
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
|
||||
if (current === '--shop-name') {
|
||||
output.shopNames.push(String(argv[index + 1] || '').trim())
|
||||
index += 1
|
||||
continue
|
||||
}
|
||||
|
||||
console.error(`未知参数: ${current}`)
|
||||
printHelp()
|
||||
process.exit(1)
|
||||
for (const tableName of RESET_TABLES) {
|
||||
const result = await query(`SELECT COUNT(*)::int AS total FROM ${tableName}`)
|
||||
output.push({
|
||||
tableName,
|
||||
total: Number(result.rows[0]?.total || 0),
|
||||
})
|
||||
}
|
||||
|
||||
return output
|
||||
}
|
||||
|
||||
function printSummary(dbPath, selectors, matched, apply) {
|
||||
console.log(`数据库: ${dbPath}`)
|
||||
console.log(`模式: ${apply ? '执行删除' : '预览'}`)
|
||||
console.log('筛选条件:')
|
||||
console.log(JSON.stringify(selectors, null, 2))
|
||||
|
||||
console.log('\n匹配结果:')
|
||||
console.log(`orders: ${matched.orders.length}`)
|
||||
printRows(matched.orders, ['id', 'provider', 'platform', 'shop_id', 'shop_name', 'platform_order_id'])
|
||||
console.log(`delivery_tasks: ${matched.taskIds.length}`)
|
||||
console.log(`webhook_events: ${matched.webhookEvents.length}`)
|
||||
printRows(matched.webhookEvents, ['id', 'provider', 'platform', 'shop_id', 'shop_name', 'event_type', 'related_order_id'])
|
||||
console.log(`message_deliveries: ${matched.messageDeliveries.length}`)
|
||||
printRows(matched.messageDeliveries, ['id', 'provider', 'platform', 'shop_id', 'shop_name', 'platform_order_id', 'status'])
|
||||
}
|
||||
|
||||
function printRows(rows, keys) {
|
||||
if (!Array.isArray(rows) || rows.length === 0) {
|
||||
return
|
||||
function parseArgs(argv) {
|
||||
return {
|
||||
apply: argv.includes('--apply'),
|
||||
help: argv.includes('-h') || argv.includes('--help'),
|
||||
}
|
||||
|
||||
const preview = rows.slice(0, 10).map((row) => Object.fromEntries(keys.map((key) => [key, row[key]])))
|
||||
console.log(JSON.stringify(preview, null, 2))
|
||||
}
|
||||
|
||||
function placeholders(count) {
|
||||
return new Array(count).fill('?').join(', ')
|
||||
}
|
||||
|
||||
function uniqueList(values) {
|
||||
return [...new Set(values.map((item) => String(item || '').trim()).filter(Boolean))]
|
||||
}
|
||||
|
||||
function normalizeNumberList(values) {
|
||||
return uniqueList(values)
|
||||
.map((item) => Number(item))
|
||||
.filter((item) => Number.isInteger(item) && item > 0)
|
||||
}
|
||||
|
||||
function hasAnySelector(selectors) {
|
||||
return Boolean(
|
||||
selectors.provider ||
|
||||
selectors.platform ||
|
||||
selectors.orderIds.length > 0 ||
|
||||
selectors.platformOrderIds.length > 0 ||
|
||||
selectors.shopIds.length > 0 ||
|
||||
selectors.shopNames.length > 0,
|
||||
)
|
||||
}
|
||||
|
||||
function printHelp() {
|
||||
console.log(`
|
||||
用法:
|
||||
node scripts/cleanup-dev-data.js [筛选条件] [--apply]
|
||||
node scripts/cleanup-dev-data.js [--apply]
|
||||
|
||||
常用参数:
|
||||
--platform-order-id <id> 按平台订单号删除,可重复传入
|
||||
--shop-id <id> 按店铺 ID 删除,可重复传入
|
||||
--shop-name <name> 按店铺名删除,可重复传入
|
||||
--order-id <id> 按内部订单 ID 删除,可重复传入
|
||||
--provider <name> 限定 provider,例如 agiso
|
||||
--platform <name> 限定业务平台,例如 xianyu
|
||||
--db-path <path> 手动指定数据库文件
|
||||
--preset codex-debug 清理当前对话里生成的调试样例
|
||||
--apply 真正执行删除;不传时只预览
|
||||
说明:
|
||||
基于当前 PostgreSQL fulfillment schema 清空测试业务数据。
|
||||
默认只预览各表记录数,追加 --apply 后执行 TRUNCATE。
|
||||
|
||||
示例:
|
||||
npm run cleanup:dev-data -- --platform-order-id DEBUG-ORDER-001
|
||||
npm run cleanup:dev-data -- --shop-id shop-10003 --apply
|
||||
npm run cleanup:dev-data -- --preset codex-debug --apply
|
||||
`)
|
||||
会清空:
|
||||
${RESET_TABLES.join('\n ')}
|
||||
|
||||
会保留:
|
||||
fulfillment_profiles / fulfillment_profile_requirements / sku_fulfillment_bindings
|
||||
admin_users / admin_audit_logs
|
||||
本地配置文件
|
||||
数据库连接: ${String(runtimeConfig.database?.url || '').trim() || '(未配置 DATABASE_URL)'}
|
||||
`.trim())
|
||||
}
|
||||
|
||||
function printSummary(counts) {
|
||||
const totalRows = counts.reduce((sum, item) => sum + item.total, 0)
|
||||
|
||||
console.log('准备清理当前测试业务数据:')
|
||||
for (const item of counts) {
|
||||
console.log(`- ${item.tableName}: ${item.total}`)
|
||||
}
|
||||
console.log(`- total: ${totalRows}`)
|
||||
}
|
||||
|
||||
@@ -156,11 +156,6 @@ function applyEnvOverrides(baseConfig) {
|
||||
nextConfig.orders.tokenTtlHours = tokenTtlHours
|
||||
}
|
||||
|
||||
const skuMappings = parseJsonObject(process.env.ORDER_SKU_MAPPINGS_JSON)
|
||||
if (skuMappings) {
|
||||
nextConfig.orders.skuMappings = skuMappings
|
||||
}
|
||||
|
||||
const fulfillmentBindings = parseJsonArray(process.env.ORDER_FULFILLMENT_BINDINGS_JSON)
|
||||
if (fulfillmentBindings) {
|
||||
nextConfig.orders.fulfillmentBindings = fulfillmentBindings
|
||||
|
||||
@@ -7,7 +7,7 @@ import adminRouter from './routes/admin.js'
|
||||
import claimsRouter from './routes/claims.js'
|
||||
import webhooksRouter from './routes/webhooks.js'
|
||||
import { ensureAdminUsersBootstrapped } from './services/admin/admin-auth-service.js'
|
||||
import { repairAgisoOrderData } from './services/order/order-repair-service.js'
|
||||
import { ensureFulfillmentCatalogBootstrapped } from './services/bootstrap/fulfillment-bootstrap-service.js'
|
||||
import { closeLocalOcrWorker, warmupLocalOcrWorker } from './services/session/ocr.js'
|
||||
import { closeAllTencentBrowserSessions, warmupTencentBrowser } from './services/session/session.js'
|
||||
import { logError, logInfo, logWarn } from './utils/logger.js'
|
||||
@@ -17,8 +17,8 @@ const app = express()
|
||||
const port = Number(runtimeConfig.server.port || 3000)
|
||||
|
||||
runDatabaseMigrations()
|
||||
await ensureFulfillmentCatalogBootstrapped()
|
||||
await ensureAdminUsersBootstrapped()
|
||||
await repairHistoricalOrders()
|
||||
|
||||
app.use((req, res, next) => {
|
||||
res.setHeader('Access-Control-Allow-Origin', '*')
|
||||
@@ -91,14 +91,6 @@ async function bootstrapOcr() {
|
||||
}
|
||||
}
|
||||
|
||||
async function repairHistoricalOrders() {
|
||||
try {
|
||||
await repairAgisoOrderData()
|
||||
} catch (error) {
|
||||
logWarn('[startup]', `历史 Agiso 咸鱼订单修复跳过: ${formatStartupError(error)}`)
|
||||
}
|
||||
}
|
||||
|
||||
function formatStartupError(error) {
|
||||
if (error instanceof Error && error.message) {
|
||||
return error.message.split('\n')[0].trim()
|
||||
|
||||
@@ -14,6 +14,16 @@ export async function createClaimToken(input) {
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
ON CONFLICT (task_id) DO UPDATE
|
||||
SET
|
||||
token = EXCLUDED.token,
|
||||
status = EXCLUDED.status,
|
||||
expired_at = EXCLUDED.expired_at,
|
||||
used_at = EXCLUDED.used_at,
|
||||
max_use_count = EXCLUDED.max_use_count,
|
||||
used_count = EXCLUDED.used_count,
|
||||
created_at = EXCLUDED.created_at,
|
||||
updated_at = EXCLUDED.updated_at
|
||||
RETURNING *
|
||||
`,
|
||||
[
|
||||
|
||||
@@ -2,10 +2,10 @@ import { query, withTransaction } from '../db/client.js'
|
||||
|
||||
const TASK_FIELDS = `
|
||||
ft.*,
|
||||
ct.id AS claim_token_id,
|
||||
ct.token AS claim_token,
|
||||
ct.status AS claim_token_status,
|
||||
ct.expired_at AS claim_token_expired_at,
|
||||
ct.id AS primary_claim_token_id,
|
||||
ct.token AS primary_claim_token,
|
||||
ct.status AS primary_claim_token_status,
|
||||
ct.expired_at AS primary_claim_expires_at,
|
||||
ctx.browser_session_id,
|
||||
ctx.login_type,
|
||||
ctx.nickname,
|
||||
@@ -16,10 +16,10 @@ const TASK_FIELDS = `
|
||||
ctx.screenshot_path,
|
||||
ctx.artifacts_json,
|
||||
ctx.state_json,
|
||||
inv.inventory_item_id AS reserved_cdk_id,
|
||||
inv.display_value AS cdk_code,
|
||||
inv.credential_type AS cdk_credential_type,
|
||||
inv.binding_status AS inventory_binding_status
|
||||
inv.inventory_item_id AS primary_inventory_item_id,
|
||||
inv.display_value AS primary_inventory_display_value,
|
||||
inv.credential_type AS primary_inventory_credential_type,
|
||||
inv.binding_status AS primary_inventory_binding_status
|
||||
`
|
||||
|
||||
const TASK_JOINS = `
|
||||
@@ -159,8 +159,11 @@ export async function updateTask(taskId, patch) {
|
||||
attempt_count = $11,
|
||||
last_error = $12,
|
||||
context_json = $13::jsonb,
|
||||
updated_at = $14
|
||||
WHERE id = $15
|
||||
claimed_at = $14,
|
||||
role_confirmed_at = $15,
|
||||
redeemed_at = $16,
|
||||
updated_at = $17
|
||||
WHERE id = $18
|
||||
`,
|
||||
[
|
||||
next.task_status,
|
||||
@@ -176,6 +179,9 @@ export async function updateTask(taskId, patch) {
|
||||
next.attempt_count || 0,
|
||||
next.last_error || '',
|
||||
next.context_json || '{}',
|
||||
next.claimed_at || null,
|
||||
next.role_confirmed_at || null,
|
||||
next.redeemed_at || null,
|
||||
next.updated_at,
|
||||
Number(taskId),
|
||||
],
|
||||
|
||||
@@ -1,463 +1,32 @@
|
||||
import { Router } from 'express'
|
||||
|
||||
import {
|
||||
closeAdminTask,
|
||||
createAdminCdk,
|
||||
getAdminAgisoShopConfigs,
|
||||
getAdminCdks,
|
||||
getAdminDashboardSummary,
|
||||
getAdminOrderDetail,
|
||||
getAdminOrders,
|
||||
getAdminTaskDetail,
|
||||
getAdminTaskScreenshotPath,
|
||||
getAdminTasks,
|
||||
getAdminWebhookEventDetail,
|
||||
getAdminWebhookEvents,
|
||||
importAdminCdks,
|
||||
invalidateAdminCdk,
|
||||
markAdminTaskManualReview,
|
||||
replayAdminWebhookEvent,
|
||||
releaseAdminInventoryCdk,
|
||||
regenerateAdminTaskClaimLink,
|
||||
releaseAdminTaskCdk,
|
||||
retryAdminTask,
|
||||
updateAdminAgisoShopConfigs,
|
||||
} from '../services/admin/admin-service.js'
|
||||
import {
|
||||
createManagedAdminUser,
|
||||
getAdminUserList,
|
||||
getAdminSessionSummary,
|
||||
loginAdmin,
|
||||
resetManagedAdminUserPassword,
|
||||
requireAdminRole,
|
||||
updateManagedAdminUserRole,
|
||||
updateManagedAdminUserStatus,
|
||||
verifyAdminSessionToken,
|
||||
} from '../services/admin/admin-auth-service.js'
|
||||
import { getAdminAuditLogs, writeAdminAuditLog } from '../services/admin/admin-audit-service.js'
|
||||
import { buildNotFoundPayload, buildSuccessPayload, createHttpError, sendRouteError } from '../utils/http.js'
|
||||
import authRouter from './admin/auth.js'
|
||||
import auditLogsRouter from './admin/audit-logs.js'
|
||||
import cdksRouter from './admin/cdks.js'
|
||||
import dashboardRouter from './admin/dashboard.js'
|
||||
import ordersRouter from './admin/orders.js'
|
||||
import platformConfigRouter from './admin/platform-config.js'
|
||||
import { requireAdminSession } from './admin/shared.js'
|
||||
import tasksRouter from './admin/tasks.js'
|
||||
import usersRouter from './admin/users.js'
|
||||
import webhookEventsRouter from './admin/webhook-events.js'
|
||||
import { buildNotFoundPayload } from '../utils/http.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.post('/auth/login', (req, res) => {
|
||||
try {
|
||||
const data = loginAdmin(req.body?.username, req.body?.password)
|
||||
res.json(buildSuccessPayload(data, '登录成功'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '后台登录失败', '[admin/auth/login]')
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/auth/session', (req, res) => {
|
||||
try {
|
||||
const data = getAdminSessionSummary(extractBearerToken(req))
|
||||
res.json(buildSuccessPayload(data, 'ok'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '读取后台登录态失败', '[admin/auth/session]')
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/auth/logout', (_req, res) => {
|
||||
res.json(buildSuccessPayload({ success: true }, '已退出登录'))
|
||||
})
|
||||
|
||||
router.use((req, res, next) => {
|
||||
try {
|
||||
req.adminSession = verifyAdminSessionToken(extractBearerToken(req))
|
||||
next()
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '后台鉴权失败', '[admin/auth]')
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/dashboard/summary', (req, res) => {
|
||||
try {
|
||||
const data = getAdminDashboardSummary()
|
||||
res.json(buildSuccessPayload(data, 'ok'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '读取后台概览失败', '[admin/dashboard/summary]')
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/users', (req, res) => {
|
||||
try {
|
||||
requireAdminRole(req.adminSession, ['admin'])
|
||||
const data = getAdminUserList(req.query)
|
||||
res.json(buildSuccessPayload(data, 'ok'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '读取后台用户列表失败', '[admin/users]')
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/users', (req, res) => {
|
||||
try {
|
||||
requireAdminRole(req.adminSession, ['admin'])
|
||||
const data = createManagedAdminUser(req.body)
|
||||
writeAdminAuditLog(req.adminSession, {
|
||||
action: 'admin_user_created',
|
||||
targetType: 'admin_user',
|
||||
targetId: String(data.user.userId),
|
||||
data: {
|
||||
username: data.user.username,
|
||||
role: data.user.role,
|
||||
status: data.user.status,
|
||||
},
|
||||
})
|
||||
res.json(buildSuccessPayload(data, '后台用户已创建'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '创建后台用户失败', '[admin/users:create]')
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/users/:userId/role', (req, res) => {
|
||||
try {
|
||||
requireAdminRole(req.adminSession, ['admin'])
|
||||
const data = updateManagedAdminUserRole(req.params.userId, req.body, req.adminSession)
|
||||
writeAdminAuditLog(req.adminSession, {
|
||||
action: 'admin_user_role_updated',
|
||||
targetType: 'admin_user',
|
||||
targetId: String(data.user.userId),
|
||||
data: {
|
||||
username: data.user.username,
|
||||
role: data.user.role,
|
||||
},
|
||||
})
|
||||
res.json(buildSuccessPayload(data, '用户角色已更新'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '更新用户角色失败', '[admin/users/:userId/role]')
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/users/:userId/status', (req, res) => {
|
||||
try {
|
||||
requireAdminRole(req.adminSession, ['admin'])
|
||||
const data = updateManagedAdminUserStatus(req.params.userId, req.body, req.adminSession)
|
||||
writeAdminAuditLog(req.adminSession, {
|
||||
action: 'admin_user_status_updated',
|
||||
targetType: 'admin_user',
|
||||
targetId: String(data.user.userId),
|
||||
data: {
|
||||
username: data.user.username,
|
||||
status: data.user.status,
|
||||
},
|
||||
})
|
||||
res.json(buildSuccessPayload(data, '用户状态已更新'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '更新用户状态失败', '[admin/users/:userId/status]')
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/users/:userId/reset-password', (req, res) => {
|
||||
try {
|
||||
requireAdminRole(req.adminSession, ['admin'])
|
||||
const data = resetManagedAdminUserPassword(req.params.userId, req.body)
|
||||
writeAdminAuditLog(req.adminSession, {
|
||||
action: 'admin_user_password_reset',
|
||||
targetType: 'admin_user',
|
||||
targetId: String(data.user.userId),
|
||||
data: {
|
||||
username: data.user.username,
|
||||
},
|
||||
})
|
||||
res.json(buildSuccessPayload(data, '用户密码已重置'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '重置用户密码失败', '[admin/users/:userId/reset-password]')
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/audit-logs', (req, res) => {
|
||||
try {
|
||||
requireAdminRole(req.adminSession, ['admin'])
|
||||
const data = getAdminAuditLogs(req.query)
|
||||
res.json(buildSuccessPayload(data, 'ok'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '读取操作审计日志失败', '[admin/audit-logs]')
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/platform-config/agiso-shops', (req, res) => {
|
||||
try {
|
||||
requireAdminRole(req.adminSession, ['admin'])
|
||||
const data = getAdminAgisoShopConfigs()
|
||||
res.json(buildSuccessPayload(data, 'ok'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '读取 Agiso 店铺配置失败', '[admin/platform-config/agiso-shops]')
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/platform-config/agiso-shops', (req, res) => {
|
||||
try {
|
||||
requireAdminRole(req.adminSession, ['admin'])
|
||||
const data = updateAdminAgisoShopConfigs(req.body)
|
||||
writeAdminAuditLog(req.adminSession, {
|
||||
action: 'platform_shop_config_updated',
|
||||
targetType: 'platform_config',
|
||||
targetId: 'agiso_shops',
|
||||
data: {
|
||||
shopCount: data.shops.length,
|
||||
filePath: data.filePath,
|
||||
},
|
||||
})
|
||||
res.json(buildSuccessPayload(data, 'Agiso 店铺配置已保存'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '保存 Agiso 店铺配置失败', '[admin/platform-config/agiso-shops]')
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/orders', (req, res) => {
|
||||
try {
|
||||
const data = getAdminOrders(req.query)
|
||||
res.json(buildSuccessPayload(data, 'ok'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '读取订单列表失败', '[admin/orders]')
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/orders/:orderId', (req, res) => {
|
||||
try {
|
||||
const data = getAdminOrderDetail(req.params.orderId)
|
||||
res.json(buildSuccessPayload(data, 'ok'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '读取订单详情失败', '[admin/orders/:orderId]')
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/tasks', (req, res) => {
|
||||
try {
|
||||
const data = getAdminTasks(req.query)
|
||||
res.json(buildSuccessPayload(data, 'ok'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '读取任务列表失败', '[admin/tasks]')
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/tasks/:taskId', (req, res) => {
|
||||
try {
|
||||
const data = getAdminTaskDetail(req.params.taskId)
|
||||
res.json(buildSuccessPayload(data, 'ok'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '读取任务详情失败', '[admin/tasks/:taskId]')
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/tasks/:taskId/screenshot', (req, res) => {
|
||||
try {
|
||||
const screenshotPath = getAdminTaskScreenshotPath(req.params.taskId)
|
||||
res.sendFile(screenshotPath)
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '读取任务截图失败', '[admin/tasks/:taskId/screenshot]')
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/tasks/:taskId/retry', (req, res) => {
|
||||
try {
|
||||
const data = retryAdminTask(req.params.taskId)
|
||||
res.json(buildSuccessPayload(data, '任务已重试'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '重试任务失败', '[admin/tasks/:taskId/retry]')
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/tasks/:taskId/release-cdk', (req, res) => {
|
||||
try {
|
||||
requireAdminRole(req.adminSession, ['admin'])
|
||||
const data = releaseAdminTaskCdk(req.params.taskId)
|
||||
writeAdminAuditLog(req.adminSession, {
|
||||
action: 'task_release_cdk',
|
||||
targetType: 'task',
|
||||
targetId: String(req.params.taskId),
|
||||
data: {
|
||||
taskId: data.task.taskId,
|
||||
taskNo: data.task.taskNo,
|
||||
reservedCdkId: data.task.reservedCdkId,
|
||||
},
|
||||
})
|
||||
res.json(buildSuccessPayload(data, 'CDK 已释放'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '释放 CDK 失败', '[admin/tasks/:taskId/release-cdk]')
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/tasks/:taskId/regenerate-claim-link', (req, res) => {
|
||||
try {
|
||||
requireAdminRole(req.adminSession, ['admin'])
|
||||
const data = regenerateAdminTaskClaimLink(req.params.taskId)
|
||||
writeAdminAuditLog(req.adminSession, {
|
||||
action: 'task_regenerate_claim_link',
|
||||
targetType: 'task',
|
||||
targetId: String(req.params.taskId),
|
||||
data: {
|
||||
taskId: data.task.taskId,
|
||||
taskNo: data.task.taskNo,
|
||||
claimTokenId: data.task.claimTokenId,
|
||||
},
|
||||
})
|
||||
res.json(buildSuccessPayload(data, '领取链接已重新生成'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '重新生成领取链接失败', '[admin/tasks/:taskId/regenerate-claim-link]')
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/tasks/:taskId/close', (req, res) => {
|
||||
try {
|
||||
requireAdminRole(req.adminSession, ['admin'])
|
||||
const data = closeAdminTask(req.params.taskId)
|
||||
writeAdminAuditLog(req.adminSession, {
|
||||
action: 'task_closed',
|
||||
targetType: 'task',
|
||||
targetId: String(req.params.taskId),
|
||||
data: {
|
||||
taskId: data.task.taskId,
|
||||
taskNo: data.task.taskNo,
|
||||
status: data.task.status,
|
||||
},
|
||||
})
|
||||
res.json(buildSuccessPayload(data, '任务已关闭'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '关闭任务失败', '[admin/tasks/:taskId/close]')
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/tasks/:taskId/mark-manual-review', (req, res) => {
|
||||
try {
|
||||
requireAdminRole(req.adminSession, ['admin'])
|
||||
const data = markAdminTaskManualReview(req.params.taskId)
|
||||
writeAdminAuditLog(req.adminSession, {
|
||||
action: 'task_mark_manual_review',
|
||||
targetType: 'task',
|
||||
targetId: String(req.params.taskId),
|
||||
data: {
|
||||
taskId: data.task.taskId,
|
||||
taskNo: data.task.taskNo,
|
||||
status: data.task.status,
|
||||
},
|
||||
})
|
||||
res.json(buildSuccessPayload(data, '任务已转人工处理'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '标记人工处理失败', '[admin/tasks/:taskId/mark-manual-review]')
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/cdks', (req, res) => {
|
||||
try {
|
||||
const data = getAdminCdks(req.query)
|
||||
res.json(buildSuccessPayload(data, 'ok'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '读取 CDK 列表失败', '[admin/cdks]')
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/cdks', (req, res) => {
|
||||
try {
|
||||
const data = createAdminCdk(req.body)
|
||||
res.json(buildSuccessPayload(data, 'CDK 已新增'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '新增 CDK 失败', '[admin/cdks]')
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/cdks/import', (req, res) => {
|
||||
try {
|
||||
const data = importAdminCdks(req.body)
|
||||
res.json(buildSuccessPayload(data, '导入完成'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '导入 CDK 失败', '[admin/cdks/import]')
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/cdks/:cdkId/release', (req, res) => {
|
||||
try {
|
||||
requireAdminRole(req.adminSession, ['admin'])
|
||||
const data = releaseAdminInventoryCdk(req.params.cdkId)
|
||||
writeAdminAuditLog(req.adminSession, {
|
||||
action: 'inventory_cdk_released',
|
||||
targetType: 'cdk',
|
||||
targetId: String(req.params.cdkId),
|
||||
data: {
|
||||
cdkId: data.cdk?.cdkId,
|
||||
skuCode: data.cdk?.skuCode,
|
||||
cdkCode: data.cdk?.cdkCode,
|
||||
},
|
||||
})
|
||||
res.json(buildSuccessPayload(data, 'CDK 已释放'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '释放库存 CDK 失败', '[admin/cdks/:cdkId/release]')
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/cdks/:cdkId/invalidate', (req, res) => {
|
||||
try {
|
||||
requireAdminRole(req.adminSession, ['admin'])
|
||||
const data = invalidateAdminCdk(req.params.cdkId, req.body)
|
||||
writeAdminAuditLog(req.adminSession, {
|
||||
action: 'inventory_cdk_invalidated',
|
||||
targetType: 'cdk',
|
||||
targetId: String(req.params.cdkId),
|
||||
data: {
|
||||
cdkId: data.cdk?.cdkId,
|
||||
skuCode: data.cdk?.skuCode,
|
||||
invalidReason: data.cdk?.invalidReason,
|
||||
},
|
||||
})
|
||||
res.json(buildSuccessPayload(data, 'CDK 已作废'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '作废 CDK 失败', '[admin/cdks/:cdkId/invalidate]')
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/webhook-events', (req, res) => {
|
||||
try {
|
||||
const data = getAdminWebhookEvents(req.query)
|
||||
res.json(buildSuccessPayload(data, 'ok'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '读取 webhook 列表失败', '[admin/webhook-events]')
|
||||
}
|
||||
})
|
||||
|
||||
router.get('/webhook-events/:eventId', (req, res) => {
|
||||
try {
|
||||
const data = getAdminWebhookEventDetail(req.params.eventId)
|
||||
res.json(buildSuccessPayload(data, 'ok'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '读取 webhook 详情失败', '[admin/webhook-events/:eventId]')
|
||||
}
|
||||
})
|
||||
|
||||
router.post('/webhook-events/:eventId/replay', async (req, res) => {
|
||||
try {
|
||||
requireAdminRole(req.adminSession, ['admin'])
|
||||
const data = await replayAdminWebhookEvent(req.params.eventId)
|
||||
writeAdminAuditLog(req.adminSession, {
|
||||
action: 'webhook_replayed',
|
||||
targetType: 'webhook_event',
|
||||
targetId: String(req.params.eventId),
|
||||
data: {
|
||||
eventId: data.eventId,
|
||||
replayed: data.replayed,
|
||||
},
|
||||
})
|
||||
res.json(buildSuccessPayload(data, 'Webhook 已重放'))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '重放 webhook 失败', '[admin/webhook-events/:eventId/replay]')
|
||||
}
|
||||
})
|
||||
router.use(authRouter)
|
||||
router.use(requireAdminSession)
|
||||
router.use(dashboardRouter)
|
||||
router.use(usersRouter)
|
||||
router.use(auditLogsRouter)
|
||||
router.use(platformConfigRouter)
|
||||
router.use(ordersRouter)
|
||||
router.use(tasksRouter)
|
||||
router.use(cdksRouter)
|
||||
router.use(webhookEventsRouter)
|
||||
|
||||
router.use((req, res) => {
|
||||
res.status(404).json(buildNotFoundPayload(req))
|
||||
})
|
||||
|
||||
export default router
|
||||
|
||||
function extractBearerToken(req) {
|
||||
const authorization = String(req.headers.authorization || '').trim()
|
||||
const matched = authorization.match(/^Bearer\s+(.+)$/i)
|
||||
|
||||
if (!matched) {
|
||||
throw createHttpError('未登录或登录已失效', {
|
||||
statusCode: 401,
|
||||
errorCode: 'admin_auth_required',
|
||||
})
|
||||
}
|
||||
|
||||
return matched[1]
|
||||
}
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Router } from 'express'
|
||||
|
||||
import { getAdminAuditLogs } from '../../services/admin/admin-audit-service.js'
|
||||
import { createJsonHandler, requireAdminRoles } from './shared.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.use(requireAdminRoles(['admin']))
|
||||
|
||||
router.get('/audit-logs', createJsonHandler(
|
||||
(req) => getAdminAuditLogs(req.query),
|
||||
{
|
||||
successMessage: 'ok',
|
||||
errorMessage: '读取操作审计日志失败',
|
||||
scope: '[admin/audit-logs]',
|
||||
},
|
||||
))
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Router } from 'express'
|
||||
|
||||
import { getAdminSessionSummary, loginAdmin } from '../../services/admin/admin-auth-service.js'
|
||||
import { createJsonHandler, extractBearerToken } from './shared.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.post('/auth/login', createJsonHandler(
|
||||
(req) => loginAdmin(req.body?.username, req.body?.password),
|
||||
{
|
||||
successMessage: '登录成功',
|
||||
errorMessage: '后台登录失败',
|
||||
scope: '[admin/auth/login]',
|
||||
},
|
||||
))
|
||||
|
||||
router.get('/auth/session', createJsonHandler(
|
||||
(req) => getAdminSessionSummary(extractBearerToken(req)),
|
||||
{
|
||||
successMessage: 'ok',
|
||||
errorMessage: '读取后台登录态失败',
|
||||
scope: '[admin/auth/session]',
|
||||
},
|
||||
))
|
||||
|
||||
router.post('/auth/logout', createJsonHandler(
|
||||
() => ({ success: true }),
|
||||
{
|
||||
successMessage: '已退出登录',
|
||||
errorMessage: '后台退出失败',
|
||||
scope: '[admin/auth/logout]',
|
||||
},
|
||||
))
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,79 @@
|
||||
import { Router } from 'express'
|
||||
|
||||
import {
|
||||
createAdminCdk,
|
||||
getAdminCdks,
|
||||
importAdminCdks,
|
||||
invalidateAdminCdk,
|
||||
releaseAdminInventoryCdk,
|
||||
} from '../../services/admin/admin-service.js'
|
||||
import { createJsonHandler, requireAdminRoles } from './shared.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.get('/cdks', createJsonHandler(
|
||||
(req) => getAdminCdks(req.query),
|
||||
{
|
||||
successMessage: 'ok',
|
||||
errorMessage: '读取 CDK 列表失败',
|
||||
scope: '[admin/cdks]',
|
||||
},
|
||||
))
|
||||
|
||||
router.post('/cdks', createJsonHandler(
|
||||
(req) => createAdminCdk(req.body),
|
||||
{
|
||||
successMessage: 'CDK 已新增',
|
||||
errorMessage: '新增 CDK 失败',
|
||||
scope: '[admin/cdks]',
|
||||
},
|
||||
))
|
||||
|
||||
router.post('/cdks/import', createJsonHandler(
|
||||
(req) => importAdminCdks(req.body),
|
||||
{
|
||||
successMessage: '导入完成',
|
||||
errorMessage: '导入 CDK 失败',
|
||||
scope: '[admin/cdks/import]',
|
||||
},
|
||||
))
|
||||
|
||||
router.post('/cdks/:cdkId/release', requireAdminRoles(['admin']), createJsonHandler(
|
||||
(req) => releaseAdminInventoryCdk(req.params.cdkId),
|
||||
{
|
||||
successMessage: 'CDK 已释放',
|
||||
errorMessage: '释放库存 CDK 失败',
|
||||
scope: '[admin/cdks/:cdkId/release]',
|
||||
audit: (req, data) => ({
|
||||
action: 'inventory_cdk_released',
|
||||
targetType: 'cdk',
|
||||
targetId: String(req.params.cdkId),
|
||||
data: {
|
||||
cdkId: data.cdk?.cdkId,
|
||||
skuCode: data.cdk?.skuCode,
|
||||
cdkCode: data.cdk?.cdkCode,
|
||||
},
|
||||
}),
|
||||
},
|
||||
))
|
||||
|
||||
router.post('/cdks/:cdkId/invalidate', requireAdminRoles(['admin']), createJsonHandler(
|
||||
(req) => invalidateAdminCdk(req.params.cdkId, req.body),
|
||||
{
|
||||
successMessage: 'CDK 已作废',
|
||||
errorMessage: '作废 CDK 失败',
|
||||
scope: '[admin/cdks/:cdkId/invalidate]',
|
||||
audit: (req, data) => ({
|
||||
action: 'inventory_cdk_invalidated',
|
||||
targetType: 'cdk',
|
||||
targetId: String(req.params.cdkId),
|
||||
data: {
|
||||
cdkId: data.cdk?.cdkId,
|
||||
skuCode: data.cdk?.skuCode,
|
||||
invalidReason: data.cdk?.invalidReason,
|
||||
},
|
||||
}),
|
||||
},
|
||||
))
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,17 @@
|
||||
import { Router } from 'express'
|
||||
|
||||
import { getAdminDashboardSummary } from '../../services/admin/admin-service.js'
|
||||
import { createJsonHandler } from './shared.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.get('/dashboard/summary', createJsonHandler(
|
||||
() => getAdminDashboardSummary(),
|
||||
{
|
||||
successMessage: 'ok',
|
||||
errorMessage: '读取后台概览失败',
|
||||
scope: '[admin/dashboard/summary]',
|
||||
},
|
||||
))
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Router } from 'express'
|
||||
|
||||
import { getAdminOrderDetail, getAdminOrders } from '../../services/admin/admin-service.js'
|
||||
import { createJsonHandler } from './shared.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.get('/orders', createJsonHandler(
|
||||
(req) => getAdminOrders(req.query),
|
||||
{
|
||||
successMessage: 'ok',
|
||||
errorMessage: '读取订单列表失败',
|
||||
scope: '[admin/orders]',
|
||||
},
|
||||
))
|
||||
|
||||
router.get('/orders/:orderId', createJsonHandler(
|
||||
(req) => getAdminOrderDetail(req.params.orderId),
|
||||
{
|
||||
successMessage: 'ok',
|
||||
errorMessage: '读取订单详情失败',
|
||||
scope: '[admin/orders/:orderId]',
|
||||
},
|
||||
))
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,37 @@
|
||||
import { Router } from 'express'
|
||||
|
||||
import { getAdminAgisoShopConfigs, updateAdminAgisoShopConfigs } from '../../services/admin/admin-service.js'
|
||||
import { createJsonHandler, requireAdminRoles } from './shared.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.use(requireAdminRoles(['admin']))
|
||||
|
||||
router.get('/platform-config/agiso-shops', createJsonHandler(
|
||||
() => getAdminAgisoShopConfigs(),
|
||||
{
|
||||
successMessage: 'ok',
|
||||
errorMessage: '读取 Agiso 店铺配置失败',
|
||||
scope: '[admin/platform-config/agiso-shops]',
|
||||
},
|
||||
))
|
||||
|
||||
router.post('/platform-config/agiso-shops', createJsonHandler(
|
||||
(req) => updateAdminAgisoShopConfigs(req.body),
|
||||
{
|
||||
successMessage: 'Agiso 店铺配置已保存',
|
||||
errorMessage: '保存 Agiso 店铺配置失败',
|
||||
scope: '[admin/platform-config/agiso-shops]',
|
||||
audit: (_req, data) => ({
|
||||
action: 'platform_shop_config_updated',
|
||||
targetType: 'platform_config',
|
||||
targetId: 'agiso_shops',
|
||||
data: {
|
||||
shopCount: data.shops.length,
|
||||
filePath: data.filePath,
|
||||
},
|
||||
}),
|
||||
},
|
||||
))
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,84 @@
|
||||
import { requireAdminRole, verifyAdminSessionToken } from '../../services/admin/admin-auth-service.js'
|
||||
import { writeAdminAuditLog } from '../../services/admin/admin-audit-service.js'
|
||||
import { buildSuccessPayload, createHttpError, sendRouteError } from '../../utils/http.js'
|
||||
import { logWarn } from '../../utils/logger.js'
|
||||
|
||||
export function createJsonHandler(action, { successMessage = 'ok', errorMessage, scope, audit } = {}) {
|
||||
return async (req, res) => {
|
||||
try {
|
||||
const data = await action(req, res)
|
||||
await recordAdminAudit(req.adminSession, req, data, audit)
|
||||
res.json(buildSuccessPayload(data, successMessage))
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, errorMessage, scope)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function createFileHandler(action, { errorMessage, scope } = {}) {
|
||||
return async (req, res) => {
|
||||
try {
|
||||
const filePath = await action(req, res)
|
||||
res.sendFile(filePath)
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, errorMessage, scope)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function requireAdminSession(req, res, next) {
|
||||
try {
|
||||
req.adminSession = await verifyAdminSessionToken(extractBearerToken(req))
|
||||
next()
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '后台鉴权失败', '[admin/auth]')
|
||||
}
|
||||
}
|
||||
|
||||
export function requireAdminRoles(allowedRoles) {
|
||||
return (req, res, next) => {
|
||||
try {
|
||||
requireAdminRole(req.adminSession, allowedRoles)
|
||||
next()
|
||||
} catch (error) {
|
||||
sendRouteError(res, error, '后台鉴权失败', '[admin/auth/role]')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function recordAdminAudit(session, req, data, audit) {
|
||||
if (!audit) {
|
||||
return
|
||||
}
|
||||
|
||||
const payload = typeof audit === 'function' ? audit(req, data) : audit
|
||||
|
||||
if (!payload) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
await writeAdminAuditLog(session, payload)
|
||||
} catch (error) {
|
||||
logWarn('[admin/audit]', '后台审计日志写入失败,已跳过', {
|
||||
action: payload.action,
|
||||
targetType: payload.targetType,
|
||||
targetId: payload.targetId,
|
||||
error,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export function extractBearerToken(req) {
|
||||
const authorization = String(req.headers.authorization || '').trim()
|
||||
const matched = authorization.match(/^Bearer\s+(.+)$/i)
|
||||
|
||||
if (!matched) {
|
||||
throw createHttpError('未登录或登录已失效', {
|
||||
statusCode: 401,
|
||||
errorCode: 'admin_auth_required',
|
||||
})
|
||||
}
|
||||
|
||||
return matched[1]
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { Router } from 'express'
|
||||
|
||||
import {
|
||||
closeAdminTask,
|
||||
getAdminTaskDetail,
|
||||
getAdminTaskScreenshotPath,
|
||||
getAdminTasks,
|
||||
markAdminTaskManualReview,
|
||||
regenerateAdminTaskClaimLink,
|
||||
releaseAdminTaskCdk,
|
||||
retryAdminTask,
|
||||
} from '../../services/admin/admin-service.js'
|
||||
import { createFileHandler, createJsonHandler, requireAdminRoles } from './shared.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.get('/tasks', createJsonHandler(
|
||||
(req) => getAdminTasks(req.query),
|
||||
{
|
||||
successMessage: 'ok',
|
||||
errorMessage: '读取任务列表失败',
|
||||
scope: '[admin/tasks]',
|
||||
},
|
||||
))
|
||||
|
||||
router.get('/tasks/:taskId', createJsonHandler(
|
||||
(req) => getAdminTaskDetail(req.params.taskId),
|
||||
{
|
||||
successMessage: 'ok',
|
||||
errorMessage: '读取任务详情失败',
|
||||
scope: '[admin/tasks/:taskId]',
|
||||
},
|
||||
))
|
||||
|
||||
router.get('/tasks/:taskId/screenshot', createFileHandler(
|
||||
(req) => getAdminTaskScreenshotPath(req.params.taskId),
|
||||
{
|
||||
errorMessage: '读取任务截图失败',
|
||||
scope: '[admin/tasks/:taskId/screenshot]',
|
||||
},
|
||||
))
|
||||
|
||||
router.post('/tasks/:taskId/retry', createJsonHandler(
|
||||
(req) => retryAdminTask(req.params.taskId),
|
||||
{
|
||||
successMessage: '任务已重试',
|
||||
errorMessage: '重试任务失败',
|
||||
scope: '[admin/tasks/:taskId/retry]',
|
||||
},
|
||||
))
|
||||
|
||||
router.post('/tasks/:taskId/release-cdk', requireAdminRoles(['admin']), createJsonHandler(
|
||||
(req) => releaseAdminTaskCdk(req.params.taskId),
|
||||
{
|
||||
successMessage: 'CDK 已释放',
|
||||
errorMessage: '释放 CDK 失败',
|
||||
scope: '[admin/tasks/:taskId/release-cdk]',
|
||||
audit: (req, data) => ({
|
||||
action: 'task_release_cdk',
|
||||
targetType: 'task',
|
||||
targetId: String(req.params.taskId),
|
||||
data: {
|
||||
taskId: data.task.taskId,
|
||||
taskNo: data.task.taskNo,
|
||||
inventoryItemId: data.task.inventoryItemId,
|
||||
},
|
||||
}),
|
||||
},
|
||||
))
|
||||
|
||||
router.post('/tasks/:taskId/regenerate-claim-link', requireAdminRoles(['admin']), createJsonHandler(
|
||||
(req) => regenerateAdminTaskClaimLink(req.params.taskId),
|
||||
{
|
||||
successMessage: '领取链接已重新生成',
|
||||
errorMessage: '重新生成领取链接失败',
|
||||
scope: '[admin/tasks/:taskId/regenerate-claim-link]',
|
||||
audit: (req, data) => ({
|
||||
action: 'task_regenerate_claim_link',
|
||||
targetType: 'task',
|
||||
targetId: String(req.params.taskId),
|
||||
data: {
|
||||
taskId: data.task.taskId,
|
||||
taskNo: data.task.taskNo,
|
||||
claimTokenId: data.task.claimTokenId,
|
||||
},
|
||||
}),
|
||||
},
|
||||
))
|
||||
|
||||
router.post('/tasks/:taskId/close', requireAdminRoles(['admin']), createJsonHandler(
|
||||
(req) => closeAdminTask(req.params.taskId),
|
||||
{
|
||||
successMessage: '任务已关闭',
|
||||
errorMessage: '关闭任务失败',
|
||||
scope: '[admin/tasks/:taskId/close]',
|
||||
audit: (req, data) => ({
|
||||
action: 'task_closed',
|
||||
targetType: 'task',
|
||||
targetId: String(req.params.taskId),
|
||||
data: {
|
||||
taskId: data.task.taskId,
|
||||
taskNo: data.task.taskNo,
|
||||
status: data.task.status,
|
||||
},
|
||||
}),
|
||||
},
|
||||
))
|
||||
|
||||
router.post('/tasks/:taskId/mark-manual-review', requireAdminRoles(['admin']), createJsonHandler(
|
||||
(req) => markAdminTaskManualReview(req.params.taskId),
|
||||
{
|
||||
successMessage: '任务已转人工处理',
|
||||
errorMessage: '标记人工处理失败',
|
||||
scope: '[admin/tasks/:taskId/mark-manual-review]',
|
||||
audit: (req, data) => ({
|
||||
action: 'task_mark_manual_review',
|
||||
targetType: 'task',
|
||||
targetId: String(req.params.taskId),
|
||||
data: {
|
||||
taskId: data.task.taskId,
|
||||
taskNo: data.task.taskNo,
|
||||
status: data.task.status,
|
||||
},
|
||||
}),
|
||||
},
|
||||
))
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,97 @@
|
||||
import { Router } from 'express'
|
||||
|
||||
import {
|
||||
createManagedAdminUser,
|
||||
getAdminUserList,
|
||||
resetManagedAdminUserPassword,
|
||||
updateManagedAdminUserRole,
|
||||
updateManagedAdminUserStatus,
|
||||
} from '../../services/admin/admin-auth-service.js'
|
||||
import { createJsonHandler, requireAdminRoles } from './shared.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.use(requireAdminRoles(['admin']))
|
||||
|
||||
router.get('/users', createJsonHandler(
|
||||
(req) => getAdminUserList(req.query),
|
||||
{
|
||||
successMessage: 'ok',
|
||||
errorMessage: '读取后台用户列表失败',
|
||||
scope: '[admin/users]',
|
||||
},
|
||||
))
|
||||
|
||||
router.post('/users', createJsonHandler(
|
||||
(req) => createManagedAdminUser(req.body),
|
||||
{
|
||||
successMessage: '后台用户已创建',
|
||||
errorMessage: '创建后台用户失败',
|
||||
scope: '[admin/users:create]',
|
||||
audit: (_req, data) => ({
|
||||
action: 'admin_user_created',
|
||||
targetType: 'admin_user',
|
||||
targetId: String(data.user.userId),
|
||||
data: {
|
||||
username: data.user.username,
|
||||
role: data.user.role,
|
||||
status: data.user.status,
|
||||
},
|
||||
}),
|
||||
},
|
||||
))
|
||||
|
||||
router.post('/users/:userId/role', createJsonHandler(
|
||||
(req) => updateManagedAdminUserRole(req.params.userId, req.body, req.adminSession),
|
||||
{
|
||||
successMessage: '用户角色已更新',
|
||||
errorMessage: '更新用户角色失败',
|
||||
scope: '[admin/users/:userId/role]',
|
||||
audit: (_req, data) => ({
|
||||
action: 'admin_user_role_updated',
|
||||
targetType: 'admin_user',
|
||||
targetId: String(data.user.userId),
|
||||
data: {
|
||||
username: data.user.username,
|
||||
role: data.user.role,
|
||||
},
|
||||
}),
|
||||
},
|
||||
))
|
||||
|
||||
router.post('/users/:userId/status', createJsonHandler(
|
||||
(req) => updateManagedAdminUserStatus(req.params.userId, req.body, req.adminSession),
|
||||
{
|
||||
successMessage: '用户状态已更新',
|
||||
errorMessage: '更新用户状态失败',
|
||||
scope: '[admin/users/:userId/status]',
|
||||
audit: (_req, data) => ({
|
||||
action: 'admin_user_status_updated',
|
||||
targetType: 'admin_user',
|
||||
targetId: String(data.user.userId),
|
||||
data: {
|
||||
username: data.user.username,
|
||||
status: data.user.status,
|
||||
},
|
||||
}),
|
||||
},
|
||||
))
|
||||
|
||||
router.post('/users/:userId/reset-password', createJsonHandler(
|
||||
(req) => resetManagedAdminUserPassword(req.params.userId, req.body),
|
||||
{
|
||||
successMessage: '用户密码已重置',
|
||||
errorMessage: '重置用户密码失败',
|
||||
scope: '[admin/users/:userId/reset-password]',
|
||||
audit: (_req, data) => ({
|
||||
action: 'admin_user_password_reset',
|
||||
targetType: 'admin_user',
|
||||
targetId: String(data.user.userId),
|
||||
data: {
|
||||
username: data.user.username,
|
||||
},
|
||||
}),
|
||||
},
|
||||
))
|
||||
|
||||
export default router
|
||||
@@ -0,0 +1,48 @@
|
||||
import { Router } from 'express'
|
||||
|
||||
import {
|
||||
getAdminWebhookEventDetail,
|
||||
getAdminWebhookEvents,
|
||||
replayAdminWebhookEvent,
|
||||
} from '../../services/admin/admin-service.js'
|
||||
import { createJsonHandler, requireAdminRoles } from './shared.js'
|
||||
|
||||
const router = Router()
|
||||
|
||||
router.get('/webhook-events', createJsonHandler(
|
||||
(req) => getAdminWebhookEvents(req.query),
|
||||
{
|
||||
successMessage: 'ok',
|
||||
errorMessage: '读取 webhook 列表失败',
|
||||
scope: '[admin/webhook-events]',
|
||||
},
|
||||
))
|
||||
|
||||
router.get('/webhook-events/:eventId', createJsonHandler(
|
||||
(req) => getAdminWebhookEventDetail(req.params.eventId),
|
||||
{
|
||||
successMessage: 'ok',
|
||||
errorMessage: '读取 webhook 详情失败',
|
||||
scope: '[admin/webhook-events/:eventId]',
|
||||
},
|
||||
))
|
||||
|
||||
router.post('/webhook-events/:eventId/replay', requireAdminRoles(['admin']), createJsonHandler(
|
||||
(req) => replayAdminWebhookEvent(req.params.eventId),
|
||||
{
|
||||
successMessage: 'Webhook 已重放',
|
||||
errorMessage: '重放 webhook 失败',
|
||||
scope: '[admin/webhook-events/:eventId/replay]',
|
||||
audit: (req, data) => ({
|
||||
action: 'webhook_replayed',
|
||||
targetType: 'webhook_event',
|
||||
targetId: String(req.params.eventId),
|
||||
data: {
|
||||
eventId: data.eventId,
|
||||
replayed: data.replayed,
|
||||
},
|
||||
}),
|
||||
},
|
||||
))
|
||||
|
||||
export default router
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createAdminAuditLog, listAdminAuditLogs } from '../../repositories/admin-audit-log-repo.js'
|
||||
import { nowIso } from '../../utils/time.js'
|
||||
import { normalizeDateQuery, normalizePage, normalizePageSize, safeParseJson } from './admin-query-utils.js'
|
||||
|
||||
export async function writeAdminAuditLog(session, payload = {}) {
|
||||
if (!session?.userId) {
|
||||
@@ -46,38 +47,3 @@ export async function getAdminAuditLogs(query = {}) {
|
||||
pagination: { page, pageSize, total },
|
||||
}
|
||||
}
|
||||
|
||||
function normalizePage(rawValue) {
|
||||
const parsed = Number(rawValue)
|
||||
return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 1
|
||||
}
|
||||
|
||||
function normalizePageSize(rawValue) {
|
||||
const parsed = Number(rawValue)
|
||||
if (!Number.isFinite(parsed) || parsed <= 0) {
|
||||
return 20
|
||||
}
|
||||
return Math.min(100, Math.floor(parsed))
|
||||
}
|
||||
|
||||
function normalizeDateQuery(rawValue, endOfDay = false) {
|
||||
const normalized = String(rawValue || '').trim()
|
||||
|
||||
if (!normalized) {
|
||||
return ''
|
||||
}
|
||||
|
||||
if (/^\d{4}-\d{2}-\d{2}$/.test(normalized)) {
|
||||
return endOfDay ? `${normalized}T23:59:59.999Z` : `${normalized}T00:00:00.000Z`
|
||||
}
|
||||
|
||||
return normalized
|
||||
}
|
||||
|
||||
function safeParseJson(value) {
|
||||
try {
|
||||
return typeof value === 'string' ? JSON.parse(value) : value || {}
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
} from '../../repositories/admin-user-repo.js'
|
||||
import { addHours, nowIso } from '../../utils/time.js'
|
||||
import { createHttpError } from '../../utils/http.js'
|
||||
import { normalizePage, normalizePageSize } from './admin-query-utils.js'
|
||||
|
||||
export async function ensureAdminUsersBootstrapped() {
|
||||
ensureAdminAuthConfigured()
|
||||
@@ -360,19 +361,6 @@ function safeCompare(input, expected) {
|
||||
return crypto.timingSafeEqual(left, right)
|
||||
}
|
||||
|
||||
function normalizePage(rawValue) {
|
||||
const parsed = Number(rawValue)
|
||||
return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 1
|
||||
}
|
||||
|
||||
function normalizePageSize(rawValue) {
|
||||
const parsed = Number(rawValue)
|
||||
if (!Number.isFinite(parsed) || parsed <= 0) {
|
||||
return 20
|
||||
}
|
||||
return Math.min(100, Math.floor(parsed))
|
||||
}
|
||||
|
||||
function normalizeRoleQuery(role) {
|
||||
const normalized = String(role || '').trim().toLowerCase()
|
||||
return ['admin', 'operator'].includes(normalized) ? normalized : ''
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
export function normalizePage(rawValue) {
|
||||
const parsed = Number(rawValue)
|
||||
return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 1
|
||||
}
|
||||
|
||||
export function normalizePageSize(rawValue) {
|
||||
const parsed = Number(rawValue)
|
||||
if (!Number.isFinite(parsed) || parsed <= 0) {
|
||||
return 20
|
||||
}
|
||||
return Math.min(100, Math.floor(parsed))
|
||||
}
|
||||
|
||||
export function normalizeDateQuery(rawValue, endOfDay = false) {
|
||||
const normalized = String(rawValue || '').trim()
|
||||
|
||||
if (!normalized) {
|
||||
return ''
|
||||
}
|
||||
|
||||
if (/^\d{4}-\d{2}-\d{2}$/.test(normalized)) {
|
||||
return endOfDay ? `${normalized}T23:59:59.999Z` : `${normalized}T00:00:00.000Z`
|
||||
}
|
||||
|
||||
return normalized
|
||||
}
|
||||
|
||||
export function safeParseJson(rawText) {
|
||||
if (rawText && typeof rawText === 'object') {
|
||||
return rawText
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(String(rawText || '{}'))
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { runtimeConfig } from '../../config/runtime.js'
|
||||
import { getDb } from '../../db/client.js'
|
||||
import { query } from '../../db/client.js'
|
||||
import { createTaskClaimToken } from '../claim/claim-service.js'
|
||||
import {
|
||||
getAgisoShopConfig,
|
||||
@@ -18,19 +18,45 @@ import { formatFenToAmount, normalizeFen, parseAmountToFen } from '../../utils/m
|
||||
import { nowIso } from '../../utils/time.js'
|
||||
import { reserveCdkForTask } from '../order/cdk-service.js'
|
||||
import { replayAgisoTradeWebhookEvent } from '../order/webhook-service.js'
|
||||
import { normalizeDateQuery, normalizePage, normalizePageSize, safeParseJson } from './admin-query-utils.js'
|
||||
|
||||
export function getAdminDashboardSummary() {
|
||||
const db = getDb()
|
||||
export async function getAdminDashboardSummary() {
|
||||
const todayPrefix = nowIso().slice(0, 10)
|
||||
const summary = db.prepare(`
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM orders WHERE substr(created_at, 1, 10) = ?) AS today_orders,
|
||||
(SELECT COUNT(*) FROM delivery_tasks WHERE task_status IN ('paid', 'cdk_reserved', 'link_generated')) AS paid_pending_claim,
|
||||
(SELECT COUNT(*) FROM delivery_tasks WHERE task_status IN ('claimed', 'role_confirmed', 'redeeming')) AS claiming_tasks,
|
||||
(SELECT COUNT(*) FROM delivery_tasks WHERE task_status = 'redeemed' AND substr(updated_at, 1, 10) = ?) AS redeemed_today,
|
||||
(SELECT COUNT(*) FROM delivery_tasks WHERE task_status IN ('retry_pending', 'manual_review', 'waiting_inventory')) AS abnormal_tasks,
|
||||
(SELECT COUNT(DISTINCT sku_code) FROM cdk_inventory WHERE status = 'available') AS sku_with_inventory
|
||||
`).get(todayPrefix, todayPrefix)
|
||||
const result = await query(
|
||||
`
|
||||
SELECT
|
||||
(SELECT COUNT(*)::int FROM orders WHERE to_char(created_at AT TIME ZONE 'Asia/Shanghai', 'YYYY-MM-DD') = $1) AS today_orders,
|
||||
(
|
||||
SELECT COUNT(*)::int
|
||||
FROM fulfillment_tasks
|
||||
WHERE task_status IN ('paid', 'link_generated')
|
||||
OR (inventory_status = 'reserved' AND task_status NOT IN ('claimed', 'role_confirmed', 'redeeming', 'redeemed', 'closed', 'expired'))
|
||||
) AS paid_pending_claim,
|
||||
(
|
||||
SELECT COUNT(*)::int
|
||||
FROM fulfillment_tasks
|
||||
WHERE task_status IN ('claimed', 'role_confirmed', 'redeeming')
|
||||
) AS claiming_tasks,
|
||||
(
|
||||
SELECT COUNT(*)::int
|
||||
FROM fulfillment_tasks
|
||||
WHERE task_status = 'redeemed'
|
||||
AND to_char(updated_at AT TIME ZONE 'Asia/Shanghai', 'YYYY-MM-DD') = $1
|
||||
) AS redeemed_today,
|
||||
(
|
||||
SELECT COUNT(*)::int
|
||||
FROM fulfillment_tasks
|
||||
WHERE task_status IN ('retry_pending', 'manual_review', 'waiting_inventory')
|
||||
) AS abnormal_tasks,
|
||||
(
|
||||
SELECT COUNT(DISTINCT sku_code)::int
|
||||
FROM inventory_items
|
||||
WHERE status = 'available'
|
||||
) AS sku_with_inventory
|
||||
`,
|
||||
[todayPrefix],
|
||||
)
|
||||
const summary = result.rows[0] || {}
|
||||
|
||||
return {
|
||||
todayOrders: Number(summary?.today_orders || 0),
|
||||
@@ -42,10 +68,10 @@ export function getAdminDashboardSummary() {
|
||||
}
|
||||
}
|
||||
|
||||
export function getAdminOrders(query = {}) {
|
||||
export async function getAdminOrders(query = {}) {
|
||||
const page = normalizePage(query.page)
|
||||
const pageSize = normalizePageSize(query.pageSize)
|
||||
const { items, total } = listOrders({
|
||||
const { items, total } = await listOrders({
|
||||
page,
|
||||
pageSize,
|
||||
platformOrderId: String(query.platformOrderId || '').trim(),
|
||||
@@ -56,13 +82,13 @@ export function getAdminOrders(query = {}) {
|
||||
})
|
||||
|
||||
return {
|
||||
items: items.map(mapAdminOrderListItem),
|
||||
items: await Promise.all(items.map((item) => mapAdminOrderListItem(item))),
|
||||
pagination: { page, pageSize, total },
|
||||
}
|
||||
}
|
||||
|
||||
export function getAdminOrderDetail(orderId) {
|
||||
const order = getOrderById(Number(orderId))
|
||||
export async function getAdminOrderDetail(orderId) {
|
||||
const order = await getOrderById(Number(orderId))
|
||||
|
||||
if (!order) {
|
||||
throw createHttpError('订单不存在', {
|
||||
@@ -71,9 +97,11 @@ export function getAdminOrderDetail(orderId) {
|
||||
})
|
||||
}
|
||||
|
||||
const items = listOrderItemsByOrderId(order.id)
|
||||
const tasks = listTasksByOrderId(order.id)
|
||||
const webhookEvents = listWebhookEventsByOrderId(order.id)
|
||||
const [items, tasks, webhookEvents] = await Promise.all([
|
||||
listOrderItemsByOrderId(order.id),
|
||||
listTasksByOrderId(order.id),
|
||||
listWebhookEventsByOrderId(order.id),
|
||||
])
|
||||
const itemSummary = summarizeOrderItems(items)
|
||||
|
||||
return {
|
||||
@@ -105,7 +133,7 @@ export function getAdminOrderDetail(orderId) {
|
||||
skuName: item.sku_name,
|
||||
itemTitle: resolveOrderItemTitle(item),
|
||||
quantity: item.quantity,
|
||||
deliveryMode: item.delivery_mode,
|
||||
deliveryMode: resolveOrderItemDeliveryMode(tasks, item.id),
|
||||
spec: safeParseJson(item.spec_json),
|
||||
})),
|
||||
tasks: tasks.map(mapAdminTaskSummary),
|
||||
@@ -125,10 +153,10 @@ export function getAdminOrderDetail(orderId) {
|
||||
}
|
||||
}
|
||||
|
||||
export function getAdminTasks(query = {}) {
|
||||
export async function getAdminTasks(query = {}) {
|
||||
const page = normalizePage(query.page)
|
||||
const pageSize = normalizePageSize(query.pageSize)
|
||||
const { items, total } = listTasks({
|
||||
const { items, total } = await listTasks({
|
||||
page,
|
||||
pageSize,
|
||||
status: String(query.status || '').trim(),
|
||||
@@ -146,8 +174,8 @@ export function getAdminTasks(query = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
export function getAdminTaskDetail(taskId) {
|
||||
const task = getTaskById(Number(taskId))
|
||||
export async function getAdminTaskDetail(taskId) {
|
||||
const task = await getTaskById(Number(taskId))
|
||||
|
||||
if (!task) {
|
||||
throw createHttpError('任务不存在', {
|
||||
@@ -156,10 +184,13 @@ export function getAdminTaskDetail(taskId) {
|
||||
})
|
||||
}
|
||||
|
||||
const order = getOrderById(task.order_id)
|
||||
const orderItem = order ? listOrderItemsByOrderId(order.id).find((item) => item.id === task.order_item_id) || null : null
|
||||
const claimToken = task.claim_token_id ? getClaimTokenById(task.claim_token_id) : null
|
||||
const cdk = task.reserved_cdk_id ? getCdkById(task.reserved_cdk_id) : null
|
||||
const [order, claimToken, cdk] = await Promise.all([
|
||||
getOrderById(task.order_id),
|
||||
getTaskPrimaryClaimTokenId(task) ? getClaimTokenById(getTaskPrimaryClaimTokenId(task)) : Promise.resolve(null),
|
||||
getTaskPrimaryInventoryItemId(task) ? getCdkById(getTaskPrimaryInventoryItemId(task)) : Promise.resolve(null),
|
||||
])
|
||||
const orderItems = order ? await listOrderItemsByOrderId(order.id) : []
|
||||
const orderItem = orderItems.find((item) => item.id === task.order_item_id) || null
|
||||
|
||||
return {
|
||||
task: mapAdminTaskListItem({
|
||||
@@ -210,7 +241,7 @@ export function getAdminTaskDetail(taskId) {
|
||||
screenshotUrl: task.screenshot_path ? `/api/v1/admin/tasks/${task.id}/screenshot` : '',
|
||||
operations: {
|
||||
canRetry: ['retry_pending', 'manual_review', 'waiting_inventory'].includes(task.task_status),
|
||||
canReleaseCdk: Boolean(task.reserved_cdk_id && ['link_generated', 'retry_pending', 'manual_review', 'waiting_inventory', 'closed'].includes(task.task_status)),
|
||||
canReleaseCdk: Boolean(getTaskPrimaryInventoryItemId(task) && ['link_generated', 'retry_pending', 'manual_review', 'waiting_inventory', 'closed'].includes(task.task_status)),
|
||||
canRegenerateClaimLink: ['link_generated', 'claimed', 'role_confirmed', 'retry_pending', 'manual_review'].includes(task.task_status),
|
||||
canClose: !['redeemed', 'closed'].includes(task.task_status),
|
||||
canMarkManualReview: !['redeemed', 'closed', 'manual_review'].includes(task.task_status),
|
||||
@@ -218,8 +249,8 @@ export function getAdminTaskDetail(taskId) {
|
||||
}
|
||||
}
|
||||
|
||||
export function getAdminTaskScreenshotPath(taskId) {
|
||||
const task = getRequiredTask(taskId)
|
||||
export async function getAdminTaskScreenshotPath(taskId) {
|
||||
const task = await getRequiredTask(taskId)
|
||||
|
||||
if (!task.screenshot_path) {
|
||||
throw createHttpError('当前任务还没有截图', {
|
||||
@@ -231,10 +262,10 @@ export function getAdminTaskScreenshotPath(taskId) {
|
||||
return task.screenshot_path
|
||||
}
|
||||
|
||||
export function getAdminCdks(query = {}) {
|
||||
export async function getAdminCdks(query = {}) {
|
||||
const page = normalizePage(query.page)
|
||||
const pageSize = normalizePageSize(query.pageSize)
|
||||
const { items, total } = listCdks({
|
||||
const { items, total } = await listCdks({
|
||||
page,
|
||||
pageSize,
|
||||
skuCode: String(query.skuCode || '').trim(),
|
||||
@@ -243,15 +274,16 @@ export function getAdminCdks(query = {}) {
|
||||
})
|
||||
|
||||
return {
|
||||
items: items.map(mapAdminCdkListItem),
|
||||
items: await Promise.all(items.map((item) => mapAdminCdkListItem(item))),
|
||||
pagination: { page, pageSize, total },
|
||||
}
|
||||
}
|
||||
|
||||
export function createAdminCdk(payload = {}) {
|
||||
export async function createAdminCdk(payload = {}) {
|
||||
const skuCode = String(payload.skuCode || '').trim()
|
||||
const cdkCode = String(payload.cdkCode || '').trim()
|
||||
const batchNo = String(payload.batchNo || '').trim()
|
||||
const credentialType = String(payload.credentialType || 'tencent_code').trim() || 'tencent_code'
|
||||
|
||||
if (!skuCode || !cdkCode) {
|
||||
throw createHttpError('缺少 skuCode 或 cdkCode', {
|
||||
@@ -261,11 +293,12 @@ export function createAdminCdk(payload = {}) {
|
||||
}
|
||||
|
||||
const now = nowIso()
|
||||
const created = createCdks([
|
||||
const created = await createCdks([
|
||||
{
|
||||
skuCode,
|
||||
cdkCode,
|
||||
batchNo,
|
||||
credentialType,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
@@ -278,7 +311,7 @@ export function createAdminCdk(payload = {}) {
|
||||
})
|
||||
}
|
||||
|
||||
const { items } = listCdks({
|
||||
const { items } = await listCdks({
|
||||
page: 1,
|
||||
pageSize: 1,
|
||||
skuCode,
|
||||
@@ -286,11 +319,11 @@ export function createAdminCdk(payload = {}) {
|
||||
const createdItem = items.find((item) => item.cdk_code === cdkCode) || null
|
||||
|
||||
return {
|
||||
cdk: createdItem ? mapAdminCdkListItem(createdItem) : null,
|
||||
cdk: createdItem ? await mapAdminCdkListItem(createdItem) : null,
|
||||
}
|
||||
}
|
||||
|
||||
export function importAdminCdks(payload = {}) {
|
||||
export async function importAdminCdks(payload = {}) {
|
||||
const rows = normalizeCdkImportRows(payload)
|
||||
|
||||
if (rows.length === 0) {
|
||||
@@ -305,11 +338,12 @@ export function importAdminCdks(payload = {}) {
|
||||
skuCode: row.skuCode,
|
||||
batchNo: row.batchNo,
|
||||
cdkCode: row.cdkCode,
|
||||
credentialType: row.credentialType,
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
}))
|
||||
|
||||
const created = createCdks(normalizedRows)
|
||||
const created = await createCdks(normalizedRows)
|
||||
|
||||
return {
|
||||
total: normalizedRows.length,
|
||||
@@ -318,8 +352,8 @@ export function importAdminCdks(payload = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
export function releaseAdminInventoryCdk(cdkId) {
|
||||
const cdk = getRequiredCdk(cdkId)
|
||||
export async function releaseAdminInventoryCdk(cdkId) {
|
||||
const cdk = await getRequiredCdk(cdkId)
|
||||
|
||||
if (cdk.status !== 'reserved') {
|
||||
throw createHttpError('当前 CDK 不是预占状态,不能释放', {
|
||||
@@ -328,15 +362,15 @@ export function releaseAdminInventoryCdk(cdkId) {
|
||||
})
|
||||
}
|
||||
|
||||
const updated = releaseReservedCdk(cdk.id, nowIso())
|
||||
const updated = await releaseReservedCdk(cdk.id, nowIso())
|
||||
|
||||
return {
|
||||
cdk: mapAdminCdkListItem(updated),
|
||||
cdk: await mapAdminCdkListItem(updated),
|
||||
}
|
||||
}
|
||||
|
||||
export function invalidateAdminCdk(cdkId, payload = {}) {
|
||||
const cdk = getRequiredCdk(cdkId)
|
||||
export async function invalidateAdminCdk(cdkId, payload = {}) {
|
||||
const cdk = await getRequiredCdk(cdkId)
|
||||
|
||||
if (cdk.status !== 'available') {
|
||||
throw createHttpError('只有可用 CDK 才能作废,请先释放预占', {
|
||||
@@ -346,17 +380,17 @@ export function invalidateAdminCdk(cdkId, payload = {}) {
|
||||
}
|
||||
|
||||
const reason = String(payload.reason || '').trim() || '后台手动作废'
|
||||
const updated = invalidateCdk(cdk.id, reason, nowIso())
|
||||
const updated = await invalidateCdk(cdk.id, reason, nowIso())
|
||||
|
||||
return {
|
||||
cdk: mapAdminCdkListItem(updated),
|
||||
cdk: await mapAdminCdkListItem(updated),
|
||||
}
|
||||
}
|
||||
|
||||
export function getAdminWebhookEvents(query = {}) {
|
||||
export async function getAdminWebhookEvents(query = {}) {
|
||||
const page = normalizePage(query.page)
|
||||
const pageSize = normalizePageSize(query.pageSize)
|
||||
const { items, total } = listWebhookEvents({
|
||||
const { items, total } = await listWebhookEvents({
|
||||
page,
|
||||
pageSize,
|
||||
provider: String(query.provider || '').trim(),
|
||||
@@ -368,13 +402,13 @@ export function getAdminWebhookEvents(query = {}) {
|
||||
})
|
||||
|
||||
return {
|
||||
items: items.map((item) => mapAdminWebhookEvent(item)),
|
||||
items: await Promise.all(items.map((item) => mapAdminWebhookEvent(item))),
|
||||
pagination: { page, pageSize, total },
|
||||
}
|
||||
}
|
||||
|
||||
export function getAdminWebhookEventDetail(eventId) {
|
||||
const event = getWebhookEventById(Number(eventId))
|
||||
export async function getAdminWebhookEventDetail(eventId) {
|
||||
const event = await getWebhookEventById(Number(eventId))
|
||||
|
||||
if (!event) {
|
||||
throw createHttpError('Webhook 事件不存在', {
|
||||
@@ -387,7 +421,7 @@ export function getAdminWebhookEventDetail(eventId) {
|
||||
}
|
||||
|
||||
export async function replayAdminWebhookEvent(eventId) {
|
||||
const event = getWebhookEventById(Number(eventId))
|
||||
const event = await getWebhookEventById(Number(eventId))
|
||||
|
||||
if (!event) {
|
||||
throw createHttpError('Webhook 事件不存在', {
|
||||
@@ -412,19 +446,22 @@ export async function replayAdminWebhookEvent(eventId) {
|
||||
}
|
||||
}
|
||||
|
||||
export function getAdminAgisoShopConfigs() {
|
||||
export async function getAdminAgisoShopConfigs() {
|
||||
const configMap = getAgisoShopConfigMap()
|
||||
const rows = getDb().prepare(`
|
||||
SELECT
|
||||
shop_id,
|
||||
MAX(CASE WHEN trim(shop_name) != '' THEN shop_name ELSE '' END) AS detected_shop_name,
|
||||
MAX(created_at) AS latest_seen_at,
|
||||
COUNT(*) AS webhook_event_count
|
||||
FROM webhook_events
|
||||
WHERE provider = 'agiso' AND trim(shop_id) != ''
|
||||
GROUP BY shop_id
|
||||
ORDER BY latest_seen_at DESC, shop_id DESC
|
||||
`).all()
|
||||
const rowsResult = await query(
|
||||
`
|
||||
SELECT
|
||||
shop_id,
|
||||
MAX(CASE WHEN trim(shop_name) != '' THEN shop_name ELSE '' END) AS detected_shop_name,
|
||||
MAX(created_at) AS latest_seen_at,
|
||||
COUNT(*)::int AS webhook_event_count
|
||||
FROM webhook_events
|
||||
WHERE provider = 'agiso' AND trim(shop_id) != ''
|
||||
GROUP BY shop_id
|
||||
ORDER BY latest_seen_at DESC, shop_id DESC
|
||||
`,
|
||||
)
|
||||
const rows = rowsResult.rows
|
||||
|
||||
return {
|
||||
filePath: getAgisoShopsFilePath(),
|
||||
@@ -519,8 +556,8 @@ export function updateAdminAgisoShopConfigs(payload = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
export function retryAdminTask(taskId) {
|
||||
const task = getRequiredTask(taskId)
|
||||
export async function retryAdminTask(taskId) {
|
||||
const task = await getRequiredTask(taskId)
|
||||
const now = nowIso()
|
||||
|
||||
if (!['retry_pending', 'manual_review', 'waiting_inventory'].includes(task.task_status)) {
|
||||
@@ -530,39 +567,47 @@ export function retryAdminTask(taskId) {
|
||||
})
|
||||
}
|
||||
|
||||
const orderItem = listOrderItemsByOrderId(task.order_id).find((item) => item.id === task.order_item_id) || null
|
||||
let reservedCdkId = task.reserved_cdk_id
|
||||
let claimTokenId = task.claim_token_id
|
||||
const orderItems = await listOrderItemsByOrderId(task.order_id)
|
||||
const orderItem = orderItems.find((item) => item.id === task.order_item_id) || null
|
||||
const taskContext = parseTaskContext(task)
|
||||
const primaryRequirement = taskContext.primaryRequirement || null
|
||||
let reservedInventoryItemId = getTaskPrimaryInventoryItemId(task)
|
||||
let claimTokenId = getTaskPrimaryClaimTokenId(task)
|
||||
let nextStatus = 'link_generated'
|
||||
let lastError = ''
|
||||
let expiresAt = task.expires_at
|
||||
let claimExpiresAt = getTaskClaimExpiresAt(task)
|
||||
let claimUrl = ''
|
||||
let token = ''
|
||||
|
||||
if (!reservedCdkId) {
|
||||
const reserved = reserveCdkForTask(orderItem?.sku_code || '', task.id)
|
||||
if (!reservedInventoryItemId) {
|
||||
const reserved = await reserveCdkForTask({
|
||||
skuCode: orderItem?.sku_code || '',
|
||||
taskId: task.id,
|
||||
credentialType: primaryRequirement?.credentialType || 'tencent_code',
|
||||
roleKey: primaryRequirement?.roleKey || 'primary_code',
|
||||
})
|
||||
|
||||
if (!reserved) {
|
||||
nextStatus = 'waiting_inventory'
|
||||
lastError = '库存不足,等待可用 CDK'
|
||||
} else {
|
||||
reservedCdkId = reserved.id
|
||||
reservedInventoryItemId = reserved.id
|
||||
}
|
||||
}
|
||||
|
||||
if (nextStatus === 'link_generated' && !claimTokenId) {
|
||||
const claimToken = createTaskClaimToken(task.id)
|
||||
const claimToken = await createTaskClaimToken(task.id)
|
||||
claimTokenId = claimToken.id
|
||||
expiresAt = claimToken.expired_at
|
||||
claimExpiresAt = claimToken.expired_at
|
||||
claimUrl = claimToken.claimUrl
|
||||
token = claimToken.token
|
||||
}
|
||||
|
||||
const updatedTask = updateTask(task.id, {
|
||||
const updatedTask = await updateTask(task.id, {
|
||||
task_status: nextStatus,
|
||||
reserved_cdk_id: reservedCdkId,
|
||||
claim_token_id: claimTokenId,
|
||||
expires_at: expiresAt,
|
||||
inventory_status: reservedInventoryItemId ? 'reserved' : 'pending',
|
||||
claim_token: token || task.claim_token || '',
|
||||
claim_expires_at: claimExpiresAt,
|
||||
last_error: lastError,
|
||||
updated_at: now,
|
||||
})
|
||||
@@ -579,10 +624,11 @@ export function retryAdminTask(taskId) {
|
||||
return payload
|
||||
}
|
||||
|
||||
export function releaseAdminTaskCdk(taskId) {
|
||||
const task = getRequiredTask(taskId)
|
||||
export async function releaseAdminTaskCdk(taskId) {
|
||||
const task = await getRequiredTask(taskId)
|
||||
const primaryInventoryItemId = getTaskPrimaryInventoryItemId(task)
|
||||
|
||||
if (!task.reserved_cdk_id) {
|
||||
if (!primaryInventoryItemId) {
|
||||
throw createHttpError('当前任务没有预占 CDK', {
|
||||
statusCode: 409,
|
||||
errorCode: 'admin_task_no_reserved_cdk',
|
||||
@@ -596,10 +642,10 @@ export function releaseAdminTaskCdk(taskId) {
|
||||
})
|
||||
}
|
||||
|
||||
releaseReservedCdk(task.reserved_cdk_id, nowIso())
|
||||
const updatedTask = updateTask(task.id, {
|
||||
reserved_cdk_id: null,
|
||||
await releaseReservedCdk(primaryInventoryItemId, nowIso())
|
||||
const updatedTask = await updateTask(task.id, {
|
||||
task_status: 'waiting_inventory',
|
||||
inventory_status: 'pending',
|
||||
last_error: '已手动释放预占 CDK',
|
||||
updated_at: nowIso(),
|
||||
})
|
||||
@@ -609,8 +655,9 @@ export function releaseAdminTaskCdk(taskId) {
|
||||
}
|
||||
}
|
||||
|
||||
export function regenerateAdminTaskClaimLink(taskId) {
|
||||
const task = getRequiredTask(taskId)
|
||||
export async function regenerateAdminTaskClaimLink(taskId) {
|
||||
const task = await getRequiredTask(taskId)
|
||||
const primaryClaimTokenId = getTaskPrimaryClaimTokenId(task)
|
||||
|
||||
if (['redeemed', 'closed'].includes(task.task_status)) {
|
||||
throw createHttpError('当前任务状态不允许重新生成领取链接', {
|
||||
@@ -619,17 +666,17 @@ export function regenerateAdminTaskClaimLink(taskId) {
|
||||
})
|
||||
}
|
||||
|
||||
if (task.claim_token_id) {
|
||||
updateClaimToken(task.claim_token_id, {
|
||||
if (primaryClaimTokenId) {
|
||||
await updateClaimToken(primaryClaimTokenId, {
|
||||
status: 'revoked',
|
||||
updated_at: nowIso(),
|
||||
})
|
||||
}
|
||||
|
||||
const claimToken = createTaskClaimToken(task.id)
|
||||
const updatedTask = updateTask(task.id, {
|
||||
claim_token_id: claimToken.id,
|
||||
expires_at: claimToken.expired_at,
|
||||
const claimToken = await createTaskClaimToken(task.id)
|
||||
const updatedTask = await updateTask(task.id, {
|
||||
claim_token: claimToken.token,
|
||||
claim_expires_at: claimToken.expired_at,
|
||||
task_status: 'link_generated',
|
||||
last_error: '',
|
||||
updated_at: nowIso(),
|
||||
@@ -642,8 +689,8 @@ export function regenerateAdminTaskClaimLink(taskId) {
|
||||
}
|
||||
}
|
||||
|
||||
export function closeAdminTask(taskId) {
|
||||
const task = getRequiredTask(taskId)
|
||||
export async function closeAdminTask(taskId) {
|
||||
const task = await getRequiredTask(taskId)
|
||||
|
||||
if (task.task_status === 'redeemed') {
|
||||
throw createHttpError('已兑换任务不能关闭', {
|
||||
@@ -652,8 +699,9 @@ export function closeAdminTask(taskId) {
|
||||
})
|
||||
}
|
||||
|
||||
const updatedTask = updateTask(task.id, {
|
||||
const updatedTask = await updateTask(task.id, {
|
||||
task_status: 'closed',
|
||||
delivery_status: 'closed',
|
||||
last_error: task.last_error || '已手动关闭任务',
|
||||
updated_at: nowIso(),
|
||||
})
|
||||
@@ -663,9 +711,9 @@ export function closeAdminTask(taskId) {
|
||||
}
|
||||
}
|
||||
|
||||
export function markAdminTaskManualReview(taskId) {
|
||||
const task = getRequiredTask(taskId)
|
||||
const updatedTask = updateTask(task.id, {
|
||||
export async function markAdminTaskManualReview(taskId) {
|
||||
const task = await getRequiredTask(taskId)
|
||||
const updatedTask = await updateTask(task.id, {
|
||||
task_status: 'manual_review',
|
||||
last_error: task.last_error || '已转人工处理',
|
||||
updated_at: nowIso(),
|
||||
@@ -691,13 +739,13 @@ function mapAdminTaskSummary(task) {
|
||||
roleConfirmedAt: task.role_confirmed_at,
|
||||
redeemedAt: task.redeemed_at,
|
||||
lastError: task.last_error,
|
||||
retryCount: task.retry_count,
|
||||
retryCount: getTaskRetryCount(task),
|
||||
createdAt: task.created_at,
|
||||
updatedAt: task.updated_at,
|
||||
}
|
||||
}
|
||||
|
||||
function mapAdminWebhookEvent(item, { includeRaw = false } = {}) {
|
||||
async function mapAdminWebhookEvent(item, { includeRaw = false } = {}) {
|
||||
const headers = normalizeRecord(safeParseJson(item.headers_json))
|
||||
const query = normalizeRecord(safeParseJson(item.query_json))
|
||||
const body = normalizeRecord(safeParseJson(item.body_json))
|
||||
@@ -716,7 +764,7 @@ function mapAdminWebhookEvent(item, { includeRaw = false } = {}) {
|
||||
payload.buyAmount,
|
||||
])
|
||||
const totalAmountFen = parseAmountToFen(rawAmount)
|
||||
const taskCount = item.related_order_id ? listTasksByOrderId(item.related_order_id).length : 0
|
||||
const taskCount = item.related_order_id ? (await listTasksByOrderId(item.related_order_id)).length : 0
|
||||
|
||||
const mapped = {
|
||||
eventId: item.id,
|
||||
@@ -835,9 +883,9 @@ function mapAdminWebhookEvent(item, { includeRaw = false } = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
function mapAdminCdkListItem(item) {
|
||||
const task = item.reserved_by_task_id ? getTaskById(item.reserved_by_task_id) : null
|
||||
const order = task?.order_id ? getOrderById(task.order_id) : null
|
||||
async function mapAdminCdkListItem(item) {
|
||||
const task = item.reserved_by_task_id ? await getTaskById(item.reserved_by_task_id) : null
|
||||
const order = task?.order_id ? await getOrderById(task.order_id) : null
|
||||
const binding = buildTaskBindingState(task)
|
||||
|
||||
return {
|
||||
@@ -845,12 +893,13 @@ function mapAdminCdkListItem(item) {
|
||||
skuCode: item.sku_code,
|
||||
batchNo: item.batch_no,
|
||||
cdkCode: item.cdk_code,
|
||||
credentialType: item.credential_type || 'tencent_code',
|
||||
status: item.status,
|
||||
reservedByTaskId: item.reserved_by_task_id,
|
||||
reservedByTaskNo: task?.task_no || '',
|
||||
platformOrderId: order?.platform_order_id || '',
|
||||
systemBindingStatus: item.status === 'delivered' ? 'system_bound' : binding.systemBindingStatus,
|
||||
userBindingStatus: item.status === 'delivered' ? 'binding_completed' : binding.userBindingStatus,
|
||||
systemBindingStatus: item.status === 'consumed' ? 'system_bound' : binding.systemBindingStatus,
|
||||
userBindingStatus: item.status === 'consumed' ? 'binding_completed' : binding.userBindingStatus,
|
||||
invalidReason: item.invalid_reason || '',
|
||||
deliveredAt: item.delivered_at,
|
||||
createdAt: item.created_at,
|
||||
@@ -859,19 +908,23 @@ function mapAdminCdkListItem(item) {
|
||||
}
|
||||
|
||||
function mapTaskActionPayload(task) {
|
||||
const inventoryItemId = getTaskPrimaryInventoryItemId(task)
|
||||
const claimTokenId = getTaskPrimaryClaimTokenId(task)
|
||||
|
||||
return {
|
||||
taskId: task.id,
|
||||
taskNo: task.task_no,
|
||||
status: task.task_status,
|
||||
reservedCdkId: task.reserved_cdk_id,
|
||||
claimTokenId: task.claim_token_id,
|
||||
inventoryItemId,
|
||||
claimTokenId,
|
||||
reservedCdkId: inventoryItemId,
|
||||
lastError: task.last_error,
|
||||
updatedAt: task.updated_at,
|
||||
}
|
||||
}
|
||||
|
||||
function getRequiredTask(taskId) {
|
||||
const task = getTaskById(Number(taskId))
|
||||
async function getRequiredTask(taskId) {
|
||||
const task = await getTaskById(Number(taskId))
|
||||
|
||||
if (!task) {
|
||||
throw createHttpError('任务不存在', {
|
||||
@@ -883,8 +936,8 @@ function getRequiredTask(taskId) {
|
||||
return task
|
||||
}
|
||||
|
||||
function getRequiredCdk(cdkId) {
|
||||
const cdk = getCdkById(Number(cdkId))
|
||||
async function getRequiredCdk(cdkId) {
|
||||
const cdk = await getCdkById(Number(cdkId))
|
||||
|
||||
if (!cdk) {
|
||||
throw createHttpError('CDK 不存在', {
|
||||
@@ -915,19 +968,21 @@ function mapAdminTaskListItem(task) {
|
||||
claimedAt: task.claimed_at,
|
||||
roleConfirmedAt: task.role_confirmed_at,
|
||||
redeemedAt: task.redeemed_at,
|
||||
retryCount: task.retry_count,
|
||||
retryCount: getTaskRetryCount(task),
|
||||
lastError: task.last_error,
|
||||
createdAt: task.created_at,
|
||||
updatedAt: task.updated_at,
|
||||
reservedCdkCodeMasked: maskCode(task.cdk_code),
|
||||
claimToken: task.claim_token || '',
|
||||
reservedCdkCodeMasked: maskCode(task.primary_inventory_display_value),
|
||||
claimToken: task.primary_claim_token || task.claim_token || '',
|
||||
screenshotPath: task.screenshot_path || '',
|
||||
}
|
||||
}
|
||||
|
||||
function mapAdminOrderListItem(item) {
|
||||
const tasks = listTasksByOrderId(item.id)
|
||||
const orderItems = listOrderItemsByOrderId(item.id)
|
||||
async function mapAdminOrderListItem(item) {
|
||||
const [tasks, orderItems] = await Promise.all([
|
||||
listTasksByOrderId(item.id),
|
||||
listOrderItemsByOrderId(item.id),
|
||||
])
|
||||
const bindingSummary = buildOrderBindingSummary(tasks)
|
||||
const itemSummary = summarizeOrderItems(orderItems)
|
||||
|
||||
@@ -997,6 +1052,24 @@ function resolveOrderItemTitle(item) {
|
||||
])
|
||||
}
|
||||
|
||||
function resolveOrderItemDeliveryMode(tasks, orderItemId) {
|
||||
const task = (Array.isArray(tasks) ? tasks : []).find((item) => item.order_item_id === orderItemId)
|
||||
|
||||
if (!task) {
|
||||
return ''
|
||||
}
|
||||
|
||||
if (String(task.executor_key || '').trim() === 'manual_dispatch') {
|
||||
return 'manual_dispatch'
|
||||
}
|
||||
|
||||
if (task.requires_claim || getTaskPrimaryClaimTokenId(task) || task.primary_claim_token || task.claim_token) {
|
||||
return 'claim_link'
|
||||
}
|
||||
|
||||
return String(task.executor_key || '').trim()
|
||||
}
|
||||
|
||||
function buildOrderBindingSummary(tasks) {
|
||||
const normalizedTasks = Array.isArray(tasks) ? tasks : []
|
||||
const totalTaskCount = normalizedTasks.length
|
||||
@@ -1110,7 +1183,33 @@ function buildTaskBindingState(task) {
|
||||
}
|
||||
|
||||
function isTaskSystemBound(task) {
|
||||
return Boolean(task && (task.reserved_cdk_id || task.claim_token_id))
|
||||
return Boolean(task && (getTaskPrimaryInventoryItemId(task) || getTaskPrimaryClaimTokenId(task)))
|
||||
}
|
||||
|
||||
function parseTaskContext(task) {
|
||||
try {
|
||||
return JSON.parse(String(task?.context_json || '{}'))
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
function getTaskPrimaryInventoryItemId(task) {
|
||||
const value = Number(task?.primary_inventory_item_id || 0)
|
||||
return Number.isFinite(value) && value > 0 ? value : null
|
||||
}
|
||||
|
||||
function getTaskPrimaryClaimTokenId(task) {
|
||||
const value = Number(task?.primary_claim_token_id || 0)
|
||||
return Number.isFinite(value) && value > 0 ? value : null
|
||||
}
|
||||
|
||||
function getTaskClaimExpiresAt(task) {
|
||||
return task?.claim_expires_at || task?.primary_claim_expires_at || null
|
||||
}
|
||||
|
||||
function getTaskRetryCount(task) {
|
||||
return Number(task?.attempt_count || 0)
|
||||
}
|
||||
|
||||
function resolveDisplayShopName(provider, shopId, shopName) {
|
||||
@@ -1144,18 +1243,20 @@ function normalizeCdkImportRows(payload) {
|
||||
const skuCode = String(row?.skuCode || '').trim()
|
||||
const cdkCode = String(row?.cdkCode || '').trim()
|
||||
const batchNo = String(row?.batchNo || '').trim()
|
||||
const credentialType = String(row?.credentialType || payload.credentialType || 'tencent_code').trim() || 'tencent_code'
|
||||
|
||||
if (!skuCode || !cdkCode) {
|
||||
continue
|
||||
}
|
||||
|
||||
rows.push({ skuCode, cdkCode, batchNo })
|
||||
rows.push({ skuCode, cdkCode, batchNo, credentialType })
|
||||
}
|
||||
}
|
||||
|
||||
if (bulkCodes.length > 0) {
|
||||
const skuCode = String(payload.skuCode || '').trim()
|
||||
const batchNo = String(payload.batchNo || '').trim()
|
||||
const credentialType = String(payload.credentialType || 'tencent_code').trim() || 'tencent_code'
|
||||
|
||||
if (!skuCode) {
|
||||
throw createHttpError('批量导入时缺少 skuCode', {
|
||||
@@ -1169,7 +1270,7 @@ function normalizeCdkImportRows(payload) {
|
||||
if (!cdkCode) {
|
||||
continue
|
||||
}
|
||||
rows.push({ skuCode, cdkCode, batchNo })
|
||||
rows.push({ skuCode, cdkCode, batchNo, credentialType })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1181,7 +1282,7 @@ function dedupeRows(rows) {
|
||||
const output = []
|
||||
|
||||
for (const row of rows) {
|
||||
const key = `${row.skuCode}::${row.cdkCode}`
|
||||
const key = `${row.skuCode}::${row.credentialType || 'tencent_code'}::${row.cdkCode}`
|
||||
if (seen.has(key)) {
|
||||
continue
|
||||
}
|
||||
@@ -1192,41 +1293,6 @@ function dedupeRows(rows) {
|
||||
return output
|
||||
}
|
||||
|
||||
function normalizePage(rawValue) {
|
||||
const parsed = Number(rawValue)
|
||||
return Number.isFinite(parsed) && parsed > 0 ? Math.floor(parsed) : 1
|
||||
}
|
||||
|
||||
function normalizePageSize(rawValue) {
|
||||
const parsed = Number(rawValue)
|
||||
if (!Number.isFinite(parsed) || parsed <= 0) {
|
||||
return 20
|
||||
}
|
||||
return Math.min(100, Math.floor(parsed))
|
||||
}
|
||||
|
||||
function normalizeDateQuery(rawValue, endOfDay = false) {
|
||||
const normalized = String(rawValue || '').trim()
|
||||
|
||||
if (!normalized) {
|
||||
return ''
|
||||
}
|
||||
|
||||
if (/^\d{4}-\d{2}-\d{2}$/.test(normalized)) {
|
||||
return endOfDay ? `${normalized}T23:59:59.999Z` : `${normalized}T00:00:00.000Z`
|
||||
}
|
||||
|
||||
return normalized
|
||||
}
|
||||
|
||||
function safeParseJson(rawText) {
|
||||
try {
|
||||
return JSON.parse(String(rawText || '{}'))
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
function maskSecret(value) {
|
||||
const normalized = String(value || '').trim()
|
||||
if (!normalized) {
|
||||
|
||||
@@ -64,10 +64,7 @@ export async function ensureFulfillmentCatalogBootstrapped() {
|
||||
}
|
||||
}
|
||||
|
||||
const configuredBindings = normalizeConfiguredBindings(runtimeConfig.orders?.fulfillmentBindings)
|
||||
const bindingsToApply = configuredBindings.length > 0
|
||||
? configuredBindings
|
||||
: inferDefaultBindingsFromSkuMappings(runtimeConfig.orders?.skuMappings)
|
||||
const bindingsToApply = normalizeConfiguredBindings(runtimeConfig.orders?.fulfillmentBindings)
|
||||
|
||||
for (const binding of bindingsToApply) {
|
||||
const profile = profileMap[binding.profileKey] || await getFulfillmentProfileByKey(binding.profileKey)
|
||||
@@ -108,19 +105,3 @@ function normalizeConfiguredBindings(bindings) {
|
||||
}))
|
||||
.filter((binding) => binding.skuCode)
|
||||
}
|
||||
|
||||
function inferDefaultBindingsFromSkuMappings(skuMappings) {
|
||||
const values = Object.values(skuMappings || {})
|
||||
const uniqueSkuCodes = [...new Set(values.map((value) => String(value || '').trim()).filter(Boolean))]
|
||||
|
||||
return uniqueSkuCodes.map((skuCode) => ({
|
||||
skuCode,
|
||||
provider: '',
|
||||
platform: '',
|
||||
shopId: '',
|
||||
profileKey: 'tencent_claim_redeem',
|
||||
enabled: true,
|
||||
priority: 100,
|
||||
config: {},
|
||||
}))
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
createTencentBrowserSession,
|
||||
getTencentBrowserSession,
|
||||
getTencentBrowserSessionSummary,
|
||||
getTencentBrowserSessionScreenshotPath,
|
||||
redeemTencentBrowserSession,
|
||||
} from '../session/session.js'
|
||||
@@ -36,7 +37,7 @@ export async function createClaimSession(token, payload = {}) {
|
||||
|
||||
if (context.task.browser_session_id) {
|
||||
const existingSession = await getTencentBrowserSession(context.task.browser_session_id)
|
||||
const syncedTask = syncTaskWithSession(context.task, existingSession)
|
||||
const syncedTask = await syncTaskWithSession(context.task, existingSession)
|
||||
|
||||
return buildClaimDetailPayload({
|
||||
claimToken: context.claimToken,
|
||||
@@ -50,10 +51,11 @@ export async function createClaimSession(token, payload = {}) {
|
||||
const session = await createTencentBrowserSession({
|
||||
loginType: payload.loginType,
|
||||
})
|
||||
const updatedTask = updateTask(context.task.id, {
|
||||
const updatedTask = await updateTask(context.task.id, {
|
||||
task_status: 'claimed',
|
||||
browser_session_id: session.sessionId,
|
||||
login_type: session.loginType,
|
||||
user_action_status: 'claimed',
|
||||
claimed_at: context.task.claimed_at || nowIso(),
|
||||
updated_at: nowIso(),
|
||||
})
|
||||
@@ -78,7 +80,7 @@ export async function getClaimSessionSummary(token) {
|
||||
}
|
||||
|
||||
const session = await getTencentBrowserSession(context.task.browser_session_id)
|
||||
const syncedTask = syncTaskWithSession(context.task, session)
|
||||
const syncedTask = await syncTaskWithSession(context.task, session)
|
||||
|
||||
return buildClaimDetailPayload({
|
||||
claimToken: context.claimToken,
|
||||
@@ -109,13 +111,14 @@ export async function confirmClaimRole(token) {
|
||||
})
|
||||
}
|
||||
|
||||
const updatedTask = updateTask(context.task.id, {
|
||||
const updatedTask = await updateTask(context.task.id, {
|
||||
task_status: 'role_confirmed',
|
||||
nickname: String(activityInfo.nickname || ''),
|
||||
role_id: String(activityInfo.role.roleId || ''),
|
||||
role_name: String(activityInfo.role.roleName || ''),
|
||||
area: String(activityInfo.role.area || ''),
|
||||
partition_name: String(activityInfo.role.partition || ''),
|
||||
user_action_status: 'role_confirmed',
|
||||
role_confirmed_at: nowIso(),
|
||||
updated_at: nowIso(),
|
||||
last_error: '',
|
||||
@@ -148,7 +151,7 @@ export async function redeemClaimTask(token) {
|
||||
})
|
||||
}
|
||||
|
||||
const cdk = context.task.reserved_cdk_id ? getCdkById(context.task.reserved_cdk_id) : null
|
||||
const cdk = context.task.primary_inventory_item_id ? await getCdkById(context.task.primary_inventory_item_id) : null
|
||||
|
||||
if (!cdk || !String(cdk.cdk_code || '').trim()) {
|
||||
throw createHttpError('当前任务没有可用的预占 CDK', {
|
||||
@@ -157,8 +160,9 @@ export async function redeemClaimTask(token) {
|
||||
})
|
||||
}
|
||||
|
||||
updateTask(context.task.id, {
|
||||
await updateTask(context.task.id, {
|
||||
task_status: 'redeeming',
|
||||
delivery_status: 'processing',
|
||||
updated_at: nowIso(),
|
||||
last_error: '',
|
||||
})
|
||||
@@ -168,8 +172,10 @@ export async function redeemClaimTask(token) {
|
||||
code: cdk.cdk_code,
|
||||
})
|
||||
const finalRedeem = session.redeem?.final?.redeem || null
|
||||
const updatedTask = updateTask(context.task.id, {
|
||||
const updatedTask = await updateTask(context.task.id, {
|
||||
task_status: 'redeemed',
|
||||
inventory_status: 'consumed',
|
||||
delivery_status: 'delivered',
|
||||
result_code: String(finalRedeem?.iRet || finalRedeem?.ret || '0'),
|
||||
result_message: String(finalRedeem?.sMsg || finalRedeem?.msg || session.notice || '兑换完成'),
|
||||
screenshot_path: session.artifacts?.hasScreenshot ? await getTencentBrowserSessionScreenshotPath(session.sessionId) : '',
|
||||
@@ -179,7 +185,7 @@ export async function redeemClaimTask(token) {
|
||||
last_error: '',
|
||||
})
|
||||
|
||||
markCdkDelivered(cdk.id, nowIso())
|
||||
await markCdkDelivered(cdk.id, nowIso())
|
||||
|
||||
return buildClaimDetailPayload({
|
||||
claimToken: context.claimToken,
|
||||
@@ -189,10 +195,11 @@ export async function redeemClaimTask(token) {
|
||||
session,
|
||||
})
|
||||
} catch (error) {
|
||||
const nextRetryCount = Number(context.task.retry_count || 0) + 1
|
||||
const failedTask = updateTask(context.task.id, {
|
||||
const nextRetryCount = Number(context.task.attempt_count || 0) + 1
|
||||
const failedTask = await updateTask(context.task.id, {
|
||||
task_status: 'retry_pending',
|
||||
retry_count: nextRetryCount,
|
||||
delivery_status: 'pending',
|
||||
attempt_count: nextRetryCount,
|
||||
last_error: error instanceof Error ? error.message : String(error || ''),
|
||||
updated_at: nowIso(),
|
||||
})
|
||||
@@ -230,7 +237,7 @@ async function getClaimContext(token) {
|
||||
})
|
||||
}
|
||||
|
||||
const claimToken = findClaimTokenByToken(normalized)
|
||||
const claimToken = await findClaimTokenByToken(normalized)
|
||||
|
||||
if (!claimToken) {
|
||||
throw createHttpError('领取链接无效或不存在', {
|
||||
@@ -239,7 +246,7 @@ async function getClaimContext(token) {
|
||||
})
|
||||
}
|
||||
|
||||
const task = findTaskByClaimTokenId(claimToken.id)
|
||||
const task = await findTaskByClaimTokenId(claimToken.id)
|
||||
|
||||
if (!task) {
|
||||
throw createHttpError('领取任务不存在', {
|
||||
@@ -256,7 +263,7 @@ async function getClaimContext(token) {
|
||||
}
|
||||
|
||||
if (claimToken.expired_at && new Date(claimToken.expired_at).getTime() <= Date.now()) {
|
||||
const expiredContext = expireClaimContext(claimToken, task)
|
||||
const expiredContext = await expireClaimContext(claimToken, task)
|
||||
|
||||
throw createHttpError('领取链接已过期', {
|
||||
statusCode: 410,
|
||||
@@ -265,8 +272,10 @@ async function getClaimContext(token) {
|
||||
})
|
||||
}
|
||||
|
||||
const order = getOrderById(task.order_id)
|
||||
const orderItem = getOrderItemById(task.order_item_id)
|
||||
const [order, orderItem] = await Promise.all([
|
||||
getOrderById(task.order_id),
|
||||
getOrderItemById(task.order_item_id),
|
||||
])
|
||||
|
||||
if (!order || !orderItem) {
|
||||
throw createHttpError('领取任务关联订单不完整', {
|
||||
@@ -292,9 +301,9 @@ function assertTaskCanProceed(task) {
|
||||
}
|
||||
}
|
||||
|
||||
function expireClaimContext(claimToken, task) {
|
||||
async function expireClaimContext(claimToken, task) {
|
||||
const now = nowIso()
|
||||
const nextClaimToken = updateClaimToken(claimToken.id, {
|
||||
const nextClaimToken = await updateClaimToken(claimToken.id, {
|
||||
status: 'expired',
|
||||
updated_at: now,
|
||||
})
|
||||
@@ -302,13 +311,14 @@ function expireClaimContext(claimToken, task) {
|
||||
let nextTask = task
|
||||
|
||||
if (!CLAIM_TERMINAL_STATUSES.has(String(task.task_status || '')) && task.task_status !== 'redeemed') {
|
||||
if (task.reserved_cdk_id) {
|
||||
releaseReservedCdk(task.reserved_cdk_id, now)
|
||||
if (task.primary_inventory_item_id) {
|
||||
await releaseReservedCdk(task.primary_inventory_item_id, now)
|
||||
}
|
||||
|
||||
nextTask = updateTask(task.id, {
|
||||
nextTask = await updateTask(task.id, {
|
||||
task_status: 'expired',
|
||||
reserved_cdk_id: null,
|
||||
inventory_status: 'pending',
|
||||
user_action_status: 'expired',
|
||||
last_error: '领取链接已过期,预占 CDK 已释放',
|
||||
updated_at: now,
|
||||
})
|
||||
@@ -330,7 +340,7 @@ async function loadTaskSession(task, { includeQrImage = false } = {}) {
|
||||
: getTencentBrowserSessionSummary(task.browser_session_id)
|
||||
}
|
||||
|
||||
function syncTaskWithSession(task, session) {
|
||||
async function syncTaskWithSession(task, session) {
|
||||
const activityInfo = session.activityInfo || null
|
||||
const patch = {
|
||||
login_type: String(session.loginType || task.login_type || ''),
|
||||
@@ -350,6 +360,7 @@ function syncTaskWithSession(task, session) {
|
||||
|
||||
if (task.task_status === 'link_generated') {
|
||||
patch.task_status = 'claimed'
|
||||
patch.user_action_status = 'claimed'
|
||||
patch.claimed_at = task.claimed_at || nowIso()
|
||||
}
|
||||
|
||||
@@ -372,7 +383,7 @@ function buildClaimDetailPayload({ claimToken, task, order, orderItem, session }
|
||||
taskId: task.id,
|
||||
taskNo: task.task_no,
|
||||
status: task.task_status,
|
||||
expiresAt: task.expires_at,
|
||||
expiresAt: claimToken.expired_at,
|
||||
claimedAt: task.claimed_at,
|
||||
roleConfirmedAt: task.role_confirmed_at,
|
||||
redeemedAt: task.redeemed_at,
|
||||
|
||||
@@ -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()
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -140,7 +140,16 @@ export interface AdminTaskOperations {
|
||||
}
|
||||
|
||||
export interface AdminTaskActionResponse {
|
||||
task: Record<string, unknown>
|
||||
task: {
|
||||
taskId: number
|
||||
taskNo: string
|
||||
status: string
|
||||
inventoryItemId: number | null
|
||||
claimTokenId: number | null
|
||||
reservedCdkId?: number | null
|
||||
lastError: string
|
||||
updatedAt: string
|
||||
}
|
||||
claimUrl?: string
|
||||
token?: string
|
||||
}
|
||||
|
||||
+26
-2
@@ -1,4 +1,22 @@
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-bookworm
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
TZ: ${TZ:-Asia/Shanghai}
|
||||
POSTGRES_DB: ${POSTGRES_DB:-order_site}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-postgres}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres}
|
||||
ports:
|
||||
- "${POSTGRES_PORT:-5432}:5432"
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-postgres} -d ${POSTGRES_DB:-order_site}"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
volumes:
|
||||
- postgres_dev_data:/var/lib/postgresql/data
|
||||
|
||||
backend:
|
||||
build:
|
||||
context: .
|
||||
@@ -11,10 +29,15 @@ services:
|
||||
"npm install --no-fund --no-audit &&
|
||||
python3 -m pip install --no-cache-dir --break-system-packages -e /app/subservices/ocr-worker &&
|
||||
npm run dev"
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
TZ: ${TZ:-Asia/Shanghai}
|
||||
PORT: ${BACKEND_PORT:-3000}
|
||||
DATABASE_FILE_PATH: /app/data/order-site.db
|
||||
DATABASE_URL: ${DATABASE_URL:-postgres://postgres:postgres@postgres:5432/order_site}
|
||||
DATABASE_SSL: ${DATABASE_SSL:-false}
|
||||
DATABASE_MAX_CONNECTIONS: ${DATABASE_MAX_CONNECTIONS:-10}
|
||||
OCR_PROJECT_ROOT: /app/subservices/ocr-worker
|
||||
CLAIM_BASE_URL: ${CLAIM_BASE_URL:-http://localhost/#/claim}
|
||||
TENCENT_REDEEM_PROOF_MODE: ${TENCENT_REDEEM_PROOF_MODE:-basic}
|
||||
@@ -24,7 +47,7 @@ services:
|
||||
TENCENT_SESSION_DEBUG: ${TENCENT_SESSION_DEBUG:-false}
|
||||
ADMIN_SESSION_SECRET: ${ADMIN_SESSION_SECRET}
|
||||
ADMIN_DEFAULT_USERS_JSON: ${ADMIN_DEFAULT_USERS_JSON}
|
||||
ORDER_SKU_MAPPINGS_JSON: ${ORDER_SKU_MAPPINGS_JSON}
|
||||
ORDER_FULFILLMENT_BINDINGS_JSON: ${ORDER_FULFILLMENT_BINDINGS_JSON:-[]}
|
||||
AGISO_APP_SECRET: ${AGISO_APP_SECRET:-}
|
||||
AGISO_MESSAGING_ENABLED: ${AGISO_MESSAGING_ENABLED:-false}
|
||||
AGISO_APP_ID: ${AGISO_APP_ID:-}
|
||||
@@ -72,5 +95,6 @@ services:
|
||||
- ./deploy/caddy/Caddyfile.dev:/etc/caddy/Caddyfile:ro
|
||||
|
||||
volumes:
|
||||
postgres_dev_data:
|
||||
backend_node_modules:
|
||||
frontend_node_modules:
|
||||
|
||||
+24
-2
@@ -1,4 +1,20 @@
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:16-bookworm
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
TZ: ${TZ:-Asia/Shanghai}
|
||||
POSTGRES_DB: ${POSTGRES_DB:-order_site}
|
||||
POSTGRES_USER: ${POSTGRES_USER:-postgres}
|
||||
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres}
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-postgres} -d ${POSTGRES_DB:-order_site}"]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
|
||||
backend:
|
||||
build:
|
||||
context: .
|
||||
@@ -6,10 +22,15 @@ services:
|
||||
restart: unless-stopped
|
||||
env_file:
|
||||
- .env
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
TZ: ${TZ:-Asia/Shanghai}
|
||||
PORT: ${BACKEND_PORT:-3000}
|
||||
DATABASE_FILE_PATH: /app/data/order-site.db
|
||||
DATABASE_URL: ${DATABASE_URL:-postgres://postgres:postgres@postgres:5432/order_site}
|
||||
DATABASE_SSL: ${DATABASE_SSL:-false}
|
||||
DATABASE_MAX_CONNECTIONS: ${DATABASE_MAX_CONNECTIONS:-20}
|
||||
OCR_PROJECT_ROOT: /app/subservices/ocr-worker
|
||||
CLAIM_BASE_URL: ${CLAIM_BASE_URL:-http://localhost/#/claim}
|
||||
TENCENT_REDEEM_PROOF_MODE: ${TENCENT_REDEEM_PROOF_MODE:-basic}
|
||||
@@ -19,7 +40,7 @@ services:
|
||||
TENCENT_SESSION_DEBUG: ${TENCENT_SESSION_DEBUG:-false}
|
||||
ADMIN_SESSION_SECRET: ${ADMIN_SESSION_SECRET}
|
||||
ADMIN_DEFAULT_USERS_JSON: ${ADMIN_DEFAULT_USERS_JSON}
|
||||
ORDER_SKU_MAPPINGS_JSON: ${ORDER_SKU_MAPPINGS_JSON}
|
||||
ORDER_FULFILLMENT_BINDINGS_JSON: ${ORDER_FULFILLMENT_BINDINGS_JSON:-[]}
|
||||
AGISO_APP_SECRET: ${AGISO_APP_SECRET:-}
|
||||
AGISO_MESSAGING_ENABLED: ${AGISO_MESSAGING_ENABLED:-false}
|
||||
AGISO_APP_ID: ${AGISO_APP_ID:-}
|
||||
@@ -51,5 +72,6 @@ services:
|
||||
|
||||
volumes:
|
||||
backend_data:
|
||||
postgres_data:
|
||||
caddy_data:
|
||||
caddy_config:
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
# Backend Refactor Status
|
||||
|
||||
最后更新:2026-04-09(已切换到“测试数据可丢弃,不做历史迁移兼容”前提)
|
||||
|
||||
## 当前结论
|
||||
|
||||
后端正在从“单一腾讯领取兑换工具”迁移到“通用订单履约系统”。
|
||||
|
||||
当前代码已经完成了下面两件大事:
|
||||
|
||||
1. 数据层已经切到 PostgreSQL,并引入了新的通用履约模型。
|
||||
2. 仓库结构已经分出 `db / repositories / services / routes / frontend / deploy` 等清晰边界。
|
||||
|
||||
当前仍处于新旧架构并存阶段,但已经明确采用下面的推进原则:
|
||||
|
||||
- 现有数据库数据视为测试数据,可直接清空
|
||||
- 不再为了旧测试数据保留历史迁移修复逻辑
|
||||
- 新配置只认当前履约模型,不再从旧映射自动推导
|
||||
|
||||
当前主要表现为:
|
||||
|
||||
- 新 schema 已经使用 `fulfillment_* / inventory_items / task_inventory_bindings`
|
||||
- 核心 service 主链路已经开始直接使用“主 token / 主库存绑定”语义
|
||||
- 边角脚本、前端命名和少量后台返回结构仍处于过渡期
|
||||
|
||||
## 当前真实架构
|
||||
|
||||
从工程实现视角,当前后端可以按 5 层理解:
|
||||
|
||||
1. 接口层
|
||||
- `src/routes/`
|
||||
- 负责接 HTTP 请求、鉴权、组装响应
|
||||
2. 应用编排层
|
||||
- `src/services/order/`
|
||||
- `src/services/claim/`
|
||||
- `src/services/admin/`
|
||||
- 负责订单、任务、库存、领取、后台操作编排
|
||||
3. 执行能力层
|
||||
- `src/services/session/`
|
||||
- `src/services/platforms/`
|
||||
- 负责浏览器自动化、平台消息发送、OCR 调用
|
||||
4. 持久化层
|
||||
- `src/repositories/`
|
||||
- 负责 orders、tasks、inventory、claim_tokens、webhook_events 的读写
|
||||
5. 基础设施层
|
||||
- `src/db/`
|
||||
- `src/config/`
|
||||
- 负责数据库连接、迁移、运行时配置、bootstrap
|
||||
|
||||
## 已完成部分
|
||||
|
||||
### 1. 通用履约模型已经落库
|
||||
|
||||
当前迁移文件已经不再围绕旧式单 CDK 模型设计,而是引入了:
|
||||
|
||||
- `fulfillment_profiles`
|
||||
- `fulfillment_profile_requirements`
|
||||
- `sku_fulfillment_bindings`
|
||||
- `inventory_items`
|
||||
- `fulfillment_tasks`
|
||||
- `task_inventory_bindings`
|
||||
- `tencent_browser_contexts`
|
||||
- `message_deliveries`
|
||||
|
||||
这说明系统底层已经支持:
|
||||
|
||||
- 同一个 SKU 绑定不同履约方式
|
||||
- 不同 provider / platform / shop 的差异化履约策略
|
||||
- 一个任务绑定多个库存项
|
||||
- 不同 `credential_type` 的库存凭据
|
||||
- 手动发货与腾讯领取兑换并存
|
||||
|
||||
### 2. 履约目录 bootstrap 已经具备基础抽象
|
||||
|
||||
当前 bootstrap 中已经定义了两个核心 profile:
|
||||
|
||||
- `manual_review`
|
||||
- `tencent_claim_redeem`
|
||||
|
||||
说明“手动发货”和“腾讯领取兑换”已经从业务概念上进入统一履约目录,而不是散落在业务代码里。
|
||||
|
||||
### 3. Admin 路由已经完成按领域拆分
|
||||
|
||||
后台路由不再全部堆在一个文件里,而是按:
|
||||
|
||||
- auth
|
||||
- dashboard
|
||||
- users
|
||||
- orders
|
||||
- tasks
|
||||
- cdks
|
||||
- webhook-events
|
||||
- platform-config
|
||||
|
||||
拆成独立模块,便于继续演进。
|
||||
|
||||
### 4. 核心任务读写已经开始切回新 schema 语义
|
||||
|
||||
当前仓库层已经明确暴露:
|
||||
|
||||
- `primary_claim_token_*`
|
||||
- `primary_inventory_item_*`
|
||||
|
||||
应用层也开始改为基于这些字段处理“主领取 token / 主库存绑定”,而不是继续把它们伪装成旧 `claim_token_id / reserved_cdk_id`。
|
||||
|
||||
另外,`claimed_at / role_confirmed_at / redeemed_at` 这些任务时间字段现在也已真正通过 repository 落库,不再只是 service 层表面传值。
|
||||
|
||||
## 当前未完成部分
|
||||
|
||||
### 1. 新 schema 和部分 service 仍然错位
|
||||
|
||||
当前最主要的问题不是“没功能”,而是“新数据模型已经落地,但应用层还没有完全跟上”。
|
||||
|
||||
典型现象:
|
||||
|
||||
- 前后端接口命名还留着一部分旧 CDK 心智
|
||||
- 局部 service 仍需要继续统一 async/await 与新仓库接口写法
|
||||
|
||||
### 2. 多凭据任务能力还没有完全上浮到应用层
|
||||
|
||||
底层已经支持一个任务绑定多个库存项,但上层展示和操作仍偏向:
|
||||
|
||||
- 一个任务只看一个预占 CDK
|
||||
- 一个任务只暴露一个领取 token
|
||||
- 后台仍以单库存项视角管理任务
|
||||
|
||||
### 3. 手动发货 profile 还没有形成完整闭环
|
||||
|
||||
当前模型和 bootstrap 已有 `manual_dispatch` 方向,但完整的手动履约执行链路还没有完全落到 service、admin 操作和结果回写上。
|
||||
|
||||
### 4. repository 与 admin API 之间仍有一层过渡期命名
|
||||
|
||||
虽然内部主链路已经开始使用 `primary_*` 字段,但部分 admin 返回 payload 仍保留 `reservedCdkId / claimTokenId` 这样的旧命名,以避免前端同时大面积改动。
|
||||
|
||||
## 现在最该继续做的事
|
||||
|
||||
1. 让 admin 层完全对齐新的 `fulfillment_tasks / inventory_items` 语义
|
||||
2. 把“单个 reserved CDK”心智继续升级为“任务库存绑定”
|
||||
3. 把 `manual_review / manual_dispatch` 从 profile 扩展成完整可执行链路
|
||||
4. 补一套基于 PostgreSQL 和新 schema 的清库/种子数据脚本
|
||||
|
||||
当前这件事已经完成一半:
|
||||
|
||||
- 旧 SQLite 思路的 `scripts/cleanup-dev-data.js` 已经替换为基于 PostgreSQL 新 schema 的清库脚本
|
||||
- 但种子数据脚本还没补,bootstrap 目前主要负责 profile/catalog,不负责完整测试数据生成
|
||||
|
||||
## 文档说明
|
||||
|
||||
以下旧文档已删除,不再作为事实来源:
|
||||
|
||||
- `apps/backend/方案A-订单编排与自动兑换设计.md`
|
||||
- `apps/backend/阶段1-4实施规格说明.md`
|
||||
|
||||
后续请以代码、迁移文件和本状态文档为准。
|
||||
Reference in New Issue
Block a user