fix(consignment): 寄售提报强制固化分类,修复空分类库存后台不可见

This commit is contained in:
2026-11-16 15:16:54 +08:00
parent 866f0d37fd
commit 748d45dace
4 changed files with 339 additions and 6 deletions
@@ -0,0 +1,272 @@
#!/usr/bin/env node
/**
* 回填寄卖库存 / 提报单缺失的分类与配置归属。
*
* 背景:打手端旧页面提交时没带 profileId,提报单的 category_id / profile_id 落空,
* 审核入库时原样复制到库存,后台「寄售仓库」按分类筛选永远看不到这些货。
* 本脚本只处理「在库 + category_id 为空」的库存,以及它们的来源提报单,
* 分类 / 配置 / 版本 / 规格键全部按目标寄卖配置的已发布版本生成,不手拼 JSON。
*
* 默认 dry-run(只读 + 打印),加 --apply 才写库。
*
* 用法(apps/backend 目录下):
* npx tsx scripts/backfill-consignment-category.ts
* npx tsx scripts/backfill-consignment-category.ts --apply
*/
import process from 'node:process'
import { closeDb, query, withTransaction } from '../src/db/client.js'
import {
buildConsignmentSpecKey,
buildConsignmentSpecText,
normalizeConsignmentSpecValues,
parseConsignmentSpecValues,
} from '../src/services/worker-platform/consignment-spec-service.js'
import { getPublishedConsignmentProfileById } from '../src/services/worker-platform/consignment-profile-service.js'
/** 目标寄卖配置:当前仅「苏尔南手枪寄卖」存在旧版五字段提报。 */
const TARGET_PROFILE_ID = 1
const apply = process.argv.includes('--apply')
type InventoryRow = {
id: number
inventory_no: string
item_name: string
status: string
source_submission_id: number | null
category_id: number | null
profile_id: number | null
profile_version_id: number | null
profile_snapshot_json: unknown
system: string | null
server_zone: string | null
series: string | null
diamond_level: number | null
brilliance_count: number | null
spec_values_json: unknown
spec_key: string | null
spec_text: string | null
}
type SubmissionRow = {
id: number
submission_no: string
status: string
category_id: number | null
profile_id: number | null
profile_version_id: number | null
profile_snapshot_json: unknown
spec_values_json: unknown
spec_key: string | null
spec_text: string | null
}
type Plan = {
inventory: InventoryRow
submission: SubmissionRow | null
specValues: Record<string, string | number>
specValuesJson: string
specKey: string
specText: string
snapshotJson: string
}
function show(value: unknown): string {
if (value === null || value === undefined || value === '') return '(空)'
if (typeof value === 'object') return JSON.stringify(value)
return String(value)
}
async function loadInventories(): Promise<InventoryRow[]> {
const res = await query<InventoryRow>(
`SELECT id, inventory_no, item_name, status, source_submission_id,
category_id, profile_id, profile_version_id, profile_snapshot_json,
system, server_zone, series, diamond_level, brilliance_count,
spec_values_json, spec_key, spec_text
FROM consignment_inventories
WHERE status = 'in_stock' AND category_id IS NULL
ORDER BY id`,
)
return res.rows
}
async function loadSubmissions(ids: number[]): Promise<Map<number, SubmissionRow>> {
if (ids.length === 0) return new Map()
const res = await query<SubmissionRow>(
`SELECT id, submission_no, status, category_id, profile_id, profile_version_id,
profile_snapshot_json, spec_values_json, spec_key, spec_text
FROM consignment_submissions
WHERE id = ANY($1::bigint[])`,
[ids],
)
return new Map(res.rows.map((row) => [Number(row.id), row]))
}
async function main() {
const profile = await getPublishedConsignmentProfileById(TARGET_PROFILE_ID)
if (!profile || !Number(profile.categoryId)) {
throw new Error(`寄卖配置 ${TARGET_PROFILE_ID} 不存在或未发布,中止`)
}
const snapshotJson = JSON.stringify({
profileId: profile.profileId,
categoryId: profile.categoryId,
categoryName: profile.categoryName,
versionId: profile.versionId,
versionNo: profile.versionNo,
config: profile.config,
})
const inventories = await loadInventories()
const submissions = await loadSubmissions(
inventories
.map((row) => Number(row.source_submission_id || 0))
.filter((id) => Number.isInteger(id) && id > 0),
)
console.log(
`目标配置:id=${profile.profileId} 分类=${profile.categoryId}(${profile.categoryName}) ` +
`版本 id=${profile.versionId} / no=${profile.versionNo}`,
)
console.log(`扫描:在库且 category_id 为空的库存 ${inventories.length} 条`)
const plans: Plan[] = []
const skipped: Array<{ row: InventoryRow; reason: string }> = []
for (const row of inventories) {
const legacyValues = {
system: row.system || '',
serverZone: row.server_zone || '',
series: row.series || '',
diamondLevel: row.diamond_level ?? '',
brillianceCount: row.brilliance_count ?? '',
...parseConsignmentSpecValues(row.spec_values_json),
}
const validation = normalizeConsignmentSpecValues(profile.config.specs, {
specValues: legacyValues,
})
if (validation.errors.length > 0) {
skipped.push({ row, reason: validation.errors.join(';') })
continue
}
plans.push({
inventory: row,
submission: submissions.get(Number(row.source_submission_id || 0)) || null,
specValues: validation.values,
specValuesJson: JSON.stringify(validation.values),
specKey: buildConsignmentSpecKey(profile.config.specs, validation.values),
specText: buildConsignmentSpecText(profile.config.specs, validation.values),
snapshotJson,
})
}
console.log('')
for (const [index, plan] of plans.entries()) {
const { inventory, submission } = plan
console.log(
`[${index + 1}] 库存 ${inventory.id} ${inventory.inventory_no} ` +
`${inventory.item_name}${submission ? ` / 提报 ${submission.id} ${submission.submission_no}` : ''}`,
)
console.log(
` inventory 分类 ${show(inventory.category_id)} → ${profile.categoryId} | ` +
`配置 ${show(inventory.profile_id)} → ${profile.profileId} | ` +
`版本 ${show(inventory.profile_version_id)} → ${profile.versionId}`,
)
console.log(
` spec_key ${show(inventory.spec_key)} → ${show(plan.specKey)}\n` +
` spec_text ${show(inventory.spec_text)} → ${show(plan.specText)}`,
)
if (submission) {
console.log(
` submission 分类 ${show(submission.category_id)} → ${profile.categoryId} | ` +
`配置 ${show(submission.profile_id)} → ${profile.profileId} | ` +
`版本 ${show(submission.profile_version_id)} → ${profile.versionId}`,
)
} else {
console.log(' submission (无来源提报单,跳过)')
}
}
if (skipped.length > 0) {
console.log('\n跳过(规格与目标配置不匹配,需人工确认):')
for (const item of skipped) {
console.log(
` - 库存 ${item.row.id} ${item.row.inventory_no} ${item.row.item_name}:${item.reason}`,
)
}
}
if (plans.length === 0) {
console.log('\n没有需要回填的数据。')
return
}
if (!apply) {
console.log('\n当前为预览模式,未写库。确认后追加 `--apply` 执行。')
return
}
await withTransaction(async (client) => {
for (const plan of plans) {
await client.query(
`UPDATE consignment_inventories
SET category_id = $1,
profile_id = $2,
profile_version_id = $3,
profile_snapshot_json = $4::jsonb,
spec_values_json = $5::jsonb,
spec_key = $6,
spec_text = $7,
updated_at = NOW()
WHERE id = $8 AND category_id IS NULL`,
[
profile.categoryId,
profile.profileId,
profile.versionId,
plan.snapshotJson,
plan.specValuesJson,
plan.specKey,
plan.specText,
plan.inventory.id,
],
)
if (plan.submission) {
await client.query(
`UPDATE consignment_submissions
SET category_id = $1,
profile_id = $2,
profile_version_id = $3,
profile_snapshot_json = $4::jsonb,
spec_values_json = $5::jsonb,
spec_key = $6,
spec_text = $7,
updated_at = NOW()
WHERE id = $8`,
[
profile.categoryId,
profile.profileId,
profile.versionId,
plan.snapshotJson,
plan.specValuesJson,
plan.specKey,
plan.specText,
plan.submission.id,
],
)
}
}
})
console.log(`\n已回填 ${plans.length} 条库存(提报单同步更新)。`)
}
try {
await main()
} finally {
await closeDb()
}
@@ -848,6 +848,14 @@ export async function approveAdminConsignmentSubmission(
errorCode: 'submission_already_reviewed',
})
}
// 分类/配置缺失的提报单不允许入库:库存一旦落 NULL,后台按分类永远查不到。
// 发布端已强制要求 profileId,这里是旧数据/旧客户端的最后一道防线。
if (!Number(submission.category_id) || !Number(submission.profile_id)) {
throw createHttpError('该提报单缺少寄卖分类,无法入库;请让打手在最新页面重新提报', {
statusCode: 409,
errorCode: 'consignment_category_required',
})
}
const now = nowIso()
const inventoryNo = generateConsignmentInventoryNo()
@@ -0,0 +1,43 @@
import assert from 'node:assert/strict'
import { readFile } from 'node:fs/promises'
import test from 'node:test'
async function readSource(fileName: string) {
return readFile(new URL(fileName, import.meta.url), 'utf8')
}
test('打手发布寄卖必须带已发布且挂有效分类的配置', async () => {
const source = await readSource('./consignment-worker-service.ts')
// 旧版页面不带 profileId:必须直接拒绝,不能落 category_id = NULL 的库存
assert.ok(
source.includes("errorCode: 'consignment_profile_required'"),
'缺少 profileId 时必须拒绝旧版页面提交',
)
assert.ok(source.includes('if (!profile) {'), '必须校验配置存在且已发布')
assert.ok(source.includes('if (!Number(profile.categoryId)) {'), '必须校验配置挂在有效分类下')
assert.ok(
source.includes("errorCode: 'consignment_category_required'"),
'配置缺少分类时必须有明确错误码',
)
})
test('审核入库必须拒绝缺少分类或配置的提报单', async () => {
const source = await readSource('./consignment-admin-service.ts')
assert.ok(
source.includes('!Number(submission.category_id) || !Number(submission.profile_id)'),
'审核入库前必须同时校验分类与配置',
)
assert.ok(
source.includes("errorCode: 'consignment_category_required'"),
'缺少分类时必须返回明确错误码',
)
// 校验必须早于入库写入,不能等 approveConsignmentSubmissionWithInbound 插完再报错
const guardIndex = source.indexOf(
'!Number(submission.category_id) || !Number(submission.profile_id)',
)
const inboundIndex = source.indexOf('approveConsignmentSubmissionWithInbound({')
assert.ok(guardIndex > 0 && inboundIndex > guardIndex, '分类校验必须早于入库写入')
})
@@ -343,18 +343,28 @@ export async function publishWorkerConsignment(workerId: number, payload: JsonOb
})
}
// 分类级寄卖配置:新链路必须带 profileId;存量调用不带则沿用旧逻辑。
// 分类级寄卖配置:发布必须带 profileId,且配置必须挂在有效分类下。
// 旧版页面不带 profileId 时不再落空分类(否则库存按分类永远查不到),直接要求刷新页面。
const profileIdInput = Number(payload.profileId ?? payload.profile_id ?? 0)
const profile =
Number.isInteger(profileIdInput) && profileIdInput > 0
? await getPublishedConsignmentProfileById(profileIdInput)
: null
if (Number.isInteger(profileIdInput) && profileIdInput > 0 && !profile) {
if (!Number.isInteger(profileIdInput) || profileIdInput <= 0) {
throw createHttpError('寄卖页面版本过旧,请刷新页面后重试', {
statusCode: 409,
errorCode: 'consignment_profile_required',
})
}
const profile = await getPublishedConsignmentProfileById(profileIdInput)
if (!profile) {
throw createHttpError('寄卖配置不存在或未发布', {
statusCode: 400,
errorCode: 'consignment_profile_unavailable',
})
}
if (!Number(profile.categoryId)) {
throw createHttpError('寄卖配置缺少分类,请联系管理员检查配置', {
statusCode: 409,
errorCode: 'consignment_category_required',
})
}
// 「允许修改寄售数量」关闭时固定 1 件:前端会禁用输入框,这里再兜一层防绕过。
const quantity = resolveConsignmentPublishQuantity(
profile?.config.fields.quantity !== false,