import express from 'express'; import request from 'supertest'; import { readFileSync } from 'fs'; import path from 'path'; import { beforeEach, describe, expect, it, vi } from 'vitest'; /** * 需求预测:模型改名 / 计算时间自选 / 客户筛选(默认全部客户)。 * 背景与口径见 docs/design/20260917-demand-forecast-model-rename-calc-window-customer.md */ const mocks = vi.hoisted(() => ({ getDemandForecast: vi.fn(), })); vi.mock('../src/middleware/auth', () => ({ authMiddleware: (req: any, _res: any, next: any) => { req.userId = 'u1'; next(); }, })); vi.mock('../src/modules/workflow/context', () => ({ getWorkflowCtx: async () => ({ userId: 'u1', roles: ['admin'], permissions: [] }), requireWorkflowPermission: () => undefined, requireAdminRole: () => undefined, requireSuperAdminRole: () => undefined, })); vi.mock('../src/services/tenantScope', () => ({ getEffectiveBranchCode: () => 'BR002', readOperatingBranchCode: () => 'BR002', loadTenantContext: async () => ({ branchCode: 'BR002' }), })); vi.mock('../src/services/demandForecastService', () => ({ getDemandForecast: mocks.getDemandForecast, })); import { mountPlatformConfigWorkflowRoutes } from '../src/modules/workflow/routes/platformRoutes'; const readSource = (rel: string) => readFileSync(path.join(__dirname, '..', rel), 'utf8'); const readLocale = (loc: string) => readFileSync(path.join(__dirname, '..', '..', 'src', 'i18n', 'locales', loc, 'dashboard.ts'), 'utf8'); function buildApp() { const app = express(); const router = express.Router(); mountPlatformConfigWorkflowRoutes(router); app.use('/api', router); return app; } describe('GET /api/ai/demand-forecast:客户与计算时间参数贯通', () => { beforeEach(() => { vi.clearAllMocks(); mocks.getDemandForecast.mockResolvedValue({ days: 14, horizon_days: 1, model: 'ma', window: { from: '2026-09-04', to: '2026-09-17', label: '09-04 ~ 09-17' }, target: { from: '2026-09-18', to: '2026-09-18', label: '明天(09-18)' }, rows: [], }); }); it('不带范围参数时按旧默认下发(days 缺省、horizon 1、limit 100)', async () => { const res = await request(buildApp()).get('/api/ai/demand-forecast'); expect(res.status).toBe(200); expect(mocks.getDemandForecast).toHaveBeenCalledWith({ branchCode: 'BR002', days: undefined, horizonDays: 1, limit: 100, model: undefined, categoryCodes: undefined, skuCodes: undefined, customerCodes: undefined, dateFrom: undefined, dateTo: undefined, }); expect(res.body.data.window).toEqual({ from: '2026-09-04', to: '2026-09-17', label: '09-04 ~ 09-17' }); }); it('透传 customer_codes / date_from / date_to / model', async () => { const res = await request(buildApp()).get( '/api/ai/demand-forecast?horizon_days=7&model=weekly&customer_codes=C1,C2&date_from=2026-08-01&date_to=2026-08-20&sku_codes=S1' ); expect(res.status).toBe(200); expect(mocks.getDemandForecast).toHaveBeenCalledWith( expect.objectContaining({ horizonDays: 7, model: 'weekly', customerCodes: 'C1,C2', dateFrom: '2026-08-01', dateTo: '2026-08-20', skuCodes: 'S1', }) ); }); }); describe('服务端:模型不再按 horizon 强制,客户与计算时间进 SQL', () => { const src = readSource('src/services/demandForecastService.ts'); it('取消了 horizon > 7 强制 weekly,改为尊重入参', () => { expect(src).not.toContain("horizon > 7 ? 'weekly'"); expect(src).toContain("input?.model === 'weekly' ? 'weekly' : 'ma'"); }); it('客户筛选与分类/商品取交集(AND),未传即全部客户', () => { expect(src).toContain('selectedCustomers'); expect(src).toContain('o.customer_code = ANY('); expect(src).toContain('selectedCustomers.length'); }); it('计算时间按中国日历日闭区间过滤,并回传实际生效窗口', () => { expect(src).toContain("(o.created_at AT TIME ZONE 'Asia/Shanghai')::date >="); expect(src).toContain('window.explicit'); expect(src).toContain('window: {'); }); it('计算时间夹取 7–90 天,结束日不晚于今天', () => { expect(src).toContain('MIN_WINDOW_DAYS = 7'); expect(src).toContain('MAX_WINDOW_DAYS = 90'); expect(src).toContain('if (to > today) to = today'); }); }); describe('前端:模型解锁、客户多选、计算时间区间', () => { const page = readSource('../src/pages/Dashboard.tsx'); it('不再锁模型,按所选模型下发', () => { expect(page).not.toContain('monthLocked'); expect(page).not.toContain("forecastHorizon === 30 ? 'weekly'"); expect(page).toContain('model: forecastModel'); }); it('客户多选默认全部客户,随请求下发 customer_codes', () => { expect(page).toContain('selectedForecastCustomers'); expect(page).toContain('customer_codes: selectedForecastCustomers'); expect(page).toContain("t('dashboard.forecast.allCustomers')"); }); it('分类与客户默认全部:未选时显示「全部分类 / 全部客户」胶囊', () => { expect(page).toContain("selectedForecastCategories.length === 0"); expect(page).toContain("t('dashboard.forecast.allCategories')"); expect(page).toContain("selectedForecastCustomers.length === 0"); }); it('计算时间可选区间并随请求下发 date_from/date_to', () => { expect(page).toContain('forecastCalcRange'); expect(page).toContain('date_from: forecastCalcRange?.start'); expect(page).toContain('date_to: forecastCalcRange?.end'); }); it('不再拦截空范围:默认全部(分类/商品/客户)可直接点「开始预测」', () => { expect(page).not.toContain('notifyScope'); expect(page).toContain("notify(t('dashboard.forecast.notifyBranch'))"); }); }); describe('i18n:改名与新增键三语齐备,monthLocked 已移除', () => { const keys = [ 'forecast.calcWindow', 'forecast.calcWindowDefault', 'forecast.allCategories', 'forecast.addCustomer', 'forecast.custLoading', 'forecast.tagCustomer', 'forecast.removeCustomer', 'forecast.allCustomers', ]; for (const loc of ['zh-CN', 'en', 'id']) { it(`${loc} 键齐备且不再有 monthLocked`, () => { const text = readLocale(loc); for (const key of keys) { expect(text, `${loc} ${key}`).toContain(`'${key}'`); } expect(text, `${loc} monthLocked`).not.toContain('forecast.monthLocked'); }); it(`${loc} 空范围不再要求先选分类/商品,logic1 与默认全部一致`, () => { const text = readLocale(loc); expect(text, `${loc} notifyScope`).not.toContain('forecast.notifyScope'); const emptyLine = text.split('\n').find((l) => l.includes("'forecast.emptyPick'")) || ''; expect(emptyLine, loc).not.toContain('请先选择'); const idx = text.indexOf("'forecast.logic1'"); expect(text.slice(idx, idx + 400), loc).not.toContain('须从下拉添加'); expect(text.slice(idx, idx + 400), loc).not.toContain('Add categories and/or SKUs'); expect(text.slice(idx, idx + 400), loc).not.toContain('Tambah kategori dan/atau SKU'); }); } it('中文改名为「平均值预测 / 同周期预测」,占位符保留', () => { const zh = readLocale('zh-CN'); expect(zh).toContain("'forecast.modelMa': '平均值预测'"); expect(zh).toContain("'forecast.modelWeekly': '同周期预测'"); expect(zh).toContain("'forecast.modelMaAvg': '平均值预测'"); const block = zh.slice(zh.indexOf("'forecast.calcWindowDefault'")); expect(block.slice(0, 120)).toContain('{days}'); }); it('logic4 同步改写,不再写「一个月固定使用」', () => { for (const loc of ['zh-CN', 'en', 'id']) { const text = readLocale(loc); const idx = text.indexOf("'forecast.logic4'"); expect(idx, loc).toBeGreaterThan(-1); const block = text.slice(idx, idx + 600); expect(block, loc).not.toContain('月预测固定使用'); expect(block, loc).not.toContain('always uses that model'); expect(block, loc).toContain(loc === 'zh-CN' ? '平均值预测' : loc === 'en' ? 'Average forecast' : 'Prakiraan rata-rata'); } }); });