'use client'
import Select from '@/components/ui/Select'
import Link from 'next/link'
import { useCallback, useEffect, useState } from 'react'
import {
AlertTriangle,
ArrowLeft,
Database,
RefreshCw,
} from 'lucide-react'
import DepartmentShell from './DepartmentShell'
import {
PERFORMANCE_CONVERSION_METRICS,
buildIntentRateWindowSummary,
type PerformanceConversionDailyMetric,
type PerformanceConversionMetricKey,
type PerformanceConversionTimeseries,
} from './performance-conversion'
type DetailState = {
data: PerformanceConversionTimeseries | null
loading: boolean
error: string | null
}
function formatDate(value: string | null, includeTime = false) {
if (!value) return '—'
const date = /^\d{4}-\d{2}-\d{2}$/.test(value) ? new Date(`${value}T00:00:00+08:00`) : new Date(value)
if (Number.isNaN(date.getTime())) return '—'
return new Intl.DateTimeFormat('zh-CN', {
timeZone: 'Asia/Shanghai',
year: 'numeric',
month: '2-digit',
day: '2-digit',
...(includeTime ? { hour: '2-digit', minute: '2-digit', hour12: false } : {}),
}).format(date)
}
function formatMetric(value: number | null, format: string) {
if (value === null || !Number.isFinite(value)) return '—'
if (format === 'percent') return `${(value * 100).toFixed(2)}%`
if (format === 'currency') {
return new Intl.NumberFormat('zh-CN', {
style: 'currency',
currency: 'CNY',
maximumFractionDigits: 2,
}).format(value)
}
if (format === 'decimal') return value.toFixed(2)
return new Intl.NumberFormat('zh-CN', { maximumFractionDigits: 0 }).format(value)
}
function metricDefinition(key: PerformanceConversionMetricKey) {
return PERFORMANCE_CONVERSION_METRICS.find((metric) => metric.key === key) || PERFORMANCE_CONVERSION_METRICS[0]
}
function TrendChart({ daily, metricKey }: {
daily: PerformanceConversionDailyMetric[]
metricKey: PerformanceConversionMetricKey
}) {
const definition = metricDefinition(metricKey)
const width = 900
const height = 240
const plot = { left: 24, right: 876, top: 18, bottom: 194 }
const values = daily.map((day) => day[metricKey])
const present = values.filter((value): value is number => value !== null && Number.isFinite(value))
const min = present.length ? Math.min(...present) : 0
const max = present.length ? Math.max(...present) : 0
const range = max - min || Math.max(Math.abs(max), 1)
const x = (index: number) => plot.left + (daily.length <= 1 ? 0 : index / (daily.length - 1)) * (plot.right - plot.left)
const y = (value: number) => plot.bottom - ((value - min) / range) * (plot.bottom - plot.top)
const segments: string[] = []
let current: string[] = []
values.forEach((value, index) => {
if (value === null || !Number.isFinite(value)) {
if (current.length) segments.push(current.join(' '))
current = []
return
}
current.push(`${current.length ? 'L' : 'M'} ${x(index).toFixed(2)} ${y(value).toFixed(2)}`)
})
if (current.length) segments.push(current.join(' '))
const middleIndex = Math.max(0, Math.floor((daily.length - 1) / 2))
if (!present.length) {
return (
监控区间内暂无{definition.label}数据
)
}
return (
缺失日期保持断点,准确数值见下方每日明细表。
)
}
function MetricSummary({ data }: { data: PerformanceConversionTimeseries }) {
const groups = ['流量', '兴趣', '成交'] as const
return (
{groups.map((group) => (
{group}
{PERFORMANCE_CONVERSION_METRICS.filter((metric) => metric.group === group).map((metric) => (
- {metric.label}
-
{formatMetric(data.latest?.[metric.key] ?? null, metric.format)}
))}
))}
)
}
function IntentRateSummary({ daily }: { daily: PerformanceConversionDailyMetric[] }) {
const summary = buildIntentRateWindowSummary(daily)
const formatWindowValue = (value: number | null) => value === null ? '——' : `${(value * 100).toFixed(2)}%`
return (
- 完结后7日意向率平均
- {formatWindowValue(summary.sevenDayIntentRate)}
- 完结后15日意向率平均
- {formatWindowValue(summary.fifteenDayIntentRate)}
- 意向率环比(15日 / 7日)
- {formatWindowValue(summary.intentRateChange)}
意向率 = (收藏人数 + 加购人数)÷ 商品访客数 × 100% + 支付转化率
)
}
function DetailContent({ data }: { data: PerformanceConversionTimeseries }) {
const [metricKey, setMetricKey] = useState('paymentAmount')
const [detailGroup, setDetailGroup] = useState<'流量' | '兴趣' | '成交'>('流量')
const visibleMetrics = PERFORMANCE_CONVERSION_METRICS.filter((metric) => metric.group === detailGroup)
const hasDailyData = data.daily.some((day) => PERFORMANCE_CONVERSION_METRICS.some((metric) => day[metric.key] !== null))
return (
商品 ID {data.product.id}
{data.product.name || '未匹配到天猫经营数据'}
{data.product.category || '暂无类目信息'}
{data.product.sourceBrand ? ` · 数据品牌 ${data.product.sourceBrand}` : ''}
- 审批编号
- 审批编号 {data.workflow.approvalNumber || '—'}
- 流程完结
- 流程完结 {formatDate(data.workflow.completedAt, true)}
- 经营数据更新
- 经营数据更新至 {formatDate(data.coverage.sourceLatestDate)}
{data.product.brandMatchesWorkflow === false && (
流程品牌与经营数据品牌不一致,请核对商品 ID。
)}
{!hasDailyData ? (
该商品在流程完结后的监控区间内暂无经营数据
监控区间 {data.coverage.monitorStartDate} 至 {data.coverage.monitorEndDate}
) : (
<>
每日趋势
已有 {data.coverage.coveredDays} 天 / 应有 {data.coverage.expectedDaysToDate} 天,缺失日期保留断点
{(['流量', '兴趣', '成交'] as const).map((group) => (
))}
| 日期 |
{visibleMetrics.map((metric) => {metric.label} | )}
{[...data.daily].reverse().map((day) => (
| {day.date} |
{visibleMetrics.map((metric) => (
{formatMetric(day[metric.key], metric.format)}
|
))}
))}
>
)}
)
}
export default function PerformanceConversionDetail({
workflowId,
productId,
returnHref,
}: {
workflowId: string
productId: string
returnHref: string
}) {
const [state, setState] = useState({ data: null, loading: true, error: null })
const loadDetail = useCallback(async (signal?: AbortSignal) => {
if (!workflowId || !productId) {
setState({ data: null, loading: false, error: '详情链接缺少流程实例或商品 ID' })
return
}
setState({ data: null, loading: true, error: null })
try {
const params = new URLSearchParams({ workflowId, productId })
const response = await fetch(`/api/department-dashboard/performance-conversion/timeseries?${params}`, {
cache: 'no-store',
signal,
})
const payload = await response.json().catch(() => null)
if (!response.ok || !payload?.success || !payload.data) {
throw new Error(payload?.error || '商品经营数据读取失败')
}
setState({ data: payload.data, loading: false, error: null })
} catch (error) {
if ((error as Error).name === 'AbortError') return
setState({ data: null, loading: false, error: (error as Error).message || '商品经营数据读取失败' })
}
}, [productId, workflowId])
useEffect(() => {
const controller = new AbortController()
void loadDetail(controller.signal)
return () => controller.abort()
}, [loadDetail])
return (
返回业绩转化
流程实例 {workflowId || '—'}
{state.loading ? (
) : state.error || !state.data ? (
无法打开商品数据
{state.error || '商品经营数据读取失败'}
) : (
)}
)
}