#!/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 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 { const res = await query( `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> { if (ids.length === 0) return new Map() const res = await query( `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() }