subform-duplicate-validation.js 3.5 KB
/** 模板驱动的 subform 重复值校验。 */
import {
	getVisibleList,
	getVisibleGroupChildFields,
	resolveEffectiveRowFields
} from './visibility.js'
import { getSubformRowTemplate } from './field-types.js'
import { buildGroupErrorKey, getGroupRows } from './group-values.js'
import { resolveSubformChildValue } from './subform-child-validation-value.js'

export function normalizeDuplicateValue(value) {
	if (value === undefined || value === null) return null
	if (typeof value === 'string') {
		const normalized = value.trim()
		return normalized === '' ? null : normalized
	}
	if (Array.isArray(value)) {
		return value.length ? JSON.stringify(value) : null
	}
	if (typeof value === 'object') {
		return JSON.stringify(value)
	}
	return String(value)
}

function resolveDuplicateKeys(group = {}) {
	if (!Array.isArray(group.validateDuplicates)) return []
	const childKeys = new Set(getSubformRowTemplate(group).map(child => child.key))
	return group.validateDuplicates.filter(
		key => typeof key === 'string' && key !== '' && childKeys.has(key)
	)
}

function findDuplicateRowIndexes(group, child, list, ctx, values, groupRowsCache) {
	const rows = getGroupRows(values, group.key)
	const rowFieldsList = groupRowsCache[group.key] || []
	const rowCount = Math.max(rows.length, rowFieldsList.length)
	const indexesByValue = new Map()

	for (let rowIndex = 0; rowIndex < rowCount; rowIndex++) {
		const row = rows[rowIndex] || {}
		const rowFields = rowFieldsList[rowIndex] || []
		const effectiveRowFields = resolveEffectiveRowFields(group, rowFields, row)
		const visibleKeys = new Set(
			getVisibleGroupChildFields(
				group,
				ctx,
				values,
				list,
				effectiveRowFields,
				row
			).map(field => field.key)
		)
		if (!visibleKeys.has(child.key)) continue

		const rowField = effectiveRowFields.find(field => field.key === child.key)
		const normalized = normalizeDuplicateValue(
			resolveSubformChildValue(child, row, rowField)
		)
		if (normalized === null) continue
		const indexes = indexesByValue.get(normalized) || []
		indexes.push(rowIndex)
		indexesByValue.set(normalized, indexes)
	}

	return [...indexesByValue.values()]
		.filter(indexes => indexes.length > 1)
		.flat()
		.sort((left, right) => left - right)
}

/**
 * @returns {{ ok: boolean, errors: Array, errorMap: object }}
 */
export function validateSubformDuplicates(
	list = [],
	ctx = {},
	values = {},
	groupRowsCache = {}
) {
	const visibleGroups = getVisibleList(list, ctx, values).filter(
		field => field.type === 'subform'
	)

	for (const group of visibleGroups) {
		const children = getSubformRowTemplate(group)
		for (const childKey of resolveDuplicateKeys(group)) {
			const child = children.find(field => field.key === childKey)
			if (!child) continue
			const rowIndexes = findDuplicateRowIndexes(
				group,
				child,
				list,
				ctx,
				values,
				groupRowsCache
			)
			if (!rowIndexes.length) continue

			const rowNumbers = rowIndexes.map(index => index + 1)
			const message = `第${rowNumbers.join(',')}行${child.label}重复`
			const errorMap = {}
			rowIndexes.forEach(rowIndex => {
				errorMap[buildGroupErrorKey(group.key, rowIndex, child.key)] = message
			})
			const firstRowIndex = rowIndexes[0]
			return {
				ok: false,
				errors: [{
					key: buildGroupErrorKey(group.key, firstRowIndex, child.key),
					label: `${group.label} 第${firstRowIndex + 1}行 ${child.label}`,
					message,
					groupKey: group.key,
					rowIndex: firstRowIndex,
					childKey: child.key
				}],
				errorMap
			}
		}
	}

	return { ok: true, errors: [], errorMap: {} }
}