feat(core): 完成 Phase 2 核心功能开发

- 实现查询API (query.py): 支持star_id/unique_id/nickname三种查询方式
- 实现计算模块 (calculator.py): CPM/自然搜索UV/搜索成本计算
- 实现品牌API集成 (brand_api.py): 批量并发调用,10并发限制
- 实现导出服务 (export_service.py): Excel/CSV导出
- 前端组件: QueryForm/ResultTable/ExportButton
- 主页面集成: 支持6种页面状态
- 测试: 44个测试全部通过,覆盖率88%

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
zfc
2026-01-28 14:38:38 +08:00
co-authored by Claude Opus 4.5
parent ac0f086821
commit 8fbcb72a3f
21 changed files with 1677 additions and 100 deletions
+105 -95
View File
@@ -1,101 +1,111 @@
import Image from "next/image";
'use client';
import { useState } from 'react';
import { QueryForm, ResultTable, ExportButton } from '@/components';
import { QueryType, VideoData, PageState } from '@/types';
import { queryVideos } from '@/lib/api';
export default function Home() {
return (
<div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
<main className="flex flex-col gap-8 row-start-2 items-center sm:items-start">
<Image
className="dark:invert"
src="https://nextjs.org/icons/next.svg"
alt="Next.js logo"
width={180}
height={38}
priority
/>
<ol className="list-inside list-decimal text-sm text-center sm:text-left font-[family-name:var(--font-geist-mono)]">
<li className="mb-2">
Get started by editing{" "}
<code className="bg-black/[.05] dark:bg-white/[.06] px-1 py-0.5 rounded font-semibold">
src/app/page.tsx
</code>
.
</li>
<li>Save and see your changes instantly.</li>
</ol>
const [pageState, setPageState] = useState<PageState>('default');
const [data, setData] = useState<VideoData[]>([]);
const [total, setTotal] = useState(0);
const [error, setError] = useState<string | null>(null);
<div className="flex gap-4 items-center flex-col sm:flex-row">
<a
className="rounded-full border border-solid border-transparent transition-colors flex items-center justify-center bg-foreground text-background gap-2 hover:bg-[#383838] dark:hover:bg-[#ccc] text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5"
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
className="dark:invert"
src="https://nextjs.org/icons/vercel.svg"
alt="Vercel logomark"
width={20}
height={20}
/>
Deploy now
</a>
<a
className="rounded-full border border-solid border-black/[.08] dark:border-white/[.145] transition-colors flex items-center justify-center hover:bg-[#f2f2f2] dark:hover:bg-[#1a1a1a] hover:border-transparent text-sm sm:text-base h-10 sm:h-12 px-4 sm:px-5 sm:min-w-44"
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Read our docs
</a>
</div>
</main>
<footer className="row-start-3 flex gap-6 flex-wrap items-center justify-center">
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="https://nextjs.org/icons/file.svg"
alt="File icon"
width={16}
height={16}
/>
Learn
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="https://nextjs.org/icons/window.svg"
alt="Window icon"
width={16}
height={16}
/>
Examples
</a>
<a
className="flex items-center gap-2 hover:underline hover:underline-offset-4"
href="https://nextjs.org?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
<Image
aria-hidden
src="https://nextjs.org/icons/globe.svg"
alt="Globe icon"
width={16}
height={16}
/>
Go to nextjs.org
</a>
</footer>
const handleQuery = async (type: QueryType, values: string[]) => {
setPageState('loading');
setError(null);
try {
const response = await queryVideos({ type, values });
if (response.success) {
setData(response.data);
setTotal(response.total);
setPageState(response.total > 0 ? 'result' : 'empty');
} else {
setError(response.error || '查询失败');
setPageState('error');
}
} catch (err) {
console.error('Query error:', err);
setError(err instanceof Error ? err.message : '网络错误,请检查后端服务是否正常');
setPageState('error');
}
};
const handleRetry = () => {
setPageState('default');
setError(null);
setData([]);
setTotal(0);
};
return (
<div className="max-w-7xl mx-auto px-4 py-8">
{/* 查询区域 */}
<section className="mb-8">
<QueryForm onSubmit={handleQuery} isLoading={pageState === 'loading'} />
</section>
{/* 结果区域 */}
<section>
{/* 默认态 */}
{pageState === 'default' && (
<div className="bg-white rounded-lg shadow-sm p-12 text-center">
<div className="text-gray-400 text-6xl mb-4">🔍</div>
<p className="text-gray-500"></p>
</div>
)}
{/* 加载态 */}
{pageState === 'loading' && (
<div className="bg-white rounded-lg shadow-sm p-12 text-center">
<div className="animate-spin text-primary text-4xl mb-4"></div>
<p className="text-gray-500">...</p>
</div>
)}
{/* 结果态 */}
{pageState === 'result' && (
<div>
<div className="flex justify-between items-center mb-4">
<h2 className="text-lg font-medium text-gray-900"></h2>
<ExportButton hasData={total > 0} />
</div>
<ResultTable data={data} total={total} />
</div>
)}
{/* 空结果态 */}
{pageState === 'empty' && (
<div className="bg-white rounded-lg shadow-sm p-12 text-center">
<div className="text-gray-400 text-6xl mb-4">📦</div>
<p className="text-gray-700 mb-2"></p>
<p className="text-gray-500 text-sm mb-4"></p>
<button
onClick={handleRetry}
className="px-4 py-2 text-sm font-medium text-primary border border-primary rounded hover:bg-primary hover:text-white"
>
</button>
</div>
)}
{/* 错误态 */}
{pageState === 'error' && (
<div className="bg-white rounded-lg shadow-sm p-12 text-center">
<div className="text-error text-6xl mb-4"></div>
<p className="text-gray-700 mb-2"></p>
<p className="text-gray-500 text-sm mb-4">{error || '可能原因:网络异常或数据库连接失败'}</p>
<button
onClick={handleRetry}
className="px-4 py-2 text-sm font-medium text-white bg-primary rounded hover:bg-primary-dark"
>
</button>
</div>
)}
</section>
</div>
);
}
+63
View File
@@ -0,0 +1,63 @@
'use client';
import { useState } from 'react';
interface ExportButtonProps {
hasData: boolean;
}
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000/api/v1';
export default function ExportButton({ hasData }: ExportButtonProps) {
const [isExporting, setIsExporting] = useState(false);
const handleExport = async (format: 'xlsx' | 'csv') => {
if (!hasData) {
alert('无数据可导出');
return;
}
setIsExporting(true);
try {
const response = await fetch(`${API_BASE_URL}/export?format=${format}`);
if (!response.ok) {
throw new Error('导出失败');
}
const blob = await response.blob();
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `kol_data_${new Date().toISOString().slice(0, 10)}.${format}`;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
} catch (error) {
console.error('Export error:', error);
alert('导出失败,请重试');
} finally {
setIsExporting(false);
}
};
return (
<div className="flex gap-2">
<button
onClick={() => handleExport('xlsx')}
disabled={!hasData || isExporting}
className="px-3 py-1.5 text-sm font-medium text-white bg-success rounded hover:bg-green-600 disabled:opacity-50 disabled:cursor-not-allowed"
>
{isExporting ? '导出中...' : '导出 Excel'}
</button>
<button
onClick={() => handleExport('csv')}
disabled={!hasData || isExporting}
className="px-3 py-1.5 text-sm font-medium text-white bg-success rounded hover:bg-green-600 disabled:opacity-50 disabled:cursor-not-allowed"
>
{isExporting ? '导出中...' : '导出 CSV'}
</button>
</div>
);
}
+81
View File
@@ -0,0 +1,81 @@
'use client';
import { useState } from 'react';
import { QueryType, QUERY_TYPE_OPTIONS, QUERY_PLACEHOLDER } from '@/types';
interface QueryFormProps {
onSubmit: (type: QueryType, values: string[]) => void;
isLoading: boolean;
}
export default function QueryForm({ onSubmit, isLoading }: QueryFormProps) {
const [queryType, setQueryType] = useState<QueryType>('star_id');
const [inputValue, setInputValue] = useState('');
const handleSubmit = () => {
const values = inputValue
.split('\n')
.map((line) => line.trim())
.filter((line) => line.length > 0);
if (values.length === 0) {
return;
}
onSubmit(queryType, values);
};
const handleClear = () => {
setInputValue('');
};
return (
<div className="bg-white rounded-lg shadow-sm p-6">
<div className="mb-4">
<label className="block text-sm font-medium text-gray-700 mb-2"></label>
<div className="flex gap-4">
{QUERY_TYPE_OPTIONS.map((option) => (
<label key={option.value} className="flex items-center cursor-pointer">
<input
type="radio"
name="queryType"
value={option.value}
checked={queryType === option.value}
onChange={(e) => setQueryType(e.target.value as QueryType)}
className="w-4 h-4 text-primary border-gray-300 focus:ring-primary"
/>
<span className="ml-2 text-sm text-gray-700">{option.label}</span>
</label>
))}
</div>
</div>
<div className="mb-4">
<textarea
value={inputValue}
onChange={(e) => setInputValue(e.target.value)}
placeholder={QUERY_PLACEHOLDER[queryType]}
className="w-full h-32 px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent resize-none"
disabled={isLoading}
/>
</div>
<div className="flex justify-end gap-2">
<button
onClick={handleClear}
disabled={isLoading || !inputValue}
className="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-md hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
>
</button>
<button
onClick={handleSubmit}
disabled={isLoading || !inputValue.trim()}
className="px-4 py-2 text-sm font-medium text-white bg-primary rounded-md hover:bg-primary-dark disabled:opacity-50 disabled:cursor-not-allowed"
>
{isLoading ? '查询中...' : '开始查询'}
</button>
</div>
</div>
);
}
+195
View File
@@ -0,0 +1,195 @@
'use client';
import { useState } from 'react';
import { VideoData } from '@/types';
import { formatNumber, formatLargeNumber, formatPercent, formatCurrency, formatDate } from '@/lib/utils';
interface ResultTableProps {
data: VideoData[];
total: number;
}
// 表格列定义
const columns = [
{ key: 'item_id', label: '视频ID', width: 120 },
{ key: 'title', label: '视频标题', width: 200 },
{ key: 'viral_type', label: '爆文类型', width: 100 },
{ key: 'video_url', label: '视频链接', width: 100 },
{ key: 'star_nickname', label: '达人昵称', width: 120 },
{ key: 'star_unique_id', label: '达人unique_id', width: 150 },
{ key: 'natural_play_cnt', label: '自然曝光数', width: 120 },
{ key: 'heated_play_cnt', label: '加热曝光数', width: 120 },
{ key: 'total_play_cnt', label: '总曝光数', width: 120 },
{ key: 'total_interact', label: '总互动', width: 100 },
{ key: 'like_cnt', label: '点赞', width: 100 },
{ key: 'share_cnt', label: '转发', width: 100 },
{ key: 'comment_cnt', label: '评论', width: 100 },
{ key: 'new_a3_rate', label: '新增A3率', width: 100 },
{ key: 'after_view_search_uv', label: '看后搜人数', width: 120 },
{ key: 'return_search_cnt', label: '回搜次数', width: 100 },
{ key: 'industry_name', label: '合作行业', width: 120 },
{ key: 'brand_name', label: '合作品牌', width: 150 },
{ key: 'publish_time', label: '发布时间', width: 120 },
{ key: 'estimated_video_cost', label: '预估视频价格', width: 120 },
{ key: 'estimated_natural_cpm', label: '预估自然CPM', width: 120 },
{ key: 'estimated_natural_search_uv', label: '预估自然看后搜人数', width: 150 },
{ key: 'estimated_natural_search_cost', label: '预估看后搜成本', width: 150 },
];
const PAGE_SIZE = 20;
export default function ResultTable({ data, total }: ResultTableProps) {
const [currentPage, setCurrentPage] = useState(1);
const [sortKey, setSortKey] = useState<string | null>(null);
const [sortOrder, setSortOrder] = useState<'asc' | 'desc'>('desc');
// 排序
const sortedData = [...data].sort((a, b) => {
if (!sortKey) return 0;
const aVal = a[sortKey as keyof VideoData];
const bVal = b[sortKey as keyof VideoData];
if (aVal === null || aVal === undefined) return 1;
if (bVal === null || bVal === undefined) return -1;
if (typeof aVal === 'number' && typeof bVal === 'number') {
return sortOrder === 'asc' ? aVal - bVal : bVal - aVal;
}
return sortOrder === 'asc'
? String(aVal).localeCompare(String(bVal))
: String(bVal).localeCompare(String(aVal));
});
// 分页
const totalPages = Math.ceil(sortedData.length / PAGE_SIZE);
const paginatedData = sortedData.slice(
(currentPage - 1) * PAGE_SIZE,
currentPage * PAGE_SIZE
);
const handleSort = (key: string) => {
if (sortKey === key) {
setSortOrder(sortOrder === 'asc' ? 'desc' : 'asc');
} else {
setSortKey(key);
setSortOrder('desc');
}
};
const renderCell = (row: VideoData, key: string) => {
const value = row[key as keyof VideoData];
switch (key) {
case 'video_url':
return value ? (
<a
href={value as string}
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline"
>
</a>
) : (
'-'
);
case 'natural_play_cnt':
case 'heated_play_cnt':
case 'total_play_cnt':
return formatLargeNumber(value as number);
case 'total_interact':
case 'like_cnt':
case 'share_cnt':
case 'comment_cnt':
case 'after_view_search_uv':
case 'return_search_cnt':
return formatNumber(value as number);
case 'new_a3_rate':
return formatPercent(value as number);
case 'estimated_video_cost':
case 'estimated_natural_search_cost':
return formatCurrency(value as number);
case 'estimated_natural_cpm':
case 'estimated_natural_search_uv':
return value !== null && value !== undefined ? (value as number).toFixed(2) : '-';
case 'publish_time':
return formatDate(value as string);
case 'title':
const title = value as string;
return title && title.length > 20 ? (
<span title={title}>{title.slice(0, 20)}...</span>
) : (
title || '-'
);
default:
return value !== null && value !== undefined ? String(value) : '-';
}
};
return (
<div className="bg-white rounded-lg shadow-sm">
<div className="p-4 border-b border-gray-200 flex justify-between items-center">
<span className="text-sm text-gray-600"> ( {total} )</span>
</div>
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
{columns.map((col) => (
<th
key={col.key}
onClick={() => handleSort(col.key)}
className="px-3 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider cursor-pointer hover:bg-gray-100"
style={{ minWidth: col.width }}
>
<div className="flex items-center gap-1">
{col.label}
{sortKey === col.key && (
<span>{sortOrder === 'asc' ? '↑' : '↓'}</span>
)}
</div>
</th>
))}
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{paginatedData.map((row, idx) => (
<tr key={row.item_id} className={idx % 2 === 0 ? 'bg-white' : 'bg-gray-50'}>
{columns.map((col) => (
<td
key={col.key}
className="px-3 py-2 text-sm text-gray-900 whitespace-nowrap"
>
{renderCell(row, col.key)}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
{/* 分页 */}
{totalPages > 1 && (
<div className="px-4 py-3 border-t border-gray-200 flex justify-center items-center gap-2">
<button
onClick={() => setCurrentPage((p) => Math.max(1, p - 1))}
disabled={currentPage === 1}
className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
>
</button>
<span className="text-sm text-gray-600">
{currentPage} / {totalPages}
</span>
<button
onClick={() => setCurrentPage((p) => Math.min(totalPages, p + 1))}
disabled={currentPage === totalPages}
className="px-3 py-1 text-sm border border-gray-300 rounded hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed"
>
</button>
</div>
)}
</div>
);
}
+3
View File
@@ -1,2 +1,5 @@
export { default as Header } from './Header';
export { default as Footer } from './Footer';
export { default as QueryForm } from './QueryForm';
export { default as ResultTable } from './ResultTable';
export { default as ExportButton } from './ExportButton';
+29
View File
@@ -0,0 +1,29 @@
import { QueryRequest, QueryResponse } from '@/types';
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000/api/v1';
export async function queryVideos(request: QueryRequest): Promise<QueryResponse> {
const response = await fetch(`${API_BASE_URL}/query`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(request),
});
if (!response.ok) {
throw new Error(`查询失败: ${response.statusText}`);
}
return response.json();
}
export async function exportData(format: 'xlsx' | 'csv'): Promise<Blob> {
const response = await fetch(`${API_BASE_URL}/export?format=${format}`);
if (!response.ok) {
throw new Error(`导出失败: ${response.statusText}`);
}
return response.blob();
}
+70
View File
@@ -0,0 +1,70 @@
/**
* 格式化数字为千分位分隔
*/
export function formatNumber(num: number | null | undefined): string {
if (num === null || num === undefined) {
return '-';
}
return num.toLocaleString('zh-CN');
}
/**
* 格式化大数值 (K/M 缩写)
*/
export function formatLargeNumber(num: number | null | undefined): string {
if (num === null || num === undefined) {
return '-';
}
if (num >= 1000000) {
return `${(num / 1000000).toFixed(1)}M`;
}
if (num >= 1000) {
return `${(num / 1000).toFixed(1)}K`;
}
return num.toString();
}
/**
* 格式化百分比
*/
export function formatPercent(num: number | null | undefined): string {
if (num === null || num === undefined) {
return '-';
}
return `${(num * 100).toFixed(2)}%`;
}
/**
* 格式化金额
*/
export function formatCurrency(num: number | null | undefined): string {
if (num === null || num === undefined) {
return '-';
}
return `¥${num.toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
}
/**
* 格式化日期
*/
export function formatDate(dateStr: string | null | undefined): string {
if (!dateStr) {
return '-';
}
const date = new Date(dateStr);
return date.toLocaleDateString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
});
}
/**
* 解析输入文本为数组 (按换行分隔)
*/
export function parseInputToArray(input: string): string[] {
return input
.split('\n')
.map((line) => line.trim())
.filter((line) => line.length > 0);
}
+63
View File
@@ -0,0 +1,63 @@
// 查询类型
export type QueryType = 'star_id' | 'unique_id' | 'nickname';
// 查询请求
export interface QueryRequest {
type: QueryType;
values: string[];
}
// 视频数据
export interface VideoData {
item_id: string;
title: string | null;
viral_type: string | null;
video_url: string | null;
star_id: string;
star_unique_id: string;
star_nickname: string;
publish_time: string | null;
natural_play_cnt: number;
heated_play_cnt: number;
total_play_cnt: number;
total_interact: number;
like_cnt: number;
share_cnt: number;
comment_cnt: number;
new_a3_rate: number | null;
after_view_search_uv: number;
return_search_cnt: number;
industry_id: string | null;
industry_name: string | null;
brand_id: string | null;
brand_name: string | null;
estimated_video_cost: number;
estimated_natural_cpm: number | null;
estimated_natural_search_uv: number | null;
estimated_natural_search_cost: number | null;
}
// 查询响应
export interface QueryResponse {
success: boolean;
data: VideoData[];
total: number;
error?: string;
}
// 页面状态
export type PageState = 'default' | 'input' | 'loading' | 'result' | 'empty' | 'error';
// 查询方式选项
export const QUERY_TYPE_OPTIONS = [
{ value: 'star_id' as QueryType, label: '星图ID' },
{ value: 'unique_id' as QueryType, label: '达人unique_id' },
{ value: 'nickname' as QueryType, label: '达人昵称' },
];
// 查询方式对应的提示文本
export const QUERY_PLACEHOLDER: Record<QueryType, string> = {
star_id: '请输入星图ID,每行一个...',
unique_id: '请输入达人unique_id,每行一个...',
nickname: '请输入达人昵称关键词...',
};