equityMenu.test.mjs 15.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 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
/**
 * 权益首页 Menu 模块单元测试
 *
 * 运行:npm run test:equity
 * 用例前缀:IT-EQ-MENU-*
 */
import { describe, it, beforeEach, afterEach } from 'node:test'
import assert from 'node:assert/strict'
import {
	setupWxMock,
	createDefaultEquityAsyncDeps
} from './menuTestHelpers.mjs'

const globalRef = globalThis

describe('equityMenu', async () => {
	setupWxMock(globalRef)

	const { clearMenuApiCache } = await import('../menu/menuApiCache.js')

	beforeEach(() => {
		clearMenuApiCache()
	})

	const { buildEquityMenusSync, buildEquityMenusAsync } = await import(
		'../menu/buildMenus.js'
	)
	const { createEquityMenuContext, getMenuFingerprint } = await import(
		'../menu/context.js'
	)
	const { createPolicies } = await import('../menu/policies.js')
	const { EQUITY_MENU_REGISTRY, ASYNC_MENU_REGISTRY, DYNAMIC_FORM_MENU_IDS } = await import(
		'../menu/registry.js'
	)
	const { registryItemToViewModel } = await import('../menu/toViewModel.js')
	const { resolveAsyncMenuProviders, resolveCustomerClue } = await import(
		'../menu/asyncProviders.js'
	)

	const { __setApiClientForTest, clearDailyReportNewVersionCache } =
		await import('../../utils/dailyReportNewVersionGate.js')

	let originalGetApp
	let originalWx

	beforeEach(() => {
		clearDailyReportNewVersionCache()
		__setApiClientForTest(null)
		originalGetApp = globalRef.getApp
		originalWx = globalRef.wx
		setupWxMock(globalRef)
		globalRef.getApp = () => ({ globalData: { isStaff: true } })
	})

	afterEach(() => {
		clearDailyReportNewVersionCache()
		__setApiClientForTest(null)
		globalRef.getApp = originalGetApp
		globalRef.wx = originalWx
	})

	// --- Registry ---

	it('IT-EQ-MENU-REG-001: EQUITY_MENU_REGISTRY entries have stable id and label', () => {
		const ids = new Set()
		EQUITY_MENU_REGISTRY.forEach(entry => {
			assert.ok(entry.id)
			assert.ok(entry.label)
			assert.ok(entry.action, `${entry.id} needs action`)
			assert.ok(!ids.has(entry.id), `duplicate id ${entry.id}`)
			ids.add(entry.id)
		})
	})

	it('IT-EQ-MENU-REG-002: ASYNC_MENU_REGISTRY entries have unique id and provider', () => {
		const ids = new Set()
		ASYNC_MENU_REGISTRY.forEach(entry => {
			assert.ok(entry.provider)
			assert.ok(!ids.has(entry.id))
			ids.add(entry.id)
		})
	})

	it('IT-EQ-MENU-REG-002b: dynamic registry identifies the route-backed store daily entry', () => {
		assert.deepEqual(
			DYNAMIC_FORM_MENU_IDS.map(item => ({ id: item.id, label: item.label })),
			[{ id: 'store_daily_report', label: '门店日报' }]
		)
	})

	it('IT-EQ-MENU-GUIDE-001: registry ids are stable snake_case', () => {
		const idPattern = /^[a-z][a-z0-9_]*$/
		const allEntries = [...EQUITY_MENU_REGISTRY, ...ASYNC_MENU_REGISTRY]
		allEntries.forEach(entry => {
			assert.match(
				entry.id,
				idPattern,
				`${entry.id} must be snake_case (see ADD-MENU-GUIDE-EQUITY.md)`
			)
		})
	})

	it('IT-EQ-MENU-REG-003: registry entries have required schema fields', () => {
		const requiredSync = ['id', 'label', 'icon', 'section', 'action']
		EQUITY_MENU_REGISTRY.forEach(entry => {
			requiredSync.forEach(key => {
				assert.ok(entry[key] != null && entry[key] !== '', `${entry.id} missing ${key}`)
			})
			assert.equal(typeof entry.visible, 'function', `${entry.id} needs visible(ctx)`)
			assert.ok(entry.action?.type, `${entry.id} action.type required`)
		})
		ASYNC_MENU_REGISTRY.forEach(entry => {
			requiredSync.forEach(key => {
				assert.ok(entry[key] != null && entry[key] !== '', `${entry.id} missing ${key}`)
			})
			assert.equal(typeof entry.provider, 'string', `${entry.id} needs provider`)
			assert.ok(entry.action?.type, `${entry.id} action.type required`)
		})
	})

	// --- Sync pipeline ---

	it('IT-EQ-MENU-SYNC-001: staff with mode shows defeat_order', () => {
		const menuList = buildEquityMenusSync(
			createEquityMenuContext({
				userInfo: { loginRole: 4, subLoginUser: { loginRole: 4 } },
				isStaff: true,
				mode: 1
			})
		)
		assert.ok(menuList.some(i => i.id === 'defeat_order'))
	})

	it('IT-EQ-MENU-SYNC-002: mode=0 hides defeat_order', () => {
		const menuList = buildEquityMenusSync(
			createEquityMenuContext({
				userInfo: { loginRole: 4 },
				isStaff: true,
				mode: 0
			})
		)
		assert.ok(!menuList.some(i => i.id === 'defeat_order'))
	})

	it('IT-EQ-MENU-SYNC-003: staff gets create_order and staff_daily_report', () => {
		const menuList = buildEquityMenusSync(
			createEquityMenuContext({
				userInfo: { loginRole: 4, sceneType: 0 },
				isStaff: true,
				mode: 1
			})
		)
		assert.ok(menuList.some(i => i.id === 'create_order'))
		assert.ok(menuList.some(i => i.id === 'staff_daily_report'))
	})

	it('IT-EQ-MENU-SYNC-004: supervisor gets BI report', () => {
		const menuList = buildEquityMenusSync(
			createEquityMenuContext({
				userInfo: { loginRole: 3, sceneType: 0 },
				isStaff: false,
				mode: 0
			})
		)
		assert.ok(menuList.some(i => i.id === 'bi_report'))
	})

	it('IT-EQ-MENU-SYNC-005: work report trio always in sync base', () => {
		const menuList = buildEquityMenusSync(
			createEquityMenuContext({ userInfo: {}, isStaff: false, mode: 0 })
		)
		assert.ok(menuList.some(i => i.id === 'work_daily_report'))
		assert.ok(menuList.some(i => i.id === 'work_weekly_report'))
		assert.ok(menuList.some(i => i.id === 'work_monthly_report'))
	})

	it('IT-EQ-MENU-SYNC-006: delivery target for loginRoleOnSelectMerchant 4', () => {
		const menuList = buildEquityMenusSync(
			createEquityMenuContext({
				userInfo: { loginRoleOnSelectMerchant: 4 },
				isStaff: true,
				mode: 0
			})
		)
		assert.ok(menuList.some(i => i.id === 'delivery_target'))
	})

	it('IT-EQ-MENU-SYNC-007: study_center hidden for channelType 9', () => {
		const menuList = buildEquityMenusSync(
			createEquityMenuContext({
				userInfo: { subLoginUser: { channelType: 9 } },
				isStaff: true,
				mode: 0
			})
		)
		assert.ok(!menuList.some(i => i.id === 'study_center'))
	})

	// --- View model ---

	it('IT-EQ-MENU-VM-001: registryItemToViewModel maps label to menuText', () => {
		const vm = registryItemToViewModel({
			id: 'create_order',
			label: '新建工单',
			icon: 'create_order',
			action: { type: 'createOrderPrompt', target: '' }
		})
		assert.equal(vm.menuText, '新建工单')
		assert.equal(vm.path, '')
	})

	it('IT-EQ-MENU-VM-002: registryItemToViewModel maps navigate action', () => {
		const vm = registryItemToViewModel({
			id: 'scene_market',
			label: '场景集市',
			icon: 'sceneMarket',
			action: {
				type: 'navigate',
				target: '/packageEquity/pages/sceneMarket/index/index'
			}
		})
		assert.equal(vm.menuText, '场景集市')
		assert.equal(vm.navigateToUrl, '/packageEquity/pages/sceneMarket/index/index')
	})

	it('IT-EQ-MENU-VM-003: registryItemToViewModel maps router extract to path', () => {
		const vm = registryItemToViewModel({
			id: 'script_extract',
			label: '话术萃取',
			icon: 'extract_icon',
			action: {
				type: 'router',
				target: 'packageEquity.extract',
				params: { type: 1 }
			}
		})
		assert.equal(vm.path, 'packageEquity.extract')
		assert.deepEqual(vm.params, { type: 1 })
	})

	// --- Fingerprint ---

	it('IT-EQ-MENU-FP-001: getMenuFingerprint stable for same user', () => {
		const user = { uuid: 'u1', shopMerchantId: 's1', loginRole: 4 }
		assert.equal(getMenuFingerprint(user), getMenuFingerprint(user))
	})

	it('IT-EQ-MENU-FP-002: getMenuFingerprint changes when shopMerchantId changes', () => {
		const a = getMenuFingerprint({ uuid: 'u1', shopMerchantId: 's1' })
		const b = getMenuFingerprint({ uuid: 'u1', shopMerchantId: 's2' })
		assert.notEqual(a, b)
	})

	it('IT-EQ-MENU-FP-003: getMenuFingerprint changes when mode mentorFlag or isStaff changes', () => {
		const user = { uuid: 'u1', shopMerchantId: 's1', loginRole: 4 }
		const base = getMenuFingerprint(user, { isStaff: true, mentorFlag: false, mode: 0 })
		const mentor = getMenuFingerprint(user, { isStaff: true, mentorFlag: true, mode: 0 })
		const mode1 = getMenuFingerprint(user, { isStaff: true, mentorFlag: false, mode: 1 })
		assert.notEqual(base, mentor)
		assert.notEqual(base, mode1)
	})

	it('IT-EQ-MENU-FP-004: getMenuFingerprint changes when default4SStoreInfo.merchantId changes', () => {
		const a = getMenuFingerprint({
			uuid: 'u1',
			shopMerchantId: 's1',
			default4SStoreInfo: { merchantId: 'store-a' }
		})
		const b = getMenuFingerprint({
			uuid: 'u1',
			shopMerchantId: 's1',
			default4SStoreInfo: { merchantId: 'store-b' }
		})
		assert.notEqual(a, b)
	})

	// --- Role snapshots ---

	function syncMenuIds(ctx) {
		return buildEquityMenusSync(ctx)
			.map(i => i.id)
			.sort()
	}

	it('IT-EQ-MENU-SNAP-001: regional supervisor sync menu id snapshot', () => {
		const ids = syncMenuIds(
			createEquityMenuContext({
				userInfo: { loginRole: 3, sceneType: 0 },
				isStaff: false,
				mode: 0
			})
		)
		assert.ok(ids.includes('bi_report'))
		assert.ok(ids.includes('pending_approval'))
		assert.ok(!ids.includes('recruit_manage'))
	})

	it('IT-EQ-MENU-SNAP-002: resident staff with mode sync snapshot', () => {
		const ids = syncMenuIds(
			createEquityMenuContext({
				userInfo: { loginRole: 4, sceneType: 0 },
				isStaff: true,
				mode: 1
			})
		)
		assert.ok(ids.includes('create_order'))
		assert.ok(ids.includes('defeat_order'))
		assert.ok(ids.includes('staff_daily_report'))
		assert.ok(ids.includes('work_daily_report'))
	})

	// --- Policies ---

	it('IT-EQ-MENU-POL-001: createPolicies hasDefeatOrderMode follows mode', () => {
		const ctx0 = createEquityMenuContext({ mode: 0 })
		const ctx1 = createEquityMenuContext({ mode: 1 })
		assert.equal(ctx0.policies.hasDefeatOrderMode(), false)
		assert.equal(ctx1.policies.hasDefeatOrderMode(), true)
	})

	it('IT-EQ-MENU-POL-002: createPolicies staffOrMultiStoreDaily', () => {
		const ctx = createEquityMenuContext({
			userInfo: { loginRole: 4 },
			isStaff: true
		})
		assert.equal(ctx.policies.staffOrMultiStoreDaily(), true)
	})

	// --- Async providers ---

	it('IT-EQ-MENU-ASYNC-001: super gets salary_appeal without hasPerformanceConfig', async () => {
		const result = await buildEquityMenusAsync({
			userInfo: { isSuper: true, loginRole: 8, sceneType: 0 },
			isStaff: false,
			mode: 0,
			deps: createDefaultEquityAsyncDeps({
				commonApi: {
					hasPerformanceConfig: async () => {
						throw new Error('should not call API for super')
					}
				}
			})
		})
		assert.ok(result.menuList.some(i => i.id === 'salary_appeal'))
	})

	it('IT-EQ-MENU-ASYNC-002: salary appeal when hasPerformanceConfig true', async () => {
		const result = await buildEquityMenusAsync({
			userInfo: { loginRole: 4, sceneType: 0, shopMerchantId: 'm1' },
			isStaff: true,
			mode: 0,
			deps: createDefaultEquityAsyncDeps({
				commonApi: {
					hasPerformanceConfig: async () => ({ data: true })
				}
			})
		})
		assert.ok(result.menuList.some(i => i.id === 'salary_appeal'))
	})

	it('IT-EQ-MENU-ASYNC-003: script verify when extractCheck returns true', async () => {
		const result = await buildEquityMenusAsync({
			userInfo: { loginRole: 4, sceneType: 0 },
			isStaff: true,
			mode: 0,
			deps: createDefaultEquityAsyncDeps({
				aiApi: {
					extractCheck: async () => ({ data: true })
				}
			})
		})
		assert.ok(result.menuList.some(i => i.id === 'script_verify'))
	})

	it('IT-EQ-MENU-ASYNC-004: missing reception returns sideEffects', async () => {
		const result = await buildEquityMenusAsync({
			userInfo: {
				loginRole: 4,
				sceneType: 0,
				shopMerchantId: 'm1',
				uuid: 'u1',
				merchantId: 'yq1'
			},
			isStaff: true,
			mode: 0,
			deps: createDefaultEquityAsyncDeps({
				receptionRecordsApi: {
					checkMerchantDirect: async () => ({ data: true }),
					checkMissingReception: async () => ({
						code: 0,
						data: [
							{
								missingReceptionRecord: true,
								hasReceptionReport: false,
								reportDate: '2026-06-01'
							}
						]
					})
				}
			})
		})
		assert.ok(result.menuList.some(i => i.id === 'missing_reception'))
		assert.equal(result.sideEffects.missingRecordTodoList.length, 1)
	})

	it('IT-EQ-MENU-ASYNC-005: resident target sets taskId sideEffect', async () => {
		const result = await buildEquityMenusAsync({
			userInfo: {
				loginRole: 4,
				sceneType: 0,
				default4SStoreInfo: { merchantId: 'store1' }
			},
			isStaff: true,
			mode: 0,
			deps: createDefaultEquityAsyncDeps({
				commonApi: {
					getStaffTargetTaskApi: async () => ({
						code: 0,
						data: [{ id: 'task-99', readFlag: 'N', promptFlag: 'N' }]
					})
				}
			})
		})
		assert.ok(result.menuList.some(i => i.id === 'resident_target'))
		assert.equal(result.sideEffects.taskId, 'task-99')
		assert.equal(result.sideEffects.showTaskDialog, true)
	})

	it('IT-EQ-MENU-ASYNC-006: salary performance via getBusinessSchoolScene', async () => {
		const result = await buildEquityMenusAsync({
			userInfo: { loginRole: 4, sceneType: 0 },
			isStaff: true,
			mode: 0,
			deps: createDefaultEquityAsyncDeps({
				getBusinessSchoolScene: async () => true
			})
		})
		assert.ok(result.menuList.some(i => i.id === 'salary_performance_api'))
	})

	it('IT-EQ-MENU-ASYNC-007: customer clue when exchange flag Y', async () => {
		const ctx = createEquityMenuContext({
			userInfo: { loginRole: 4, merchantId: 'yq1', sceneType: 0 },
			isStaff: true
		})
		const result = await resolveCustomerClue(ctx, null, {
			getYqStoreConfig: async () => ({
				data: { customerExchangeFlag: 'Y' }
			})
		})
		assert.equal(result.customerClue.visible, true)
	})

	it('IT-EQ-MENU-ASYNC-008: gate true replaces legacy staff daily with exactly one store daily', async () => {
		__setApiClientForTest({
			dailyReportNewVersionIsNeed: async () => ({ code: 0, data: true })
		})
		const result = await buildEquityMenusAsync({
			userInfo: {
				loginRole: 4,
				sceneType: 0,
				shopMerchantId: 'merchant-1'
			},
			isStaff: true,
			mode: 0,
			deps: createDefaultEquityAsyncDeps()
		})
		const dailyItems = result.menuList.filter(i =>
			['staff_daily_report', 'store_daily_report'].includes(i.id)
		)
		assert.deepEqual(
			dailyItems.map(item => ({ id: item.id, menuText: item.menuText })),
			[{ id: 'store_daily_report', menuText: '门店日报' }]
		)
	})

	it('IT-EQ-MENU-ASYNC-008b: gate false preserves legacy staff daily without store daily', async () => {
		__setApiClientForTest({
			dailyReportNewVersionIsNeed: async () => ({ code: 0, data: false })
		})
		const result = await buildEquityMenusAsync({
			userInfo: {
				loginRole: 4,
				sceneType: 0,
				shopMerchantId: 'merchant-1'
			},
			isStaff: true,
			mode: 0,
			deps: createDefaultEquityAsyncDeps()
		})
		assert.equal(result.menuList.some(item => item.id === 'staff_daily_report'), true)
		assert.equal(result.menuList.some(item => item.id === 'store_daily_report'), false)
	})

	it('IT-EQ-MENU-ASYNC-008c: gate error preserves legacy staff daily without store daily', async () => {
		__setApiClientForTest({
			dailyReportNewVersionIsNeed: async () => {
				throw new Error('gate unavailable')
			}
		})
		const result = await buildEquityMenusAsync({
			userInfo: {
				loginRole: 4,
				sceneType: 0,
				shopMerchantId: 'merchant-1'
			},
			isStaff: true,
			mode: 0,
			deps: createDefaultEquityAsyncDeps()
		})
		assert.equal(result.menuList.some(item => item.id === 'staff_daily_report'), true)
		assert.equal(result.menuList.some(item => item.id === 'store_daily_report'), false)
	})

	it('IT-EQ-MENU-ASYNC-009: reception records when merchant in list', async () => {
		const result = await buildEquityMenusAsync({
			userInfo: {
				loginRole: 4,
				sceneType: 0,
				default4SStoreInfo: { merchantId: 'store-1' }
			},
			isStaff: true,
			mode: 0,
			deps: createDefaultEquityAsyncDeps({
				carLifeApi: {
					selectrecmerchantList: async () => ({
						code: 0,
						data: [{ merchantNo: 'store-1' }]
					})
				}
			})
		})
		assert.ok(result.menuList.some(i => i.id === 'reception_records'))
		assert.ok(result.menuList.some(i => i.id === 'illegal_recording'))
		assert.equal(result.sideEffects.showReceive, true)
	})

	it('IT-EQ-MENU-ASYNC-010: ai_fun_practice hidden for mentor role', async () => {
		const result = await buildEquityMenusAsync({
			userInfo: { loginRole: 6, sceneType: 0 },
			isStaff: false,
			mode: 0,
			deps: createDefaultEquityAsyncDeps()
		})
		assert.ok(!result.menuList.some(i => i.id === 'ai_fun_practice'))
	})
})