diff --git a/app/api/department-dashboard/core-metrics/monthly-launches/route.test.ts b/app/api/department-dashboard/core-metrics/monthly-launches/route.test.ts new file mode 100644 index 00000000..1dba1834 --- /dev/null +++ b/app/api/department-dashboard/core-metrics/monthly-launches/route.test.ts @@ -0,0 +1,54 @@ +/** @jest-environment node */ + +import { getServerSession } from 'next-auth' +import { getMonthlyLaunchSummary, DingWorkflowMetricApiError } from '@/lib/ding-workflow-sync' + +jest.mock('next-auth', () => ({ + getServerSession: jest.fn(), +})) + +jest.mock('@/lib/auth', () => ({ authOptions: {} })) + +jest.mock('@/lib/ding-workflow-sync', () => { + const actual = jest.requireActual('@/lib/ding-workflow-sync') + return { + ...actual, + getMonthlyLaunchSummary: jest.fn(), + } +}) + +const { GET } = require('@/app/api/department-dashboard/core-metrics/monthly-launches/route') as typeof import('@/app/api/department-dashboard/core-metrics/monthly-launches/route') + +describe('GET /api/department-dashboard/core-metrics/monthly-launches', () => { + beforeEach(() => { + jest.clearAllMocks() + ;(getServerSession as jest.Mock).mockResolvedValue({ user: { id: 'manager-1' } }) + ;(getMonthlyLaunchSummary as jest.Mock).mockResolvedValue({ completed: 2, ongoing: 1, total: 3 }) + }) + + it('passes month filter to the service', async () => { + const response = await GET(new Request('https://sc.jiansun.vip/api/department-dashboard/core-metrics/monthly-launches?month=2026-08')) + expect(response.status).toBe(200) + expect(getMonthlyLaunchSummary).toHaveBeenCalledWith( + { user: { id: 'manager-1' } }, + { month: '2026-08', startDate: null, endDate: null }, + ) + }) + + it('accepts inclusive custom date range aliases', async () => { + const response = await GET(new Request('https://sc.jiansun.vip/api/department-dashboard/core-metrics/monthly-launches?start=2026-08-01&end=2026-08-31')) + expect(response.status).toBe(200) + expect(getMonthlyLaunchSummary).toHaveBeenCalledWith( + { user: { id: 'manager-1' } }, + { month: null, startDate: '2026-08-01', endDate: '2026-08-31' }, + ) + }) + + it('returns service errors with their status', async () => { + ;(getMonthlyLaunchSummary as jest.Mock).mockRejectedValue(new DingWorkflowMetricApiError('month格式应为YYYY-MM', 400)) + const response = await GET(new Request('https://sc.jiansun.vip/api/department-dashboard/core-metrics/monthly-launches?month=2026/08')) + expect(response.status).toBe(400) + await expect(response.json()).resolves.toEqual({ success: false, error: 'month格式应为YYYY-MM' }) + }) +}) + diff --git a/app/api/department-dashboard/core-metrics/monthly-launches/route.ts b/app/api/department-dashboard/core-metrics/monthly-launches/route.ts index a2f1af9c..b5d0209f 100644 --- a/app/api/department-dashboard/core-metrics/monthly-launches/route.ts +++ b/app/api/department-dashboard/core-metrics/monthly-launches/route.ts @@ -14,10 +14,14 @@ const PRIVATE_HEADERS = { 'Cache-Control': 'private, no-store, max-age=0', } -export async function GET() { +export async function GET(request: Request) { try { const session = await getServerSession(authOptions) - const data = await getMonthlyLaunchSummary(session) + const params = new URL(request.url).searchParams + const month = params.get('month') + const startDate = params.get('startDate') || params.get('start') + const endDate = params.get('endDate') || params.get('end') + const data = await getMonthlyLaunchSummary(session, { month, startDate, endDate }) return NextResponse.json({ success: true, data }, { headers: PRIVATE_HEADERS }) } catch (error) { if (error instanceof DingWorkflowMetricApiError) { diff --git a/app/workspaces/[section]/[item]/[metric]/page.tsx b/app/workspaces/[section]/[item]/[metric]/page.tsx index be5b02c0..f1a1cd25 100644 --- a/app/workspaces/[section]/[item]/[metric]/page.tsx +++ b/app/workspaces/[section]/[item]/[metric]/page.tsx @@ -16,7 +16,7 @@ import { type CoreMetricPageProps = { params: { section: string; item: string; metric: string } - searchParams?: { page?: string; q?: string } + searchParams?: { page?: string; q?: string; month?: string; startDate?: string; endDate?: string; start?: string; end?: string } } export const dynamic = 'force-dynamic' @@ -45,7 +45,11 @@ export default async function CoreMetricPage({ params, searchParams }: CoreMetri if (metric.key === 'monthly-launches') { const session = await getServerSession(authOptions) - const monthlyLaunches = await getMonthlyLaunchInsights(session) + const monthlyLaunches = await getMonthlyLaunchInsights(session, { + month: searchParams?.month, + startDate: searchParams?.startDate || searchParams?.start, + endDate: searchParams?.endDate || searchParams?.end, + }) return } diff --git a/components/department-dashboard/CoreMetricDetail.test.tsx b/components/department-dashboard/CoreMetricDetail.test.tsx index 39970b32..e7726b0d 100644 --- a/components/department-dashboard/CoreMetricDetail.test.tsx +++ b/components/department-dashboard/CoreMetricDetail.test.tsx @@ -7,6 +7,11 @@ jest.mock('next-auth/react', () => ({ signOut: jest.fn(), })) +jest.mock('next/navigation', () => ({ + usePathname: () => '/workspaces/dashboard/core-metrics/monthly-launches', + useRouter: () => ({ push: jest.fn() }), +})) + describe('CoreMetricDetail', () => { it('按品牌与当前节点处理人展示真实进行中项目', () => { const metric = getCoreMetric('ongoing-projects')! @@ -226,10 +231,10 @@ describe('CoreMetricDetail', () => { expect(screen.getByRole('heading', { level: 1, name: '本月上新' })).toBeInTheDocument() expect(screen.getByText('1/2')).toBeInTheDocument() - expect(screen.getByRole('heading', { name: '亿家达 · 本月已完结新品' })).toBeInTheDocument() + expect(screen.getByRole('heading', { name: /亿家达 · .*已完结新品/ })).toBeInTheDocument() expect(screen.getAllByText('流程已完结').length).toBeGreaterThan(0) expect(screen.getAllByText('新品主视觉申请').length).toBeGreaterThan(0) - const completedTable = screen.getByRole('table', { name: /亿家达本月已完结新品流程明细横向滚动表格/ }) + const completedTable = screen.getByRole('table', { name: /亿家达.*已完结新品流程明细横向滚动表格/ }) ;[ '审批单标题', '审批编号', diff --git a/components/department-dashboard/CoreMetricDetail.tsx b/components/department-dashboard/CoreMetricDetail.tsx index 2f233ac1..f3066070 100644 --- a/components/department-dashboard/CoreMetricDetail.tsx +++ b/components/department-dashboard/CoreMetricDetail.tsx @@ -26,6 +26,7 @@ import OnTimeDeliveryInsightsView from './OnTimeDeliveryInsights' import OnTimeDeliveryRate from './OnTimeDeliveryRate' import TeamWorkloadInsightsView from './TeamWorkloadInsights' import type { CoreMetric } from './core-metrics' +import { formatMonthlyLaunchPeriod } from './monthly-launch-period' type CoreMetricDetailProps = { metric: CoreMetric @@ -61,7 +62,6 @@ function formatRate(rate: number | null) { return `${Number.isInteger(rate) ? rate.toFixed(0) : rate.toFixed(1)}%` } - const CURRENT_REVIEW_STATUS_LABELS: Record = { approved: '当前已通过', pending_review: '当前评审中', @@ -297,6 +297,9 @@ export default function CoreMetricDetail({ metric, query, projectInsights, month const hasFirstPassSource = metric.key === 'first-pass-rate' && firstPassPage const hasOnTimeDeliverySource = metric.key === 'on-time-delivery' && onTimeDelivery const hasTeamWorkloadSource = metric.key === 'team-workload' && teamWorkload + const monthlyLaunchPeriod = hasMonthlyLaunchSource + ? formatMonthlyLaunchPeriod(monthlyLaunches.summary.monthStart, monthlyLaunches.summary.monthEnd) + : '' return ( @@ -308,14 +311,14 @@ export default function CoreMetricDetail({ metric, query, projectInsights, month
-

{hasFirstPassSource ? '当前首轮通过率' : hasRealProjectSource ? '当前未完结流程' : hasMonthlyLaunchSource ? '本月已完结 / 新品流程总数' : hasOnTimeDeliverySource ? '本月按时交付率' : hasTeamWorkloadSource ? '品牌中心平均负荷' : '总览示例值'}

+

{hasFirstPassSource ? '当前首轮通过率' : hasRealProjectSource ? '当前未完结流程' : hasMonthlyLaunchSource ? `${monthlyLaunchPeriod}已完结 / 新品流程总数` : hasOnTimeDeliverySource ? '本月按时交付率' : hasTeamWorkloadSource ? '品牌中心平均负荷' : '总览示例值'}

{hasOnTimeDeliverySource && onTimeDelivery.summary.rate !== null ? :

{hasFirstPassSource ? formatRate(firstPassPage.summary.rate) : hasRealProjectSource ? projectInsights.total : hasMonthlyLaunchSource ? `${monthlyLaunches.summary.completed}/${monthlyLaunches.summary.total}` : hasOnTimeDeliverySource ? '—' : hasTeamWorkloadSource ? formatRate(teamWorkload.summary.averageLoadPercent) : metric.exampleValue}

}

明细数据

-

{hasFirstPassSource ? `V1通过 ${firstPassPage.summary.firstPassApproved} / 已通过 ${firstPassPage.summary.totalApproved}` : hasRealProjectSource ? `${projectInsights.total} 条流程快照` : hasMonthlyLaunchSource ? `本月已完结 ${monthlyLaunches.summary.completed} / 当前进行中 ${monthlyLaunches.summary.ongoing}` : hasOnTimeDeliverySource ? `未超时审核节点完成 ${onTimeDelivery.summary.onTime} / 审核节点完成 ${onTimeDelivery.summary.total}` : hasTeamWorkloadSource ? `${teamWorkload.summary.busyPersonnel} 人有进行中流程 / 共 ${teamWorkload.summary.personnelCount} 人` : '等待业务数据源'}

+

{hasFirstPassSource ? `V1通过 ${firstPassPage.summary.firstPassApproved} / 已通过 ${firstPassPage.summary.totalApproved}` : hasRealProjectSource ? `${projectInsights.total} 条流程快照` : hasMonthlyLaunchSource ? `${monthlyLaunchPeriod}已完结 ${monthlyLaunches.summary.completed} / 当前进行中 ${monthlyLaunches.summary.ongoing}` : hasOnTimeDeliverySource ? `未超时审核节点完成 ${onTimeDelivery.summary.onTime} / 审核节点完成 ${onTimeDelivery.summary.total}` : hasTeamWorkloadSource ? `${teamWorkload.summary.busyPersonnel} 人有进行中流程 / 共 ${teamWorkload.summary.personnelCount} 人` : '等待业务数据源'}

同步状态

diff --git a/components/department-dashboard/MonthlyLaunchPeriodFilter.test.tsx b/components/department-dashboard/MonthlyLaunchPeriodFilter.test.tsx new file mode 100644 index 00000000..5857ff94 --- /dev/null +++ b/components/department-dashboard/MonthlyLaunchPeriodFilter.test.tsx @@ -0,0 +1,67 @@ +import { fireEvent, render, screen } from '@testing-library/react' +import MonthlyLaunchPeriodFilter from './MonthlyLaunchPeriodFilter' + +const mockPush = jest.fn() + +jest.mock('next/navigation', () => ({ + usePathname: () => '/workspaces/dashboard/core-metrics/monthly-launches', + useRouter: () => ({ push: mockPush }), +})) + +const summary = { + completed: 4, + ongoing: 2, + total: 6, + monthStart: '2026-07-31T16:00:00.000Z', + monthEnd: '2026-08-31T16:00:00.000Z', + lastSyncedAt: '2026-08-31T04:00:00.000Z', + syncStatus: 'ready' as const, +} + +const options = [ + { value: '2026-08', label: '本月', startDate: '2026-08-01', endDate: '2026-08-31' }, + { value: '2026-07', label: '上月', startDate: '2026-07-01', endDate: '2026-07-31' }, +] + +describe('MonthlyLaunchPeriodFilter', () => { + beforeEach(() => mockPush.mockClear()) + + it('shows available month presets and navigates with a month query', () => { + render() + + expect(screen.getByRole('option', { name: '本月' })).toBeInTheDocument() + expect(screen.getByRole('option', { name: '上月' })).toBeInTheDocument() + expect(screen.getByRole('option', { name: '自定义日期' })).toBeInTheDocument() + + fireEvent.change(screen.getByRole('combobox', { name: '选择统计月份' }), { + target: { value: '2026-07' }, + }) + + expect(mockPush).toHaveBeenCalledWith( + '/workspaces/dashboard/core-metrics/monthly-launches?month=2026-07', + ) + }) + + it('submits an inclusive custom date range', () => { + render() + + fireEvent.change(screen.getByLabelText(/统计开始日期/), { target: { value: '2026-06-15' } }) + fireEvent.change(screen.getByLabelText(/统计结束日期/), { target: { value: '2026-06-30' } }) + expect(screen.getByRole('combobox', { name: '选择统计月份' })).toHaveValue('custom') + fireEvent.submit(screen.getByRole('form', { name: '本月上新日期筛选' })) + + expect(mockPush).toHaveBeenCalledWith( + '/workspaces/dashboard/core-metrics/monthly-launches?startDate=2026-06-15&endDate=2026-06-30', + ) + }) + + it('disables apply when the end date is before the start date', () => { + render() + + fireEvent.change(screen.getByLabelText(/统计开始日期/), { target: { value: '2026-08-20' } }) + fireEvent.change(screen.getByLabelText(/统计结束日期/), { target: { value: '2026-08-10' } }) + + expect(screen.getByRole('button', { name: /应用筛选/ })).toBeDisabled() + expect(mockPush).not.toHaveBeenCalled() + }) +}) diff --git a/components/department-dashboard/MonthlyLaunchPeriodFilter.tsx b/components/department-dashboard/MonthlyLaunchPeriodFilter.tsx new file mode 100644 index 00000000..1dda18df --- /dev/null +++ b/components/department-dashboard/MonthlyLaunchPeriodFilter.tsx @@ -0,0 +1,127 @@ +'use client' + +import { CalendarDays, Filter } from 'lucide-react' +import { FormEvent, useEffect, useState } from 'react' +import { usePathname, useRouter } from 'next/navigation' +import type { + MonthlyLaunchMonthOption, + MonthlyLaunchSummary, +} from '@/lib/ding-workflow-sync' +import { toShanghaiDateInput } from './monthly-launch-period' + +function formatDateLabel(value: string) { + const [year, month, day] = value.split('-') + return year && month && day ? `${year}/${month}/${day}` : value +} + +export default function MonthlyLaunchPeriodFilter({ + summary, + options, +}: { + summary: MonthlyLaunchSummary + options: MonthlyLaunchMonthOption[] +}) { + const router = useRouter() + const pathname = usePathname() + const initialStartDate = toShanghaiDateInput(summary.monthStart) + const initialEndDate = toShanghaiDateInput(summary.monthEnd, true) + const initialPreset = options.find((option) => option.startDate === initialStartDate && option.endDate === initialEndDate)?.value || 'custom' + const [startDate, setStartDate] = useState(initialStartDate) + const [endDate, setEndDate] = useState(initialEndDate) + const [preset, setPreset] = useState(initialPreset) + + useEffect(() => { + setStartDate(initialStartDate) + setEndDate(initialEndDate) + setPreset(initialPreset) + }, [initialEndDate, initialPreset, initialStartDate]) + + const navigate = (params: URLSearchParams) => { + const query = params.toString() + router.push(`${pathname}${query ? `?${query}` : ''}`) + } + + const handlePresetChange = (value: string) => { + if (value === 'custom') { + setPreset('custom') + return + } + const option = options.find((candidate) => candidate.value === value) + if (!option) return + setStartDate(option.startDate) + setEndDate(option.endDate) + setPreset(option.value) + navigate(new URLSearchParams({ month: option.value })) + } + + const handleSubmit = (event: FormEvent) => { + event.preventDefault() + if (!startDate || !endDate || startDate > endDate) return + navigate(new URLSearchParams({ startDate, endDate })) + } + + return ( +
+ + + + + + + +
+ ) +} diff --git a/components/department-dashboard/MonthlyLaunchesInsights.tsx b/components/department-dashboard/MonthlyLaunchesInsights.tsx index a2d0b668..d093be3a 100644 --- a/components/department-dashboard/MonthlyLaunchesInsights.tsx +++ b/components/department-dashboard/MonthlyLaunchesInsights.tsx @@ -12,16 +12,20 @@ import type { MonthlyLaunchInsights, MonthlyLaunchWorkflowStatus, } from '@/lib/ding-workflow-sync' +import MonthlyLaunchPeriodFilter from './MonthlyLaunchPeriodFilter' +import { formatMonthlyLaunchPeriod } from './monthly-launch-period' import WorkflowDetailTable from './WorkflowDetailTable' -function statusLabel(status: MonthlyLaunchWorkflowStatus) { - return status === 'completed' ? '本月已完结新品' : '当前进行中新品' +function statusLabel(status: MonthlyLaunchWorkflowStatus, period: string) { + return status === 'completed' ? `${period}已完结新品` : '当前进行中新品' } export default function MonthlyLaunchesInsights({ insights }: { insights: MonthlyLaunchInsights }) { const [selectedBrand, setSelectedBrand] = useState(insights.brands[0]?.brand || '亿家达') const [selectedStatus, setSelectedStatus] = useState('completed') const [visibleCount, setVisibleCount] = useState(30) + const period = formatMonthlyLaunchPeriod(insights.summary.monthStart, insights.summary.monthEnd) + const monthOptions = insights.availableMonths || [] const selectedItems = useMemo(() => insights.items.filter((item) => ( item.brand === selectedBrand && item.launchStatus === selectedStatus @@ -37,16 +41,18 @@ export default function MonthlyLaunchesInsights({ insights }: { insights: Monthl
-

六品牌本月新品流程

+

六品牌{period}新品流程

- 已完结按整条美术设计流程的本月完结时间统计;进行中复用“进行中项目”的当前品牌中心在办美术流程口径。流程自 2026 年 4 月 1 日起计入。 + 已完结按所选日期范围内整条美术设计流程的完结时间统计;进行中复用“进行中项目”的当前品牌中心在办美术流程口径。流程自 2026 年 4 月 1 日起计入。

- 本月已完结 {insights.summary.completed} · 当前进行中 {insights.summary.ongoing} + {period}已完结 {insights.summary.completed} · 当前进行中 {insights.summary.ongoing}

+ +
{insights.brands.map((brand) => (
@@ -60,20 +66,21 @@ export default function MonthlyLaunchesInsights({ insights }: { insights: Monthl { status: 'ongoing' as const, label: '当前进行中', count: brand.ongoing, icon: Clock3 }, ]).map((group) => { const Icon = group.icon + const groupLabel = group.status === 'completed' ? `${period}已完结` : group.label const selected = selectedBrand === brand.brand && selectedStatus === group.status return (