submit-adapter.js 11.6 KB
/**
 * 提交与回显适配 — jsonContent / fieldDataList / subformDataList
 * @see packageDynamicForm/docs/ARCHITECTURE.md
 * @see packageDynamicForm/docs/group-repeater.md
 *
 * buildDynamicSavePayload:lists 仅可见;jsonContent 含持久化隐藏值
 * parseJsonContentDetailValues:仅从 jsonContent 解析 values;radio/select/multipleSelect 归一化
 */
import { getVisibleList, getVisibleLeafFields } from './visibility.js'
import { normalizeRadioValuesInMap } from './radio-value.js'
import { normalizeSelectValuesInMap, coerceSelectValue } from './select-value.js'
import { normalizeMultipleSelectValuesInMap, coerceMultipleSelectValue } from './multiple-select-value.js'
import { getGroupRows } from './group-values.js'
import { getSubformRowTemplate, getStaticGroupChildren } from './field-types.js'
import {
	rowsToValueMaps,
	rowsToStorageValueMaps,
	extractSubformValuesFromField,
	getRowTemplate,
	valueMapsToRowFieldsList,
	isRowFieldsList,
	rowFieldsToValueMap
} from './group-row-adapter.js'
import {
	normalizeJsonContentList,
	getSectionRowFieldsList,
	isValueMapList,
	buildNormalizedFieldDataList,
	buildNormalizedSubformDataList,
	mapSchemaFieldToStorageType,
	serializeFieldValueForStorage,
	buildAppNormalizedListsFromJsonContent,
	buildAppJsonContent,
	serializeFormListForAppJsonStorage,
	resolveAppRowFieldEngineValue
} from './app-subform-json.js'
import { buildJsonContentPersistList } from './json-content-persist.js'

export {
	buildJsonContentPersistList,
	hasMeaningfulPersistValue,
	isTemplateOnlyDefaultValue,
	shouldPersistHiddenBlock,
	failsStructuralPersistVisibility
} from './json-content-persist.js'

export {
	buildNormalizedFieldDataList,
	buildNormalizedSubformDataList,
	mapSchemaFieldToStorageType,
	serializeFieldValueForStorage
} from './app-subform-json.js'

function cloneJson(data) {
	return JSON.parse(JSON.stringify(data))
}

function applyStaticGroupValues(field = {}, values = {}) {
	const next = { ...field }
	const children = getStaticGroupChildren(field).map(child => {
		const nextChild = { ...child }
		if (values[child.key] !== undefined) {
			nextChild.value = values[child.key]
		}
		return nextChild
	})
	return { ...next, children }
}

function applyValuesToFormList(list = [], values = {}) {
	return (list || []).map(field => {
		if (field.type === 'subform') {
			const nextGroup = { ...field }
			const template = getRowTemplate(field)
			const maps = getGroupRows(values, field.key)
			if (maps.length && template.length) {
				nextGroup.value = valueMapsToRowFieldsList(template, maps)
			} else if (values[field.key] !== undefined) {
				nextGroup.value = cloneJson(values[field.key])
			}
			return nextGroup
		}
		if (field.type === 'group') {
			return applyStaticGroupValues(field, values)
		}
		const nextField = { ...field }
		if (values[field.key] !== undefined) {
			nextField.value = values[field.key]
		}
		return nextField
	})
}

/** 将 values 回写到 schema list 各字段的 value 属性 */
export function mergeValuesIntoSchema(schemaRoot = {}, values = {}) {
	const nextSchema = cloneJson(schemaRoot)
	nextSchema.list = applyValuesToFormList(nextSchema.list || [], values)
	return nextSchema
}

/** 构建带当前值的可见 formList(用于 jsonContent 提交) */
export function buildVisibleFormList(visibleList = [], values = {}) {
	return applyValuesToFormList(cloneJson(visibleList), values)
}

/** 保存前收集 engine 最新 values(subform 以 groupRowsCache 为准与 UI 对齐) */
export function collectSaveValues(engine, visibleList = []) {
	const values = { ...(engine.getValues?.() || {}) }
	const cache = engine.getGroupRowsCache?.() || {}
	;(visibleList || []).forEach(field => {
		if (field.type !== 'subform') {
			return
		}
		const rowFieldsList = cache[field.key]
		if (Array.isArray(rowFieldsList) && rowFieldsList.length) {
			values[field.key] = rowsToValueMaps(rowFieldsList)
		}
	})
	return values
}

/** subform 行 valueMap(fieldDataList / subformDataList 专用,optionsKey 保留完整 object) */
export function collectSubformStorageValues(engine, visibleList = []) {
	const values = {}
	const cache = engine.getGroupRowsCache?.() || {}
	;(visibleList || []).forEach(field => {
		if (field.type !== 'subform') {
			return
		}
		const rowFieldsList = cache[field.key]
		if (Array.isArray(rowFieldsList) && rowFieldsList.length) {
			values[field.key] = rowsToStorageValueMaps(rowFieldsList)
		}
	})
	return values
}

function mergeStorageValues(saveValues = {}, engine, visibleList = []) {
	return { ...saveValues, ...collectSubformStorageValues(engine, visibleList) }
}

function assembleFormListForSaveListsWithValues(engine, visibleList = [], saveValues = {}) {
	const cache = engine.getGroupRowsCache?.() || {}
	const topLevel = buildVisibleFormList(
		visibleList.filter(field => field.type !== 'subform'),
		saveValues
	)
	const subformSections = buildAppJsonContent(visibleList, cache)
	return [...topLevel, ...subformSections]
}

/** 组装 fieldDataList/subformDataList 用的 formList(顶层 + App 形态 subform children) */
export function assembleFormListForSaveLists(engine, visibleList = []) {
	const saveValues = collectSaveValues(engine, visibleList)
	return assembleFormListForSaveListsWithValues(engine, visibleList, saveValues)
}

/** 组装 jsonContent 用的 formList(可见 + 有值的隐藏字段) */
export function assembleFormListForJsonContent(engine) {
	const schemaList = engine.getSchemaList?.() || []
	const visibleList = engine.getVisibleList?.() || []
	const values = engine.getValues?.() || {}
	const cache = engine.getGroupRowsCache?.() || {}
	const ctx = engine.getPageContext?.() || {}
	const persistList = buildJsonContentPersistList(
		schemaList,
		visibleList,
		values,
		cache,
		ctx
	)
	const saveValues = collectSaveValues(engine, persistList)
	return assembleFormListForSaveListsWithValues(engine, persistList, saveValues)
}

/** 从 formList 提取 values(含 subform 行与静态 group 子字段) */
export function extractValuesFromFormList(list = []) {
	const values = {}
	;(list || []).forEach(field => {
		if (field.type === 'subform') {
			const maps = extractSubformValuesFromField(field)
			if (maps?.length) {
				values[field.key] = maps
			}
			return
		}
		if (field.type === 'group') {
			getStaticGroupChildren(field).forEach(child => {
				if (
					child.value !== undefined &&
					child.value !== null &&
					child.value !== ''
				) {
					values[child.key] = child.value
				}
			})
			return
		}
		if (field.type === 'divider') {
			return
		}
		const v = resolveAppRowFieldEngineValue(field)
		if (v !== undefined && v !== null && v !== '') {
			if (Array.isArray(v) && v.length === 0) {
				return
			}
			values[field.key] =
				field.type === 'multipleSelect' && !field.optionsKey
					? coerceMultipleSelectValue(v)
					: field.type === 'select' && !field.optionsKey
						? coerceSelectValue(v)
						: v
		}
	})
	return values
}

function pushFieldDataItem(items, item) {
	items.push(item)
}

/** 构建原始 fieldDataList(含 groupKey/rowIndex,非规范化存储类型) */
export function buildFieldDataList(visibleList = [], values = {}) {
	const items = []
	;(visibleList || []).forEach(field => {
		if (field.type === 'subform') {
			return
		}
		if (field.type === 'group') {
			getStaticGroupChildren(field).forEach(child => {
				const fieldValue = values[child.key]
				if (fieldValue === undefined || fieldValue === null || fieldValue === '') {
					return
				}
				pushFieldDataItem(items, {
					fieldKey: child.key,
					fieldName: child.label,
					fieldType: child.type,
					fieldValue
				})
			})
			return
		}
		if (field.type === 'divider') {
			return
		}
		const fieldValue = values[field.key]
		if (fieldValue === undefined || fieldValue === null || fieldValue === '') {
			return
		}
		pushFieldDataItem(items, {
			fieldKey: field.key,
			fieldName: field.label,
			fieldType: field.type,
			fieldValue
		})
	})
	return items
}

/** 组装动态表单保存 payload(jsonContent + fieldDataList + subformDataList) */
export function buildDynamicSavePayload({
	reportTemplateId,
	dailyReportRecordId,
	engine,
	reportDate,
	normalizedFieldDataList = false
}) {
	const visibleList = engine.getVisibleList()
	const saveValues = collectSaveValues(engine, visibleList)
	const listValues = normalizedFieldDataList
		? mergeStorageValues(saveValues, engine, visibleList)
		: saveValues
	let fieldDataList
	let subformDataList = []
	let jsonContent
	if (normalizedFieldDataList) {
		const formListForLists = assembleFormListForSaveLists(engine, visibleList)
		const formListForJson = assembleFormListForJsonContent(engine)
		jsonContent = JSON.stringify(serializeFormListForAppJsonStorage(formListForJson))
		;({ fieldDataList, subformDataList } = buildAppNormalizedListsFromJsonContent(
			JSON.stringify(formListForLists)
		))
	} else {
		fieldDataList = buildFieldDataList(visibleList, listValues)
		jsonContent = JSON.stringify(
			serializeFormListForAppJsonStorage(assembleFormListForJsonContent(engine))
		)
	}
	const payload = {
		reportTemplateId,
		jsonContent,
		fieldDataList,
		subformDataList
	}
	if (dailyReportRecordId) {
		payload.dailyReportRecordId = dailyReportRecordId
	}
	return payload
}

/** 将 fieldDataList 条目值按 fieldType 反序列化为 JS 值 */
export function coerceFieldDataListValue(item = {}) {
	const { fieldValue, fieldType } = item
	if (fieldValue === undefined || fieldValue === null || fieldValue === '') {
		return undefined
	}
	if (fieldType === 'JSON' && typeof fieldValue === 'string') {
		try {
			return JSON.parse(fieldValue)
		} catch (error) {
			return fieldValue
		}
	}
	if (fieldType === 'INT' || fieldType === 'DECIMAL') {
		if (typeof fieldValue === 'string') {
			const num = Number(fieldValue)
			return Number.isNaN(num) ? fieldValue : num
		}
	}
	if (fieldType === 'BOOL' && typeof fieldValue === 'string') {
		if (fieldValue === 'true') return true
		if (fieldValue === 'false') return false
	}
	return fieldValue
}

/** 从 detail.get jsonContent 解析 values(唯一回显数据源) */
export function parseJsonContentDetailValues(jsonContent, schemaList = []) {
	const list = normalizeJsonContentList(jsonContent)
	if (!list.length) {
		return {}
	}

	let values = {}
	list.forEach(field => {
		if (field.type === 'subform') {
			const rowFieldsList = getSectionRowFieldsList(field)
			if (!rowFieldsList.length) {
				return
			}
			if (isRowFieldsList(rowFieldsList)) {
				values[field.key] = rowsToValueMaps(rowFieldsList)
			} else if (isValueMapList(rowFieldsList)) {
				values[field.key] = cloneJson(rowFieldsList)
			} else {
				values[field.key] = [rowFieldsToValueMap(rowFieldsList)]
			}
			return
		}
		Object.assign(values, extractValuesFromFormList([field]))
	})

	if (Array.isArray(schemaList) && schemaList.length) {
		values = normalizeRadioValuesInMap(schemaList, values)
		values = normalizeSelectValuesInMap(schemaList, values)
		values = normalizeMultipleSelectValuesInMap(schemaList, values)
	}

	return values
}

/** 从品牌列表提取 brandId 数组(含 -1 占位取 firstBrandId) */
export function mapBrandListToBrandIds(list = []) {
	const brandIds = []
	list.forEach(item => {
		if (item.brandId > 0) {
			brandIds.push(item.brandId)
		} else if (item.brandId === -1 && item.firstBrandId) {
			brandIds.push(item.firstBrandId)
		}
	})
	return brandIds
}

export default {
	buildFieldDataList,
	buildNormalizedFieldDataList,
	buildNormalizedSubformDataList,
	buildDynamicSavePayload,
	buildVisibleFormList,
	assembleFormListForSaveLists,
	assembleFormListForJsonContent,
	buildJsonContentPersistList,
	collectSaveValues,
	mergeValuesIntoSchema,
	extractValuesFromFormList,
	parseJsonContentDetailValues,
	mapBrandListToBrandIds,
	mapSchemaFieldToStorageType,
	serializeFieldValueForStorage,
	coerceFieldDataListValue,
	getVisibleLeafFields
}