feat: add monthly launch date filters

This commit is contained in:
江林铖 2026-09-01 12:07:32 +08:00
parent cae0e68a04
commit 8a3122b1fd
12 changed files with 503 additions and 26 deletions

View File

@ -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' })
})
})

View File

@ -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) {

View File

@ -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 <CoreMetricDetail metric={metric} monthlyLaunches={monthlyLaunches} />
}

View File

@ -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: /亿家达.*已完结新品流程明细横向滚动表格/ })
;[
'审批单标题',
'审批编号',

View File

@ -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<string, string> = {
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 (
<DepartmentShell>
@ -308,14 +311,14 @@ export default function CoreMetricDetail({ metric, query, projectInsights, month
<section aria-label="指标口径" className="mt-6 grid overflow-hidden rounded-lg border border-[#e2e8f0] bg-white sm:grid-cols-3">
<div className="border-b border-slate-200 p-5 sm:border-b-0 sm:border-r">
<p className="text-xs font-bold text-slate-500">{hasFirstPassSource ? '当前首轮通过率' : hasRealProjectSource ? '当前未完结流程' : hasMonthlyLaunchSource ? '本月已完结 / 新品流程总数' : hasOnTimeDeliverySource ? '本月按时交付率' : hasTeamWorkloadSource ? '品牌中心平均负荷' : '总览示例值'}</p>
<p className="text-xs font-bold text-slate-500">{hasFirstPassSource ? '当前首轮通过率' : hasRealProjectSource ? '当前未完结流程' : hasMonthlyLaunchSource ? `${monthlyLaunchPeriod}已完结 / 新品流程总数` : hasOnTimeDeliverySource ? '本月按时交付率' : hasTeamWorkloadSource ? '品牌中心平均负荷' : '总览示例值'}</p>
{hasOnTimeDeliverySource && onTimeDelivery.summary.rate !== null
? <OnTimeDeliveryRate rate={onTimeDelivery.summary.rate} contextLabel="按时交付当前值" size="summary" />
: <p className="mt-2 text-2xl font-bold tabular-nums">{hasFirstPassSource ? formatRate(firstPassPage.summary.rate) : hasRealProjectSource ? projectInsights.total : hasMonthlyLaunchSource ? `${monthlyLaunches.summary.completed}/${monthlyLaunches.summary.total}` : hasOnTimeDeliverySource ? '—' : hasTeamWorkloadSource ? formatRate(teamWorkload.summary.averageLoadPercent) : metric.exampleValue}</p>}
</div>
<div className="border-b border-slate-200 p-5 sm:border-b-0 sm:border-r">
<p className="text-xs font-bold text-slate-500">明细数据</p>
<p className="mt-2 text-base font-bold">{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} 人` : '等待业务数据源'}</p>
<p className="mt-2 text-base font-bold">{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} 人` : '等待业务数据源'}</p>
</div>
<div className="p-5">
<p className="text-xs font-bold text-slate-500">同步状态</p>

View File

@ -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(<MonthlyLaunchPeriodFilter summary={summary} options={options} />)
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(<MonthlyLaunchPeriodFilter summary={summary} options={options} />)
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(<MonthlyLaunchPeriodFilter summary={summary} options={options} />)
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()
})
})

View File

@ -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<HTMLFormElement>) => {
event.preventDefault()
if (!startDate || !endDate || startDate > endDate) return
navigate(new URLSearchParams({ startDate, endDate }))
}
return (
<form
onSubmit={handleSubmit}
aria-label="本月上新日期筛选"
className="mt-6 flex flex-col gap-3 rounded-xl border border-slate-200 bg-white p-4 sm:flex-row sm:flex-wrap sm:items-end"
>
<label className="flex min-w-0 flex-1 flex-col gap-1.5 sm:min-w-[180px] sm:flex-none">
<span className="text-xs font-bold text-slate-500">快捷月份</span>
<select
value={preset}
onChange={(event) => handlePresetChange(event.target.value)}
aria-label="选择统计月份"
className="h-11 w-full rounded-lg border border-slate-300 bg-white px-3 text-sm font-semibold text-slate-800 outline-none transition focus:border-[#1677ff] focus:ring-2 focus:ring-[#1677ff]/20"
>
{options.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}
<option value="custom">自定义日期</option>
</select>
</label>
<label className="flex min-w-0 flex-1 flex-col gap-1.5 sm:min-w-[180px] sm:flex-none">
<span className="text-xs font-bold text-slate-500">开始日期</span>
<span className="relative">
<CalendarDays className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" aria-hidden="true" />
<input
type="date"
value={startDate}
max={endDate || undefined}
onChange={(event) => {
setStartDate(event.target.value)
setPreset('custom')
}}
aria-label={`统计开始日期 ${formatDateLabel(startDate)}`}
className="h-11 w-full rounded-lg border border-slate-300 bg-white pl-10 pr-3 text-sm font-semibold text-slate-800 outline-none transition focus:border-[#1677ff] focus:ring-2 focus:ring-[#1677ff]/20"
/>
</span>
</label>
<label className="flex min-w-0 flex-1 flex-col gap-1.5 sm:min-w-[180px] sm:flex-none">
<span className="text-xs font-bold text-slate-500">结束日期</span>
<span className="relative">
<CalendarDays className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-slate-400" aria-hidden="true" />
<input
type="date"
value={endDate}
min={startDate || undefined}
onChange={(event) => {
setEndDate(event.target.value)
setPreset('custom')
}}
aria-label={`统计结束日期 ${formatDateLabel(endDate)}`}
className="h-11 w-full rounded-lg border border-slate-300 bg-white pl-10 pr-3 text-sm font-semibold text-slate-800 outline-none transition focus:border-[#1677ff] focus:ring-2 focus:ring-[#1677ff]/20"
/>
</span>
</label>
<button
type="submit"
disabled={!startDate || !endDate || startDate > endDate}
className="inline-flex h-11 shrink-0 items-center justify-center gap-2 rounded-lg bg-[#1677ff] px-4 text-sm font-bold text-white transition hover:bg-[#0d63d6] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#1677ff] focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:bg-slate-300"
>
<Filter className="h-4 w-4" aria-hidden="true" />应用筛选
</button>
</form>
)
}

View File

@ -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<MonthlyLaunchWorkflowStatus>('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
<section aria-labelledby="monthly-launch-title" className="mt-10">
<div className="flex flex-col gap-3 lg:flex-row lg:items-end lg:justify-between">
<div>
<h2 id="monthly-launch-title" className="text-xl font-bold tracking-[-0.02em] sm:text-2xl">六品牌本月新品流程</h2>
<h2 id="monthly-launch-title" className="text-xl font-bold tracking-[-0.02em] sm:text-2xl">六品牌{period}新品流程</h2>
<p className="mt-1 max-w-3xl text-sm leading-6 text-slate-600">
已完结按整条美术设计流程的本月完结时间统计;进行中复用“进行中项目”的当前品牌中心在办美术流程口径。流程自 2026 年 4 月 1 日起计入。
已完结按所选日期范围内整条美术设计流程的完结时间统计;进行中复用“进行中项目”的当前品牌中心在办美术流程口径。流程自 2026 年 4 月 1 日起计入。
</p>
</div>
<p className="text-sm font-semibold tabular-nums text-slate-600">
本月已完结 {insights.summary.completed} · 当前进行中 {insights.summary.ongoing}
{period}已完结 {insights.summary.completed} · 当前进行中 {insights.summary.ongoing}
</p>
</div>
<MonthlyLaunchPeriodFilter summary={insights.summary} options={monthOptions} />
<div className="mt-5 grid gap-3 lg:grid-cols-2" aria-label="六品牌新品流程数量">
{insights.brands.map((brand) => (
<article key={brand.brand} className="min-w-0 overflow-hidden rounded-xl border border-slate-200 bg-white">
@ -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 (
<button
key={group.status}
type="button"
aria-pressed={selected}
aria-label={`查看${brand.brand}${group.label}明细,共${group.count}条`}
aria-label={`查看${brand.brand}${groupLabel}明细,共${group.count}条`}
onClick={() => selectGroup(brand.brand, group.status)}
className={`group min-w-0 px-5 py-4 text-left transition-colors focus-visible:z-10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[#5a9ce6] ${selected ? 'bg-[#e5f2ff] text-[#075fab]' : 'bg-white hover:bg-slate-50'}`}
>
<div className="flex items-start justify-between gap-3">
<span className="inline-flex min-w-0 items-center gap-2 text-sm font-bold">
<Icon className="h-4 w-4 shrink-0" aria-hidden="true" />
<span className="truncate">{group.label}</span>
<span className="truncate">{groupLabel}</span>
</span>
<span className="shrink-0 text-2xl font-bold tabular-nums">{group.count}</span>
</div>
@ -89,7 +96,7 @@ export default function MonthlyLaunchesInsights({ insights }: { insights: Monthl
<div className="flex flex-col gap-2 border-b border-slate-200 px-5 py-4 sm:flex-row sm:items-center sm:justify-between">
<div>
<h3 id="monthly-launch-detail-title" className="text-lg font-bold text-slate-950">
{selectedBrand} · {statusLabel(selectedStatus)}
{selectedBrand} · {statusLabel(selectedStatus, period)}
</h3>
<p className="mt-1 text-sm text-slate-500">明细字段与“进行中项目”一致,完整展示表单信息、当前节点与业务时间。</p>
</div>
@ -107,8 +114,8 @@ export default function MonthlyLaunchesInsights({ insights }: { insights: Monthl
<div className="p-4 sm:p-5">
<WorkflowDetailTable
items={selectedItems.slice(0, visibleCount)}
tableLabel={`${selectedBrand}${statusLabel(selectedStatus)}流程明细横向滚动表格`}
mobileListLabel={`${selectedBrand}${statusLabel(selectedStatus)}流程列表`}
tableLabel={`${selectedBrand}${statusLabel(selectedStatus, period)}流程明细横向滚动表格`}
mobileListLabel={`${selectedBrand}${statusLabel(selectedStatus, period)}流程列表`}
/>
</div>
</>

View File

@ -43,7 +43,7 @@ export const CORE_METRICS: CoreMetric[] = [
exampleValue: '18/24',
description: '本月已完结的新品美术设计流程与当前进行中新品美术设计流程的对照。',
icon: PackagePlus,
detailDescription: '查看 2026 年 4 月 1 日起发起的新品美术设计流程;分子按本月整条流程完结时间统计,分母为本月已完结与当前进行中流程之和。',
detailDescription: '可按月份或自定义日期范围查看 2026 年 4 月 1 日起发起的新品美术设计流程;已完结按所选范围统计,进行中沿用当前流程快照。',
plannedFields: ['流程编码', '品牌', '发起人', '所在部门', '当前节点', '业务时间'],
},
{

View File

@ -0,0 +1,29 @@
const DAY_MS = 24 * 60 * 60 * 1000
const SHANGHAI_OFFSET_MS = 8 * 60 * 60 * 1000
export function toShanghaiDateInput(value: string, endExclusive = false) {
const instant = new Date(value).getTime() - (endExclusive ? DAY_MS : 0)
if (!Number.isFinite(instant)) return ''
return new Date(instant + SHANGHAI_OFFSET_MS).toISOString().slice(0, 10)
}
function monthValue(value: Date) {
const shifted = new Date(value.getTime() + SHANGHAI_OFFSET_MS)
return shifted.toISOString().slice(0, 7)
}
/** 完整自然月显示“本月/2026年8月”,自定义区间显示起止日期。 */
export function formatMonthlyLaunchPeriod(monthStart: string, monthEnd: string) {
const startDate = toShanghaiDateInput(monthStart)
const endDate = toShanghaiDateInput(monthEnd, true)
if (!startDate || !endDate) return '所选期间'
const [year, month, day] = startDate.split('-').map(Number)
const [, , endDay] = endDate.split('-').map(Number)
const lastDay = new Date(Date.UTC(year, month, 0)).getUTCDate()
if (day === 1 && endDay === lastDay && endDate.slice(0, 7) === startDate.slice(0, 7)) {
const current = monthValue(new Date())
return startDate.slice(0, 7) === current ? '本月' : `${year}年${month}月`
}
return `${startDate.replaceAll('-', '/')} - ${endDate.replaceAll('-', '/')}`
}

View File

@ -8,6 +8,9 @@ import {
buildMonthlyLaunchOngoingWorkflowWhere,
buildMonthlyLaunchWorkflowWhere,
getShanghaiMonthRange,
getShanghaiMonthRangeForValue,
getMonthlyLaunchMonthOptions,
resolveMonthlyLaunchDateRange,
getDingWorkflowActivityNodeName,
getDingWorkflowProjectType,
isDingWorkflowTaskOngoing,
@ -82,6 +85,39 @@ describe('ding workflow snapshot sync semantics', () => {
expect(isDingWorkflowCompletedInRange('COMPLETED', null, range)).toBe(false)
})
it('resolves a requested Shanghai month and inclusive custom date range', () => {
expect(getShanghaiMonthRangeForValue('2026-08')).toEqual({
start: new Date('2026-07-31T16:00:00.000Z'),
end: new Date('2026-08-31T16:00:00.000Z'),
})
expect(resolveMonthlyLaunchDateRange({ startDate: '2026-08-01', endDate: '2026-08-31' })).toEqual({
start: new Date('2026-07-31T16:00:00.000Z'),
end: new Date('2026-08-31T16:00:00.000Z'),
})
})
it('offers month presets from the April 2026 cutoff through the current month', () => {
const options = getMonthlyLaunchMonthOptions(new Date('2026-09-15T00:00:00.000Z'))
expect(options.map((option) => option.value)).toEqual([
'2026-09',
'2026-08',
'2026-07',
'2026-06',
'2026-05',
'2026-04',
])
expect(options[0]).toMatchObject({ label: '本月', startDate: '2026-09-01', endDate: '2026-09-30' })
expect(options[1]).toMatchObject({ label: '上月', startDate: '2026-08-01', endDate: '2026-08-31' })
})
it('rejects invalid or ambiguous monthly launch date filters', () => {
expect(() => getShanghaiMonthRangeForValue('2026-13')).toThrow('month不是有效月份')
expect(() => getShanghaiMonthRangeForValue('2026/08')).toThrow('month格式应为YYYY-MM')
expect(() => resolveMonthlyLaunchDateRange({ startDate: '2026-02-30', endDate: '2026-03-01' })).toThrow('startDate不是有效日期')
expect(() => resolveMonthlyLaunchDateRange({ month: '2026-08', startDate: '2026-08-01' })).toThrow('month不能与startDate/endDate同时使用')
expect(() => resolveMonthlyLaunchDateRange({ startDate: '2026-09-01', endDate: '2026-08-31' })).toThrow('endDate不能早于startDate')
})
it('uses the delivery assessment finish node for monthly inclusion and excludes pending', () => {
const range = getShanghaiMonthRange(new Date('2026-08-26T03:00:00.000Z'))
expect(isDingWorkflowDeliveryAssessmentInRange({

View File

@ -437,10 +437,31 @@ export type MonthlyLaunchSummary = {
syncStatus: DingWorkflowSyncStatus
}
/** 查询本月上新指标时可选的日期筛选参数。月份使用 YYYY-MM,
* 自定义区间使用上海本地日期(YYYY-MM-DD,结束日期含当天)。 */
export type MonthlyLaunchRangeInput = {
month?: string | null
startDate?: string | null
endDate?: string | null
}
export type MonthlyLaunchDateRange = {
start: Date
end: Date
}
export type MonthlyLaunchMonthOption = {
value: string
label: string
startDate: string
endDate: string
}
export type MonthlyLaunchInsights = {
items: MonthlyLaunchWorkflowItem[]
brands: MonthlyLaunchBrandSummary[]
summary: MonthlyLaunchSummary
availableMonths?: MonthlyLaunchMonthOption[]
}
export type OnTimeDeliveryWorkflowItem = OngoingDingWorkflowListItem & {
@ -1037,6 +1058,115 @@ export function getShanghaiMonthRange(now = new Date()) {
}
}
const SHANGHAI_OFFSET_MS = 8 * 60 * 60 * 1000
const SHANGHAI_MONTH_PATTERN = /^(\d{4})-(\d{2})$/
const SHANGHAI_DATE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})$/
function parseShanghaiCalendarDate(value: unknown, label: string): { year: number; month: number; day: number } {
const normalized = clean(value)
const match = normalized?.match(SHANGHAI_DATE_PATTERN)
if (!match) throw new DingWorkflowMetricApiError(`${label}格式应为YYYY-MM-DD`, 400)
const year = Number(match[1])
const month = Number(match[2])
const day = Number(match[3])
const candidate = new Date(Date.UTC(year, month - 1, day))
if (
!Number.isFinite(candidate.getTime())
|| candidate.getUTCFullYear() !== year
|| candidate.getUTCMonth() !== month - 1
|| candidate.getUTCDate() !== day
) {
throw new DingWorkflowMetricApiError(`${label}不是有效日期`, 400)
}
return { year, month, day }
}
/** 将上海本地月份转换为 UTC Date 区间,区间结束点为下月一日(不含)。 */
export function getShanghaiMonthRangeForValue(value: unknown): MonthlyLaunchDateRange {
const normalized = clean(value)
const match = normalized?.match(SHANGHAI_MONTH_PATTERN)
if (!match) throw new DingWorkflowMetricApiError('month格式应为YYYY-MM', 400)
const year = Number(match[1])
const month = Number(match[2])
if (month < 1 || month > 12) throw new DingWorkflowMetricApiError('month不是有效月份', 400)
return {
start: new Date(Date.UTC(year, month - 1, 1) - SHANGHAI_OFFSET_MS),
end: new Date(Date.UTC(year, month, 1) - SHANGHAI_OFFSET_MS),
}
}
/** 解析月份或上海本地日期区间。自定义 endDate 含当天。 */
export function resolveMonthlyLaunchDateRange(
input: MonthlyLaunchRangeInput = {},
now = new Date(),
): MonthlyLaunchDateRange {
const month = clean(input.month)
const startDate = clean(input.startDate)
const endDate = clean(input.endDate)
if (month && (startDate || endDate)) {
throw new DingWorkflowMetricApiError('month不能与startDate/endDate同时使用', 400)
}
if (month) return getShanghaiMonthRangeForValue(month)
if (!startDate && !endDate) return getShanghaiMonthRange(now)
if (!startDate || !endDate) {
throw new DingWorkflowMetricApiError('startDate和endDate必须同时提供', 400)
}
const start = parseShanghaiCalendarDate(startDate, 'startDate')
const end = parseShanghaiCalendarDate(endDate, 'endDate')
const startInstant = new Date(Date.UTC(start.year, start.month - 1, start.day) - SHANGHAI_OFFSET_MS)
const endExclusive = new Date(Date.UTC(end.year, end.month - 1, end.day + 1) - SHANGHAI_OFFSET_MS)
if (endExclusive <= startInstant) {
throw new DingWorkflowMetricApiError('endDate不能早于startDate', 400)
}
return { start: startInstant, end: endExclusive }
}
function shanghaiMonthValue(value: Date) {
const parts = new Intl.DateTimeFormat('en-US', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
}).formatToParts(value)
const year = parts.find((part) => part.type === 'year')?.value || '0000'
const month = parts.find((part) => part.type === 'month')?.value || '01'
return `${year}-${month}`
}
function formatShanghaiDateInput(value: Date) {
const shifted = new Date(value.getTime() + SHANGHAI_OFFSET_MS)
return shifted.toISOString().slice(0, 10)
}
/** 返回从 2026 年 4 月起到当前月份的筛选选项,供详情页下拉框使用。 */
export function getMonthlyLaunchMonthOptions(now = new Date()): MonthlyLaunchMonthOption[] {
const currentValue = shanghaiMonthValue(now)
const [currentYear, currentMonth] = currentValue.split('-').map(Number)
const cutoffValue = shanghaiMonthValue(new Date(DING_WORKFLOW_STARTED_AT_CUTOFF_ISO))
const [cutoffYear, cutoffMonth] = cutoffValue.split('-').map(Number)
const options: MonthlyLaunchMonthOption[] = []
const previousMonthValue = currentMonth === 1
? `${currentYear - 1}-12`
: `${currentYear}-${String(currentMonth - 1).padStart(2, '0')}`
let year = currentYear
let month = currentMonth
while (year > cutoffYear || (year === cutoffYear && month >= cutoffMonth)) {
const value = `${year}-${String(month).padStart(2, '0')}`
const range = getShanghaiMonthRangeForValue(value)
options.push({
value,
label: value === currentValue ? '本月' : value === previousMonthValue ? '上月' : `${year}年${month}月`,
startDate: formatShanghaiDateInput(range.start),
endDate: formatShanghaiDateInput(new Date(range.end.getTime() - 24 * 60 * 60 * 1000)),
})
month -= 1
if (month === 0) {
month = 12
year -= 1
}
}
return options
}
export function isDingWorkflowCompletedInRange(
status: unknown,
finishedAt: unknown,
@ -2168,8 +2298,11 @@ export function buildMonthlyLaunchOngoingWorkflowWhere() {
}
}
async function readMonthlyLaunchInsightsWithoutAccessCheck(now = new Date()): Promise<MonthlyLaunchInsights> {
const range = getShanghaiMonthRange(now)
async function readMonthlyLaunchInsightsWithoutAccessCheck(
input: MonthlyLaunchRangeInput = {},
now = new Date(),
): Promise<MonthlyLaunchInsights> {
const range = resolveMonthlyLaunchDateRange(input, now)
const baseWhere = buildMonthlyLaunchWorkflowWhere()
const [completedCandidates, ongoingRows, state] = await Promise.all([
prisma.dingWorkflowSnapshot.findMany({
@ -2184,6 +2317,7 @@ async function readMonthlyLaunchInsightsWithoutAccessCheck(now = new Date()): Pr
select: MONTHLY_LAUNCH_WORKFLOW_SELECT,
}),
prisma.dingWorkflowSnapshot.findMany({
// “当前进行中”沿用进行中项目的全量在办口径,与所选完结月份无关。
where: buildMonthlyLaunchOngoingWorkflowWhere(),
select: MONTHLY_LAUNCH_WORKFLOW_SELECT,
}),
@ -2240,17 +2374,24 @@ async function readMonthlyLaunchInsightsWithoutAccessCheck(now = new Date()): Pr
lastSyncedAt: state?.lastCompletedAt?.toISOString() || null,
syncStatus: normalizeSyncStatus(state),
},
availableMonths: getMonthlyLaunchMonthOptions(now),
}
}
export async function getMonthlyLaunchSummary(session: Session | null): Promise<MonthlyLaunchSummary> {
export async function getMonthlyLaunchSummary(
session: Session | null,
input: MonthlyLaunchRangeInput = {},
): Promise<MonthlyLaunchSummary> {
await assertDashboardAccess(session)
return (await readMonthlyLaunchInsightsWithoutAccessCheck()).summary
return (await readMonthlyLaunchInsightsWithoutAccessCheck(input)).summary
}
export async function getMonthlyLaunchInsights(session: Session | null): Promise<MonthlyLaunchInsights> {
export async function getMonthlyLaunchInsights(
session: Session | null,
input: MonthlyLaunchRangeInput = {},
): Promise<MonthlyLaunchInsights> {
await assertDashboardAccess(session)
return readMonthlyLaunchInsightsWithoutAccessCheck()
return readMonthlyLaunchInsightsWithoutAccessCheck(input)
}
async function readOnTimeDeliveryInsightsWithoutAccessCheck(now = new Date()): Promise<OnTimeDeliveryInsights> {