storeDailyReportDetail.test.mjs 22.4 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 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { createRequire } from 'node:module'

const require = createRequire(import.meta.url)
const {
	parseJsonContentDetailValues,
	mergeValuesIntoSchema
} = await import('../form-engine/submit-adapter.js')
const { createFormEngine } = await import('../form-engine/core.js')
const { isReportSubmitted, normalizeReportStatus } = require('../utils/report-status.js')
const {
	buildStoreDailyDetailResponseData
} = require('../utils/store-daily-detail-response.js')
const { DEFAULT_REPORT_TEMPLATE_ID } = require('../api/mockStoreDynamicDetail.js')
const { loadSchemaFixture } = await import('./schemaFixture.mjs')

const storeDailyApiUrl = new URL('../api/storeDailyReport.js', import.meta.url)

function loadStoreDailyApi(overrides = {}, dependencies = {}) {
	const apiRequire = createRequire(storeDailyApiUrl)
	const actualAdapters = apiRequire('./storeDailyReportAdapters.js')
	const requireForApi = specifier => {
		if (specifier === '~/config.js') {
			return { envIndex: 0 }
		}
		if (specifier === './dynamicDailyReport.js') {
			return dependencies.dynamicDailyReport || {
				dynamicDailyReportSave: async () => ({ code: 0, data: {} })
			}
		}
		if (specifier === './fieldOptionsService.js' && dependencies.fieldOptionsService) {
			return dependencies.fieldOptionsService
		}
		if (specifier === './storeDailyReportAdapters.js') {
			return { ...actualAdapters, ...overrides }
		}
		return apiRequire(specifier)
	}
	const source = readFileSync(storeDailyApiUrl, 'utf8').replace(
		/import\s*\{([\s\S]*?)\}\s*from\s*['"]([^'"]+)['"]/g,
		(_match, imports, specifier) => `const {${imports}} = require('${specifier}')`
	)
	const module = { exports: {} }
	new Function('require', 'module', 'exports', 'wx', source)(
		requireForApi,
		module,
		module.exports,
		dependencies.wx || {}
	)
	return module.exports
}

function selectValueMapId(value) {
	if (value != null && typeof value === 'object' && !Array.isArray(value)) {
		return value.id ?? value.value
	}
	return value
}

function normalizeDetailFixture(detail = {}, reportTemplateId) {
	const jsonContent = detail.jsonContent || ''
	return buildStoreDailyDetailResponseData({
		detail,
		reportTemplateId,
		defaultReportTemplateId: DEFAULT_REPORT_TEMPLATE_ID,
		jsonContent,
		values: parseJsonContentDetailValues(jsonContent, [])
	})
}

describe('storeDailyReport detail response', () => {
	it('IT-STORE-DETAIL-007: valid detail jsonContent is the schema snapshot without loading the current template', async () => {
		let currentTemplateCalls = 0
		const api = loadStoreDailyApi({
			fetchSchemaRootAdapter: async () => {
				currentTemplateCalls += 1
				return {
					code: 0,
					message: 'ok',
					data: {
						list: [
							{ key: 'F2-101', label: '新模板字段', type: 'numberInput' }
						]
					}
				}
			}
		})
		const historicalList = [
			{
				label: '其他品牌售后部数据 (轻改)',
				key: 'F2-58',
				type: 'subform',
				rules: { maxRows: 20 },
				origin_children: [
					{
						label: 'SA',
						key: 'F2-58-1',
						type: 'select',
						optionsKey: '4sStaffList'
					},
					{ label: '今日谈客数', key: 'F2-58-2', type: 'numberInput' },
					{ label: '今日成交数', key: 'F2-58-3', type: 'numberInput' },
					{ label: '今日成交金额', key: 'F2-58-4', type: 'numberInput' }
				],
				childrenValue: [
					{
						'F2-58': {
							'F2-58-1': {
								text: '测试1230622',
								value: '1a1ba1477f684b7886be8aa01440a260'
							},
							'F2-58-2': 2,
							'F2-58-3': 3,
							'F2-58-4': 15
						}
					}
				]
			}
		]

		const result = await api.fetchSchema({
			reportTemplateId: 10002,
			baseSceneCode: 100101,
			merchantId: 'm-old-template',
			detail: { jsonContent: JSON.stringify(historicalList) }
		})

		assert.equal(currentTemplateCalls, 0)
		assert.equal(result.code, 0)
		assert.deepEqual(result.data.list.map(field => field.key), ['F2-58'])
		assert.equal(result.data.list[0].label, '其他品牌售后部数据 (轻改)')
		assert.equal(
			result.initialValues['F2-58'][0]['F2-58-1'].id,
			'1a1ba1477f684b7886be8aa01440a260'
		)
		assert.equal(result.initialValues['F2-58'][0]['F2-58-2'], 2)
		assert.equal(result.initialValues['F2-58'][0]['F2-58-3'], 3)
		assert.equal(result.initialValues['F2-58'][0]['F2-58-4'], 15)
	})

	it('IT-STORE-DETAIL-008: incomplete detail schema falls back to the current template', async () => {
		let currentTemplateCalls = 0
		const api = loadStoreDailyApi({
			fetchSchemaRootAdapter: async () => {
				currentTemplateCalls += 1
				return {
					code: 0,
					message: 'ok',
					data: {
						list: [
							{ key: 'F2-101', label: '当前模板字段', type: 'numberInput' }
						]
					}
				}
			}
		})

		const result = await api.fetchSchema({
			reportTemplateId: 10002,
			baseSceneCode: 100101,
			merchantId: 'm-invalid-snapshot',
			detail: {
				jsonContent: JSON.stringify([
					{ key: 'F2-58', label: '损坏的历史子表单', type: 'subform' }
				])
			}
		})

		assert.equal(currentTemplateCalls, 1)
		assert.equal(result.code, 0)
		assert.deepEqual(result.data.list.map(field => field.key), ['F2-101'])
	})

	it('IT-STORE-DETAIL-009: detail snapshot revalidation skips only the current schema refresh', async () => {
		const calls = { brand: 0, scene: 0, schema: 0 }
		const api = loadStoreDailyApi({
			fetchBrandAdapter: async () => {
				calls.brand += 1
				return { code: 0, data: [] }
			},
			fetchSceneAdapter: async () => {
				calls.scene += 1
				return { code: 0, data: [] }
			},
			fetchSchemaRootAdapter: async () => {
				calls.schema += 1
				return { code: 0, data: { list: [] } }
			}
		})

		await api.revalidateCachedMetadata({
			userContext: { merchantId: 'm-old-template', staffUuid: 's1' },
			baseSceneCode: 100101,
			reportTemplateId: 10002,
			skipSchema: true
		})

		assert.deepEqual(calls, { brand: 1, scene: 1, schema: 0 })
	})

	it('IT-STORE-DETAIL-001: normalizeDetailResponse maps reportStatus', () => {
		const data = normalizeDetailFixture(
			{
				id: 99001,
				reportTemplateId: 10002,
				reportStatus: 1,
				jsonContent: JSON.stringify([{ key: 'F2-2', type: 'numberInput', value: 3 }])
			},
			10002
		)
		assert.equal(data.dailyReportRecordId, 99001)
		assert.equal(data.reportStatus, '1')
		assert.equal(data.values['F2-2'], 3)
	})

	it('IT-STORE-DETAIL-002: empty detail defaults reportStatus to 0', () => {
		const data = normalizeDetailFixture({}, 10002)
		assert.equal(data.reportStatus, '0')
		assert.equal(data.dailyReportRecordId, null)
		assert.equal(data.reportTemplateId, DEFAULT_REPORT_TEMPLATE_ID)
	})

	it('IT-STORE-DETAIL-004: F2-1 echoes from jsonContent through schema merge and engine init', () => {
		const storeSchema = loadSchemaFixture('store')
		const detail = normalizeDetailFixture({
			jsonContent: JSON.stringify([
				{ key: 'F2-2', type: 'numberInput', value: 3 },
				{ key: 'F2-1', type: 'multipleSelect', value: ['staff-001', 'staff-002'] }
			])
		})
		const values = parseJsonContentDetailValues(detail.jsonContent, storeSchema.list)
		const mergedSchema = mergeValuesIntoSchema(storeSchema, values)
		const engine = createFormEngine()
		const viewState = engine.init(mergedSchema, {
			baseSceneCode: 110201,
			brandIds: [3067, 3454],
			sceneList: [{ baseSceneCode: 110201 }]
		})
		assert.deepEqual(viewState.values['F2-1'], ['staff-001', 'staff-002'])
		assert.equal(viewState.values['F2-2'], 3)
	})

	it('IT-STORE-DETAIL-006: F2-1 dual key jsonContent echoes id and name pairs', () => {
		const storeSchema = loadSchemaFixture('store')
		const detail = normalizeDetailFixture({
			jsonContent: JSON.stringify([
				{ key: 'F2-2', type: 'numberInput', value: 3 },
				{
					key: 'F2-1',
					type: 'multipleSelect',
					optionsKey: 'storeStaffList',
					value: '张三/李四',
					'F2-1': ['staff-001', 'staff-002']
				}
			])
		})
		const values = parseJsonContentDetailValues(detail.jsonContent, storeSchema.list)
		const mergedSchema = mergeValuesIntoSchema(storeSchema, values)
		const engine = createFormEngine()
		const viewState = engine.init(mergedSchema, {
			baseSceneCode: 110201,
			brandIds: [3067, 3454],
			sceneList: [{ baseSceneCode: 110201 }]
		})
		assert.deepEqual(viewState.values['F2-1'], [
			{ id: 'staff-001', name: '张三' },
			{ id: 'staff-002', name: '李四' }
		])
	})

	it('IT-STORE-SAVE-STAFF-001: F2-101 id-only echo saves real staff names in requestJson', async () => {
		const staffIds = [
			'54ad4f759690407899a691f1bdc57ab6',
			'79113db6545841d886687ae35ffe8651'
		]
		let submittedRequest = null
		let fieldOptionsCall = null
		const api = loadStoreDailyApi(
			{ saveEchoAdapter: payload => payload },
			{
				dynamicDailyReport: {
					dynamicDailyReportSave: async request => {
						submittedRequest = request
						return { code: 0, message: 'ok', data: { dailyReportRecordId: 'record-1' } }
					}
				},
				fieldOptionsService: {
					fetchFieldOptions: async (params, options) => {
						fieldOptionsCall = { params, options }
						return {
							code: 0,
							message: 'ok',
							data: [
								{ id: staffIds[0], value: staffIds[0], name: '驻店人员甲', label: '驻店人员甲' },
								{ id: staffIds[1], value: staffIds[1], name: '驻店人员乙', label: '驻店人员乙' }
							]
						}
					}
				},
				wx: {
					$util: {
						getUserInfo: () => ({
							merchantId: 'shop-1',
							yqMerchantId: 'yq-1',
							staffUuid: 'reporter-1',
							staffName: '填报人'
						})
					}
				}
			}
		)
		const schema = {
			list: [{
				key: 'F2-101',
				label: '今日驻店人员',
				type: 'multipleSelect',
				optionsKey: 'storeStaffList',
				options: []
			}]
		}
		const idOnlyJsonContent = JSON.stringify([{
			...schema.list[0],
			value: staffIds.join('/'),
			'F2-101': staffIds
		}])
		const initialValues = parseJsonContentDetailValues(idOnlyJsonContent, schema.list)
		const engine = createFormEngine()
		engine.init(schema, {
			merchantId: 'shop-1',
			yqMerchantId: 'yq-1',
			initialValues
		})

		const result = await api.submitForm({
			engine,
			reportTemplateId: 'template-1',
			reportDate: '2026-08-26'
		})

		assert.equal(result.code, 0)
		const f2101 = JSON.parse(submittedRequest.requestJson).fieldDataList.find(
			item => item.fieldKey === 'F2-101'
		)
		assert.deepEqual(JSON.parse(f2101.fieldValue), [
			{ id: staffIds[0], name: '驻店人员甲' },
			{ id: staffIds[1], name: '驻店人员乙' }
		])
		assert.equal(fieldOptionsCall.params.optionsKey, 'storeStaffList')
		assert.equal(fieldOptionsCall.params.yqMerchantId, 'yq-1')
		assert.deepEqual(fieldOptionsCall.options, { useCache: false })
	})

	it('IT-STORE-SAVE-STAFF-002: unresolved legacy F2-1 staff UUID blocks save instead of using UUID as name', async () => {
		const missingStaffId = '54ad4f759690407899a691f1bdc57ab6'
		let submitCalls = 0
		const api = loadStoreDailyApi(
			{},
			{
				dynamicDailyReport: {
					dynamicDailyReportSave: async () => {
						submitCalls += 1
						return { code: 0, data: {} }
					}
				},
				fieldOptionsService: {
					fetchFieldOptions: async () => ({ code: 0, message: 'ok', data: [] })
				},
				wx: {
					$util: {
						getUserInfo: () => ({
							merchantId: 'shop-1',
							yqMerchantId: 'yq-1',
							staffUuid: 'reporter-1'
						})
					}
				}
			}
		)
		const schema = {
			list: [{
				key: 'F2-1',
				label: '今日驻店人员',
				type: 'multipleSelect',
				optionsKey: 'storeStaffList',
				options: []
			}]
		}
		const engine = createFormEngine()
		engine.init(schema, {
			merchantId: 'shop-1',
			yqMerchantId: 'yq-1',
			initialValues: { 'F2-1': [missingStaffId] }
		})

		const result = await api.submitForm({
			engine,
			reportTemplateId: 'template-1',
			reportDate: '2026-08-26'
		})

		assert.equal(result.code, 10002)
		assert.match(result.message, /今日驻店人员信息已失效,请重新选择/)
		assert.equal(submitCalls, 0)
	})

	it('IT-STORE-SAVE-STAFF-003: staff option failures block save and consistently ask for reselection', async () => {
		const staffId = '54ad4f759690407899a691f1bdc57ab6'
		const scenarios = [
			{
				label: 'request throws',
				fetchFieldOptions: async () => { throw new Error('network error') }
			},
			{
				label: 'backend returns an error',
				fetchFieldOptions: async () => ({ code: 500, message: '员工接口异常', data: [] })
			},
			{
				label: 'success payload is malformed',
				fetchFieldOptions: async () => ({ code: 0, message: 'ok', data: {} })
			}
		]

		for (const scenario of scenarios) {
			let submitCalls = 0
			const api = loadStoreDailyApi(
				{},
				{
					dynamicDailyReport: {
						dynamicDailyReportSave: async () => {
							submitCalls += 1
							return { code: 0, data: {} }
						}
					},
					fieldOptionsService: {
						fetchFieldOptions: scenario.fetchFieldOptions
					},
					wx: {
						$util: {
							getUserInfo: () => ({
								merchantId: 'shop-1',
								yqMerchantId: 'yq-1',
								staffUuid: 'reporter-1'
							})
						}
					}
				}
			)
			const engine = createFormEngine()
			engine.init({
				list: [{
					key: 'F2-101',
					label: '今日驻店人员',
					type: 'multipleSelect',
					optionsKey: 'storeStaffList',
					options: []
				}]
			}, {
				merchantId: 'shop-1',
				yqMerchantId: 'yq-1',
				initialValues: { 'F2-101': [staffId] }
			})

			const result = await api.submitForm({
				engine,
				reportTemplateId: 'template-1',
				reportDate: '2026-08-26'
			})

			assert.notEqual(result.code, 0, scenario.label)
			assert.match(result.message, /请重新选择/, scenario.label)
			assert.equal(submitCalls, 0, scenario.label)
		}
	})

	it('IT-STORE-SAVE-LATEST-001: edited staff and remark override stale detail dual-key values', async () => {
		const staffIds = [
			'54ad4f759690407899a691f1bdc57ab6',
			'79113db6545841d886687ae35ffe8651',
			'bea8b2af2b4143c0ab0c3af100b1437f'
		]
		const editedStaff = [
			{ id: staffIds[0], name: '驻店人员甲' },
			{ id: staffIds[1], name: '驻店人员乙' },
			{ id: staffIds[2], name: '驻店人员丙' }
		]
		let submittedRequest = null
		const api = loadStoreDailyApi(
			{},
			{
				dynamicDailyReport: {
					dynamicDailyReportSave: async request => {
						submittedRequest = request
						return { code: 0, message: 'ok', data: { dailyReportRecordId: 'record-1' } }
					}
				},
				wx: {
					$util: {
						getUserInfo: () => ({
							merchantId: 'shop-1',
							yqMerchantId: 'yq-1',
							staffUuid: 'reporter-1',
							staffName: '填报人'
						})
					}
				}
			}
		)
		const schema = {
			list: [
				{
					key: 'F2-101',
					label: '今日驻店人员',
					type: 'multipleSelect',
					optionsKey: 'storeStaffList',
					options: [],
					value: staffIds.slice(0, 2).join('/'),
					'F2-101': staffIds.slice(0, 2)
				},
				{
					key: 'F2-remark',
					label: '备注',
					type: 'textarea',
					rules: { maxLength: 100 },
					value: '旧备注'
				}
			]
		}
		const initialValues = parseJsonContentDetailValues(
			JSON.stringify(schema.list),
			schema.list
		)
		const engine = createFormEngine()
		engine.init(schema, {
			merchantId: 'shop-1',
			yqMerchantId: 'yq-1',
			initialValues
		})
		engine.setFieldValue('F2-101', editedStaff)
		engine.setFieldValue('F2-remark', '编辑后的最新备注')

		const result = await api.submitForm({
			engine,
			reportTemplateId: 'template-1',
			dailyReportRecordId: 'record-1',
			reportDate: '2026-08-26'
		})

		assert.equal(result.code, 0)
		const fieldDataList = JSON.parse(submittedRequest.requestJson).fieldDataList
		const staffField = fieldDataList.find(item => item.fieldKey === 'F2-101')
		const remarkField = fieldDataList.find(item => item.fieldKey === 'F2-remark')
		assert.deepEqual(JSON.parse(staffField.fieldValue), editedStaff)
		assert.equal(remarkField.fieldValue, '编辑后的最新备注')
	})

	it('IT-STORE-SAVE-LATEST-002: cleared staff and remark do not reuse stale detail values', async () => {
		const staffIds = [
			'54ad4f759690407899a691f1bdc57ab6',
			'79113db6545841d886687ae35ffe8651'
		]
		let submittedRequest = null
		const api = loadStoreDailyApi(
			{},
			{
				dynamicDailyReport: {
					dynamicDailyReportSave: async request => {
						submittedRequest = request
						return { code: 0, message: 'ok', data: { dailyReportRecordId: 'record-1' } }
					}
				},
				wx: {
					$util: {
						getUserInfo: () => ({
							merchantId: 'shop-1',
							yqMerchantId: 'yq-1',
							staffUuid: 'reporter-1',
							staffName: '填报人'
						})
					}
				}
			}
		)
		const schema = {
			list: [
				{
					key: 'F2-101',
					label: '今日驻店人员',
					type: 'multipleSelect',
					optionsKey: 'storeStaffList',
					options: [],
					value: staffIds.join('/'),
					'F2-101': staffIds
				},
				{
					key: 'F2-remark',
					label: '备注',
					type: 'textarea',
					rules: { maxLength: 100 },
					value: '旧备注'
				}
			]
		}
		const initialValues = parseJsonContentDetailValues(
			JSON.stringify(schema.list),
			schema.list
		)
		const engine = createFormEngine()
		engine.init(schema, {
			merchantId: 'shop-1',
			yqMerchantId: 'yq-1',
			initialValues
		})
		engine.setFieldValue('F2-101', [])
		engine.setFieldValue('F2-remark', '')

		const result = await api.submitForm({
			engine,
			reportTemplateId: 'template-1',
			dailyReportRecordId: 'record-1',
			reportDate: '2026-08-26'
		})

		assert.equal(result.code, 0)
		const fieldDataList = JSON.parse(submittedRequest.requestJson).fieldDataList
		assert.ok(!fieldDataList.some(item => item.fieldKey === 'F2-101'))
		assert.ok(!fieldDataList.some(item => item.fieldKey === 'F2-remark'))
		const jsonContent = JSON.parse(submittedRequest.jsonContent)
		const staffField = jsonContent.find(item => item.key === 'F2-101')
		const remarkField = jsonContent.find(item => item.key === 'F2-remark')
		assert.ok(!Object.hasOwn(staffField, 'value'))
		assert.ok(!Object.hasOwn(staffField, 'F2-101'))
		assert.ok(!Object.hasOwn(remarkField, 'value'))
	})

	it('IT-STORE-SAVE-LATEST-003: edited non-deal reason overrides stale subform childrenValue', async () => {
		let submittedRequest = null
		const api = loadStoreDailyApi(
			{},
			{
				dynamicDailyReport: {
					dynamicDailyReportSave: async request => {
						submittedRequest = request
						return { code: 0, message: 'ok', data: { dailyReportRecordId: 'record-1' } }
					}
				},
				wx: {
					$util: {
						getUserInfo: () => ({
							merchantId: 'shop-1',
							yqMerchantId: 'yq-1',
							staffUuid: 'reporter-1',
							staffName: '填报人'
						})
					}
				}
			}
		)
		const customerGroup = {
			key: 'F2-107',
			label: '今日非成交客户',
			type: 'subform',
			childrenShowRules: {
				'F2-107-18': {
					keys: ['F2-107-7'],
					result: "val1 && Array.isArray(val1) && val1.includes('1')"
				}
			},
			origin_children: [
				{
					key: 'F2-107-7',
					label: '客户标签',
					type: 'multipleSelect',
					options: [{ label: '已触客', value: '1' }]
				},
				{ key: 'F2-107-18', label: '未成交原因', type: 'input' }
			],
			childrenValue: [{
				'F2-107': {
					'F2-107-7': { text: '已触客', value: ['1'] },
					'F2-107-18': '保存前的旧原因'
				}
			}]
		}
		const detailJsonContent = JSON.stringify([customerGroup])
		const initialValues = parseJsonContentDetailValues(detailJsonContent, [customerGroup])
		const engine = createFormEngine()
		engine.init({ list: [customerGroup] }, { initialValues })
		engine.mutateSubform('F2-107', 0, 'F2-107-18', '本次编辑的最新原因')

		const result = await api.submitForm({
			engine,
			reportTemplateId: 'template-1',
			dailyReportRecordId: 'record-1',
			reportDate: '2026-08-26'
		})

		assert.equal(result.code, 0)
		const requestJson = JSON.parse(submittedRequest.requestJson)
		const reasonItem = requestJson.subformDataList.find(item => (
			item.parentFieldKey === 'F2-107' &&
			item.rowIndex === 0 &&
			item.columnFieldKey === 'F2-107-18'
		))
		assert.equal(reasonItem.fieldValue, '本次编辑的最新原因')
		const savedRow = JSON.parse(submittedRequest.jsonContent)[0]
			.childrenValue[0]['F2-107']
		assert.equal(savedRow['F2-107-18'], '本次编辑的最新原因')
	})

	it('IT-SUBMIT-MERGE-SPARSE-001: sparse schema merge preserves defaults not present in values', () => {
		const merged = mergeValuesIntoSchema({
			list: [
				{ key: 'count', type: 'numberInput', value: 0 },
				{ key: 'remark', type: 'textarea', value: '模板默认' }
			]
		}, {})

		assert.equal(merged.list[0].value, 0)
		assert.equal(merged.list[1].value, '模板默认')
	})

	it('IT-STORE-SUB-001: F2-9 dual rows echo via valueMap jsonContent', () => {
		const storeSchema = loadSchemaFixture('store')
		const detail = normalizeDetailFixture({
			jsonContent: JSON.stringify([
				{
					key: 'F2-9',
					type: 'subform',
					value: [
						{ 'F2-9-1': '4s-001', 'F2-9-2': 1 },
						{ 'F2-9-1': '4s-002', 'F2-9-2': 2 }
					]
				}
			])
		})
		const values = parseJsonContentDetailValues(detail.jsonContent, storeSchema.list)
		const mergedSchema = mergeValuesIntoSchema(storeSchema, values)
		const engine = createFormEngine()
		const viewState = engine.init(mergedSchema, {
			baseSceneCode: 110201,
			brandIds: [3067, 3454],
			sceneList: [{ baseSceneCode: 110201 }]
		})
		assert.equal(viewState.values['F2-9'].length, 2)
		assert.equal(viewState.groupRowsCache['F2-9'].length, 2)
		assert.equal(viewState.values['F2-9'][1]['F2-9-1'], '4s-002')
	})

	it('IT-STORE-DETAIL-005: F2-9-1 delivery specialist echoes from jsonContent App children', () => {
		const storeSchema = loadSchemaFixture('store')
		const detail = normalizeDetailFixture({
			jsonContent: JSON.stringify([
				{
					key: 'F2-9',
					type: 'subform',
					children: [
						[
							{
								key: 'F2-9-1',
								type: 'select',
								optionsKey: '4sStaffList',
								value: '交付专员B',
								'F2-9-1': '4s-002'
							},
							{ key: 'F2-9-2', type: 'numberInput', value: 1 }
						]
					]
				}
			])
		})
		const values = parseJsonContentDetailValues(detail.jsonContent, storeSchema.list)
		const mergedSchema = mergeValuesIntoSchema(storeSchema, values)
		const engine = createFormEngine()
		const viewState = engine.init(mergedSchema, {
			baseSceneCode: 110201,
			brandIds: [3067, 3454],
			sceneList: [{ baseSceneCode: 110201 }]
		})
		assert.equal(selectValueMapId(viewState.values['F2-9'][0]['F2-9-1']), '4s-002')
	})
})

describe('report-status utils', () => {
	it('IT-STORE-DETAIL-003: isReportSubmitted handles string and number', () => {
		assert.equal(isReportSubmitted('1'), true)
		assert.equal(isReportSubmitted(1), true)
		assert.equal(isReportSubmitted('0'), false)
		assert.equal(isReportSubmitted(null), false)
		assert.equal(normalizeReportStatus(undefined), '0')
	})
})