阶段七:完成Dashboard React feature化与统计查询边界

This commit is contained in:
Christ committed 2026-08-15 01:35:47 +08:00
1 parent 2ec7bec05f
commit 56b20507f3
17 files changed
+1208 -776

No files matched your search

File diff suppressed because it is too large. Load diff
+3 -1
View File
@@ -175,7 +175,8 @@ app shell / routes
- 已完成阶段 7 第四个 PR 切片“React CardList feature 化与卡密库存/批量追加行为边界”:按 `app/features/cards` 提取卡密 API 适配层、库存数据 Hook、批量导入/追加状态 Hook 和弹窗组件;卡密筛选、追加预览、提交取消、失败重试与账号切换过期响应均由 feature 状态边界负责,保留旧组件入口和 API 路径;新增状态模型测试并通过前端类型检查、全量测试、注释检查和构建门禁,合并为一个可回滚提交;
- 已完成阶段 7 第五个 PR 切片“React OrderList feature 化与订单导入/刷新行为边界”:按 `app/features/orders` 提取订单 API 适配层、查询/分页 Hook、导入 Hook、筛选栏和导入弹窗;订单查询与辅助数据支持并行加载、取消和代次门禁,导入支持文件预检、取消、失败重试和导入后刷新;新增筛选、导入归一化、API 取消信号和过期响应测试,保留旧组件入口和 API 路径;前端类型检查、全量测试、注释检查和构建门禁通过,合并为一个可回滚提交;
- 已完成阶段 7 第六个 PR 切片“React Notifications feature 化与渠道/事件绑定行为边界”:按 `app/features/notifications` 提取通知渠道/SMTP API 适配层、静态渠道配置、数据与动作 Hook、渠道列表、事件绑定选择器、渠道编辑弹窗和 SMTP 面板;渠道与 SMTP 请求支持取消和代次门禁,表单支持渠道字段/独立 SMTP 校验、保存失败重试和过期响应保护;更新架构字符串测试并新增状态/API 取消信号测试,保留旧页面入口和 API 路径;前端类型检查、全量测试、注释检查和构建门禁通过,合并为一个可回滚提交;
- 阶段 7 下一 PR 切片为“React Dashboard feature 化与统计/趋势查询行为边界”:提取 Dashboard API、统计数据 Hook 和趋势图表组件,补充并行查询、刷新取消、失败重试和过期响应测试;
- 已完成阶段 7 第七个 PR 切片“React Dashboard feature 化与统计/趋势查询行为边界”:按 `app/features/dashboard` 提取 Dashboard API 适配层、统计数据 Hook、趋势/排行派生状态和请求边界;概览、趋势和有效订单支持并行加载、刷新取消、失败重试与过期响应保护;新增统计派生数据、API 取消信号和请求代次测试,保留旧页面入口和 API 路径;前端类型检查、全量测试、注释检查和构建门禁通过并合并为一个可回滚提交;
- 阶段 7 下一 PR 切片为“React Settings feature 化与系统配置校验边界”:提取设置 API、配置表单状态和敏感字段校验,补充保存取消、失败重试和过期响应测试;
- 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。
## 6. 阶段 0:治理文档与强约束
@@ -600,3 +601,4 @@ npm --prefix frontend run build
| 2026-08-15 | 完成阶段 7 第四个 PR 切片“React CardList feature 化与卡密库存/批量追加行为边界” | 按 `app/features/cards` 提取卡密 API 适配层、库存数据 Hook、批量导入/追加状态 Hook 和弹窗组件;卡密筛选、追加预览、提交取消、失败重试与账号切换过期响应均由 feature 状态边界负责,保留旧组件入口和 API 路径;新增状态模型测试并通过前端类型检查、全量测试、注释检查和构建门禁,合并为一个可回滚提交 | 阶段 7:React OrderList feature 化与订单导入/刷新行为边界 |
| 2026-08-15 | 完成阶段 7 第五个 PR 切片“React OrderList feature 化与订单导入/刷新行为边界” | 按 `app/features/orders` 提取订单 API 适配层、查询/分页 Hook、导入 Hook、筛选栏和导入弹窗;订单查询与辅助数据支持并行加载、取消和代次门禁,导入支持文件预检、取消、失败重试和导入后刷新;新增筛选、导入归一化、API 取消信号和过期响应测试,保留旧组件入口和 API 路径;前端类型检查、全量测试、注释检查和构建门禁通过并合并为一个可回滚提交 | 阶段 7:React Notifications feature 化与渠道/事件绑定行为边界 |
| 2026-08-15 | 完成阶段 7 第六个 PR 切片“React Notifications feature 化与渠道/事件绑定行为边界” | 按 `app/features/notifications` 提取通知渠道/SMTP API 适配层、静态渠道配置、数据与动作 Hook、渠道列表、事件绑定选择器、渠道编辑弹窗和 SMTP 面板;渠道与 SMTP 请求支持取消和代次门禁,表单支持渠道字段/独立 SMTP 校验、保存失败重试和过期响应保护;更新架构字符串测试并新增状态/API 取消信号测试,保留旧页面入口和 API 路径;前端类型检查、全量测试、注释检查和构建门禁通过并合并为一个可回滚提交 | 阶段 7:React Dashboard feature 化与统计/趋势查询行为边界 |
| 2026-08-15 | 完成阶段 7 第七个 PR 切片“React Dashboard feature 化与统计/趋势查询行为边界” | 按 `app/features/dashboard` 提取 Dashboard API 适配层、统计数据 Hook、趋势/排行派生状态和请求边界;概览、趋势和有效订单支持并行加载、刷新取消、失败重试与过期响应保护;新增统计派生数据、API 取消信号和请求代次测试,保留旧页面入口和 API 路径;前端类型检查、全量测试、注释检查和构建门禁通过并合并为一个可回滚提交 | 阶段 7:React Settings feature 化与系统配置校验边界 |
@@ -0,0 +1,86 @@
import React from 'react';
import { ShoppingCart } from 'lucide-react';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar, Cell } from 'recharts';
import type { DashboardChartPoint } from './state';
/** 趋势图组件的输入参数。 */
export type DashboardTrendChartProps = {
/** 趋势图的日期与营收数据点。 */
chartData: DashboardChartPoint[];
/** 当前选择范围的中文名称。 */
selectedRangeLabel: string;
/** 当前范围的营收总额。 */
totalAmount: number;
};
/** 读取设计系统颜色变量。 */
const cssColor = (token: string, alpha?: number): string => (
alpha === undefined ? `rgb(var(--color-${token}))` : `rgb(var(--color-${token}) / ${alpha})`
);
/** 展示 Dashboard 营收趋势,并根据数据点数量选择柱状图或面积图。 */
export const DashboardTrendChart: React.FC<DashboardTrendChartProps> = ({ chartData, selectedRangeLabel, totalAmount }) => (
<div className="ios-card p-8 rounded-xl">
<div className="mb-10">
<h3 className="text-xl font-bold text-gray-900">营收趋势分析</h3>
<p className="text-sm text-gray-400 mt-1">{selectedRangeLabel}的销售额走势</p>
</div>
<div className="dashboard-revenue-chart h-[350px] w-full">
{chartData.length === 0 || totalAmount === 0 ? (
<div className="h-full flex flex-col items-center justify-center text-gray-400">
<ShoppingCart className="w-16 h-16 mb-4 opacity-20" />
<p className="text-lg font-medium">暂无营收数据</p>
<p className="text-sm mt-2">所选时间范围内暂无订单记录</p>
</div>
) : chartData.length <= 2 ? (
// 数据点少于等于2个时使用美化柱状图。
<ResponsiveContainer width="100%" height="100%">
<BarChart data={chartData} margin={{ top: 30, right: 20, left: 0, bottom: 30 }} barCategoryGap="45%">
<XAxis dataKey="name" axisLine={false} tickLine={false} tick={{ fill: cssColor('neutral-700'), fontSize: 14, fontWeight: 600 }} dy={10} />
<YAxis axisLine={false} tickLine={false} tick={{ fill: cssColor('neutral-400'), fontSize: 13, fontWeight: 500 }} tickFormatter={
// value 是纵轴刻度的原始金额。
value => `¥${value}`
} />
<Tooltip
contentStyle={{ backgroundColor: cssColor('white'), borderRadius: '8px', border: `1px solid ${cssColor('neutral-200')}`, boxShadow: 'var(--shadow-xl)', padding: '12px 16px' }}
labelStyle={{ color: cssColor('neutral-500'), fontWeight: 500 }}
itemStyle={{ color: cssColor('brand'), fontWeight: 600 }}
cursor={{ fill: cssColor('brand', 0.08) }}
formatter={
// value 是提示框当前数据点的原始金额。
value => [`¥${Number(value).toFixed(2)}`, '营收']
}
/>
<Bar dataKey="amount" fill={cssColor('brand')} maxBarSize={72} radius={[12, 12, 0, 0]} activeBar={false} stroke="none" strokeWidth={0}>
{chartData.map(
// index 用于生成稳定的图表扇区键。
(_, index) => <Cell key={`cell-${index}`} fill={cssColor('brand')} stroke="none" strokeWidth={0} />,
)}
</Bar>
</BarChart>
</ResponsiveContainer>
) : (
// 数据点多于2个时使用面积图。
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={chartData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
<defs>
<linearGradient id="colorAmount" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor={cssColor('brand')} stopOpacity={0.5} />
<stop offset="95%" stopColor={cssColor('brand')} stopOpacity={0} />
</linearGradient>
</defs>
<XAxis dataKey="name" axisLine={false} tickLine={false} tick={{ fill: cssColor('neutral-400'), fontSize: 13, fontWeight: 500 }} dy={15} />
<YAxis axisLine={false} tickLine={false} tick={{ fill: cssColor('neutral-400'), fontSize: 13, fontWeight: 500 }} />
<CartesianGrid vertical={false} stroke={cssColor('neutral-100')} strokeDasharray="3 3" />
<Tooltip
contentStyle={{ backgroundColor: cssColor('white'), borderRadius: '8px', border: `1px solid ${cssColor('neutral-200')}`, boxShadow: 'var(--shadow-xl)', padding: '12px 16px' }}
labelStyle={{ color: cssColor('neutral-500'), fontWeight: 500 }}
itemStyle={{ color: cssColor('brand'), fontWeight: 600 }}
cursor={{ stroke: cssColor('brand'), strokeWidth: 2, strokeDasharray: '4 4' }}
/>
<Area type="monotone" dataKey="amount" stroke={cssColor('brand')} strokeWidth={4} fillOpacity={1} fill="url(#colorAmount)" activeDot={{ r: 8, fill: cssColor('white'), stroke: cssColor('brand'), strokeWidth: 2 }} />
</AreaChart>
</ResponsiveContainer>
)}
</div>
</div>
);
+2
View File
@@ -0,0 +1,2 @@
/** Dashboard 数据接口集中导出,避免页面组件直接依赖通用 API 模块。 */
export { getDashboardStats, getItems, getOrderAnalytics, getValidOrders } from '../../../services/api';
+125
View File
@@ -0,0 +1,125 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { getDateRange, getPreviousDateRange } from '../../../dateRange';
import type { TimeRange } from '../../../dateRange';
import { buildCategoryData, buildChartData, buildItemNameMap, buildProductSalesData, buildSourceData, getMaxProductSales, getRangeLabel, getTrendPercent, isCurrentDashboardRequest } from './state';
import { getDashboardStats, getItems, getOrderAnalytics, getValidOrders } from './api';
import type { DashboardData, DashboardRangeSelection, DashboardStatus } from './types';
/** Dashboard Hook 的输入参数。 */
export type UseDashboardOptions = DashboardRangeSelection & { customRangeVersion: number };
/** Dashboard Hook 暴露给页面的可视化数据与操作。 */
export type UseDashboardResult = {
data: DashboardData | null;
status: DashboardStatus;
chartData: ReturnType<typeof buildChartData>;
productSalesData: ReturnType<typeof buildProductSalesData>;
sourceData: ReturnType<typeof buildSourceData>;
categoryData: ReturnType<typeof buildCategoryData>;
maxProductSales: number;
trendPercent: string | null;
selectedRangeLabel: string;
refresh: () => void;
};
/** 判断请求错误是否来自用户主动取消。 */
const isAbortError = (error: unknown): boolean => error instanceof Error && error.message === '请求已取消';
/** 统一转换 Dashboard 请求错误。 */
const errorMessage = (error: unknown, fallback: string): string => error instanceof Error ? error.message : fallback;
/** 加载 Dashboard 概览、趋势和订单明细,并隔离过期响应。 */
export const useDashboard = (options: UseDashboardOptions): UseDashboardResult => {
const { range, customStartDate, customEndDate, customRangeVersion } = options;
const [overview, setOverview] = useState<Pick<DashboardData, 'stats' | 'items' | 'itemNames'> | null>(null);
const [rangeData, setRangeData] = useState<Pick<DashboardData, 'analytics' | 'previousAnalytics' | 'validOrders' | 'dateRange'> | null>(null);
const [status, setStatus] = useState<DashboardStatus>({ overview: 'idle', range: 'idle', error: '' });
const [refreshKey, setRefreshKey] = useState(0);
const requestSequence = useRef(0);
const rangeSelection = useMemo(
// selection 是当前时间范围的不可变快照。
() => ({ range, customStartDate, customEndDate }),
[customEndDate, customStartDate, range],
);
const refresh = useCallback(
// 重新加载按钮回调只递增版本号,实际请求由两个 effect 统一管理。
() => setRefreshKey(value => value + 1),
[],
);
useEffect(() => {
const controller = new AbortController();
setStatus(current => ({ ...current, overview: 'loading', error: '' }));
Promise.all([
getDashboardStats({ signal: controller.signal }),
getItems(undefined, { signal: controller.signal }),
]).then(([stats, items]) => {
if (controller.signal.aborted) return;
setOverview({ stats, items, itemNames: buildItemNameMap(items) });
setStatus(current => ({ ...current, overview: 'success' }));
}).catch(error => {
if (controller.signal.aborted || isAbortError(error)) return;
setStatus(current => ({ ...current, overview: 'error', error: errorMessage(error, '概览加载失败') }));
});
return () => controller.abort();
}, [refreshKey]);
useEffect(() => {
let dateRange;
try {
dateRange = getDateRange(range, new Date(), customStartDate, customEndDate);
} catch (error) {
setStatus(current => ({ ...current, range: 'error', error: errorMessage(error, '日期范围无效') }));
return;
}
const previousRange = getPreviousDateRange(dateRange);
const sequence = ++requestSequence.current;
const controller = new AbortController();
setStatus(current => ({ ...current, range: 'loading', error: '' }));
Promise.all([
getOrderAnalytics({ start_date: dateRange.startDate, end_date: dateRange.endDate }, { signal: controller.signal }),
getOrderAnalytics({ start_date: previousRange.startDate, end_date: previousRange.endDate }, { signal: controller.signal }),
getValidOrders({ start_date: dateRange.startDate, end_date: dateRange.endDate }, { signal: controller.signal }),
]).then(([analytics, previousAnalytics, validOrders]) => {
if (!isCurrentDashboardRequest(requestSequence.current, sequence, controller.signal)) return;
setRangeData({ analytics, previousAnalytics, validOrders, dateRange });
setStatus(current => ({ ...current, range: 'success' }));
}).catch(error => {
if (!isCurrentDashboardRequest(requestSequence.current, sequence, controller.signal) || isAbortError(error)) return;
setStatus(current => ({ ...current, range: 'error', error: errorMessage(error, '经营数据加载失败') }));
});
return () => controller.abort();
}, [customRangeVersion, range, refreshKey]);
const data = useMemo<DashboardData | null>(
// dashboardData 只有在概览和时间范围请求都成功后才对页面可见。
() => overview && rangeData ? { ...overview, ...rangeData } : null,
[overview, rangeData],
);
const itemNames = overview?.itemNames || {};
const analytics = rangeData?.analytics || null;
const chartData = useMemo(() => analytics ? buildChartData(analytics) : [], [analytics]);
const productSalesData = useMemo(() => analytics ? buildProductSalesData(analytics, itemNames) : [], [analytics, itemNames]);
const colors = useMemo(
// colors 是图表使用的主题颜色序列。
() => ['rgb(var(--color-brand))', 'rgb(var(--color-brand-highlight))', 'rgb(var(--color-success-500))', 'rgb(var(--color-warning-500))', 'rgb(var(--color-accent-500))'],
[],
);
const sourceData = useMemo(() => analytics ? buildSourceData(analytics, itemNames, colors) : [], [analytics, colors, itemNames]);
const categoryData = useMemo(() => analytics ? buildCategoryData(analytics, itemNames, colors) : [], [analytics, colors, itemNames]);
const maxProductSales = useMemo(() => getMaxProductSales(productSalesData), [productSalesData]);
return {
data,
status,
chartData,
productSalesData,
sourceData,
categoryData,
maxProductSales,
trendPercent: getTrendPercent(analytics, data?.previousAnalytics || null),
selectedRangeLabel: getRangeLabel(rangeSelection),
refresh,
};
};
@@ -0,0 +1,28 @@
import { expect, test } from 'vitest';
import type { OrderAnalytics } from '../../../types';
import { buildChartData, buildProductSalesData, getTrendPercent, isCurrentDashboardRequest } from './state';
// analyticsFixture 是覆盖趋势、商品排行和零值边界的最小分析数据。
const analyticsFixture: OrderAnalytics = {
revenue_stats: { total_amount: 120, total_orders: 3 },
daily_stats: [{ date: '2026-08-15', amount: 120, order_count: 3 }],
item_stats: [{ item_id: 'item-1', order_count: 3, total_amount: 120, avg_amount: 40 }],
};
test('Dashboard 派生数据保持趋势和排行口径一致',
// 派生数据测试验证日期、商品名称和营收趋势不会在组件渲染中漂移。
() => {
expect(buildChartData(analyticsFixture)[0]).toMatchObject({ name: '08-15', orders: 3, avgAmount: '40.00' });
expect(buildProductSalesData(analyticsFixture, { 'item-1': '测试商品' })).toEqual([{ name: '测试商品', sales: 3 }]);
expect(getTrendPercent(analyticsFixture, { ...analyticsFixture, revenue_stats: { total_amount: 100, total_orders: 2 } })).toBe('+20.0%');
});
test('Dashboard 请求代次和取消信号拒绝过期响应',
// 请求边界测试验证刷新后的旧请求不能覆盖新数据,主动取消也不会写入状态。
() => {
// controller 是模拟页面生命周期取消的控制器。
const controller = new AbortController();
expect(isCurrentDashboardRequest(4, 4, controller.signal)).toBe(true);
expect(isCurrentDashboardRequest(3, 4, controller.signal)).toBe(false);
controller.abort();
expect(isCurrentDashboardRequest(4, 4, controller.signal)).toBe(false);
});
+176
View File
@@ -0,0 +1,176 @@
import type { Item, OrderAnalytics } from '../../../types';
import type { DateRange, TimeRange } from '../../../dateRange';
import type { DashboardRangeSelection } from './types';
/** 趋势图中的单个日期数据点。 */
export type DashboardChartPoint = {
/** 图表横轴显示的日期文本。 */
name: string;
/** 当日营收金额。 */
amount: number;
/** 当日订单数。 */
orders: number;
/** 当日平均订单金额。 */
avgAmount: number | string;
};
/** 商品排行图中的单个数据点。 */
export type DashboardProductPoint = {
/** 商品展示名称。 */
name: string;
/** 商品订单数。 */
sales: number;
};
/** 商品占比图中的单个数据点。 */
export type DashboardSourcePoint = {
/** 商品展示名称。 */
name: string;
/** 商品订单数。 */
value: number;
/** 商品订单占比。 */
percent: number;
/** 图表主题颜色。 */
color: string;
};
/** 商品金额图中的单个数据点。 */
export type DashboardCategoryPoint = {
/** 商品展示名称。 */
name: string;
/** 商品总金额。 */
value: number;
/** 商品订单数。 */
orderCount: number;
/** 商品金额占比文本。 */
percentage: string;
/** 图表主题颜色。 */
color: string;
};
/** 将商品列表转换为商品 ID 到商品名称的索引。 */
export const buildItemNameMap = (items: Item[]): Record<string, string> => {
// itemNames 是商品 ID 到展示名称的索引。
const itemNames: Record<string, string> = {};
items.forEach(
// item 是待建立索引的商品记录。
item => {
itemNames[item.item_id] = item.item_title || item.item_id;
},
);
return itemNames;
};
/** 将订单分析数据转换为趋势图需要的平面数据。 */
export const buildChartData = (analytics: OrderAnalytics): DashboardChartPoint[] => (
analytics.daily_stats?.map(
// dailyStat 是某一天的订单统计。
dailyStat => ({
name: dailyStat.date.slice(5),
amount: dailyStat.amount,
orders: dailyStat.order_count,
avgAmount: dailyStat.order_count > 0 ? (dailyStat.amount / dailyStat.order_count).toFixed(2) : 0,
}),
) || []
);
/** 将商品统计转换为销量排行数据。 */
export const buildProductSalesData = (analytics: OrderAnalytics, itemNames: Record<string, string>): DashboardProductPoint[] => (
(analytics.item_stats || [])
.map(
// item 是单个商品的销售统计。
item => {
// itemName 是商品优先使用标题的展示名称。
const itemName = itemNames[item.item_id] || item.item_id;
return { name: itemName.length > 12 ? `${itemName.substring(0, 12)}...` : itemName, sales: item.order_count };
},
)
.sort((left, right) => right.sales - left.sales)
.slice(0, 10)
);
/** 将商品统计转换为订单来源占比数据。 */
export const buildSourceData = (analytics: OrderAnalytics, itemNames: Record<string, string>, colors: string[]): DashboardSourcePoint[] => {
// totalOrders 是当前分析周期的订单总数。
const totalOrders = analytics.revenue_stats.total_orders || 0;
return (analytics.item_stats || [])
.map(
// item 是单个商品的订单统计。
item => {
// itemName 是商品优先使用标题的展示名称。
const itemName = itemNames[item.item_id] || item.item_id;
return {
name: itemName.length > 10 ? `${itemName.substring(0, 10)}...` : itemName,
value: item.order_count,
percent: totalOrders > 0 ? (item.order_count / totalOrders) * 100 : 0,
};
},
)
.sort((left, right) => right.value - left.value)
.slice(0, 6)
.map(
// item 是截取后的商品占比数据,index 用于选择稳定颜色。
(item, index) => ({ ...item, color: colors[index % colors.length] }),
);
};
/** 将商品统计转换为金额排行数据。 */
export const buildCategoryData = (analytics: OrderAnalytics, itemNames: Record<string, string>, colors: string[]): DashboardCategoryPoint[] => {
// totalAmount 是当前分析周期的营收总额。
const totalAmount = analytics.revenue_stats.total_amount || 0;
return (analytics.item_stats || [])
.map(
// item 是单个商品的金额统计。
item => {
// itemName 是商品优先使用标题的展示名称。
const itemName = itemNames[item.item_id] || item.item_id;
return {
name: itemName.length > 12 ? `${itemName.substring(0, 12)}...` : itemName,
value: item.total_amount,
orderCount: item.order_count,
percentage: totalAmount > 0 ? (item.total_amount / totalAmount) * 100 : 0,
};
},
)
.sort((left, right) => right.value - left.value)
.slice(0, 5)
.map(
// item 是截取后的金额排行数据,index 用于选择稳定颜色。
(item, index) => ({ ...item, color: colors[index % colors.length], percentage: item.percentage.toFixed(1) }),
);
};
/** 根据当前与上一个周期的营收计算趋势百分比。 */
export const getTrendPercent = (analytics: OrderAnalytics | null, previousAnalytics: OrderAnalytics | null): string | null => {
if (!analytics || !previousAnalytics) return null;
// currentAmount 是本周期的营收金额。
const currentAmount = analytics.revenue_stats.total_amount;
// previousAmount 是上一个等长周期的营收金额。
const previousAmount = previousAnalytics.revenue_stats.total_amount;
if (previousAmount === 0) return currentAmount > 0 ? '+100%' : '0%';
// percent 是两个周期之间的营收变化比例。
const percent = ((currentAmount - previousAmount) / previousAmount) * 100;
return `${percent >= 0 ? '+' : ''}${percent.toFixed(1)}%`;
};
/** 返回时间范围选择器显示文本。 */
export const getRangeLabel = (selection: DashboardRangeSelection): string => {
// labels 是时间范围到中文展示文本的映射。
const labels: Record<TimeRange, string> = {
today: '今天',
yesterday: '昨天',
'3days': '三天内',
'7days': '7天内',
'30days': '一个月内',
custom: '自定义',
};
return labels[selection.range] || '所选范围';
};
/** 计算销量排行中用于进度条归一化的最大值。 */
export const getMaxProductSales = (productSales: DashboardProductPoint[]): number => Math.max(...productSales.map(item => item.sales), 1);
/** 判断旧的日期范围请求结果是否仍然可以写入当前页面。 */
export const isCurrentDashboardRequest = (currentSequence: number, requestSequence: number, signal: AbortSignal): boolean => (
currentSequence === requestSequence && !signal.aborted
);
+53
View File
@@ -0,0 +1,53 @@
import type { Item, Order, OrderAnalytics, DashboardStats } from '../../../types';
import type { DateRange, TimeRange } from '../../../dateRange';
/** Dashboard 请求状态。 */
export type DashboardRequestState = 'idle' | 'loading' | 'success' | 'error';
/** Dashboard 当前选中的时间范围。 */
export type DashboardRangeSelection = {
/** 当前选择的快捷时间范围。 */
range: TimeRange;
/** 自定义范围起始日期。 */
customStartDate: string;
/** 自定义范围结束日期。 */
customEndDate: string;
};
/** Dashboard 订单明细分页结果。 */
export type DashboardValidOrders = {
/** 当前范围内参与统计的订单。 */
orders: Order[];
/** 后端匹配到的订单总数。 */
total: number;
/** 是否因为上限而截断订单明细。 */
truncated: boolean;
};
/** Dashboard 页面请求得到的完整数据。 */
export type DashboardData = {
/** 概览统计数据。 */
stats: DashboardStats;
/** 当前时间范围的订单分析。 */
analytics: OrderAnalytics;
/** 上一个等长时间范围的订单分析。 */
previousAnalytics: OrderAnalytics;
/** 当前范围的有效订单明细。 */
validOrders: DashboardValidOrders;
/** 页面商品列表。 */
items: Item[];
/** 商品名称索引。 */
itemNames: Record<string, string>;
/** 当前生效的日期范围。 */
dateRange: DateRange;
};
/** Dashboard 各类请求的可观察状态。 */
export type DashboardStatus = {
/** 概览统计请求状态。 */
overview: DashboardRequestState;
/** 趋势和订单请求状态。 */
range: DashboardRequestState;
/** 最近一次可展示的错误。 */
error: string;
};
+5 -4
View File
@@ -6,6 +6,7 @@ import { describe, expect, test } from 'vitest';
import { StatusBadge } from './Dashboard';
const dashboardSource = readFileSync(resolve(__dirname, 'Dashboard.tsx'), 'utf8');
const trendChartSource = readFileSync(resolve(__dirname, '../app/features/dashboard/DashboardTrendChart.tsx'), 'utf8');
const globalStyles = readFileSync(resolve(__dirname, '../index.css'), 'utf8');
describe('Dashboard presentation safeguards', () => {
@@ -31,10 +32,10 @@ describe('Dashboard presentation safeguards', () => {
expect(dashboardSource.match(/wrapperStyle=\{\{ zIndex: 30, outline: 'none' \}\}/g)).toHaveLength(2);
expect(dashboardSource.match(/absolute inset-0 z-10/g)).toHaveLength(2);
expect(globalStyles).toContain('.dashboard-pie-chart .recharts-sector:focus');
expect(dashboardSource).toContain('dashboard-revenue-chart h-[350px] w-full');
expect(dashboardSource).toContain('activeBar={false}');
expect(dashboardSource).not.toMatch(/#[0-9A-Fa-f]{3,8}/);
expect(dashboardSource).toContain("fill={cssColor('brand')}");
expect(trendChartSource).toContain('dashboard-revenue-chart h-[350px] w-full');
expect(trendChartSource).toContain('activeBar={false}');
expect(trendChartSource).not.toMatch(/#[0-9A-Fa-f]{3,8}/);
expect(trendChartSource).toContain("fill={cssColor('brand')}");
expect(globalStyles).toContain('.dashboard-revenue-chart .recharts-rectangle:focus');
expect(globalStyles).toContain('.dashboard-revenue-chart .recharts-curve:focus');
expect(globalStyles).toContain('.dashboard-revenue-chart [class*="recharts-zIndex-layer_"]:focus');
+27 -268
View File
@@ -1,10 +1,11 @@
import React, { useEffect, useRef, useState } from 'react';
import { DashboardStats, OrderAnalytics, Order, OrderStatus, Item } from '../types';
import { getDashboardStats, getOrderAnalytics, getValidOrders, getItems } from '../services/api';
import { getDateRange, getPreviousDateRange, TimeRange } from '../dateRange';
import React, { useState } from 'react';
import { OrderStatus } from '../types';
import { getDateRange, TimeRange } from '../dateRange';
import { formatLocalDateTime } from '../dateTime';
import { TrendingUp, Users, ShoppingCart, AlertCircle, DollarSign, Activity, Package, ArrowUpRight, Calendar, X, BarChart3, PackageCheck, ExternalLink, Eye, Edit } from 'lucide-react';
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, BarChart, Bar, PieChart, Pie, Cell, Legend } from 'recharts';
import { Tooltip, ResponsiveContainer, PieChart, Pie, Cell, Legend } from 'recharts';
import { useDashboard } from '../app/features/dashboard/hooks';
import { DashboardTrendChart } from '../app/features/dashboard/DashboardTrendChart';
const cssColor = (token: string, alpha?: number) => (
alpha === undefined
@@ -60,25 +61,21 @@ const StatCard: React.FC<{ title: string; value: string | number; icon: React.El
);
const Dashboard: React.FC = () => {
const [stats, setStats] = useState<DashboardStats | null>(null);
const [analytics, setAnalytics] = useState<OrderAnalytics | null>(null);
const [loadError, setLoadError] = useState('');
const [timeRange, setTimeRange] = useState<TimeRange>('7days');
const [customStartDate, setCustomStartDate] = useState('');
const [customEndDate, setCustomEndDate] = useState('');
const [previousAnalytics, setPreviousAnalytics] = useState<OrderAnalytics | null>(null); // 用于计算趋势
// 搜索词
const [searchTerm, setSearchTerm] = useState('');
// 参与统计的订单列表
const [validOrders, setValidOrders] = useState<Order[]>([]);
const [validOrdersTotal, setValidOrdersTotal] = useState(0);
const [validOrdersTruncated, setValidOrdersTruncated] = useState(false);
const [ordersLoading, setOrdersLoading] = useState(false);
// 商品列表
const [items, setItems] = useState<Item[]>([]);
const [itemNames, setItemNames] = useState<Record<string, string>>({});
const rangeRequestSequence = useRef(0);
const [customRangeVersion, setCustomRangeVersion] = useState(0);
const dashboard = useDashboard({ range: timeRange, customStartDate, customEndDate, customRangeVersion });
const { data, status, chartData, productSalesData, sourceData: sourceDataData, categoryData: categoryDataData, maxProductSales, trendPercent, selectedRangeLabel, refresh } = dashboard;
const stats = data?.stats || null;
const analytics = data?.analytics || null;
const previousAnalytics = data?.previousAnalytics || null;
const validOrders = data?.validOrders.orders || [];
const validOrdersTotal = data?.validOrders.total || 0;
const validOrdersTruncated = data?.validOrders.truncated || false;
const ordersLoading = status.range === 'loading';
const loadError = status.error;
// 颜色配置
const COLORS = [
@@ -89,150 +86,20 @@ const Dashboard: React.FC = () => {
cssColor('accent-500'),
];
const formatCurrency = (value: number) => `¥${Number(value || 0).toLocaleString('zh-CN', { maximumFractionDigits: 2 })}`;
const loadRange = async (range: TimeRange) => {
let currentRange;
try {
currentRange = getDateRange(range, new Date(), customStartDate, customEndDate);
} catch (error) {
setLoadError(error instanceof Error ? error.message : '日期范围无效');
return;
}
const { startDate, endDate } = currentRange;
const params = { start_date: startDate, end_date: endDate };
const previous = getPreviousDateRange(currentRange);
const sequence = ++rangeRequestSequence.current;
setOrdersLoading(true);
setLoadError('');
try {
const [currentAnalytics, previousResult, orders] = await Promise.all([
getOrderAnalytics(params),
getOrderAnalytics({ start_date: previous.startDate, end_date: previous.endDate }),
getValidOrders(params),
]);
if (sequence !== rangeRequestSequence.current) return;
setAnalytics(currentAnalytics);
setPreviousAnalytics(previousResult);
setValidOrders(orders.orders);
setValidOrdersTotal(orders.total);
setValidOrdersTruncated(orders.truncated);
} catch (error) {
if (sequence === rangeRequestSequence.current) {
setLoadError(error instanceof Error ? error.message : '经营数据加载失败');
}
} finally {
if (sequence === rangeRequestSequence.current) setOrdersLoading(false);
}
};
// 计算趋势百分比
const getTrendPercent = () => {
if (!analytics || !previousAnalytics) return null;
const currentAmount = analytics.revenue_stats.total_amount;
const previousAmount = previousAnalytics.revenue_stats.total_amount;
if (previousAmount === 0) {
return currentAmount > 0 ? '+100%' : '0%';
}
const percent = ((currentAmount - previousAmount) / previousAmount) * 100;
const sign = percent >= 0 ? '+' : '';
return `${sign}${percent.toFixed(1)}%`;
};
useEffect(() => {
let cancelled = false;
Promise.all([getDashboardStats(), getItems()]).then(([dashboardStats, itemList]) => {
if (cancelled) return;
setStats(dashboardStats);
setItems(itemList);
// 建立 item_id 到 item_title 的映射
const nameMap: Record<string, string> = {};
itemList.forEach(item => {
nameMap[item.item_id] = item.item_title || item.item_id;
});
setItemNames(nameMap);
}).catch(error => {
if (!cancelled) setLoadError(error instanceof Error ? error.message : '概览加载失败');
});
return () => { cancelled = true; };
}, []);
useEffect(() => {
if (timeRange !== 'custom') void loadRange(timeRange);
}, [timeRange]);
if (loadError && (!stats || !analytics)) {
return (
<div className="p-8 flex flex-col items-center gap-3 text-red-600">
<AlertCircle className="w-8 h-8" />
<span>{loadError}</span>
<button type="button" className="ios-btn-primary px-4 py-2 rounded-xl" onClick={() => window.location.reload()}>重新加载</button>
<button type="button" className="ios-btn-primary px-4 py-2 rounded-xl" onClick={refresh}>重新加载</button>
</div>
);
}
if (!stats || !analytics) return <div className="p-8 flex justify-center text-gray-400"><Activity className="w-8 h-8 animate-spin text-brand" /></div>;
const chartData = analytics.daily_stats?.map(d => ({
name: d.date.slice(5), // MM-DD
amount: d.amount,
orders: d.order_count,
avgAmount: d.order_count > 0 ? (d.amount / d.order_count).toFixed(2) : 0
})) || [];
// 计算图表数据(在渲染时直接计算)
const itemStats = analytics.item_stats || [];
const totalOrders = analytics.revenue_stats.total_orders || 0;
const totalAmount = analytics.revenue_stats.total_amount || 0;
// 1. 商品销量排行:按订单数量排序
const productSalesData = itemStats.length > 0 ? itemStats
.map(item => ({
name: (itemNames[item.item_id] || item.item_id).length > 12
? (itemNames[item.item_id] || item.item_id).substring(0, 12) + '...'
: (itemNames[item.item_id] || item.item_id),
sales: item.order_count
}))
.sort((a, b) => b.sales - a.sales)
.slice(0, 10) : [];
const maxProductSales = Math.max(...productSalesData.map(item => item.sales), 1);
// 2. 商品下单占比:每个商品的订单数占总订单数的百分比
const sourceDataData = itemStats.length > 0 ? itemStats
.map(item => ({
name: (itemNames[item.item_id] || item.item_id).length > 10
? (itemNames[item.item_id] || item.item_id).substring(0, 10) + '...'
: (itemNames[item.item_id] || item.item_id),
value: item.order_count,
percent: totalOrders > 0 ? (item.order_count / totalOrders) * 100 : 0
}))
.sort((a, b) => b.value - a.value)
.slice(0, 6)
.map((item, index) => ({
...item,
color: COLORS[index % COLORS.length]
})) : [];
// 3. 商品金额分析:按金额排序,取前5
const categoryDataData = itemStats.length > 0 ? itemStats
.map(item => ({
name: (itemNames[item.item_id] || item.item_id).length > 12
? (itemNames[item.item_id] || item.item_id).substring(0, 12) + '...'
: (itemNames[item.item_id] || item.item_id),
value: item.total_amount,
orderCount: item.order_count,
percentage: totalAmount > 0
? (item.total_amount / totalAmount) * 100
: 0
}))
.sort((a, b) => b.value - a.value)
.slice(0, 5)
.map((item, index) => ({
...item,
color: COLORS[index % COLORS.length],
percentage: item.percentage.toFixed(1)
})) : [];
const timeRangeOptions = [
{ key: 'today' as TimeRange, label: '今天' },
{ key: 'yesterday' as TimeRange, label: '昨天' },
@@ -241,7 +108,6 @@ const Dashboard: React.FC = () => {
{ key: '30days' as TimeRange, label: '一个月内' },
{ key: 'custom' as TimeRange, label: '自定义' },
];
const selectedRangeLabel = timeRangeOptions.find(option => option.key === timeRange)?.label || '所选范围';
let currentRangeDates;
try {
currentRangeDates = getDateRange(timeRange, new Date(), customStartDate, customEndDate);
@@ -258,6 +124,12 @@ const Dashboard: React.FC = () => {
return (
<div className="space-y-8 animate-fade-in">
{loadError && (
<div className="flex items-center justify-between gap-3 rounded-xl border border-red-100 bg-red-50 px-4 py-3 text-sm text-red-700">
<span>{loadError}</span>
<button type="button" className="font-bold underline" onClick={refresh}>重试</button>
</div>
)}
<div className="flex flex-col md:flex-row justify-between md:items-end gap-4">
<div>
<h2 className="text-4xl font-extrabold text-gray-900 tracking-tight">运营概览</h2>
@@ -302,14 +174,7 @@ const Dashboard: React.FC = () => {
className="px-3 py-2 rounded-xl text-sm border border-gray-200 focus:outline-none focus:ring-2 focus:ring-brand"
/>
<button
onClick={() => {
try {
setLoadError('');
void loadRange('custom');
} catch (error) {
setLoadError(error instanceof Error ? error.message : '日期范围无效');
}
}}
onClick={() => setCustomRangeVersion(value => value + 1)}
className="px-4 py-2 rounded-xl text-sm font-bold bg-black text-white hover:bg-gray-800 transition-colors"
>
应用
@@ -325,7 +190,7 @@ const Dashboard: React.FC = () => {
value={`¥${analytics.revenue_stats.total_amount.toLocaleString('zh-CN', { minimumFractionDigits: 2 })}`}
icon={DollarSign}
colorClass="bg-blue-400"
trend={getTrendPercent() || undefined}
trend={trendPercent || undefined}
/>
<StatCard
title="活跃账号 / 总数"
@@ -347,113 +212,7 @@ const Dashboard: React.FC = () => {
/>
</div>
{/* Main Chart Section */}
<div className="ios-card p-8 rounded-xl">
<div className="mb-10">
<h3 className="text-xl font-bold text-gray-900">营收趋势分析</h3>
<p className="text-sm text-gray-400 mt-1">{selectedRangeLabel}的销售额走势</p>
</div>
<div className="dashboard-revenue-chart h-[350px] w-full">
{chartData.length === 0 || analytics.revenue_stats.total_amount === 0 ? (
<div className="h-full flex flex-col items-center justify-center text-gray-400">
<ShoppingCart className="w-16 h-16 mb-4 opacity-20" />
<p className="text-lg font-medium">暂无营收数据</p>
<p className="text-sm mt-2">所选时间范围内暂无订单记录</p>
</div>
) : chartData.length <= 2 ? (
// 数据点少于等于2个时使用美化柱状图
<ResponsiveContainer width="100%" height="100%">
<BarChart data={chartData} margin={{ top: 30, right: 20, left: 0, bottom: 30 }} barCategoryGap="45%">
<XAxis
dataKey="name"
axisLine={false}
tickLine={false}
tick={{fill: cssColor('neutral-700'), fontSize: 14, fontWeight: 600}}
dy={10}
/>
<YAxis
axisLine={false}
tickLine={false}
tick={{fill: cssColor('neutral-400'), fontSize: 13, fontWeight: 500}}
tickFormatter={(value) => `¥${value}`}
/>
<Tooltip
contentStyle={{
backgroundColor: cssColor('white'),
borderRadius: '8px',
border: `1px solid ${cssColor('neutral-200')}`,
boxShadow: 'var(--shadow-xl)',
padding: '12px 16px'
}}
labelStyle={{ color: cssColor('neutral-500'), fontWeight: 500 }}
itemStyle={{ color: cssColor('brand'), fontWeight: 600 }}
cursor={{ fill: cssColor('brand', 0.08) }}
formatter={(value) => {
const num = Number(value);
return [`¥${num.toFixed(2)}`, '营收'];
}}
/>
<Bar
dataKey="amount"
fill={cssColor('brand')}
maxBarSize={72}
radius={[12, 12, 0, 0]}
activeBar={false}
stroke="none"
strokeWidth={0}
>
{chartData.map((_, index) => (
<Cell
key={`cell-${index}`}
fill={cssColor('brand')}
stroke="none"
strokeWidth={0}
/>
))}
</Bar>
</BarChart>
</ResponsiveContainer>
) : (
// 数据点多于2个时使用折线图
<ResponsiveContainer width="100%" height="100%">
<AreaChart data={chartData} margin={{ top: 10, right: 10, left: -20, bottom: 0 }}>
<defs>
<linearGradient id="colorAmount" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor={cssColor('brand')} stopOpacity={0.5}/>
<stop offset="95%" stopColor={cssColor('brand')} stopOpacity={0}/>
</linearGradient>
</defs>
<XAxis
dataKey="name"
axisLine={false}
tickLine={false}
tick={{fill: cssColor('neutral-400'), fontSize: 13, fontWeight: 500}}
dy={15}
/>
<YAxis
axisLine={false}
tickLine={false}
tick={{fill: cssColor('neutral-400'), fontSize: 13, fontWeight: 500}}
/>
<CartesianGrid vertical={false} stroke={cssColor('neutral-100')} strokeDasharray="3 3" />
<Tooltip
contentStyle={{
backgroundColor: cssColor('white'),
borderRadius: '8px',
border: `1px solid ${cssColor('neutral-200')}`,
boxShadow: 'var(--shadow-xl)',
padding: '12px 16px'
}}
labelStyle={{ color: cssColor('neutral-500'), fontWeight: 500 }}
itemStyle={{ color: cssColor('brand'), fontWeight: 600 }}
cursor={{ stroke: cssColor('brand'), strokeWidth: 2, strokeDasharray: '4 4' }}
/>
<Area type="monotone" dataKey="amount" stroke={cssColor('brand')} strokeWidth={4} fillOpacity={1} fill="url(#colorAmount)" activeDot={{ r: 8, fill: cssColor('white'), stroke: cssColor('brand'), strokeWidth: 2 }} />
</AreaChart>
</ResponsiveContainer>
)}
</div>
</div>
<DashboardTrendChart chartData={chartData} selectedRangeLabel={selectedRangeLabel} totalAmount={totalAmount} />
{/* 商品销量排行和订单来源分布 */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-8">
+20
View File
@@ -160,6 +160,26 @@ test('订单查询和导入 API 转发外部取消信号', async () => {
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/orders/import', expect.objectContaining({ signal: expect.any(AbortSignal) }));
});
test('Dashboard 统计 API 转发外部取消信号', async () => {
// fetchMock 验证 Dashboard 的概览、趋势和订单明细共用同一个取消信号。
const fetchMock = vi.fn()
.mockResolvedValueOnce(jsonResponse({ total_cookies: 1, active_cookies: 1, available_card_stock: 2 }))
.mockResolvedValueOnce(jsonResponse([]))
.mockResolvedValueOnce(jsonResponse({ revenue_stats: { total_amount: 1, total_orders: 1 }, daily_stats: [] }))
.mockResolvedValueOnce(jsonResponse({ revenue_stats: { total_amount: 0, total_orders: 0 }, daily_stats: [] }))
.mockResolvedValueOnce(jsonResponse({ orders: [], total: 0, truncated: false }));
vi.stubGlobal('fetch', fetchMock);
// controller 是 Dashboard feature Hook 传入 API 的请求控制器。
const controller = new AbortController();
await getDashboardStats({ signal: controller.signal });
await getItems(undefined, { signal: controller.signal });
await getOrderAnalytics({ start_date: '2026-08-15', end_date: '2026-08-15' }, { signal: controller.signal });
await getValidOrders({ start_date: '2026-08-15', end_date: '2026-08-15' }, { signal: controller.signal });
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/analytics/dashboard', expect.objectContaining({ signal: expect.any(AbortSignal) }));
expect(fetchMock).toHaveBeenNthCalledWith(3, expect.stringContaining('/api/v1/analytics/orders?'), expect.objectContaining({ signal: expect.any(AbortSignal) }));
expect(fetchMock).toHaveBeenNthCalledWith(4, expect.stringContaining('/api/v1/analytics/orders/valid?'), expect.objectContaining({ signal: expect.any(AbortSignal) }));
});
test('通知渠道和 SMTP API 转发外部取消信号', async () => {
// fetchMock 验证渠道读取、保存和 SMTP 读写都支持取消控制。
const fetchMock = vi.fn()
+6 -6
View File
@@ -380,11 +380,11 @@ export const getAdminStats = async (): Promise<AdminStatsResponse> => {
return get('/api/v1/admin/stats');
};
export const getDashboardStats = async (): Promise<DashboardStatsResponse> => {
return get('/api/v1/analytics/dashboard');
export const getDashboardStats = async (options?: RequestControlOptions): Promise<DashboardStatsResponse> => {
return get('/api/v1/analytics/dashboard', undefined, options);
};
export const getOrderAnalytics = async (daysOrParams: number | {start_date: string; end_date: string} = 7): Promise<OrderAnalyticsResponse> => {
export const getOrderAnalytics = async (daysOrParams: number | {start_date: string; end_date: string} = 7, options?: RequestControlOptions): Promise<OrderAnalyticsResponse> => {
let params: {start_date: string; end_date: string};
if (typeof daysOrParams === 'number') {
@@ -402,7 +402,7 @@ export const getOrderAnalytics = async (daysOrParams: number | {start_date: stri
return get('/api/v1/analytics/orders', {
...params,
timezone_offset_minutes: -new Date().getTimezoneOffset(),
});
}, options);
}
export interface ValidOrdersResult {
@@ -411,12 +411,12 @@ export interface ValidOrdersResult {
truncated: boolean;
}
export const getValidOrders = async (dateRange: {start_date: string; end_date: string}): Promise<ValidOrdersResult> => {
export const getValidOrders = async (dateRange: {start_date: string; end_date: string}, options?: RequestControlOptions): Promise<ValidOrdersResult> => {
const res = await get<ValidOrdersResponse | ValidOrderResponse[]>('/api/v1/analytics/orders/valid', {
start_date: dateRange.start_date,
end_date: dateRange.end_date,
timezone_offset_minutes: -new Date().getTimezoneOffset(),
});
}, options);
const orders = Array.isArray(res) ? res : (res.orders || []);
const normalized = orders.map((order: any) => ({
...order,
@@ -413,4 +413,4 @@ import{r as h}from"./react-vendor-C_od1ZSF.js";/**
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*/const F1=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],_0=e("zap",F1);export{k2 as $,O1 as A,Q1 as B,i2 as C,r2 as D,l2 as E,d0 as F,u2 as G,W2 as H,s0 as I,c0 as J,f2 as K,z2 as L,P2 as M,q2 as N,x2 as O,D2 as P,I2 as Q,O2 as R,X2 as S,y0 as T,i0 as U,n2 as V,N2 as W,M0 as X,v2 as Y,_0 as Z,e0 as _,K1 as a,m2 as a0,B2 as a1,d2 as a2,o2 as a3,y2 as a4,b2 as a5,Z1 as a6,j2 as a7,p2 as a8,e2 as a9,J2 as aa,A2 as ab,n0 as ac,h2 as ad,g2 as ae,w2 as af,G2 as ag,L2 as ah,p0 as ai,l0 as aj,r0 as ak,X1 as al,a0 as am,$2 as an,H2 as ao,Q2 as b,t2 as c,a2 as d,V2 as e,c2 as f,Y2 as g,E2 as h,h0 as i,C2 as j,U2 as k,T2 as l,t0 as m,J1 as n,Z2 as o,Y1 as p,s2 as q,M2 as r,_2 as s,k0 as t,G1 as u,S2 as v,R2 as w,F2 as x,o0 as y,K2 as z};
*/const F1=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]],_0=e("zap",F1);export{k2 as $,O1 as A,Q1 as B,i2 as C,r2 as D,l2 as E,d0 as F,u2 as G,W2 as H,s0 as I,c0 as J,f2 as K,z2 as L,P2 as M,q2 as N,x2 as O,D2 as P,I2 as Q,O2 as R,X2 as S,y0 as T,i0 as U,n2 as V,N2 as W,M0 as X,v2 as Y,_0 as Z,e0 as _,K1 as a,m2 as a0,B2 as a1,d2 as a2,o2 as a3,y2 as a4,b2 as a5,Z1 as a6,j2 as a7,p2 as a8,e2 as a9,J2 as aa,A2 as ab,n0 as ac,h2 as ad,g2 as ae,w2 as af,G2 as ag,L2 as ah,p0 as ai,l0 as aj,r0 as ak,X1 as al,a0 as am,$2 as an,H2 as ao,Q2 as b,t2 as c,a2 as d,V2 as e,Y2 as f,c2 as g,E2 as h,h0 as i,C2 as j,U2 as k,T2 as l,t0 as m,J1 as n,Z2 as o,Y1 as p,s2 as q,M2 as r,_2 as s,k0 as t,G1 as u,S2 as v,R2 as w,F2 as x,o0 as y,K2 as z};
@@ -0,0 +1,20 @@
import{j as e,r,c as ks,b as Te,d as Xa}from"./react-vendor-C_od1ZSF.js";import{L as er,U as ha,M as ms,C as Cs,B as ga,S as ba,Z as us,a as wt,b as Ss,G as Ts,c as As,d as Ls,e as tr,f as fa,g as lt,A as Es,D as sr,P as ya,h as Mt,E as ja,T as ar,i as rr,j as Se,X as Ie,k as lr,l as nr,m as Is,n as Na,o as et,p as Ke,q as va,K as ir,r as ot,s as rt,Q as Xt,t as dt,u as yt,v as Et,R as We,w as _a,x as or,y as Ve,z as vt,F as $t,H as tt,I as $s,J as jt,N as cr,O as dr,V as xr,W as wa,Y as ka,_ as Ca,$ as mr,a0 as ur,a1 as es,a2 as Ft,a3 as ps,a4 as pr,a5 as hr,a6 as hs,a7 as Ds,a8 as gr,a9 as br,aa as Dt,ab as Ms,ac as Jt,ad as Sa,ae as fr,af as yr,ag as Zt,ah as Aa,ai as jr,aj as Nr,ak as vr,al as _r,am as wr,an as kr,ao as Bs}from"./icons-vendor-i_74xDZy.js";import{R as Qt,B as Cr,X as qs,Y as Fs,T as Vt,a as Sr,C as gs,A as Ar,b as Lr,c as Ir,P as zs,d as Us,L as Rr}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))l(n);new MutationObserver(n=>{for(const m of n)if(m.type==="childList")for(const p of m.addedNodes)p.tagName==="LINK"&&p.rel==="modulepreload"&&l(p)}).observe(document,{childList:!0,subtree:!0});function a(n){const m={};return n.integrity&&(m.integrity=n.integrity),n.referrerPolicy&&(m.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?m.credentials="include":n.crossOrigin==="anonymous"?m.credentials="omit":m.credentials="same-origin",m}function l(n){if(n.ep)return;n.ep=!0;const m=a(n);fetch(n.href,m)}})();const Or=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),bs=({sizeClass:t="w-12 h-12",logoClassName:s="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23Line truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(Ss,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:Fe,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:ue,children:"取消"}),e.jsxs("button",{onClick:c,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:ue,children:[ue?e.jsx(Se,{className:"w-4 h-4 animate-spin"}):e.jsx(et,{className:"w-4 h-4"}),ue?"保存中...":"保存"]})]})})]})}),document.body)]})},Rn=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],On=t=>{const s=typeof t=="object"&&t!==null?t:{},a=Array.isArray(s.results)?s.results:[];return{total:Number(s.total||0),success_count:Number(s.success_count||0),failed_count:Number(s.failed_count||0),results:a.map(Pn)}},Pn=t=>{const s=typeof t=="object"&&t!==null?t:{};return{order_id:String(s.order_id||"unknown"),success:s.success===!0,message:String(s.message||"")}},Tn=t=>(t==null?void 0:t.results.filter(En))||[],En=t=>!t.success,$n=(t,s)=>t!==null&&!s,Dn=t=>{if(!t)return"请选择订单文件";const s=t.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(s)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},ct=(t,s)=>t===s,Mn=(t,s)=>t instanceof Error&&t.message?t.message:s,Bn=({filter:t,onFilterChange:s,accountFilter:a,onAccountFilterChange:l,accounts:n,accountName:m,searchText:p,onSearchChange:f})=>{const u=g=>s(g.currentTarget.dataset.status||"all"),N=g=>l(g.target.value),x=g=>f(g.target.value);return e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:Rn.map(g=>e.jsx("button",{"data-status":g.key,onClick:u,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${t===g.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:g.label},g.key))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(dt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:a,onChange:N,className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),n.map(g=>e.jsx("option",{value:g.id,children:m(g.id)},g.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(vt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:p,onChange:x,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},qn=t=>{const s=m=>{var p;t.setImportFile(((p=m.target.files)==null?void 0:p[0])||null)},a=()=>t.closeImportModal(),l=()=>void t.handleImportOrders(),n=()=>void t.handleRetryImport();return t.showImportModal?Te.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:a,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Ie,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:s,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xl Line truncated
VIP-002
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["预览:",a.appendPreview.length," 个有效卡密,空行自动忽略。"]})]}),a.appendError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-200 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.appendError}),e.jsx("button",{type:"button",onClick:x,disabled:a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),a.appendResult&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",a.appendResult.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:p,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),a.batchTab==="create"?e.jsxs("button",{onClick:P,disabled:!a.batchFile||a.batchBusy,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(Se,{className:"w-4 h-4 animate-spin"}):e.jsx($t,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:W,disabled:!a.appendTargetId||a.appendPreview.length===0||a.batchBusy||t.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(Se,{className:"w-4 h-4 animate-spin"}):e.jsx(tt,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},Gn=({type:t})=>{switch(t){case"text":return e.jsx(ka,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(wa,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(xr,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(Cs,{className:"w-5 h-5 text-gray-500"})}},Jn=(t,s,a)=>{const l=a.trim().toLocaleLowerCase();return t.filter(n=>(!s||n.type===s)&&(!l||n.name.toLocaleLowerCase().includes(l)))},Ua=t=>t.split(`
`).map(s=>s.trim()).filter(Boolean),Qn=(t,s,a)=>!!(t&&Ua(s).length>0&&!a),ft=(t,s,a,l)=>t===s&&a===l,Vn=()=>{const[t,s]=r.useState([]),[a,l]=r.useState(!0),n=r.useRef(0),m=r.useRef(null),p=r.useCallback(async()=>{var N;const f=++n.current;(N=m.current)==null||N.abort();const u=new AbortController;m.current=u,l(!0);try{const x=await Os({signal:u.signal});if(f!==n.current)return;s(x)}catch(x){f===n.current&&!u.signal.aborted&&console.error("加载卡密库存失败:",x)}finally{f===n.current&&l(!1)}},[]);return r.useEffect(()=>(p(),()=>{var u;n.current+=1,(u=m.current)==null||u.abort()}),[p]),{cards:t,setCards:s,loading:a,loadCards:p}},Kn=t=>{const s=t.dataCards,a=t.loadCards,[l,n]=r.useState(!1),[m,p]=r.useState("create"),[f,u]=r.useState(null),[N,x]=r.useState(null),[g,v]=r.useState(!1),[P,W]=r.useState(""),[j,T]=r.useState(""),[D,G]=r.useState(null),[K,Z]=r.useState(""),S=r.useRef(0),L=r.useRef(null),V=r.useRef(""),q=r.useMemo(()=>Ua(j),[j]),z=r.useCallback(()=>{var w;p("create"),u(null),x(null),W((w=s[0])!=null&&w.id?String(s[0].id):""),T(""),G(null),Z(""),n(!0)},[s]),d=r.useCallback(()=>{var w;S.current+=1,(w=L.current)==null||w.abort(),v(!1),n(!1)},[]),M=r.useCallback(async()=>{var I;if(!f||g)return;const w=++S.current;(I=L.current)==null||I.abort();const E=new AbortController;L.current=E,v(!0),x(null);try{const U=await Il(f,{signal:E.signal});if(!ft(w,S.current,"",""))return;x(U),U.created>0&&await a()}catch(U){if(!ft(w,S.current,"",""))return;x({error:(U==null?void 0:U.message)||"上传失败"})}finally{ft(w,S.current,"","")&&v(!1)}},[g,f,a]),J=r.useCallback(async()=>{var U;if(!Qn(P,j,g))return;const w=P,E=++S.current;V.current=w,(U=L.current)==null||U.abort();const I=new AbortController;L.current=I,v(!0),G(null),Z("");try{const F=await Rl(w,j,{signal:I.signal});if(!ft(E,S.current,w,P))return;G({added:F.added}),T(""),await a()}catch(F){if(!ft(E,S.current,w,P))return;Z((F==null?void 0:F.message)||"追加失败")}finally{ft(E,S.current,w,P)&&v(!1)}},[j,P,g,a]),R=r.useCallback(async()=>{await M()},[M]),_=r.useCallback(async()=>{V.current&&P!==V.current||await J()},[P,J]);return{showBatchModal:l,setShowBatchModal:n,batchTab:m,setBatchTab:p,batchFile:f,setBatchFile:u,batchResult:N,batchBusy:g,appendTargetId:P,setAppendTargetId:W,appendContent:j,setAppendContent:T,appendResult:D,appendError:K,appendPreview:q,openBatchModal:z,closeBatchModal:d,handleBatchCreate:M,handleBatchAppend:J,handleRetryBatchCreate:R,handleRetryBatchAppend:_}},ta=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),Hn=()=>{const{cards:t,loadCards:s}=Vn(),[a,l]=r.useState(!1),[n,m]=r.useState(!1),[p,f]=r.useState(null),[u,N]=r.useState({}),[x,g]=r.useState(ta),[v,P]=r.useState(""),[W,j]=r.useState(""),T=r.useMemo(()=>t.filter(d=>d.type==="data"),[t]),D=Kn({dataCards:T,loadCards:s}),G=d=>{var M,J,R,_,w;f(d),N({id:d.id,name:d.name||"",type:d.type||"text",api_url:((M=d.api_config)==null?void 0:M.url)||"",api_method:((J=d.api_config)==null?void 0:J.method)||"GET",api_timeout:((R=d.api_config)==null?void 0:R.timeout)||10,api_headers:((_=d.api_config)==null?void 0:_.headers)||"",api_params:((w=d.api_config)==null?void 0:w.params)||"",text_content:d.text_content||"",data_content:d.data_content||"",image_url:d.image_url||"",delay_seconds:d.delay_seconds||0,description:d.description||"",enabled:d.enabled}),l(!0)},K=async()=>{var d,M,J,R,_,w,E,I;if(p){if(!((d=u.name)!=null&&d.trim())){alert("请输入卡密名称");return}if(!u.type){alert("请选择卡密类型");return}try{const U={name:u.name.trim(),type:u.type,description:(M=u.description)==null?void 0:M.trim(),delay_seconds:u.delay_seconds||0,enabled:u.enabled??!0};u.type==="api"?U.api_config={url:((J=u.api_url)==null?void 0:J.trim())||"",method:u.api_method,timeout:u.api_timeout||10,headers:((R=u.api_headers)==null?void 0:R.trim())||void 0,params:((_=u.api_params)==null?void 0:_.trim())||void 0}:u.type==="text"?U.text_content=((w=u.text_content)==null?void 0:w.trim())||"":u.type==="data"?U.data_content=((E=u.data_content)==null?void 0:E.trim())||"":u.type==="image"&&(U.image_url=((I=u.image_url)==null?void 0:I.trim())||""),await Vs(p.id,U),l(!1),await s()}catch(U){console.error("更新卡密失败:",U),alert("更新失败,请重试")}}},Z=async d=>{if(confirm("确认删除该卡密吗?"))try{await Ll(d),await s()}catch(M){console.error("删除卡密失败:",M),alert("删除失败,请重试")}},S=async()=>{if(!x.name.trim()){alert("请输入卡密名称");return}if(!x.content.trim()){alert(x.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const d={name:x.name.trim(),type:x.type,description:x.description.trim(),enabled:x.enabled,delay_seconds:x.delay_seconds};x.type==="text"&&(d.text_content=x.content.trim()),x.type==="data"&&(d.data_content=x.content.trim()),x.type==="image"&&(d.image_url=x.content.trim()),x.type==="api"&&(d.api_config={url:x.content.trim(),method:x.api_me Line truncated
VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(E=>E.map(I=>`"${String(I).replace(/"/g,'""')}"`).join(",")).join(`
`),R=new Blob(["\uFEFF"+J],{type:"text/csv;charset=utf-8"}),_=URL.createObjectURL(R),w=document.createElement("a");w.href=_,w.download="卡密组批量导入模板.csv",document.body.appendChild(w),w.click(),w.remove(),URL.revokeObjectURL(_)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:D.openBatchModal,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx($t,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>m(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(tt,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(Ca,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:v,onChange:d=>P(d.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(vt,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:W,onChange:d=>j(d.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",q.length," / ",t.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:q.map(d=>{let M="";return d.type==="data"&&d.data_content?M=`库存: ${d.data_content.split(`
`).filter(R=>R.trim()).length} 条`:d.type==="text"&&d.text_content?M=d.text_content:d.type==="api"&&d.api_config?M=d.api_config.url:d.type==="image"&&d.image_url&&(M="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(Gn,{type:d.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:d.name,children:d.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>V(d.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:d.id}),e.jsx(mr,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${d.type==="text"?"bg-blue-50 text-blue-600":d.type==="data"?"bg-purple-50 text-purple-600":d.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:d.type==="text"?"文本":d.type==="data"?"批量":d.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:M,children:M})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:d.description||"-",children:d.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>L(d),className:`w-12 h-8 rounded-full relative transition-colors ${d.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${d.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>G(d),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(jt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>Z(d.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Ve,{className:"h-4 w-4"})})]})})]},d.id)})})]})}),q.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(ya,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),a&&p&&Te.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>l(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(Ie,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:u.name||"",onChange:d=>N({...u,name:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:u.type||"text",onChange:d=>N({...u,type:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(p==null?void 0:p.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),u.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:u.api_url||"",onChange:d=>N({...u,api_url:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxsLine truncated
卡号1:密码1
卡号2:密码2
或者
兑换码1
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:u.data_content?u.data_content.split(`
`).filter(d=>d.trim()).length:0})," 条"]})]})]}),u.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:u.image_url||"",onChange:d=>N({...u,image_url:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),u.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:u.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:d=>{d.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:u.delay_seconds||0,onChange:d=>N({...u,delay_seconds:parseInt(d.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:u.description||"",onChange:d=>N({...u,description:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>N({...u,enabled:!u.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${u.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${u.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>l(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:K,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(et,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),n&&Te.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>m(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(Ie,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:x.name,onChange:d=>g({...x,name:d.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>g({...x,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${x.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(Cs,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>g({...x,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${x.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(ka,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>g({...x,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${x.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children: Line truncated
CODE-789012
...`:"请输入每次发货时发送的固定文字"}),x.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:x.content.split(`
`).filter(d=>d.trim()).length})," 条"]})]}),x.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:x.api_method,onChange:d=>g({...x,api_method:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:x.api_timeout,onChange:d=>g({...x,api_timeout:parseInt(d.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:x.api_headers,onChange:d=>g({...x,api_headers:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:x.api_params,onChange:d=>g({...x,api_params:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:x.description,onChange:d=>g({...x,description:d.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:x.delay_seconds,onChange:d=>g({...x,delay_seconds:parseInt(d.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>m(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:S,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(tt,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(Wn,{dataCards:T,downloadCardTemplate:z,...D})]})},sa="ydisks-amap-js-api",Zn="c9b68d4ce9a2a97f22a4a439404488ca";let It=null;const Yn=()=>Zn,Xn=()=>window.AMap?Promise.resolve(window.AMap):It||(It=new Promise((t,s)=>{const a=document.getElementById(sa),l=a||document.createElement("script"),n=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(p)},m=()=>{window.AMap?(n(),t(window.AMap)):(n(),s(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},p=window.setTimeout(()=>{n(),s(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=m,l.id=sa,l.async=!0,l.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(Yn())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,l.onerror=()=>{n(),s(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},a||document.head.appendChild(l)}).catch(t=>{throw It=null,t}),It),Ht=t=>Number.isFinite(t)&&t!==0,ei=t=>{var n,m;const s=Number((n=t.location)==null?void 0:n.lng),a=Number((m=t.location)==null?void 0:m.lat),l={area:String(t.adname||"").trim(),city:String(t.cityname||"").trim(),division_id:String(t.adcode||"").trim(),longitude:s,latitude:a,poi_id:String(t.id||"").trim(),poi_name:String(t.name||"").trim(),province:String(t.pname||"").trim()};return!l.division_id||!l.province||!l.city||!l.poi_id||!l.poi_name||!Ht(s)||!Ht(a)||s<-180||s>180||a<-90||a>90?null:l},ti=async(t,s)=>{if(!Ht(t)||!Ht(s)||t<-180||t>180||s<-90||s>90)throw new Error("经纬度无效");const a=await Xn();return new Promise((l,n)=>{new a.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[t,s],1e3,(p,f)=>{var N;if(p!=="complete"){if(p==="no_data"){l([]);return}n(new Error("高德地图附近地址查询失败,请稍后重试"));return}const u=(((N=f==null?void 0:f.poiList)==null?void 0:N.pois)||[]).map(ei).filter(x=>x!==null);l(u)})})},si=t=>t.find(s=>s.status==="running"||s.status==="canceling"),_s=t=>t==="running"||t==="canceling",ai=t=>!!(t!=null&&t.previ Line truncated
`),Re=new Blob(["\uFEFF"+he],{type:"text/csv;charset=utf-8"}),Qe=URL.createObjectURL(Re),Fe=document.createElement("a");Fe.href=Qe,Fe.download="批量铺货模板.csv",document.body.appendChild(Fe),Fe.click(),Fe.remove(),URL.revokeObjectURL(Qe)},St=()=>{E(c=>({...c,cookie_id:f||c.cookie_id})),G(!0)},xt=()=>{U(c=>({...c,cookie_id:f||c.cookie_id})),Z(!0)},mt=async c=>{if(!(c?f:I.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");L(!0),navigator.geolocation.getCurrentPosition(async he=>{try{const Re=await ti(he.coords.longitude,he.coords.latitude);if(!Re.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");c?(b(Re),$(Re[0])):(q(Re),d(Re[0]))}catch(Re){alert((Re==null?void 0:Re.message)||"获取发货地失败")}finally{L(!1)}},he=>{L(!1),alert(he.code===he.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},At=c=>l.filter(Q=>Q.cookie_id===c.cookie_id&&Q.item_id===c.item_id).length>0?l.filter(Q=>Q.cookie_id===c.cookie_id&&Q.item_id===c.item_id):l.filter(Q=>Q.cookie_id===c.cookie_id&&!Q.item_id),ut=r.useMemo(()=>new Map(m.map(c=>[c.id,c])),[m]),pt=r.useMemo(()=>N?s.filter(c=>c.cookie_id===N):s,[N,s]),Ye=c=>{const Q=ut.get(c),he=(Q==null?void 0:Q.remark)||(Q==null?void 0:Q.nickname);return he?`${he} · ${c.slice(0,6)}`:`账号 ${c.slice(0,8)}`},ht=c=>{const Q=ut.get(c);return(Q==null?void 0:Q.remark)||(Q==null?void 0:Q.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(ur,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:N,onChange:c=>x(c.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),m.map(c=>e.jsx("option",{value:c.id,children:Ye(c.id)},c.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(dt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:f,onChange:c=>u(c.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),m.map(c=>e.jsx("option",{value:c.id,children:Ye(c.id)},c.id))]})]})]}),e.jsxs("button",{onClick:Ae,disabled:g||!f,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(We,{className:`w-4 h-4 ${g?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:St,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(tt,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:xt,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(es,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void Y(),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-brand-highlight transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(Ft,{className:"w-4 h-4"}),oe&&["running","canceling"].includes(oe.status)?"继续批量任务":"批量铺货"]}),oe&&!["running","canceling"].includes(oe.status)&&e.jsx("button",{onClick:()=>void Ce(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[pt.map(c=>{const Q=At(c),he=Q.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex flex- Line truncated
@@ -1,20 +0,0 @@
import{j as e,r as l,c as _s,b as Ee,d as Ka}from"./react-vendor-C_od1ZSF.js";import{L as Ha,U as ua,M as xs,C as ws,B as pa,S as ha,Z as ms,a as _t,b as ks,G as Os,c as Cs,d as Ss,e as Za,f as lt,A as Ps,D as Ya,g as Ts,P as ga,h as Dt,E as ba,T as Xa,i as el,j as Ae,X as Oe,k as tl,l as sl,m as As,n as fa,o as Xe,p as Ke,q as ya,K as al,r as it,s as at,Q as Yt,t as ct,u as ft,v as Tt,R as We,w as ja,x as ll,y as Ve,z as Nt,F as Et,H as et,I as Es,J as yt,N as rl,O as nl,V as il,W as Na,Y as va,_ as _a,$ as ol,a0 as cl,a1 as Xt,a2 as qt,a3 as us,a4 as dl,a5 as xl,a6 as ps,a7 as $s,a8 as ml,a9 as ul,aa as $t,ab as Ds,ac as Qt,ad as wa,ae as pl,af as hl,ag as Ht,ah as ka,ai as gl,aj as bl,ak as fl,al as yl,am as jl,an as Nl,ao as Ms}from"./icons-vendor-BJ6r5aOc.js";import{R as Ft,B as vl,X as Bs,Y as qs,T as zt,a as _l,C as es,A as wl,b as kl,c as Cl,P as Fs,d as zs,L as Sl}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))r(n);new MutationObserver(n=>{for(const h of n)if(h.type==="childList")for(const u of h.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&r(u)}).observe(document,{childList:!0,subtree:!0});function a(n){const h={};return n.integrity&&(h.integrity=n.integrity),n.referrerPolicy&&(h.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?h.credentials="include":n.crossOrigin==="anonymous"?h.credentials="omit":h.credentials="same-origin",h}function r(n){if(n.ep)return;n.ep=!0;const h=a(n);fetch(n.href,h)}})();const Al=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),hs=({sizeClass:t="w-12 h-12",logoClassName:s="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52Line truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(ks,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:Fe,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:ne,children:"取消"}),e.jsxs("button",{onClick:c,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:ne,children:[ne?e.jsx(Ae,{className:"w-4 h-4 animate-spin"}):e.jsx(Xe,{className:"w-4 h-4"}),ne?"保存中...":"保存"]})]})})]})}),document.body)]})},bn=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],fn=t=>{const s=typeof t=="object"&&t!==null?t:{},a=Array.isArray(s.results)?s.results:[];return{total:Number(s.total||0),success_count:Number(s.success_count||0),failed_count:Number(s.failed_count||0),results:a.map(yn)}},yn=t=>{const s=typeof t=="object"&&t!==null?t:{};return{order_id:String(s.order_id||"unknown"),success:s.success===!0,message:String(s.message||"")}},jn=t=>(t==null?void 0:t.results.filter(Nn))||[],Nn=t=>!t.success,vn=(t,s)=>t!==null&&!s,_n=t=>{if(!t)return"请选择订单文件";const s=t.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(s)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},ot=(t,s)=>t===s,wn=(t,s)=>t instanceof Error&&t.message?t.message:s,kn=({filter:t,onFilterChange:s,accountFilter:a,onAccountFilterChange:r,accounts:n,accountName:h,searchText:u,onSearchChange:j})=>{const m=_=>s(_.currentTarget.dataset.status||"all"),v=_=>r(_.target.value),x=_=>j(_.target.value);return e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:bn.map(_=>e.jsx("button",{"data-status":_.key,onClick:m,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${t===_.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:_.label},_.key))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ct,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:a,onChange:v,className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),n.map(_=>e.jsx("option",{value:_.id,children:h(_.id)},_.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(Nt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:u,onChange:x,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Cn=t=>{const s=h=>{var u;t.setImportFile(((u=h.target.files)==null?void 0:u[0])||null)},a=()=>t.closeImportModal(),r=()=>void t.handleImportOrders(),n=()=>void t.handleRetryImport();return t.showImportModal?Ee.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:a,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(Oe,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:s,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xl Line truncated
VIP-002
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["预览:",a.appendPreview.length," 个有效卡密,空行自动忽略。"]})]}),a.appendError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-200 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.appendError}),e.jsx("button",{type:"button",onClick:x,disabled:a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),a.appendResult&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",a.appendResult.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:u,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),a.batchTab==="create"?e.jsxs("button",{onClick:O,disabled:!a.batchFile||a.batchBusy,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(Ae,{className:"w-4 h-4 animate-spin"}):e.jsx(Et,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:z,disabled:!a.appendTargetId||a.appendPreview.length===0||a.batchBusy||t.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(Ae,{className:"w-4 h-4 animate-spin"}):e.jsx(et,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},Rn=({type:t})=>{switch(t){case"text":return e.jsx(va,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(Na,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(il,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(ws,{className:"w-5 h-5 text-gray-500"})}},On=(t,s,a)=>{const r=a.trim().toLocaleLowerCase();return t.filter(n=>(!s||n.type===s)&&(!r||n.name.toLocaleLowerCase().includes(r)))},Ba=t=>t.split(`
`).map(s=>s.trim()).filter(Boolean),Pn=(t,s,a)=>!!(t&&Ba(s).length>0&&!a),bt=(t,s,a,r)=>t===s&&a===r,Tn=()=>{const[t,s]=l.useState([]),[a,r]=l.useState(!0),n=l.useRef(0),h=l.useRef(null),u=l.useCallback(async()=>{var v;const j=++n.current;(v=h.current)==null||v.abort();const m=new AbortController;h.current=m,r(!0);try{const x=await Is({signal:m.signal});if(j!==n.current)return;s(x)}catch(x){j===n.current&&!m.signal.aborted&&console.error("加载卡密库存失败:",x)}finally{j===n.current&&r(!1)}},[]);return l.useEffect(()=>(u(),()=>{var m;n.current+=1,(m=h.current)==null||m.abort()}),[u]),{cards:t,setCards:s,loading:a,loadCards:u}},En=t=>{const s=t.dataCards,a=t.loadCards,[r,n]=l.useState(!1),[h,u]=l.useState("create"),[j,m]=l.useState(null),[v,x]=l.useState(null),[_,w]=l.useState(!1),[O,z]=l.useState(""),[N,$]=l.useState(""),[D,Z]=l.useState(null),[Q,ae]=l.useState(""),I=l.useRef(0),P=l.useRef(null),G=l.useRef(""),q=l.useMemo(()=>Ba(N),[N]),Y=l.useCallback(()=>{var k;u("create"),m(null),x(null),z((k=s[0])!=null&&k.id?String(s[0].id):""),$(""),Z(null),ae(""),n(!0)},[s]),d=l.useCallback(()=>{var k;I.current+=1,(k=P.current)==null||k.abort(),w(!1),n(!1)},[]),U=l.useCallback(async()=>{var L;if(!j||_)return;const k=++I.current;(L=P.current)==null||L.abort();const E=new AbortController;P.current=E,w(!0),x(null);try{const F=await fr(j,{signal:E.signal});if(!bt(k,I.current,"",""))return;x(F),F.created>0&&await a()}catch(F){if(!bt(k,I.current,"",""))return;x({error:(F==null?void 0:F.message)||"上传失败"})}finally{bt(k,I.current,"","")&&w(!1)}},[_,j,a]),V=l.useCallback(async()=>{var F;if(!Pn(O,N,_))return;const k=O,E=++I.current;G.current=k,(F=P.current)==null||F.abort();const L=new AbortController;P.current=L,w(!0),Z(null),ae("");try{const B=await yr(k,N,{signal:L.signal});if(!bt(E,I.current,k,O))return;Z({added:B.added}),$(""),await a()}catch(B){if(!bt(E,I.current,k,O))return;ae((B==null?void 0:B.message)||"追加失败")}finally{bt(E,I.current,k,O)&&w(!1)}},[N,O,_,a]),R=l.useCallback(async()=>{await U()},[U]),C=l.useCallback(async()=>{G.current&&O!==G.current||await V()},[O,V]);return{showBatchModal:r,setShowBatchModal:n,batchTab:h,setBatchTab:u,batchFile:j,setBatchFile:m,batchResult:v,batchBusy:_,appendTargetId:O,setAppendTargetId:z,appendContent:N,setAppendContent:$,appendResult:D,appendError:Q,appendPreview:q,openBatchModal:Y,closeBatchModal:d,handleBatchCreate:U,handleBatchAppend:V,handleRetryBatchCreate:R,handleRetryBatchAppend:C}},Xs=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),$n=()=>{const{cards:t,loadCards:s}=Tn(),[a,r]=l.useState(!1),[n,h]=l.useState(!1),[u,j]=l.useState(null),[m,v]=l.useState({}),[x,_]=l.useState(Xs),[w,O]=l.useState(""),[z,N]=l.useState(""),$=l.useMemo(()=>t.filter(d=>d.type==="data"),[t]),D=En({dataCards:$,loadCards:s}),Z=d=>{var U,V,R,C,k;j(d),v({id:d.id,name:d.name||"",type:d.type||"text",api_url:((U=d.api_config)==null?void 0:U.url)||"",api_method:((V=d.api_config)==null?void 0:V.method)||"GET",api_timeout:((R=d.api_config)==null?void 0:R.timeout)||10,api_headers:((C=d.api_config)==null?void 0:C.headers)||"",api_params:((k=d.api_config)==null?void 0:k.params)||"",text_content:d.text_content||"",data_content:d.data_content||"",image_url:d.image_url||"",delay_seconds:d.delay_seconds||0,description:d.description||"",enabled:d.enabled}),r(!0)},Q=async()=>{var d,U,V,R,C,k,E,L;if(u){if(!((d=m.name)!=null&&d.trim())){alert("请输入卡密名称");return}if(!m.type){alert("请选择卡密类型");return}try{const F={name:m.name.trim(),type:m.type,description:(U=m.description)==null?void 0:U.trim(),delay_seconds:m.delay_seconds||0,enabled:m.enabled??!0};m.type==="api"?F.api_config={url:((V=m.api_url)==null?void 0:V.trim())||"",method:m.api_method,timeout:m.api_timeout||10,headers:((R=m.api_headers)==null?void 0:R.trim())||void 0,params:((C=m.api_params)==null?void 0:C.trim())||void 0}:m.type==="text"?F.text_content=((k=m.text_content)==null?void 0:k.trim())||"":m.type==="data"?F.data_content=((E=m.data_content)==null?void 0:E.trim())||"":m.type==="image"&&(F.image_url=((L=m.image_url)==null?void 0:L.trim())||""),await Qs(u.id,F),r(!1),await s()}catch(F){console.error("更新卡密失败:",F),alert("更新失败,请重试")}}},ae=async d=>{if(confirm("确认删除该卡密吗?"))try{await br(d),await s()}catch(U){console.error("删除卡密失败:",U),alert("删除失败,请重试")}},I=async()=>{if(!x.name.trim()){alert("请输入卡密名称");return}if(!x.content.trim()){alert(x.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const d={name:x.name.trim(),type:x.type,description:x.description.trim(),enabled:x.enabled,delay_seconds:x.delay_seconds};x.type==="text"&&(d.text_content=x.content.trim()),x.type==="data"&&(d.data_content=x.content.trim()),x.type==="image"&&(d.image_url=x.content.trim()),x.type==="api"&&(d.api_config={url:x.content.trim(),method:x.a Line truncated
VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(E=>E.map(L=>`"${String(L).replace(/"/g,'""')}"`).join(",")).join(`
`),R=new Blob(["\uFEFF"+V],{type:"text/csv;charset=utf-8"}),C=URL.createObjectURL(R),k=document.createElement("a");k.href=C,k.download="卡密组批量导入模板.csv",document.body.appendChild(k),k.click(),k.remove(),URL.revokeObjectURL(C)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:D.openBatchModal,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(Et,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>h(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(et,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(_a,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:w,onChange:d=>O(d.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(Nt,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:z,onChange:d=>N(d.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",q.length," / ",t.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:q.map(d=>{let U="";return d.type==="data"&&d.data_content?U=`库存: ${d.data_content.split(`
`).filter(R=>R.trim()).length} 条`:d.type==="text"&&d.text_content?U=d.text_content:d.type==="api"&&d.api_config?U=d.api_config.url:d.type==="image"&&d.image_url&&(U="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(Rn,{type:d.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:d.name,children:d.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>G(d.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:d.id}),e.jsx(ol,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${d.type==="text"?"bg-blue-50 text-blue-600":d.type==="data"?"bg-purple-50 text-purple-600":d.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:d.type==="text"?"文本":d.type==="data"?"批量":d.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:U,children:U})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:d.description||"-",children:d.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>P(d),className:`w-12 h-8 rounded-full relative transition-colors ${d.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${d.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>Z(d),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(yt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>ae(d.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Ve,{className:"h-4 w-4"})})]})})]},d.id)})})]})}),q.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(ga,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),a&&u&&Ee.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>r(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(Oe,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:m.name||"",onChange:d=>v({...m,name:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:m.type||"text",onChange:d=>v({...m,type:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(u==null?void 0:u.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),m.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:m.api_url||"",onChange:d=>v({...m,api_url:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxLine truncated
卡号1:密码1
卡号2:密码2
或者
兑换码1
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:m.data_content?m.data_content.split(`
`).filter(d=>d.trim()).length:0})," 条"]})]})]}),m.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:m.image_url||"",onChange:d=>v({...m,image_url:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),m.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:m.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:d=>{d.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:m.delay_seconds||0,onChange:d=>v({...m,delay_seconds:parseInt(d.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:m.description||"",onChange:d=>v({...m,description:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>v({...m,enabled:!m.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${m.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${m.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>r(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:Q,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(Xe,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),n&&Ee.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>h(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(Oe,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:x.name,onChange:d=>_({...x,name:d.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>_({...x,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${x.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(ws,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>_({...x,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${x.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(va,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>_({...x,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${x.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children: Line truncated
CODE-789012
...`:"请输入每次发货时发送的固定文字"}),x.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:x.content.split(`
`).filter(d=>d.trim()).length})," 条"]})]}),x.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:x.api_method,onChange:d=>_({...x,api_method:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:x.api_timeout,onChange:d=>_({...x,api_timeout:parseInt(d.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:x.api_headers,onChange:d=>_({...x,api_headers:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:x.api_params,onChange:d=>_({...x,api_params:d.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:x.description,onChange:d=>_({...x,description:d.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:x.delay_seconds,onChange:d=>_({...x,delay_seconds:parseInt(d.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>h(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:I,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(et,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(In,{dataCards:$,downloadCardTemplate:Y,...D})]})},ea="ydisks-amap-js-api",Dn="c9b68d4ce9a2a97f22a4a439404488ca";let Lt=null;const Mn=()=>Dn,Bn=()=>window.AMap?Promise.resolve(window.AMap):Lt||(Lt=new Promise((t,s)=>{const a=document.getElementById(ea),r=a||document.createElement("script"),n=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(u)},h=()=>{window.AMap?(n(),t(window.AMap)):(n(),s(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},u=window.setTimeout(()=>{n(),s(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=h,r.id=ea,r.async=!0,r.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(Mn())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,r.onerror=()=>{n(),s(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},a||document.head.appendChild(r)}).catch(t=>{throw Lt=null,t}),Lt),Kt=t=>Number.isFinite(t)&&t!==0,qn=t=>{var n,h;const s=Number((n=t.location)==null?void 0:n.lng),a=Number((h=t.location)==null?void 0:h.lat),r={area:String(t.adname||"").trim(),city:String(t.cityname||"").trim(),division_id:String(t.adcode||"").trim(),longitude:s,latitude:a,poi_id:String(t.id||"").trim(),poi_name:String(t.name||"").trim(),province:String(t.pname||"").trim()};return!r.division_id||!r.province||!r.city||!r.poi_id||!r.poi_name||!Kt(s)||!Kt(a)||s<-180||s>180||a<-90||a>90?null:r},Fn=async(t,s)=>{if(!Kt(t)||!Kt(s)||t<-180||t>180||s<-90||s>90)throw new Error("经纬度无效");const a=await Bn();return new Promise((r,n)=>{new a.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[t,s],1e3,(u,j)=>{var v;if(u!=="complete"){if(u==="no_data"){r([]);return}n(new Error("高德地图附近地址查询失败,请稍后重试"));return}const m=(((v=j==null?void 0:j.poiList)==null?void 0:v.pois)||[]).map(qn).filter(x=>x!==null);r(m)})})},zn=t=>t.find(s=>s.status==="running"||s.status==="canceling"),Ns=t=>t==="running"||t==="canceling",Un=t=>!!(t!=null&&t.previ Line truncated
`),Pe=new Blob(["\uFEFF"+ge],{type:"text/csv;charset=utf-8"}),Qe=URL.createObjectURL(Pe),Fe=document.createElement("a");Fe.href=Qe,Fe.download="批量铺货模板.csv",document.body.appendChild(Fe),Fe.click(),Fe.remove(),URL.revokeObjectURL(Qe)},Ct=()=>{E(c=>({...c,cookie_id:j||c.cookie_id})),Z(!0)},dt=()=>{F(c=>({...c,cookie_id:j||c.cookie_id})),ae(!0)},xt=async c=>{if(!(c?j:L.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");P(!0),navigator.geolocation.getCurrentPosition(async ge=>{try{const Pe=await Fn(ge.coords.longitude,ge.coords.latitude);if(!Pe.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");c?(y(Pe),T(Pe[0])):(q(Pe),d(Pe[0]))}catch(Pe){alert((Pe==null?void 0:Pe.message)||"获取发货地失败")}finally{P(!1)}},ge=>{P(!1),alert(ge.code===ge.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},St=c=>r.filter(W=>W.cookie_id===c.cookie_id&&W.item_id===c.item_id).length>0?r.filter(W=>W.cookie_id===c.cookie_id&&W.item_id===c.item_id):r.filter(W=>W.cookie_id===c.cookie_id&&!W.item_id),mt=l.useMemo(()=>new Map(h.map(c=>[c.id,c])),[h]),ut=l.useMemo(()=>v?s.filter(c=>c.cookie_id===v):s,[v,s]),Ze=c=>{const W=mt.get(c),ge=(W==null?void 0:W.remark)||(W==null?void 0:W.nickname);return ge?`${ge} · ${c.slice(0,6)}`:`账号 ${c.slice(0,8)}`},pt=c=>{const W=mt.get(c);return(W==null?void 0:W.remark)||(W==null?void 0:W.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(cl,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:v,onChange:c=>x(c.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),h.map(c=>e.jsx("option",{value:c.id,children:Ze(c.id)},c.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(ct,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:j,onChange:c=>m(c.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),h.map(c=>e.jsx("option",{value:c.id,children:Ze(c.id)},c.id))]})]})]}),e.jsxs("button",{onClick:Le,disabled:_||!j,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(We,{className:`w-4 h-4 ${_?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:Ct,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(et,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:dt,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(Xt,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void ee(),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-brand-highlight transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(qt,{className:"w-4 h-4"}),ie&&["running","canceling"].includes(ie.status)?"继续批量任务":"批量铺货"]}),ie&&!["running","canceling"].includes(ie.status)&&e.jsx("button",{onClick:()=>void Se(),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[ut.map(c=>{const W=St(c),ge=W.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative flex fle Line truncated
@@ -1 +1 @@
*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(147 197 253 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(147 197 253 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:rgb(var(--color-neutral-200) / 1)}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:rgb(var(--color-neutral-400) / 1)}input::placeholder,textarea::placeholder{opacity:1;color:rgb(var(--color-neutral-400) / 1)}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.\!container{width:100%!important}.container{width:100%}@media(min-width:640px){.\!container{max-width:640px!important}.container{max-width:6Line truncated
*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(147 197 253 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(147 197 253 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:rgb(var(--color-neutral-200) / 1)}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:rgb(var(--color-neutral-400) / 1)}input::placeholder,textarea::placeholder{opacity:1;color:rgb(var(--color-neutral-400) / 1)}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.\!container{width:100%!important}.container{width:100%}@media(min-width:640px){.\!container{max-width:640px!important}.container{max-width:6Line truncated
+3 -3
View File
@@ -6,12 +6,12 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ydisks闲鱼助手 - 自动发货与管家系统</title>
<meta name="description" content="Ydisks闲鱼助手 - 自动回复、自动发货、订单管理、AI智能议价一体化解决方案" />
<script type="module" crossorigin src="/static/assets/index-CdHtgMYc.js"></script>
<script type="module" crossorigin src="/static/assets/index-CEH5GXBq.js"></script>
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-C_od1ZSF.js">
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-BJ6r5aOc.js">
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-i_74xDZy.js">
<link rel="modulepreload" crossorigin href="/static/assets/vendor-D-Edl3pr.js">
<link rel="modulepreload" crossorigin href="/static/assets/charts-vendor-BxxJOyEX.js">
<link rel="stylesheet" crossorigin href="/static/assets/index-Cot5X9Jj.css">
<link rel="stylesheet" crossorigin href="/static/assets/index-CstHnrBD.css">
</head>
<body>
<div id="root"></div>