asyncProviders.js 8.94 KB
/**
 * 精品首页异步菜单 Provider
 *
 * 各 provider 并行执行,返回 `{ [providerKey]: { visible, extras?, sideEffects? } }`
 * 由 buildTabIndexMenusAsync 合并进最终 menu。单测通过 deps 注入 mock API。
 */
import dayjs from 'dayjs'
import {
	appendDynamicFormTabIndexMenusAsync,
	stripDynamicFormTabIndexMenus,
	resolveDynamicFormMenuId,
	isInjectedDynamicFormMenu
} from '../../utils/dynamicFormMenus.js'
import {
	cachedHasPerformanceConfig,
	cachedCheckMerchantDirect,
	cachedGetStaffTargetTask
} from '../../utils/menuApiCache.js'
import { registryItemToViewModel } from './toViewModel.js'

/**
 * 并行解析所有异步菜单 provider
 *
 * @param {Object} ctx - createMenuContext 返回值
 * @param {Object} [deps]
 * @param {Object} [deps.tabIndexApi] - tabIndex/api.js 方法集
 * @param {Object} [deps.commonApi] - api/api.js 方法集
 * @param {Function} [deps.getBusinessSchoolScene] - 工资绩效显隐
 * @param {boolean} [deps.includeCustomerClue] - 是否解析客户线索(园区配置)
 * @returns {Promise<Record<string, { visible: boolean, extras?: Object, sideEffects?: Object }>>}
 */
export async function resolveAsyncMenuProviders(ctx, deps = {}) {
	const { userInfo, isStaff } = ctx
	const policies = ctx.policies
	const tabIndexApi =
		deps.tabIndexApi ||
		((await import('../api.js')).default ?? (await import('../api.js')))
	const commonApiModule = deps.commonApi
		? { default: deps.commonApi }
		: await import('../../api/api.js')
	const commonApi = commonApiModule.default ?? commonApiModule

	const providers = []

	if (!policies.isTechnician()) {
		providers.push(
			resolveScriptVerify(ctx, tabIndexApi),
			resolveSalaryAppeal(ctx, tabIndexApi, isStaff),
			resolveMissingReception(ctx, tabIndexApi),
			resolveDynamicForm(ctx),
			resolveSalaryPerformance(ctx, deps.getBusinessSchoolScene),
			resolveResidentTarget(ctx, commonApi, policies)
		)
	}

	if (deps.includeCustomerClue) {
		providers.push(resolveCustomerClue(ctx, commonApi, deps))
	}

	const results = await Promise.all(providers)
	return Object.assign({}, ...results)
}

/**
 * 话术核验:非技师;`extractCheck` 返回 true 或超管可见;接口异常时仅超管可见。
 * @see tabIndex/docs/MENU-ARCHITECTURE.md 异步 Provider 表
 */
async function resolveScriptVerify(ctx, tabIndexApi) {
	const { userInfo } = ctx
	const policies = ctx.policies
	if (policies.isTechnician()) {
		return { scriptVerify: { visible: false } }
	}
	try {
		const res = await tabIndexApi.extractCheck({})
		const visible =
			(policies.isSuper() || !!res) && policies.notTechnician()
		return { scriptVerify: { visible } }
	} catch {
		return { scriptVerify: { visible: policies.isSuper() } }
	}
}

/**
 * 工资申诉:超管直显;否则 `hasPerformanceConfig` 且(`canViewRecruit` 或 `isStaff` 或 `loginRole==4`)。
 * @see tabIndex/docs/MENU-ARCHITECTURE.md 异步 Provider 表
 */
async function resolveSalaryAppeal(ctx, tabIndexApi, isStaff) {
	const { userInfo } = ctx
	const policies = ctx.policies
	if (policies.isTechnician()) {
		return { salaryAppeal: { visible: false } }
	}
	if (policies.isSuper()) {
		return { salaryAppeal: { visible: true } }
	}
	try {
		const res = await cachedHasPerformanceConfig(
			tabIndexApi,
			userInfo.shopMerchantId || userInfo.merchantId
		)
		const visible =
			!!res?.data &&
			(policies.canViewRecruit() ||
				isStaff ||
				userInfo?.loginRole == 4)
		return { salaryAppeal: { visible } }
	} catch {
		return { salaryAppeal: { visible: false } }
	}
}

/**
 * 接待缺失报备:需 `isStaff` 或 `canSelectMultiStoreForStaffDaily`;再 `checkMerchantDirect`;
 * 通过则 `checkMissingReception` 写入 `sideEffects.missingRecordTodoList`。
 * @see tabIndex/docs/MENU-ARCHITECTURE.md 异步 Provider 表
 */
async function resolveMissingReception(ctx, tabIndexApi) {
	const { userInfo, isStaff } = ctx
	const policies = ctx.policies
	if (
		policies.isTechnician() ||
		!(isStaff || policies.canSelectMultiStoreForStaffDaily())
	) {
		return {
			missingReception: {
				visible: false,
				sideEffects: { missingRecordTodoList: [] }
			}
		}
	}
	try {
		const res = await cachedCheckMerchantDirect(tabIndexApi, {
			merchantId: userInfo.shopMerchantId,
			scene: 1
		})
		if (!res?.data) {
			return {
				missingReception: {
					visible: false,
					sideEffects: { missingRecordTodoList: [] }
				}
			}
		}
		const { uuid, merchantId, shopMerchantId } = userInfo
		let missingRecordTodoList = []
		try {
			const result = await tabIndexApi.checkMissingReception({
				merchantId: shopMerchantId,
				yqMerchantId: merchantId,
				staffUuid: uuid,
				sceneType: 1,
				reportStartDate: dayjs().subtract(6, 'day').format('YYYY-MM-DD'),
				reportEndDate: dayjs().format('YYYY-MM-DD')
			})
			if (result.code == 0) {
				result.data.reverse().forEach(e => {
					if (
						e.missingReceptionRecord &&
						!e.hasReceptionReport &&
						!missingRecordTodoList.length
					) {
						missingRecordTodoList.push(e)
					}
				})
			}
		} catch {
			// ignore
		}
		return {
			missingReception: {
				visible: policies.notTechnician(),
				sideEffects: { missingRecordTodoList }
			}
		}
	} catch {
		return {
			missingReception: {
				visible: false,
				sideEffects: { missingRecordTodoList: [] }
			}
		}
	}
}

/**
 * 动态门店日报:角色门禁 + isNeed 后由 `appendDynamicFormTabIndexMenusAsync` 注入 items。
 * 返回 `{ visible, items }`,items 不经 ASYNC_MENU_REGISTRY 登记。
 * @see tabIndex/docs/MENU-ARCHITECTURE.md 异步 Provider 表
 */
async function resolveDynamicForm(ctx) {
	const { userInfo } = ctx
	const menu = []
	const newMenu = []
	stripDynamicFormTabIndexMenus(menu, newMenu)
	await appendDynamicFormTabIndexMenusAsync(menu, newMenu, userInfo)
	const items = menu.map(item => {
		return registryItemToViewModel(
			{
				id: resolveDynamicFormMenuId(item),
				label: item.name,
				icon: item.icon,
				sortVal: item.sortVal,
				action: { type: 'navigate', target: item.navigateToUrl },
				entrySource: item.entrySource,
				noCheckdailyReport: item.noCheckdailyReport,
				recordId: item.recordId
			},
			{
				navigateToUrl: item.navigateToUrl,
				trackEventCode: item.trackEventCode
			}
		)
	}).map(vm => {
		const { tipsNum, ...rest } = vm
		return rest
	})
	return {
		dynamicForm: {
			visible: items.length > 0,
			items,
			hideLegacyStaffDaily: items.some(isInjectedDynamicFormMenu)
		}
	}
}

/**
 * 工资绩效(异步项):排除技师与超管(超管走同步 `salary_performance_super`);`getBusinessSchoolScene` 有结果则显。
 * @see tabIndex/docs/MENU-ARCHITECTURE.md 异步 Provider 表
 */
async function resolveSalaryPerformance(ctx, getBusinessSchoolScene) {
	const { userInfo } = ctx
	const policies = ctx.policies
	if (policies.isTechnician() || policies.isSuper()) {
		return { salaryPerformance: { visible: false } }
	}
	if (!getBusinessSchoolScene) {
		return { salaryPerformance: { visible: false } }
	}
	const fetchScene = getBusinessSchoolScene
	try {
		const res = await fetchScene({})
		return { salaryPerformance: { visible: !!res } }
	} catch {
		return { salaryPerformance: { visible: false } }
	}
}

/**
 * 驻店目标:需 `isStaff`、非 `canSelectMultiStore`、`default4SStoreInfo.merchantId` 存在;
 * `getStaffTargetTaskApi` 有数据则显,并可能注入 `noRead` 与 `showTaskDialog` sideEffects。
 * @see tabIndex/docs/MENU-ARCHITECTURE.md 异步 Provider 表
 */
async function resolveResidentTarget(ctx, commonApi, policies) {
	const { userInfo, isStaff } = ctx
	if (
		policies.isTechnician() ||
		policies.canSelectMultiStore() ||
		!isStaff
	) {
		return { residentTarget: { visible: false } }
	}
	const merchantId = userInfo?.default4SStoreInfo?.merchantId
	if (!merchantId) {
		return { residentTarget: { visible: false } }
	}
	try {
		const res = await cachedGetStaffTargetTask(commonApi, {
			sceneType: 1,
			merchantId
		})
		const { code, data } = res
		if (code != 0 || !data?.length) {
			return { residentTarget: { visible: false } }
		}
		const sideEffects = {
			taskId: data[0]?.id,
			taskInfo: data[0],
			showTaskDialog: data[0]?.promptFlag == 'N'
		}
		return {
			residentTarget: {
				visible: true,
				extras: { noRead: data[0]?.readFlag == 'N' },
				sideEffects
			}
		}
	} catch {
		return { residentTarget: { visible: false } }
	}
}

/**
 * 客户线索入口:园区 getYqStoreConfig.customerExchangeFlag === 'Y' 时显隐
 * @param {Object} ctx
 * @param {Object} commonApi
 * @param {Object} [deps]
 */
export async function resolveCustomerClue(ctx, commonApi, deps = {}) {
	const { userInfo } = ctx
	const policies = ctx.policies
	if (policies.isTechnician()) {
		return { customerClue: { visible: false } }
	}
	try {
		const { merchantId: yqMerchantId } = userInfo
		const res = await (deps.getYqStoreConfig || commonApi.getYqStoreConfig)({
			yqMerchantId
		})
		const data = res?.data
		if (!data || data.customerExchangeFlag != 'Y') {
			return { customerClue: { visible: false } }
		}
		return { customerClue: { visible: true, tipsNum: 0 } }
	} catch {
		return { customerClue: { visible: false } }
	}
}