patch-number-input-defaults.mjs 2.33 KB
/**
 * 为 fixture 中缺少 value 的 numberInput 补 value: 0(对齐配置中心模版)
 * 排除:F2-24(本月待邀约由接口填充)
 * @see packageDynamicForm/docs/MAINTENANCE.md#schema-fixture-维护mock
 *
 * 用法:node packageDynamicForm/scripts/patch-number-input-defaults.mjs
 */
import { writeFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'

const __dirname = dirname(fileURLToPath(import.meta.url))
const pkgRoot = join(__dirname, '..')
const require = createRequire(import.meta.url)

const SKIP_KEYS = new Set(['F2-24'])

const FIXTURES = [
	'fixtures/schema-staff-daily-full.js',
	'fixtures/schema-store-daily-full.js',
	'fixtures/schema-negotiation-full.js'
]

function walkChildren(children, visit) {
	if (!children) return
	const rows = Array.isArray(children[0]) ? children : [children]
	for (const row of rows) {
		for (const child of row) {
			visit(child)
			walkChildren(child.children, visit)
		}
	}
}

function patchField(field, stats) {
	if (field?.type !== 'numberInput') return
	if (SKIP_KEYS.has(field.key)) {
		stats.skipped++
		return
	}
	if (field.value !== undefined) {
		stats.already++
		return
	}
	field.value = 0
	stats.patched++
}

function patchIndexedSchema(indexed) {
	const stats = { patched: 0, already: 0, skipped: 0 }
	for (const key of Object.keys(indexed)) {
		const field = indexed[key]
		patchField(field, stats)
		walkChildren(field.children, child => patchField(child, stats))
	}
	return stats
}

function serializeIndexed(indexed) {
	const lines = ['/** Config-center indexed schema (auto-generated) */', 'module.exports = {']
	const keys = Object.keys(indexed).sort((a, b) => Number(a) - Number(b))
	for (let i = 0; i < keys.length; i++) {
		const key = keys[i]
		const json = JSON.stringify(indexed[key], null, 2)
			.split('\n')
			.map(line => `  ${line}`)
			.join('\n')
		lines.push(`  "${key}": ${json.slice(2)}${i < keys.length - 1 ? ',' : ''}`)
	}
	lines.push('}', '')
	return lines.join('\n')
}

for (const rel of FIXTURES) {
	const filePath = join(pkgRoot, rel)
	const indexed = require(filePath)
	const stats = patchIndexedSchema(indexed)
	writeFileSync(filePath, serializeIndexed(indexed), 'utf8')
	console.log(`${rel}: patched=${stats.patched} already=${stats.already} skipped=${stats.skipped}`)
}