dailyReportCarBrand.js 2.96 KB
/**
 * 日报保存用 carBrandList — staff.daily.report.car.brand
 * 与 schema 显隐用的 merchant.info 分离
 */
const { resolveSceneType } = require('../utils/user-merchant.js')

const carBrandCache = new Map()

const MOCK_DAILY_REPORT_CAR_BRAND_LIST = [
	{
		firstBrandId: 3454,
		firstBrandName: '问界',
		brandId: 3454,
		brandName: 'AITO'
	},
	{
		firstBrandId: 3067,
		firstBrandName: '岚图',
		brandId: 3067,
		brandName: '岚图汽车'
	}
]

function getCarBrandCacheKey(merchantId, sceneType) {
	return `${merchantId || ''}:${sceneType ?? 0}`
}

function normalizeCarBrandListForSave(data = []) {
	if (!Array.isArray(data)) {
		return []
	}
	return data.map(item => {
		const firstBrandId = item.firstBrandId
		const firstBrandName = item.firstBrandName || ''
		let brandId = item.brandId
		let brandName = item.brandName || ''
		if (brandId == -1) {
			brandName = firstBrandName
		}
		return {
			firstBrandId,
			firstBrandName,
			brandId,
			brandName
		}
	})
}

function normalizeSceneCodeListToSceneList(data) {
	if (!Array.isArray(data)) {
		return []
	}
	return data
		.map(item => {
			if (item != null && typeof item === 'object' && item.baseSceneCode != null && item.baseSceneCode !== '') {
				return { baseSceneCode: Number(item.baseSceneCode) }
			}
			if (item != null && item !== '') {
				return { baseSceneCode: Number(item) }
			}
			return null
		})
		.filter(item => item != null)
}

let staffDailyReportCarBrandOverride = null

function __setStaffDailyReportCarBrand(impl) {
	staffDailyReportCarBrandOverride = impl
}

function clearDailyReportCarBrandCache() {
	carBrandCache.clear()
}

/**
 * 拉取保存用 carBrandList(merchantId + sceneType)
 * @param {Object} [params={}]
 * @returns {Promise<{code: number, message: string, data: Array}>}
 */
async function fetchDailyReportCarBrandList(params = {}) {
	const { merchantId, sceneType = 0, useMock = false } = params
	if (!merchantId) {
		return { code: 0, message: 'ok', data: [] }
	}
	if (useMock) {
		return { code: 0, message: 'ok', data: [...MOCK_DAILY_REPORT_CAR_BRAND_LIST] }
	}
	const cacheKey = getCarBrandCacheKey(merchantId, sceneType)
	const cached = carBrandCache.get(cacheKey)
	if (cached) {
		return cached
	}
	const fetcher =
		staffDailyReportCarBrandOverride ||
		((data) => require('./dynamicDailyReport.js').staffDailyReportCarBrand(data))
	const result = await fetcher({
		merchantId,
		sceneType: resolveSceneType({ sceneType })
	})
	const code = result?.code
	if (code != null && code != 0) {
		return {
			code: code ?? -1,
			message: result?.message || '获取车型失败',
			data: []
		}
	}
	const normalized = {
		code: 0,
		message: 'ok',
		data: normalizeCarBrandListForSave(result?.data)
	}
	carBrandCache.set(cacheKey, normalized)
	return normalized
}

module.exports = {
	normalizeCarBrandListForSave,
	normalizeSceneCodeListToSceneList,
	fetchDailyReportCarBrandList,
	getCarBrandCacheKey,
	clearDailyReportCarBrandCache,
	__setStaffDailyReportCarBrand,
	MOCK_DAILY_REPORT_CAR_BRAND_LIST
}