usedCarDailyReportReplacement.test.mjs 10.2 KB
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import fs from 'node:fs'
import {
	buildUsedCarStoreDailyReportUrl,
	isUsedCarStoreDailyReportSubmitted,
	resolveUsedCarShopMerchantId,
	resolvePreviousReportDate
} from '../packageUsedCar/services/usedCarStoreDailyReport.js'

const controllerPath = new URL('../packageUsedCar/ModalToQueueUsedCarControl.js', import.meta.url)
const secondHandApiPath = new URL('../packageUsedCar/secondHandApi.js', import.meta.url)
const indexPath = new URL('../packageUsedCar/pages/indexPage/index/index.js', import.meta.url)
const legacyPagePath = new URL(
	'../packageUsedCar/pages/indexPage/dailyReport/dailyReport.js',
	import.meta.url
)

class FixedDate extends Date {
	constructor(...args) {
		super(...(args.length ? args : ['2026-09-01T12:00:00+08:00']))
	}
}

function loadController({ userInfo, popupRequired = true, weeklyResult }) {
	let source = fs.readFileSync(controllerPath, 'utf8')
	source = source
		.replace(
			/import\s+\{([\s\S]*?)\}\s+from\s+['"]([^'"]+)['"];?/g,
			'const {$1} = require("$2")'
		)
		.replace(
			/import\s+(\w+)\s+from\s+['"]([^'"]+)['"];?/g,
			'const $1 = require("$2")'
		)
		.replace(/export\s*\{([\s\S]*?)\}\s*;?/g, 'module.exports = {$1}')

	const calls = {
		popup: [],
		legacyValid: [],
		weekly: [],
		navigate: []
	}
	const modules = {
		'~/api/api.js': {},
		'~/packageUsedCar/secondHandApi': {
			checkUsedCarStaffIsNew: async params => {
				calls.popup.push(params)
				return { data: popupRequired }
			},
			fetchUsedCarStoreDailyReportWeeklyList: async params => {
				calls.weekly.push(params)
				return weeklyResult
			},
			checkUsedCarStaffDailyReportValid: async params => {
				calls.legacyValid.push(params)
				return false
			}
		},
		'~/packageUsedCar/services/usedCarStoreDailyReport.js': {
			buildUsedCarStoreDailyReportUrl: reportDate =>
				`/packageDynamicForm/pages/storeDailyReport/storeDailyReport?reportDate=${reportDate}`,
			resolvePreviousReportDate: () => '2026-08-31',
			resolveUsedCarShopMerchantId: value =>
				value.shopMerchantId || value.default4SStoreInfo_usedCar?.merchantId || '',
			isUsedCarStoreDailyReportSubmitted: (list, reportDate) => list.includes(reportDate)
		}
	}
	const wx = {
		$util: { getUserInfo: () => userInfo },
		$hasPermission: { canSelectMultiStore: () => false },
		showModal: options => options.success({ confirm: true }),
		navigateTo: options => calls.navigate.push(options.url),
		__HAS_SHOW_MODAL: false
	}
	const module = { exports: {} }
	let loadError = null
	try {
		new Function('require', 'module', 'exports', 'wx', 'getCurrentPages', 'Date', source)(
			specifier => {
				if (!Object.hasOwn(modules, specifier)) throw new Error(`unexpected module: ${specifier}`)
				return modules[specifier]
			},
			module,
			module.exports,
			wx,
			() => [],
			FixedDate
		)
	} catch (error) {
		loadError = error
	}
	return { controller: module.exports, calls, loadError }
}

function transformMiniProgramImports(source) {
	return source
		.replace(
			/import\s+\{([\s\S]*?)\}\s+from\s+['"]([^'"]+)['"];?/g,
			'const {$1} = require("$2")'
		)
		.replace(
			/import\s+(\w+)\s+from\s+['"]([^'"]+)['"];?/g,
			'const $1 = require("$2")'
		)
}

function loadSecondHandApi() {
	let source = transformMiniProgramImports(fs.readFileSync(secondHandApiPath, 'utf8'))
		.replace(/export\s*\{([\s\S]*?)\}\s*;?/g, 'module.exports = {$1}')
	const calls = []
	const module = { exports: {} }
	new Function('require', 'module', 'exports', source)(
		specifier => {
			if (specifier === '~/packageUsedCar/newRequest') return {}
			if (specifier === '~/utils/request/request') {
				return {
					post: async (method, params) => {
						calls.push({ method, params })
						return { code: 0, data: [] }
					}
				}
			}
			throw new Error(`unexpected module: ${specifier}`)
		},
		module,
		module.exports
	)
	return { api: module.exports, calls }
}

function loadUsedCarIndex() {
	const source = transformMiniProgramImports(fs.readFileSync(indexPath, 'utf8'))
	let component = null
	const navigate = []
	const modules = {
		'~/packageUsedCar/api': {},
		'~/store/index': { setConfigInfo: async () => ({}) },
		'~/packageUsedCar/ModalToQueueUsedCarControl': { checkDailyReport: async () => false },
		'~/packageUsedCar/services/usedCarStoreDailyReport.js': {
			buildUsedCarStoreDailyReportUrl: () =>
				'/packageDynamicForm/pages/storeDailyReport/storeDailyReport'
		}
	}
	const wx = {
		$util: { getUserInfo: () => ({ sceneType: 7 }), showToast() {} },
		$track: { setTrackData() {} },
		navigateTo: options => navigate.push(options.url)
	}
	new Function('require', 'Component', 'wx', 'getApp', source)(
		specifier => modules[specifier],
		config => { component = config },
		wx,
		() => ({ globalData: {} })
	)
	return { component, navigate }
}

function loadLegacyDailyPage() {
	const source = transformMiniProgramImports(fs.readFileSync(legacyPagePath, 'utf8'))
	let page = null
	const redirects = []
	const modules = {
		'~/packageUsedCar/api': {},
		'~/utils/timeFormat/time-utils.js': {},
		'~/packageUsedCar/services/usedCarStoreDailyReport.js': {
			buildUsedCarStoreDailyReportUrl: reportDate =>
				`/packageDynamicForm/pages/storeDailyReport/storeDailyReport?reportDate=${reportDate}`
		}
	}
	const wx = {
		$util: { getUserInfo: () => ({ sceneType: 7 }) },
		redirectTo: options => redirects.push(options.url)
	}
	new Function('require', 'Page', 'wx', source)(
		specifier => modules[specifier],
		config => { page = config },
		wx
	)
	return { page, redirects }
}

describe('used-car daily report replacement', () => {
	it('loads the used-car modal controller without another subpackage module', () => {
		const { loadError } = loadController({
			userInfo: { shopMerchantId: 7001 },
			weeklyResult: { code: 0, data: [] }
		})

		assert.equal(loadError, null)
	})

	it('builds the dynamic route and calculates yesterday in local time', () => {
		assert.equal(
			buildUsedCarStoreDailyReportUrl(),
			'/packageDynamicForm/pages/storeDailyReport/storeDailyReport'
		)
		assert.equal(
			buildUsedCarStoreDailyReportUrl('2026-08-31'),
			'/packageDynamicForm/pages/storeDailyReport/storeDailyReport?reportDate=2026-08-31'
		)
		assert.equal(resolvePreviousReportDate(new Date(2026, 0, 1, 12)), '2025-12-31')
		assert.equal(resolvePreviousReportDate('not-a-date'), '')
		assert.equal(isUsedCarStoreDailyReportSubmitted(['2026-08-31'], '2026-08-31'), true)
		assert.equal(
			isUsedCarStoreDailyReportSubmitted([{ reportDate: '2026-08-31' }], '2026-08-31'),
			true
		)
		assert.equal(
			resolveUsedCarShopMerchantId({
				merchantId: 9001,
				default4SStoreInfo_usedCar: { merchantId: 7001 }
			}),
			7001
		)
		assert.equal(resolveUsedCarShopMerchantId({ shopMerchantId: 7002 }), 7002)
		assert.equal(resolveUsedCarShopMerchantId({ merchantId: 9001 }), '')
	})

	it('calls weekly.list from the used-car API with the store template type', async () => {
		const { api, calls } = loadSecondHandApi()
		await api.fetchUsedCarStoreDailyReportWeeklyList({
			merchantId: 7001,
			staffUuid: 'staff-7',
			sceneType: 7,
			reportStartDate: '2026-08-31',
			reportEndDate: '2026-08-31'
		})

		assert.deepEqual(calls, [{
			method: 'dj.api.smartcarlife.dailyReport.weekly.list',
			params: {
				merchantId: 7001,
				staffUuid: 'staff-7',
				sceneType: 7,
				templateType: 2,
				reportStartDate: '2026-08-31',
				reportEndDate: '2026-08-31'
			}
		}])
	})

	it('checks yesterday through dynamic store weekly.list and opens the dynamic form', async () => {
		const { controller, calls } = loadController({
			userInfo: {
				merchantId: 9001,
				default4SStoreInfo_usedCar: { merchantId: 7001 },
				uuid: 'staff-7',
				phone: '13800000000'
			},
			weeklyResult: { code: 0, data: [] }
		})

		assert.equal(await controller.checkDailyReport(7), true)
		assert.equal(calls.legacyValid.length, 0)
		assert.deepEqual(calls.popup, [{
			merchantId: 7001,
			yqMerchantId: 9001,
			staffUuid: 'staff-7',
			staffPhone: '13800000000',
			sceneType: 7
		}])
		assert.deepEqual(calls.weekly, [{
			merchantId: 7001,
			staffUuid: 'staff-7',
			sceneType: 7,
			reportStartDate: '2026-08-31',
			reportEndDate: '2026-08-31'
		}])
		assert.deepEqual(calls.navigate, [
			'/packageDynamicForm/pages/storeDailyReport/storeDailyReport?reportDate=2026-08-31'
		])
	})

	it('opens the dynamic form from the used-car index menu', () => {
		const { component, navigate } = loadUsedCarIndex()
		component.methods.navGo.call(
			{ data: component.data },
			{ currentTarget: { dataset: { item: component.data.menuList[0] } } }
		)
		assert.deepEqual(navigate, [
			'/packageDynamicForm/pages/storeDailyReport/storeDailyReport'
		])
	})

	it('redirects legacy daily-report links and translates currentDate', () => {
		const { page, redirects } = loadLegacyDailyPage()
		let legacyInitCalls = 0
		page.onLoad.call({
			setData(_data, callback) { callback?.() },
			initData() { legacyInitCalls += 1 }
		}, { currentDate: '2026-08-31' })
		assert.equal(legacyInitCalls, 0)
		assert.deepEqual(redirects, [
			'/packageDynamicForm/pages/storeDailyReport/storeDailyReport?reportDate=2026-08-31'
		])
	})

	it('does not remind when yesterday is already submitted', async () => {
		const { controller, calls } = loadController({
			userInfo: { shopMerchantId: 7001, uuid: 'staff-7' },
			weeklyResult: { code: 0, data: ['2026-08-31'] }
		})

		assert.equal(await controller.checkDailyReport(7), false)
		assert.equal(calls.legacyValid.length, 0)
		assert.equal(calls.weekly.length, 1)
		assert.deepEqual(calls.navigate, [])
	})

	it('fails open when the dynamic weekly request fails', async () => {
		const { controller, calls } = loadController({
			userInfo: { shopMerchantId: 7001, uuid: 'staff-7' },
			weeklyResult: { code: -1, message: 'network error', data: [] }
		})

		assert.equal(await controller.checkDailyReport(7), false)
		assert.equal(calls.weekly.length, 1)
		assert.deepEqual(calls.navigate, [])
	})

	it('skips weekly.list when the existing reminder gate says no report is required', async () => {
		const { controller, calls } = loadController({
			userInfo: { shopMerchantId: 7001, uuid: 'staff-7' },
			popupRequired: false,
			weeklyResult: { code: 0, data: [] }
		})

		assert.equal(await controller.checkDailyReport(7), false)
		assert.equal(calls.popup.length, 1)
		assert.equal(calls.weekly.length, 0)
	})
})