submit-adapter.js 12.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427
/**
 * 提交与回显适配 — 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, getVisibleGroupChildren } 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,
	REMOTE_SELECT_OPTIONS_KEYS,
	buildAppNormalizedListsFromJsonContent,
	buildAppJsonContent,
	serializeFormListForAppJsonStorage,
	resolveAppRowFieldEngineValue
} from './app-subform-json.js'
import { buildJsonContentPersistList } from './json-content-persist.js'
import { normalizePlanImportEchoValues } from './plan-import-echo-normalize.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 = {}, ctx = {}, schemaList = []) {
	const next = { ...field }
	const childrenSource =
		ctx && schemaList?.length
			? getVisibleGroupChildren(field, ctx, values, schemaList)
			: getStaticGroupChildren(field)
	const children = childrenSource.map(child => {
		const nextChild = { ...child }
		if (values[child.key] !== undefined) {
			nextChild.value = values[child.key]
		}
		return nextChild
	})
	return { ...next, children }
}

function applyValuesToFormList(
	list = [],
	values = {},
	ctx = {},
	schemaList = [],
	{ clearMissing = false } = {}
) {
	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, ctx, schemaList)
		}
		const nextField = { ...field }
		const isRemoteMultipleSelect = Boolean(
			field.key &&
			REMOTE_SELECT_OPTIONS_KEYS.has(field.optionsKey) &&
			field.type === 'multipleSelect'
		)
		if (values[field.key] !== undefined) {
			nextField.value = values[field.key]
			// 详情快照保留远程多选 App 双键;编辑保存时必须让 engine 当前值覆盖旧 meta。
			if (isRemoteMultipleSelect) {
				nextField[field.key] = values[field.key]
			}
		} else if (clearMissing) {
			// engine 会移除已清空字段;保存快照也必须删掉详情旧值,避免二次编辑回滚。
			delete nextField.value
			if (isRemoteMultipleSelect) {
				delete nextField[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 提交);group children 与 UI 一致按场景/品牌过滤 */
export function buildVisibleFormList(visibleList = [], values = {}, ctx = {}, schemaList = []) {
	return applyValuesToFormList(cloneJson(visibleList), values, ctx, schemaList)
}

/** 保存前收集 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 ctx = engine.getPageContext?.() || {}
	const schemaList = engine.getSchemaList?.() || []
	const topLevel = applyValuesToFormList(
		cloneJson(visibleList.filter(field => field.type !== 'subform')),
		saveValues,
		ctx,
		schemaList,
		{ clearMissing: true }
	)
	const subformSections = buildAppJsonContent(visibleList, cache, ctx)
	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)
		values = normalizePlanImportEchoValues(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
}