Compare commits

..
2 Commits
Author SHA1 Message Date
Christ c3020bde09 修复:优化二维码风控登录与批量发布兼容性
- 优化二维码登录风控提示,支持人脸验证二维码和验证截图。

- 修复批量发布发货地持久化,并兼容旧任务地址格式。

- 加强二维码登录和通知渠道的敏感数据保护。

- 补充登录风控使用说明。
2026-08-19 22:50:03 +08:00
Christ c1282dfa4e 发布 v1.0.2
## 账号与登录

- 优化二维码登录、扫码验证和密码登录流程。
- 改善账号启用、停用、重启及 Cookie 更新后的运行状态同步。
- 完善登录失败、凭证失效和账号恢复处理。
- 增加敏感设置访问记录,提升账号安全性。

## 聊天功能

- 增加全局未读消息提示。
- 支持聊天图片预览和原始尺寸发送。
- 优化消息已读状态同步。
- 修复聊天状态、验证码验证和图片卡密发送问题。
- 优化自动化消息延迟处理。

## 订单与发货

- 优化订单刷新、导入、更新、删除和详情查询。
- 提升订单批量处理和订单详情保存效率。
- 改善订单刷新失败、取消和重复操作时的状态处理。
- 完善手动发货及异常情况下的恢复处理。

## 商品、卡密与自动化

- 增加批量铺货发布间隔控制。
- 优化商品多规格识别。
- 改善卡密库存、批量追加、发送和失败重试。
- 优化自动化规则、发货动作和通知处理。
- 完善通知渠道及 SMTP 配置相关功能。

## 前端体验

- 重构账号、商品、订单、聊天、通知、设置、规则和仪表盘页面。
- 优化页面加载、批量操作、任务轮询和错误提示。
- 改善请求取消、超时和页面切换时的数据刷新体验。
- 补充空状态、异常状态和登录过程中的页面反馈。

## 数据库与部署

- 完善 SQLite、MySQL 和 PostgreSQL 支持。
- 修复 MySQL 数据库迁移回滚问题。
- 优化数据库升级、订单保存和多数据库兼容性。
2026-08-19 13:04:47 +08:00
33 changed files with 855 additions and 99 deletions

No files matched your search

+5
View File
@@ -19,6 +19,10 @@
> 本项目是社区维护的非官方工具,与闲鱼、阿里巴巴集团及其关联公司无隶属、合作或 > 本项目是社区维护的非官方工具,与闲鱼、阿里巴巴集团及其关联公司无隶属、合作或
> 授权关系。请仅在遵守当地法律法规、闲鱼平台规则及账号授权范围的前提下使用。 > 授权关系。请仅在遵守当地法律法规、闲鱼平台规则及账号授权范围的前提下使用。
> 使用自动化能力可能触发平台风控,请自行评估风险并妥善保护账号凭证。 > 使用自动化能力可能触发平台风控,请自行评估风险并妥善保护账号凭证。
>
> **有账号登录时,不要频繁重启本程序!**
>
> **每次重启都会向闲鱼申请登录凭证,达到某个频率,即会触发风控。**
## 项目简介 ## 项目简介
@@ -713,6 +717,7 @@ go run ./cmd/server -init-admin -db data/xianyu_data.db -admin-password '新密
- 根据页面二维码在闲鱼 App 完成人脸或安全验证。 - 根据页面二维码在闲鱼 App 完成人脸或安全验证。
- 检查服务器时间、时区和外网连接是否正常。 - 检查服务器时间、时区和外网连接是否正常。
- 不要同时在多个实例中运行同一个闲鱼账号,避免凭证相互覆盖。 - 不要同时在多个实例中运行同一个闲鱼账号,避免凭证相互覆盖。
- 若一直提示需要安全验证,请清除账号登录凭证,停用账号。登录闲鱼官方Web版,打开消息页面后,人工通过风控后等待一会儿后再尝试登录。
### 修改 `XIANYU_DATA_KEY` 后无法读取凭证 ### 修改 `XIANYU_DATA_KEY` 后无法读取凭证
+38
View File
@@ -340,3 +340,41 @@ $ git diff --check
``` ```
- 外部环境:2026-08-19 使用 Docker 29.4.0 临时启动 `mysql:8` 与 `postgres:17`,均绑定到本机回环地址并通过就绪检查;真实 Chromium 集成、MySQL/PostgreSQL 多方言回归和两个 `cmd/dbverify` 均已执行且通过。多数据库测试创建并清理独立 `xytest_*` 数据库,验收结束后已删除两个临时容器。未执行真实账号登录或外部平台调用。`cover.out`、`cover-browser.out` 和 `frontend/coverage/` 是生成验证产物,未纳入提交。 - 外部环境:2026-08-19 使用 Docker 29.4.0 临时启动 `mysql:8` 与 `postgres:17`,均绑定到本机回环地址并通过就绪检查;真实 Chromium 集成、MySQL/PostgreSQL 多方言回归和两个 `cmd/dbverify` 均已执行且通过。多数据库测试创建并清理独立 `xytest_*` 数据库,验收结束后已删除两个临时容器。未执行真实账号登录或外部平台调用。`cover.out`、`cover-browser.out` 和 `frontend/coverage/` 是生成验证产物,未纳入提交。
### 2026-08-19 阶段六二维码风控状态 DTO 完整性修复
- 交付范围:`publicQRStatus` 将底层二维码会话已生成的 `face_qr_url` 和 `verification_screenshot` 显式映射到具名 HTTP DTO;前端共享二维码状态契约同步声明这两个展示字段,账号 feature 的轮询类型经自身 API adapter 派生,避免共享 transport DTO 与 feature 类型漂移。
- 敏感数据边界:未重新暴露 `cookies`、`cookie_snapshot`、`unb` 或 `verification_url`。其中验证链接不属于 UI 消费字段,且既有前端契约明确禁止渲染;人脸二维码优先展示,截图只作为兜底。
- 回归保护:服务端契约测试同时断言二维码和截图透传、Cookie 脱敏;前端轮询与 Hook 测试仅使用当前公开状态字段;版本化与兼容路由继续复用同一 handler。
- 冻结边界:未修改 `internal/browser/slider.go`、`token_captcha*.go`、其测试或冻结规范。
### 本次验收
```text
$ go test ./internal/server ./internal/xianyu/qrlogin -count=1
ok xianyu-go/internal/server
ok xianyu-go/internal/xianyu/qrlogin
$ npm test --prefix frontend -- --run
Test Files 67 passed (67)
Tests 405 passed (405)
$ npm run typecheck --prefix frontend
(无输出,退出码 0)
$ npm run comments:check --prefix frontend && make comments
Go/前端 commentlint 均通过。
$ npm run build --prefix frontend
✓ built in 2.76s;已重建 internal/webui/static。
$ go run ./tools/architecturecheck && git diff --check
architecturecheck: 通过;git diff --check 无输出。
```
### 2026-08-19 阶段六前后端 DTO 字段完整性门禁
- 审计范围:共享 `frontend/shared/api-contract/transport.ts` 的全部导出对象 DTO,以及每个 `frontend/app/features/*/api.ts` 中的响应形态 DTO;健康检查 `BuildInfo` 也显式登记。门禁要求每个 DTO 都在 `frontendDTOContractSpecs` 登记,直接 HTTP DTO 的每个顶层字段必须在 `internal/server` 对应具名结构体中以 JSON 标签提供。
- 解析边界:门禁会展开 TypeScript `extends` 字段和 Go 匿名嵌入 DTO 字段,避免订单详情等兼容顶层字段产生误报;嵌套对象字段单独属于其行 DTO,不被错误归入外层响应。动态键、feature 归一化和脱敏模型必须逐项写明理由,不能静默跳过。
- 修复结果:二维码风控状态已补齐 `verification_screenshot` 和 `face_qr_url`;删除卡券时间字段、账号 AI 模型/密钥字段、通知渠道配置与时间字段等服务端从未提供且前端不消费的历史契约。通知渠道列表继续不返回配置,避免 SMTP 等秘密穿透摘要 DTO;编辑器用空配置初始化。
- 回归保护:新增真实临时仓库夹具测试,确认遗漏后端字段会触发门禁;新增匿名嵌入解析测试。冻结滑块验证码实现及其调用语义未修改。
+9 -9
View File
@@ -17,6 +17,13 @@ QRLoginGenerateResponse,QRLoginStatusResponse,QRLoginVerificationResponse
import { del,get,post,put,type RequestControlOptions } from '../../../shared/http/client'; import { del,get,post,put,type RequestControlOptions } from '../../../shared/http/client';
import { collectionFrom,objectFrom } from '../../../shared/http/contract'; import { collectionFrom,objectFrom } from '../../../shared/http/contract';
export type * from '../../../shared/api-contract/accounts'; export type * from '../../../shared/api-contract/accounts';
// QRLoginStatusResult 描述账号 feature 消费的非敏感二维码状态字段。
export type QRLoginStatusResult = Pick<
QRLoginStatusResponse,
'status' | 'message' | 'session_id' | 'account_id' | 'is_new_account' | 'verification_screenshot' | 'face_qr_url'
>;
// Accounts // Accounts
// addAccount 新增账号。 // addAccount 新增账号。
export const addAccount = async (id: string, value: string, loginMethod?: string): Promise<OperationResponse> => { export const addAccount = async (id: string, value: string, loginMethod?: string): Promise<OperationResponse> => {
@@ -294,13 +301,8 @@ export const getNotificationChannels = async (options?: RequestControlOptions):
const result = await get<unknown>('/api/v1/notifications/channels', undefined, options); const result = await get<unknown>('/api/v1/notifications/channels', undefined, options);
// channels 通知渠道列表,用于当前 API 处理流程。 // channels 通知渠道列表,用于当前 API 处理流程。
const channels = collectionFrom<NotificationChannelResponse>(result, ['data', 'channels', 'items']).map(/* 当前回调用于处理集合元素或接口响应。 */ (item: NotificationChannelResponse) => { const channels = collectionFrom<NotificationChannelResponse>(result, ['data', 'channels', 'items']).map(/* 当前回调用于处理集合元素或接口响应。 */ (item: NotificationChannelResponse) => {
// parsedConfig 解析后的通知配置,用于当前 API 处理流程。 // parsedConfig 是列表摘要刻意不返回渠道秘密时使用的空编辑初始值。
let parsedConfig; const parsedConfig: Record<string, unknown> = {};
try {
parsedConfig = typeof item.config === 'string' ? JSON.parse(item.config) : item.config;
} catch {
parsedConfig = {};
}
// normalizedType 是兼容旧渠道别名后的前端渠道类型。 // normalizedType 是兼容旧渠道别名后的前端渠道类型。
const normalizedType = (item.type === 'ding_talk' ? 'dingtalk' : (item.type === 'lark' ? 'feishu' : item.type)) as NotificationChannel['type']; const normalizedType = (item.type === 'ding_talk' ? 'dingtalk' : (item.type === 'lark' ? 'feishu' : item.type)) as NotificationChannel['type'];
return { return {
@@ -310,8 +312,6 @@ export const getNotificationChannels = async (options?: RequestControlOptions):
config: parsedConfig, config: parsedConfig,
event_types: parseNotificationEventTypes(item.event_types), event_types: parseNotificationEventTypes(item.event_types),
enabled: item.enabled, enabled: item.enabled,
created_at: item.created_at,
updated_at: item.updated_at,
}; };
}); });
return { success: true, data: channels }; return { success: true, data: channels };
@@ -59,7 +59,7 @@ describe('useAccountQRCodeLogin 二维码登录协调器', /* 当前回调验证
expect(hook.result.current.qrStatus).toBe('waiting'); expect(hook.result.current.qrStatus).toBe('waiting');
expect(hook.result.current.qrCodeUrl).toBe('qr-url'); expect(hook.result.current.qrCodeUrl).toBe('qr-url');
qrLoginMocks.checkQRLoginStatus.mockResolvedValueOnce({ status: 'success', cookies: 'a=b', unb: 'user-1' }); qrLoginMocks.checkQRLoginStatus.mockResolvedValueOnce({ status: 'success' });
await act(/* pollAction 触发二维码状态轮询。 */ async () => { await act(/* pollAction 触发二维码状态轮询。 */ async () => {
await vi.advanceTimersByTimeAsync(2000); await vi.advanceTimersByTimeAsync(2000);
await flushMicrotasks(); await flushMicrotasks();
+1 -1
View File
@@ -111,7 +111,7 @@ export const useAccountQRCodeLogin = ({ onLoginSuccess }: AccountQRCodeLoginOpti
// response 保存风控验证完成接口返回值。 // response 保存风控验证完成接口返回值。
const response = await completeQRVerification(sessionId, target?.id); const response = await completeQRVerification(sessionId, target?.id);
if (!response.success || !response.account_id) { if (!response.success || !response.account_id) {
throw new Error(response.message || '保存扫码授权失败'); throw new Error('保存扫码授权失败');
} }
return response.account_id; return response.account_id;
}; };
@@ -36,7 +36,7 @@ test('QR poller stops on success and terminal errors', /* 当前回调处理用
vi.useFakeTimers(); vi.useFakeTimers();
// checkStatus check状态,负责当前功能中的对应处理。 // checkStatus check状态,负责当前功能中的对应处理。
const checkStatus = vi.fn() const checkStatus = vi.fn()
.mockResolvedValueOnce({ status: 'success', cookies: 'a=b', unb: 'acc1' }) .mockResolvedValueOnce({ status: 'success' })
.mockResolvedValueOnce({ status: 'expired' }); .mockResolvedValueOnce({ status: 'expired' });
// onSuccess 响应当前用户操作(Success)。 // onSuccess 响应当前用户操作(Success)。
const onSuccess = vi.fn(); const onSuccess = vi.fn();
@@ -53,7 +53,7 @@ test('QR poller stops on success and terminal errors', /* 当前回调处理用
await vi.advanceTimersByTimeAsync(2000); await vi.advanceTimersByTimeAsync(2000);
await flushMicrotasks(); await flushMicrotasks();
expect(onSuccess).toHaveBeenCalledWith({ status: 'success', cookies: 'a=b', unb: 'acc1' }); expect(onSuccess).toHaveBeenCalledWith({ status: 'success' });
expect(poller.isActive()).toBe(false); expect(poller.isActive()).toBe(false);
await vi.advanceTimersByTimeAsync(4000); await vi.advanceTimersByTimeAsync(4000);
expect(checkStatus).toHaveBeenCalledTimes(1); expect(checkStatus).toHaveBeenCalledTimes(1);
@@ -76,7 +76,6 @@ test('QR poller keeps polling during verification and stops on thrown errors', /
const checkStatus = vi.fn() const checkStatus = vi.fn()
.mockResolvedValueOnce({ .mockResolvedValueOnce({
status: 'verification_required', status: 'verification_required',
verification_url: 'https://verify.example',
face_qr_url: 'https://face.example', face_qr_url: 'https://face.example',
}) })
.mockRejectedValueOnce(new Error('network down')); .mockRejectedValueOnce(new Error('network down'));
+1 -15
View File
@@ -1,18 +1,4 @@
// QRLoginStatusResult 描述二维码登录状态接口返回的可选字段。 import type { QRLoginStatusResult } from './api';
export interface QRLoginStatusResult {
// status 表示当前二维码登录状态。
status?: string;
// cookies 表示登录成功后返回的凭证字符串。
cookies?: string;
// unb 表示闲鱼账号的用户标识。
unb?: string;
// verification_url 表示风控验证地址。
verification_url?: string;
// verification_screenshot 表示风控验证截图地址。
verification_screenshot?: string;
// face_qr_url 表示人脸验证二维码地址。
face_qr_url?: string;
}
// QRLoginPollerTimers 描述轮询器使用的定时器依赖,便于测试替换时间源。 // QRLoginPollerTimers 描述轮询器使用的定时器依赖,便于测试替换时间源。
interface QRLoginPollerTimers { interface QRLoginPollerTimers {
@@ -26,8 +26,6 @@ const cardFixture: Card = {
description: '测试库存', description: '测试库存',
enabled: true, enabled: true,
delay_seconds: 0, delay_seconds: 0,
created_at: '2026-08-15T00:00:00Z',
updated_at: '2026-08-15T00:00:00Z',
}; };
// textCardFixture 表示用于筛选和新增测试的文本类型卡密组。 // textCardFixture 表示用于筛选和新增测试的文本类型卡密组。
+1 -1
View File
@@ -19,7 +19,7 @@ const batchCreateMock = vi.mocked(batchCreateCards);
const getCardsMock = vi.mocked(getCards); const getCardsMock = vi.mocked(getCards);
// cardFixture 是 data 类型卡密组的完整测试对象。 // cardFixture 是 data 类型卡密组的完整测试对象。
const cardFixture: Card = { id: 1, name: '库存一', type: 'data', enabled: true, data_content: 'old', created_at: '2026-01-01', updated_at: '2026-01-01' }; const cardFixture: Card = { id: 1, name: '库存一', type: 'data', enabled: true, data_content: 'old' };
// loadCardsFixture 是批量操作完成后的库存刷新替身。 // loadCardsFixture 是批量操作完成后的库存刷新替身。
const loadCardsFixture = vi.fn().mockResolvedValue(undefined); const loadCardsFixture = vi.fn().mockResolvedValue(undefined);
@@ -66,8 +66,6 @@ const cardFixture: Card = {
description: '测试库存', description: '测试库存',
enabled: true, enabled: true,
delay_seconds: 0, delay_seconds: 0,
created_at: '2026-08-15T00:00:00Z',
updated_at: '2026-08-15T00:00:00Z',
}; };
// textCardFixture 表示卡密页面中的文本类型卡密组。 // textCardFixture 表示卡密页面中的文本类型卡密组。
+3 -10
View File
@@ -39,18 +39,11 @@ const stringifyNotificationEventTypes = (eventTypes?: NotificationEventType[]):
/** 把后端渠道 DTO 转换为通知编辑器使用的 UI 模型。 */ /** 把后端渠道 DTO 转换为通知编辑器使用的 UI 模型。 */
const toNotificationChannel = (channel: NotificationChannelResponse): NotificationChannel => { const toNotificationChannel = (channel: NotificationChannelResponse): NotificationChannel => {
// config 是解析失败时降级为空对象的渠道配置。 // config 是列表摘要不返回 SMTP 等秘密时使用的空编辑初始值。
let config: Record<string, unknown> = {}; const config: Record<string, unknown> = {};
try {
// parsed 是配置文本解析后的未知 JSON 值。
const parsed: unknown = typeof channel.config === 'string' ? JSON.parse(channel.config) : channel.config;
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) config = parsed as Record<string, unknown>;
} catch {
// 历史损坏配置不阻止用户继续编辑渠道。
}
// type 是处理 ding_talk/lark 历史别名后的渠道类型。 // type 是处理 ding_talk/lark 历史别名后的渠道类型。
const type = (channel.type === 'ding_talk' ? 'dingtalk' : channel.type === 'lark' ? 'feishu' : channel.type) as NotificationChannel['type']; const type = (channel.type === 'ding_talk' ? 'dingtalk' : channel.type === 'lark' ? 'feishu' : channel.type) as NotificationChannel['type'];
return { id: String(channel.id), name: channel.name, type, config, event_types: parseNotificationEventTypes(channel.event_types), enabled: channel.enabled, created_at: channel.created_at, updated_at: channel.updated_at }; return { id: String(channel.id), name: channel.name, type, config, event_types: parseNotificationEventTypes(channel.event_types), enabled: channel.enabled };
}; };
/** 获取全部通知渠道并转换为编辑器模型。 */ /** 获取全部通知渠道并转换为编辑器模型。 */
+7 -27
View File
@@ -296,10 +296,6 @@ export interface Card {
spec_name?: string; spec_name?: string;
/** 规格值。 */ /** 规格值。 */
spec_value?: string; spec_value?: string;
/** 卡券组创建时间。 */
created_at: string;
/** 卡券组更新时间。 */
updated_at: string;
} }
// Items // Items
@@ -328,8 +324,6 @@ export interface Item {
multi_quantity_delivery?: number | boolean; multi_quantity_delivery?: number | boolean;
/** 是否启用多数量发货兼容字段。 */ /** 是否启用多数量发货兼容字段。 */
is_multi_qty_ship?: number | boolean; is_multi_qty_ship?: number | boolean;
/** 商品创建时间。 */
created_at?: string;
} }
export type AutomationTriggerType = 'order_paid' | 'buyer_reviewed' | 'review_missing_timeout'; export type AutomationTriggerType = 'order_paid' | 'buyer_reviewed' | 'review_missing_timeout';
@@ -536,12 +530,6 @@ export interface SystemSettings {
export interface AIReplySettings { export interface AIReplySettings {
/** 是否启用账号 AI 回复。 */ /** 是否启用账号 AI 回复。 */
ai_enabled: boolean; ai_enabled: boolean;
/** 账号使用的模型名称。 */
model_name?: string;
/** 账号 AI API 密钥。 */
api_key?: string;
/** 账号 AI 基础地址。 */
base_url?: string;
/** 最大折扣比例。 */ /** 最大折扣比例。 */
max_discount_percent: number; max_discount_percent: number;
/** 最大折扣金额。 */ /** 最大折扣金额。 */
@@ -1211,18 +1199,12 @@ export interface NotificationChannelResponse {
name: string; name: string;
/** 通知渠道类型。 */ /** 通知渠道类型。 */
type: string; type: string;
/** 通知渠道配置 JSON。 */ /** 订阅事件类型 JSON 或兼容文本。 */
config: string; event_types?: string;
/** 订阅事件类型 JSON 或兼容文本。 */
event_types?: string;
/** 通知渠道是否启用。 */ /** 通知渠道是否启用。 */
enabled: boolean; enabled: boolean;
/** 所属用户主键。 */ /** 所属用户主键。 */
user_id?: number; user_id?: number;
/** 创建时间;旧接口可能省略。 */
created_at?: string;
/** 更新时间;旧接口可能省略。 */
updated_at?: string;
} }
/** 卡券列表接口的兼容包装响应。 */ /** 卡券列表接口的兼容包装响应。 */
@@ -1507,11 +1489,13 @@ export interface QRLoginGenerateResponse {
export interface QRLoginStatusResponse { export interface QRLoginStatusResponse {
/** 当前二维码会话状态。 */ /** 当前二维码会话状态。 */
status: string; status: string;
/** 风控验证页面截图地址,在人脸二维码不可用时作为展示兜底。 */
verification_screenshot?: string;
/** 闲鱼人脸风控验证二维码地址,验证页面优先展示。 */
face_qr_url?: string;
/** 扫码登录会话标识。 */ /** 扫码登录会话标识。 */
session_id?: string; session_id?: string;
/** 平台账号标识。 */ /** 持久化后的本地账号标识。 */
unb?: string;
/** 持久化后的本地账号标识。 */
account_id?: string; account_id?: string;
/** 是否新建了本地账号。 */ /** 是否新建了本地账号。 */
is_new_account?: boolean; is_new_account?: boolean;
@@ -1531,10 +1515,6 @@ export interface QRLoginVerificationResponse {
account_id?: string; account_id?: string;
/** 是否新建了本地账号。 */ /** 是否新建了本地账号。 */
is_new_account?: boolean; is_new_account?: boolean;
/** 扫码账号与目标账号不一致时的提示标识。 */
scanned_account_id?: string;
/** 验证结果提示文本。 */
message?: string;
} }
/** 订单列表刷新逐项结果。 */ /** 订单列表刷新逐项结果。 */
+36
View File
@@ -277,12 +277,48 @@ func batchPublishLocation(raw string) (*mtop.PublishLocation, error) {
if decodeErr := json.Unmarshal([]byte(raw), &location); decodeErr != nil { if decodeErr := json.Unmarshal([]byte(raw), &location); decodeErr != nil {
return nil, errors.New("批量任务发货地配置损坏,请重新创建任务") return nil, errors.New("批量任务发货地配置损坏,请重新创建任务")
} }
if strings.TrimSpace(location.DivisionID) == "" {
// legacyLocation 保存 v1.0.2 曾持久化的 PascalCase 发货地格式,仅用于恢复和重试已有批次。
var legacyLocation legacyBatchPublishLocation
// legacyDecodeErr 保存历史格式 JSON 的解码错误;当前格式已成功解码时才尝试此兼容分支。
if legacyDecodeErr := json.Unmarshal([]byte(raw), &legacyLocation); legacyDecodeErr != nil {
return nil, errors.New("批量任务发货地配置损坏,请重新创建任务")
}
if strings.TrimSpace(legacyLocation.DivisionID) != "" {
location = mtop.PublishLocation{
Area: legacyLocation.Area, City: legacyLocation.City, DivisionID: legacyLocation.DivisionID,
Longitude: legacyLocation.Longitude, Latitude: legacyLocation.Latitude, POIID: legacyLocation.POIID,
POIName: legacyLocation.POIName, Province: legacyLocation.Province,
}
}
}
if strings.TrimSpace(location.DivisionID) == "" { if strings.TrimSpace(location.DivisionID) == "" {
return nil, nil return nil, nil
} }
return &location, nil return &location, nil
} }
// legacyBatchPublishLocation 保存 v1.0.2 因应用模型缺少 JSON 标签而写入数据库的历史发货地格式。
// 该类型只用于读取旧批次;新批次始终使用 snake_case 字段,避免再次扩大持久化兼容面。
type legacyBatchPublishLocation struct {
// Area 保存历史批次的区县名称。
Area string `json:"Area"`
// City 保存历史批次的城市名称。
City string `json:"City"`
// DivisionID 保存历史批次的平台行政区划标识。
DivisionID string `json:"DivisionID"`
// Longitude 保存历史批次的经度。
Longitude float64 `json:"Longitude"`
// Latitude 保存历史批次的纬度。
Latitude float64 `json:"Latitude"`
// POIID 保存历史批次的地图兴趣点标识。
POIID string `json:"POIID"`
// POIName 保存历史批次的地图兴趣点名称。
POIName string `json:"POIName"`
// Province 保存历史批次的省份名称。
Province string `json:"Province"`
}
// batchPublishCategory 解析批次默认类目并校验平台必需字段。 // batchPublishCategory 解析批次默认类目并校验平台必需字段。
func batchPublishCategory(raw string) (*mtop.PublishCategory, error) { func batchPublishCategory(raw string) (*mtop.PublishCategory, error) {
if strings.TrimSpace(raw) == "" || strings.TrimSpace(raw) == "{}" { if strings.TrimSpace(raw) == "" || strings.TrimSpace(raw) == "{}" {
+23 -1
View File
@@ -2,6 +2,7 @@ package adapter
import ( import (
"context" "context"
"encoding/json"
"testing" "testing"
"time" "time"
@@ -35,8 +36,15 @@ func TestItemBatchPublishPortPersistsRemoteCheckpoint(t *testing.T) {
if adminErr != nil { if adminErr != nil {
t.Fatalf("读取测试用户失败: %v", adminErr) t.Fatalf("读取测试用户失败: %v", adminErr)
} }
// location 保存实物商品最终 MTOP 请求必须携带的批次发货地。
location := mtop.PublishLocation{Area: "西湖区", City: "杭州市", DivisionID: "330106", Longitude: 120.118, Latitude: 30.259, POIID: "B0FFG7", POIName: "西湖文化广场", Province: "浙江省"}
// locationJSON 保存 worker 重启后还原发货地使用的批次 JSON。
locationJSON, locationErr := json.Marshal(location)
if locationErr != nil {
t.Fatalf("序列化测试发货地失败: %v", locationErr)
}
// batch 保存待发布的批次配置。 // batch 保存待发布的批次配置。
batch := &db.ItemPublishBatch{ID: "batch-remote-port", UserID: admin.ID, DefaultCookieID: "cid", UploadDir: t.TempDir(), LocationJSON: `{"division_id":"330100"}`, Status: "pending"} batch := &db.ItemPublishBatch{ID: "batch-remote-port", UserID: admin.ID, DefaultCookieID: "cid", UploadDir: t.TempDir(), LocationJSON: string(locationJSON), Status: "pending"}
// rows 保存待发布的单条明细。 // rows 保存待发布的单条明细。
rows := []db.ItemPublishBatchRow{{RowNo: 1, CookieID: "cid", Title: "批量商品", Description: "批量描述", Price: "12.50", Quantity: 2, PostageMode: "free", ImagesJSON: `["a.png"]`, CategoryJSON: `{"cat_id":"1","cat_name":"类目","channel_cat_id":"2"}`, Status: "pending"}} rows := []db.ItemPublishBatchRow{{RowNo: 1, CookieID: "cid", Title: "批量商品", Description: "批量描述", Price: "12.50", Quantity: 2, PostageMode: "free", ImagesJSON: `["a.png"]`, CategoryJSON: `{"cat_id":"1","cat_name":"类目","channel_cat_id":"2"}`, Status: "pending"}}
// createErr 保存批次写入错误。 // createErr 保存批次写入错误。
@@ -68,6 +76,9 @@ func TestItemBatchPublishPortPersistsRemoteCheckpoint(t *testing.T) {
if cookies == "" || request.PriceCents != 1250 || request.Quantity != 2 || len(request.Images) != 1 { if cookies == "" || request.PriceCents != 1250 || request.Quantity != 2 || len(request.Images) != 1 {
t.Fatalf("平台请求字段异常: cookies=%q price=%d quantity=%d images=%d", cookies, request.PriceCents, request.Quantity, len(request.Images)) t.Fatalf("平台请求字段异常: cookies=%q price=%d quantity=%d images=%d", cookies, request.PriceCents, request.Quantity, len(request.Images))
} }
if request.Location == nil || *request.Location != location {
t.Fatalf("平台请求未携带完整发货地: location=%+v want=%+v", request.Location, location)
}
return &mtop.PublishItemResult{ItemID: "remote-item", ItemURL: "https://example.test/item/remote-item", Title: "批量商品", PriceText: "12.50", Quantity: 2, UpdatedCookies: "unb=2; _m_h5_tk=next"}, nil return &mtop.PublishItemResult{ItemID: "remote-item", ItemURL: "https://example.test/item/remote-item", Title: "批量商品", PriceText: "12.50", Quantity: 2, UpdatedCookies: "unb=2; _m_h5_tk=next"}, nil
}} }}
// port 是绑定测试数据库、平台替身和图片回调的批量远端适配器。 // port 是绑定测试数据库、平台替身和图片回调的批量远端适配器。
@@ -114,3 +125,14 @@ func TestItemBatchPublishPortRejectsMissingDependencies(t *testing.T) {
t.Fatal("缺少数据库时不应伪装批量远端发布成功") t.Fatal("缺少数据库时不应伪装批量远端发布成功")
} }
} }
// TestBatchPublishLocationSupportsV102JSON 验证 v1.0.2 已持久化批次在重试时仍会恢复完整发货地。
func TestBatchPublishLocationSupportsV102JSON(t *testing.T) {
// raw 保存 v1.0.2 缺少 JSON 标签时由编码器生成的 PascalCase 发货地 JSON。
raw := `{"Area":"西湖区","City":"杭州市","DivisionID":"330106","Longitude":120.118,"Latitude":30.259,"POIID":"B0FFG7","POIName":"西湖文化广场","Province":"浙江省"}`
// location、locationErr 保存历史 JSON 解码后的平台发货地及错误。
location, locationErr := batchPublishLocation(raw)
if locationErr != nil || location == nil || location.Area != "西湖区" || location.City != "杭州市" || location.DivisionID != "330106" || location.Longitude != 120.118 || location.Latitude != 30.259 || location.POIID != "B0FFG7" || location.POIName != "西湖文化广场" || location.Province != "浙江省" {
t.Fatalf("v1.0.2 历史发货地恢复异常: location=%+v err=%v", location, locationErr)
}
}
+10 -1
View File
@@ -9,6 +9,7 @@ import (
itemapp "xianyu-go/internal/application/items" itemapp "xianyu-go/internal/application/items"
"xianyu-go/internal/db" "xianyu-go/internal/db"
"xianyu-go/internal/xianyu/mtop"
) )
// TestItemBatchRepositoryCreatesPreviewFromApplicationModels 验证预检应用模型到数据库字段的转换。 // TestItemBatchRepositoryCreatesPreviewFromApplicationModels 验证预检应用模型到数据库字段的转换。
@@ -27,8 +28,10 @@ func TestItemBatchRepositoryCreatesPreviewFromApplicationModels(t *testing.T) {
{RowNo: 2, CookieID: "cid", Title: "应用模型商品", Price: "10", Quantity: 2, Raw: expectedRaw, Category: itemapp.BatchPreviewCategory{CatID: "cat-1"}}, {RowNo: 2, CookieID: "cid", Title: "应用模型商品", Price: "10", Quantity: 2, Raw: expectedRaw, Category: itemapp.BatchPreviewCategory{CatID: "cat-1"}},
{RowNo: 3, CookieID: "cid", Title: "失败商品", Errors: []string{"标题错误"}}, {RowNo: 3, CookieID: "cid", Title: "失败商品", Errors: []string{"标题错误"}},
} }
// location 保存批次持久化后必须仍可还原为平台请求的完整发货地。
location := itemapp.Location{Area: "西湖区", City: "杭州市", DivisionID: "330106", Longitude: 120.118, Latitude: 30.259, POIID: "B0FFG7", POIName: "西湖文化广场", Province: "浙江省"}
// batch 保存应用层批次元数据。 // batch 保存应用层批次元数据。
batch := itemapp.BatchPreviewPersistenceBatch{ID: "preview-adapter", UserID: 1, DefaultCookieID: "cid", Filename: "items.csv", UploadDir: t.TempDir(), Location: itemapp.Location{DivisionID: "3301"}} batch := itemapp.BatchPreviewPersistenceBatch{ID: "preview-adapter", UserID: 1, DefaultCookieID: "cid", Filename: "items.csv", UploadDir: t.TempDir(), Location: location}
// err 保存应用模型落库错误。 // err 保存应用模型落库错误。
if err := repository.CreateBatch(ctx, batch, rows); err != nil { if err := repository.CreateBatch(ctx, batch, rows); err != nil {
t.Fatalf("创建预检批次失败: %v", err) t.Fatalf("创建预检批次失败: %v", err)
@@ -38,6 +41,12 @@ func TestItemBatchRepositoryCreatesPreviewFromApplicationModels(t *testing.T) {
if batchErr != nil || storedBatch.Status != "preview" || storedBatch.LocationJSON == "{}" { if batchErr != nil || storedBatch.Status != "preview" || storedBatch.LocationJSON == "{}" {
t.Fatalf("批次字段映射异常: batch=%+v err=%v", storedBatch, batchErr) t.Fatalf("批次字段映射异常: batch=%+v err=%v", storedBatch, batchErr)
} }
// restoredLocation 保存从批次 JSON 还原的平台发货地,用于防止 snake_case 字段在持久化边界丢失。
var restoredLocation mtop.PublishLocation
// locationErr 保存批次位置 JSON 解码错误。
if locationErr := json.Unmarshal([]byte(storedBatch.LocationJSON), &restoredLocation); locationErr != nil || restoredLocation.Area != location.Area || restoredLocation.City != location.City || restoredLocation.DivisionID != location.DivisionID || restoredLocation.Longitude != location.Longitude || restoredLocation.Latitude != location.Latitude || restoredLocation.POIID != location.POIID || restoredLocation.POIName != location.POIName || restoredLocation.Province != location.Province {
t.Fatalf("批次发货地序列化异常: stored=%s restored=%+v err=%v", storedBatch.LocationJSON, restoredLocation, locationErr)
}
// storedRows、rowsErr 保存数据库明细读取结果。 // storedRows、rowsErr 保存数据库明细读取结果。
storedRows, rowsErr := store.PublishBatches.Rows(ctx, batch.ID) storedRows, rowsErr := store.PublishBatches.Rows(ctx, batch.ID)
if rowsErr != nil || len(storedRows) != 2 || storedRows[1].Status != "failed" || storedRows[1].FailureKind != "validation" { if rowsErr != nil || len(storedRows) != 2 || storedRows[1].Status != "failed" || storedRows[1].FailureKind != "validation" {
+8 -8
View File
@@ -73,21 +73,21 @@ type Image struct {
// Location 是平台发布所需的发货地信息,不依赖外部平台包的 DTO。 // Location 是平台发布所需的发货地信息,不依赖外部平台包的 DTO。
type Location struct { type Location struct {
// Area 是发货地的区县名称。 // Area 是发货地的区县名称。
Area string Area string `json:"area"`
// City 是发货地的城市名称。 // City 是发货地的城市名称。
City string City string `json:"city"`
// DivisionID 是平台行政区划标识。 // DivisionID 是平台行政区划标识。
DivisionID string DivisionID string `json:"division_id"`
// Longitude 是发货地经度。 // Longitude 是发货地经度。
Longitude float64 Longitude float64 `json:"longitude"`
// Latitude 是发货地纬度。 // Latitude 是发货地纬度。
Latitude float64 Latitude float64 `json:"latitude"`
// POIID 是地图服务返回的兴趣点标识。 // POIID 是地图服务返回的兴趣点标识。
POIID string POIID string `json:"poi_id"`
// POIName 是地图服务返回的兴趣点名称。 // POIName 是地图服务返回的兴趣点名称。
POIName string POIName string `json:"poi_name"`
// Province 是发货地的省份名称。 // Province 是发货地的省份名称。
Province string Province string `json:"province"`
} }
// PublishInput 是单商品发布用例输入,携带已由 HTTP 层验证的业务字段。 // PublishInput 是单商品发布用例输入,携带已由 HTTP 层验证的业务字段。
+8
View File
@@ -302,6 +302,14 @@ func publicQRStatus(src map[string]any) qrLoginStatusResponse {
if message, ok := src["message"].(string); ok { if message, ok := src["message"].(string); ok {
status.Message = message status.Message = message
} }
// verificationScreenshot 保存风控页面截图兜底地址;ok 表示字段类型确实为字符串。
if verificationScreenshot, ok := src["verification_screenshot"].(string); ok {
status.VerificationScreenshot = verificationScreenshot
}
// faceQRURL 保存人脸风控二维码地址;ok 表示字段类型确实为字符串。
if faceQRURL, ok := src["face_qr_url"].(string); ok {
status.FaceQRURL = faceQRURL
}
// sessionID 保存扫码会话标识;ok 表示字段类型确实为字符串。 // sessionID 保存扫码会话标识;ok 表示字段类型确实为字符串。
if sessionID, ok := src["session_id"].(string); ok { if sessionID, ok := src["session_id"].(string); ok {
status.SessionID = sessionID status.SessionID = sessionID
+11 -5
View File
@@ -439,10 +439,12 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) {
// 二维码状态与验证使用测试专用平台替身。 // 二维码状态与验证使用测试专用平台替身。
setTestQRLogin(srv, &fakeQRLoginService{status: map[string]any{ setTestQRLogin(srv, &fakeQRLoginService{status: map[string]any{
"status": "waiting", "status": "verification_required",
"session_id": "contract-qr", "session_id": "contract-qr",
"custom_field": "kept", "verification_screenshot": "data:image/png;base64,screenshot",
"cookies": "must-not-leak", "face_qr_url": "data:image/png;base64,face-qr",
"custom_field": "kept",
"cookies": "must-not-leak",
}}) }})
// statusSessionID 是二维码状态测试会话标识。 // statusSessionID 是二维码状态测试会话标识。
statusSessionID := "contract-qr" statusSessionID := "contract-qr"
@@ -462,9 +464,13 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) {
if qrStatusDecodeErr := json.Unmarshal(qrStatusRecorder.Body.Bytes(), &qrStatusValue); qrStatusDecodeErr != nil { if qrStatusDecodeErr := json.Unmarshal(qrStatusRecorder.Body.Bytes(), &qrStatusValue); qrStatusDecodeErr != nil {
t.Fatalf("decode qr status response: %v", qrStatusDecodeErr) t.Fatalf("decode qr status response: %v", qrStatusDecodeErr)
} }
if qrStatusValue.Status != "waiting" || qrStatusValue.SessionID != "contract-qr" { if qrStatusValue.Status != "verification_required" || qrStatusValue.SessionID != "contract-qr" {
t.Fatalf("qr status response=%+v", qrStatusValue) t.Fatalf("qr status response=%+v", qrStatusValue)
} }
if qrStatusValue.VerificationScreenshot != "data:image/png;base64,screenshot" ||
qrStatusValue.FaceQRURL != "data:image/png;base64,face-qr" {
t.Fatalf("qr verification fields=%+v", qrStatusValue)
}
// leaked 表示二维码状态响应是否意外包含敏感 Cookie 字段。 // leaked 表示二维码状态响应是否意外包含敏感 Cookie 字段。
var rawQR map[string]any var rawQR map[string]any
// decodeErr 表示原始二维码响应反序列化失败的原因。 // decodeErr 表示原始二维码响应反序列化失败的原因。
@@ -772,6 +772,10 @@ type qrLoginStatusResponse struct {
Status string `json:"status"` Status string `json:"status"`
// Message 是可选的平台提示文本。 // Message 是可选的平台提示文本。
Message string `json:"message,omitempty"` Message string `json:"message,omitempty"`
// VerificationScreenshot 是平台风控验证页面的非敏感截图兜底地址。
VerificationScreenshot string `json:"verification_screenshot,omitempty"`
// FaceQRURL 是人脸风控验证二维码的图片地址,前端优先使用它引导用户扫码。
FaceQRURL string `json:"face_qr_url,omitempty"`
// SessionID 是可选的扫码会话标识。 // SessionID 是可选的扫码会话标识。
SessionID string `json:"session_id,omitempty"` SessionID string `json:"session_id,omitempty"`
// AccountID 是扫码成功后创建或更新的本地账号标识。 // AccountID 是扫码成功后创建或更新的本地账号标识。
@@ -1,3 +1,3 @@
import{b as ie,j as e,r as n,c as Oe}from"./react-vendor-C_od1ZSF.js";import{g as X,c as Pe,o as ke,p as ae,a as ce,d as Le}from"./index-KV7tSL6x.js";import{n as ue,X as de,f as ze,L as J,o as Ie,p as Ge,q as We,r as Te,s as $e,U as De,t as te,u as Ve,k as _e,Q as ve,v as Ee,R as Je,w as Ke,x as He,y as Ne,K as Xe,z as Ye,F as Ze,e as Fe,H as es}from"./icons-vendor-DwxdQTKt.js";const ss=(s,t)=>{const r=s.avatar_url||"";if(!r)return"";try{const a=new URL(r,window.location.origin);return a.hostname.endsWith("alicdn.com")&&a.searchParams.set("_v",t),a.toString()}catch{return r}},ts=async s=>{const t=await X("/api/v1/accounts/details",void 0,s),r=Pe(t,["data","accounts","details"]),a=Date.now().toString();return r.map(l=>({id:l.id,cookie_configured:l.has_cookie===!0,enabled:l.enabled,auto_confirm:l.auto_confirm,remark:l.remark,pause_duration:l.pause_duration,paused_until:Number(l.paused_until||0),paused:l.paused===!0,username:l.username||"",login_password_configured:void 0,show_browser:l.show_browser===!0||l.show_browser===1||l.show_browser==="1"||l.show_browser==="true",nickname:l.nickname||l.remark||`账号 ${l.id.substring(0,6)}`,avatar_url:ss(l,a),profile_error:l.profile_error||"",ai_enabled:!1,auto_rate_enabled:l.auto_rate_enabled,rate_content:l.rate_content||"不错的买家,交易愉快",auto_polish_enabled:l.auto_polish_enabled,polish_time:l.polish_time||"03:00",last_rate_scan_at:Number(l.last_rate_scan_at||0),last_polish_date:l.last_polish_date||"",last_polish_at:Number(l.last_polish_at||0)}))},as=async s=>{const t=await X("/api/v1/accounts/runtime-status",void 0,s);return ke(t,["statuses","data","result"])||{}},rs=async s=>ce("/api/v1/qr-login/generate",void 0,{...s,timeoutMs:(s==null?void 0:s.timeoutMs)??13e4}),ns=async(s,t)=>X(`/api/v1/qr-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),ls=async(s,t)=>ce(`/api/v1/qr-login/complete-verification/${s}`,{target_account_id:t||""}),os=async(s,t)=>ae(`/api/v1/accounts/${s}/status`,{enabled:t}),is=async s=>Le(`/api/v1/accounts/${s}`),cs=async(s,t,r)=>ae(`/api/v1/accounts/${s}/pause-duration`,{pause_duration:t},r),ds=async(s,t,r)=>ae(`/api/v1/accounts/${s}/settings`,t,r),us=async(s,t)=>X(`/api/v1/accounts/${s}/long-login`,void 0,t),xs=async(s,t,r)=>ae(`/api/v1/accounts/${s}/long-login`,{enabled:t},r),ms=async(s,t)=>ce("/api/v1/password-login",s,t),bs=async(s,t)=>X(`/api/v1/password-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),hs=async(s,t)=>Le(`/api/v1/password-login/cancel/${s}`,void 0,t),gs=async s=>ce(`/api/v1/accounts/${s}/refresh-profile`,{}),ps=async s=>{const t=await X("/api/v1/settings/ai-reply",void 0,s);return ke(t,["settings","data","result"])||{}},fs=async(s,t)=>X(`/api/v1/settings/ai-reply/${s}`,void 0,t),ys=async(s,t,r)=>{const a={ai_enabled:t.ai_enabled??!1,max_discount_percent:t.max_discount_percent??10,max_discount_amount:t.max_discount_amount??100,max_bargain_rounds:t.max_bargain_rounds??3,custom_prompts:t.custom_prompts??""};return ae(`/api/v1/settings/ai-reply/${s}`,a,r)},js=s=>{if(Array.isArray(s))return s.filter(Boolean);if(typeof s!="string"||!s.trim())return[];try{const t=JSON.parse(s);if(Array.isArray(t))return t.filter(Boolean)}catch{}return s.split(/[,\s;]+/).map(t=>t.trim()).filter(Boolean)},ws=async s=>{const t=await X("/api/v1/notifications/channels",void 0,s);return{success:!0,data:Pe(t,["data","channels","items"]).map(a=>{let l;try{l=typeof a.config=="string"?JSON.parse(a.config):a.config}catch{l={}}const c=a.type==="ding_talk"?"dingtalk":a.type==="lark"?"feishu":a.type;return{id:String(a.id),name:a.name,type:c,config:l,event_types:js(a.event_types),enabled:a.enabled,created_at:a.created_at,updated_at:a.updated_at}})}},_s=async(s,t)=>{const r=await X(`/api/v1/notifications/accounts/${s}/bindings`,void 0,t),a=ke(r,["data","result"])||{};return Array.isArray(a.channel_ids)?a.channel_ids:[]},vs=({account:s,settings:t,saving:r,onChange:a,onClose:l,onSave:c})=>{const i=u=>a({...t,...u}),d=()=>i({ai_enabled:!t.ai_enabled}),b=u=>i({max_discount_percent:parseInt(u.target.value,10)||0}),m=u=>i({max_discount_amount:parseInt(u.target.value,10)||0}),f=u=>i({max_bargain_rounds:parseInt(u.target.value,10)||1}),h=u=>i({custom_prompts:u.target.value});return ie.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-2xl font-extrabold text-gray-900 flex items-center gap-2",children:[e.jsx(ue,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:s.nickname||s.remark||s.id})]}),e.jsx("button",{onClick:l,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0","aria-label":"关闭 AI 设置",children:e.jsx(de,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-betweeLine truncated import{b as ie,j as e,r as n,c as Oe}from"./react-vendor-C_od1ZSF.js";import{g as X,c as Pe,o as ke,p as ae,a as ce,d as Le}from"./index-zEvleK2K.js";import{n as ue,X as de,f as ze,L as K,o as Ie,p as Ge,q as We,r as Te,s as $e,U as De,t as te,u as Ve,k as _e,Q as ve,v as Ee,R as Ke,w as He,x as Je,y as Ne,K as Xe,z as Ye,F as Ze,e as Fe,H as es}from"./icons-vendor-DwxdQTKt.js";const ss=(s,t)=>{const r=s.avatar_url||"";if(!r)return"";try{const a=new URL(r,window.location.origin);return a.hostname.endsWith("alicdn.com")&&a.searchParams.set("_v",t),a.toString()}catch{return r}},ts=async s=>{const t=await X("/api/v1/accounts/details",void 0,s),r=Pe(t,["data","accounts","details"]),a=Date.now().toString();return r.map(o=>({id:o.id,cookie_configured:o.has_cookie===!0,enabled:o.enabled,auto_confirm:o.auto_confirm,remark:o.remark,pause_duration:o.pause_duration,paused_until:Number(o.paused_until||0),paused:o.paused===!0,username:o.username||"",login_password_configured:void 0,show_browser:o.show_browser===!0||o.show_browser===1||o.show_browser==="1"||o.show_browser==="true",nickname:o.nickname||o.remark||`账号 ${o.id.substring(0,6)}`,avatar_url:ss(o,a),profile_error:o.profile_error||"",ai_enabled:!1,auto_rate_enabled:o.auto_rate_enabled,rate_content:o.rate_content||"不错的买家,交易愉快",auto_polish_enabled:o.auto_polish_enabled,polish_time:o.polish_time||"03:00",last_rate_scan_at:Number(o.last_rate_scan_at||0),last_polish_date:o.last_polish_date||"",last_polish_at:Number(o.last_polish_at||0)}))},as=async s=>{const t=await X("/api/v1/accounts/runtime-status",void 0,s);return ke(t,["statuses","data","result"])||{}},rs=async s=>ce("/api/v1/qr-login/generate",void 0,{...s,timeoutMs:(s==null?void 0:s.timeoutMs)??13e4}),ns=async(s,t)=>X(`/api/v1/qr-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),ls=async(s,t)=>ce(`/api/v1/qr-login/complete-verification/${s}`,{target_account_id:t||""}),os=async(s,t)=>ae(`/api/v1/accounts/${s}/status`,{enabled:t}),is=async s=>Le(`/api/v1/accounts/${s}`),cs=async(s,t,r)=>ae(`/api/v1/accounts/${s}/pause-duration`,{pause_duration:t},r),ds=async(s,t,r)=>ae(`/api/v1/accounts/${s}/settings`,t,r),us=async(s,t)=>X(`/api/v1/accounts/${s}/long-login`,void 0,t),xs=async(s,t,r)=>ae(`/api/v1/accounts/${s}/long-login`,{enabled:t},r),ms=async(s,t)=>ce("/api/v1/password-login",s,t),bs=async(s,t)=>X(`/api/v1/password-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),hs=async(s,t)=>Le(`/api/v1/password-login/cancel/${s}`,void 0,t),gs=async s=>ce(`/api/v1/accounts/${s}/refresh-profile`,{}),ps=async s=>{const t=await X("/api/v1/settings/ai-reply",void 0,s);return ke(t,["settings","data","result"])||{}},fs=async(s,t)=>X(`/api/v1/settings/ai-reply/${s}`,void 0,t),ys=async(s,t,r)=>{const a={ai_enabled:t.ai_enabled??!1,max_discount_percent:t.max_discount_percent??10,max_discount_amount:t.max_discount_amount??100,max_bargain_rounds:t.max_bargain_rounds??3,custom_prompts:t.custom_prompts??""};return ae(`/api/v1/settings/ai-reply/${s}`,a,r)},js=s=>{if(Array.isArray(s))return s.filter(Boolean);if(typeof s!="string"||!s.trim())return[];try{const t=JSON.parse(s);if(Array.isArray(t))return t.filter(Boolean)}catch{}return s.split(/[,\s;]+/).map(t=>t.trim()).filter(Boolean)},ws=async s=>{const t=await X("/api/v1/notifications/channels",void 0,s);return{success:!0,data:Pe(t,["data","channels","items"]).map(a=>{const o={},c=a.type==="ding_talk"?"dingtalk":a.type==="lark"?"feishu":a.type;return{id:String(a.id),name:a.name,type:c,config:o,event_types:js(a.event_types),enabled:a.enabled}})}},_s=async(s,t)=>{const r=await X(`/api/v1/notifications/accounts/${s}/bindings`,void 0,t),a=ke(r,["data","result"])||{};return Array.isArray(a.channel_ids)?a.channel_ids:[]},vs=({account:s,settings:t,saving:r,onChange:a,onClose:o,onSave:c})=>{const i=u=>a({...t,...u}),d=()=>i({ai_enabled:!t.ai_enabled}),b=u=>i({max_discount_percent:parseInt(u.target.value,10)||0}),m=u=>i({max_discount_amount:parseInt(u.target.value,10)||0}),f=u=>i({max_bargain_rounds:parseInt(u.target.value,10)||1}),h=u=>i({custom_prompts:u.target.value});return ie.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-2xl font-extrabold text-gray-900 flex items-center gap-2",children:[e.jsx(ue,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:s.nickname||s.remark||s.id})]}),e.jsx("button",{onClick:o,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0","aria-label":"关闭 AI 设置",children:e.jsx(de,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between p-4 bg-purple-50 rounded-xl",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-bold text-gray-900 flex iteLine 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(ze,{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:l,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:r,children:"取消"}),e.jsxs("button",{onClick:(()=>void c()),className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:r,children:[r?e.jsx(J,{className:"w-4 h-4 animate-spin"}):e.jsx(Ie,{className:"w-4 h-4"}),r?"保存中...":"保存"]})]})})]})}),document.body)},Ce=async(s,t)=>X(`/api/v1/account-tasks/${s}`,void 0,t),Se=async(s,t,r)=>ae(`/api/v1/account-tasks/${s}`,t,r),Ns=async(s,t,r)=>ce(`/api/v1/account-tasks/${s}/run`,{task_type:t},{timeoutMs:12e4,...r}),Re=s=>({account_id:s.id,auto_rate_enabled:s.auto_rate_enabled===!0,rate_content:s.rate_content||"不错的买家,交易愉快",auto_polish_enabled:s.auto_polish_enabled===!0,polish_time:s.polish_time||"03:00",last_rate_scan_at:s.last_rate_scan_at,last_polish_date:s.last_polish_date,last_polish_at:s.last_polish_at}),Y=(s,t,r)=>s===t&&!r.aborted,je=(s,t)=>s instanceof Error?s.message:t,we=s=>s instanceof Error&&s.message==="请求已取消",Ae=(s,t)=>!s&&t==="",ks=({account:s,onSaved:t})=>{const[r,a]=n.useState(()=>Re(s)),[l,c]=n.useState(!0),[i,d]=n.useState(!1),[b,m]=n.useState(""),[f,h]=n.useState(""),[u,A]=n.useState(null),[k,g]=n.useState(null),p=n.useRef(0),L=n.useRef(null);n.useEffect(()=>{var v;const S=++p.current;(v=L.current)==null||v.abort();const j=new AbortController;return L.current=j,a(Re(s)),A(null),h(""),d(!1),m(""),g(null),c(!0),Ce(s.id,{signal:j.signal}).then(R=>{Y(p.current,S,j.signal)&&a(R)}).catch(R=>{Y(p.current,S,j.signal)&&!we(R)&&h(je(R,"加载任务设置失败"))}).finally(()=>{Y(p.current,S,j.signal)&&c(!1)}),(()=>j.abort())},[s.id]),n.useEffect(()=>(()=>{var S;return(S=L.current)==null?void 0:S.abort()}),[]);const U=n.useCallback(async()=>{var v;if(!Ae(i,b))return;const S=++p.current;(v=L.current)==null||v.abort();const j=new AbortController;L.current=j,d(!0),h(""),g(null);try{const R=await Se(s.id,r,{signal:j.signal});if(!Y(p.current,S,j.signal))return;a(R),t(R)}catch(R){Y(p.current,S,j.signal)&&!we(R)&&(h(je(R,"保存失败")),g(()=>U))}finally{Y(p.current,S,j.signal)&&d(!1)}},[s.id,r,t,b,i]),M=n.useCallback(async S=>{var R;if(!Ae(i,b)||!s.enabled)return;const j=++p.current;(R=L.current)==null||R.abort();const v=new AbortController;L.current=v,m(S),h(""),A(null),g(null);try{await Se(s.id,r,{signal:v.signal});const w=await Ns(s.id,S,{signal:v.signal}),q=await Ce(s.id,{signal:v.signal});if(!Y(p.current,j,v.signal))return;A(w.summary),a(q),t(q)}catch(w){Y(p.current,j,v.signal)&&!we(w)&&(h(je(w,"任务执行失败")),g(()=>(()=>M(S))))}finally{Y(p.current,j,v.signal)&&m("")}},[s.enabled,s.id,r,t,b,i]),T=n.useCallback(async()=>{k&&await k()},[k]);return{form:r,loading:l,saving:i,running:b,summary:u,error:f,retryAvailable:k!==null,setForm:a,save:U,run:M,retry:T}},qe=({checked:s,onChange:t,label:r})=>e.jsx("button",{type:"button","aria-label":r,"aria-pressed":s,onClick:t,className:`relative h-8 w-14 shrink-0 rounded-full transition-colors ${s?"bg-sky-500":"bg-slate-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-sm transition-transform ${s?"translate-x-6":""}`})}),Cs=({account:s,onClose:t,onSaved:r})=>{const{form:a,loading:l,saving:c,running:i,error:d,summary:b,retryAvailable:m,setForm:f,save:h,run:u,retry:A}=ks({account:s,onSaved:r});return e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"640px"},role:"dialog","aria-modal":"true","aria-labelledby":"account-task-title",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{id:"account-task-title",className:"text-2xl font-extrabold text-slate-950",children:"账号自动任务"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:s.nickname||s.remark||s.id})]}),e.jsx("button",{type:"button",onClick:t,className:"rounded-xl p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700","aria-label":"关闭",children:e.jsx(de,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[l& Line 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(ze,{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:o,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:r,children:"取消"}),e.jsxs("button",{onClick:(()=>void c()),className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:r,children:[r?e.jsx(K,{className:"w-4 h-4 animate-spin"}):e.jsx(Ie,{className:"w-4 h-4"}),r?"保存中...":"保存"]})]})})]})}),document.body)},Ce=async(s,t)=>X(`/api/v1/account-tasks/${s}`,void 0,t),Se=async(s,t,r)=>ae(`/api/v1/account-tasks/${s}`,t,r),Ns=async(s,t,r)=>ce(`/api/v1/account-tasks/${s}/run`,{task_type:t},{timeoutMs:12e4,...r}),Re=s=>({account_id:s.id,auto_rate_enabled:s.auto_rate_enabled===!0,rate_content:s.rate_content||"不错的买家,交易愉快",auto_polish_enabled:s.auto_polish_enabled===!0,polish_time:s.polish_time||"03:00",last_rate_scan_at:s.last_rate_scan_at,last_polish_date:s.last_polish_date,last_polish_at:s.last_polish_at}),Y=(s,t,r)=>s===t&&!r.aborted,je=(s,t)=>s instanceof Error?s.message:t,we=s=>s instanceof Error&&s.message==="请求已取消",Ae=(s,t)=>!s&&t==="",ks=({account:s,onSaved:t})=>{const[r,a]=n.useState(()=>Re(s)),[o,c]=n.useState(!0),[i,d]=n.useState(!1),[b,m]=n.useState(""),[f,h]=n.useState(""),[u,A]=n.useState(null),[k,g]=n.useState(null),p=n.useRef(0),L=n.useRef(null);n.useEffect(()=>{var v;const S=++p.current;(v=L.current)==null||v.abort();const j=new AbortController;return L.current=j,a(Re(s)),A(null),h(""),d(!1),m(""),g(null),c(!0),Ce(s.id,{signal:j.signal}).then(R=>{Y(p.current,S,j.signal)&&a(R)}).catch(R=>{Y(p.current,S,j.signal)&&!we(R)&&h(je(R,"加载任务设置失败"))}).finally(()=>{Y(p.current,S,j.signal)&&c(!1)}),(()=>j.abort())},[s.id]),n.useEffect(()=>(()=>{var S;return(S=L.current)==null?void 0:S.abort()}),[]);const U=n.useCallback(async()=>{var v;if(!Ae(i,b))return;const S=++p.current;(v=L.current)==null||v.abort();const j=new AbortController;L.current=j,d(!0),h(""),g(null);try{const R=await Se(s.id,r,{signal:j.signal});if(!Y(p.current,S,j.signal))return;a(R),t(R)}catch(R){Y(p.current,S,j.signal)&&!we(R)&&(h(je(R,"保存失败")),g(()=>U))}finally{Y(p.current,S,j.signal)&&d(!1)}},[s.id,r,t,b,i]),M=n.useCallback(async S=>{var R;if(!Ae(i,b)||!s.enabled)return;const j=++p.current;(R=L.current)==null||R.abort();const v=new AbortController;L.current=v,m(S),h(""),A(null),g(null);try{await Se(s.id,r,{signal:v.signal});const w=await Ns(s.id,S,{signal:v.signal}),q=await Ce(s.id,{signal:v.signal});if(!Y(p.current,j,v.signal))return;A(w.summary),a(q),t(q)}catch(w){Y(p.current,j,v.signal)&&!we(w)&&(h(je(w,"任务执行失败")),g(()=>(()=>M(S))))}finally{Y(p.current,j,v.signal)&&m("")}},[s.enabled,s.id,r,t,b,i]),T=n.useCallback(async()=>{k&&await k()},[k]);return{form:r,loading:o,saving:i,running:b,summary:u,error:f,retryAvailable:k!==null,setForm:a,save:U,run:M,retry:T}},qe=({checked:s,onChange:t,label:r})=>e.jsx("button",{type:"button","aria-label":r,"aria-pressed":s,onClick:t,className:`relative h-8 w-14 shrink-0 rounded-full transition-colors ${s?"bg-sky-500":"bg-slate-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-sm transition-transform ${s?"translate-x-6":""}`})}),Cs=({account:s,onClose:t,onSaved:r})=>{const{form:a,loading:o,saving:c,running:i,error:d,summary:b,retryAvailable:m,setForm:f,save:h,run:u,retry:A}=ks({account:s,onSaved:r});return e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"640px"},role:"dialog","aria-modal":"true","aria-labelledby":"account-task-title",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{id:"account-task-title",className:"text-2xl font-extrabold text-slate-950",children:"账号自动任务"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:s.nickname||s.remark||s.id})]}),e.jsx("button",{type:"button",onClick:t,className:"rounded-xl p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700","aria-label":"关闭",children:e.jsx(de,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[o& Line truncated
@@ -1,4 +1,4 @@
import{r as i,b as z,j as e}from"./react-vendor-C_od1ZSF.js";import{g as Z,c as ee,p as te,d as ae,a as H,b as se}from"./index-KV7tSL6x.js";import{X as G,W as le,J as O,Y as ne,L as V,N as U,C as W,_ as re,$ as X,a0 as Y,a1 as oe,I as ie,a2 as ce,V as de,y as xe,P as pe,o as me}from"./icons-vendor-DwxdQTKt.js";const he=l=>{let n=l.api_config;if(typeof n=="string"&&n.trim())try{n=JSON.parse(n)}catch{n=void 0}return{...l,api_config:n||void 0}},K=l=>({...l,api_config:l.api_config?JSON.stringify(l.api_config):""}),ue=async l=>{const n=await Z("/api/v1/cards",void 0,l);return ee(n,["cards","data","items"]).map(he)},be=async l=>H("/api/v1/cards",K(l)),J=async(l,n)=>te(`/api/v1/cards/${l}`,K(n)),ge=async l=>ae(`/api/v1/cards/${l}`),ye=async(l,n)=>{const a=new FormData;return a.append("file",l),se("/api/v1/cards/batch",a,n)},fe=async(l,n,a)=>H(`/api/v1/cards/${l}/append-data`,{content:n},a),je=(l,n,a)=>{const u=a.trim().toLocaleLowerCase();return l.filter(m=>(!n||m.type===n)&&(!u||m.name.toLocaleLowerCase().includes(u)))},Q=l=>l.split(` import{r as i,b as z,j as e}from"./react-vendor-C_od1ZSF.js";import{g as Z,c as ee,p as te,d as ae,a as H,b as se}from"./index-zEvleK2K.js";import{X as G,W as le,J as O,Y as ne,L as V,N as U,C as W,_ as re,$ as X,a0 as Y,a1 as oe,I as ie,a2 as ce,V as de,y as xe,P as pe,o as me}from"./icons-vendor-DwxdQTKt.js";const he=l=>{let n=l.api_config;if(typeof n=="string"&&n.trim())try{n=JSON.parse(n)}catch{n=void 0}return{...l,api_config:n||void 0}},K=l=>({...l,api_config:l.api_config?JSON.stringify(l.api_config):""}),ue=async l=>{const n=await Z("/api/v1/cards",void 0,l);return ee(n,["cards","data","items"]).map(he)},be=async l=>H("/api/v1/cards",K(l)),J=async(l,n)=>te(`/api/v1/cards/${l}`,K(n)),ge=async l=>ae(`/api/v1/cards/${l}`),ye=async(l,n)=>{const a=new FormData;return a.append("file",l),se("/api/v1/cards/batch",a,n)},fe=async(l,n,a)=>H(`/api/v1/cards/${l}/append-data`,{content:n},a),je=(l,n,a)=>{const u=a.trim().toLocaleLowerCase();return l.filter(m=>(!n||m.type===n)&&(!u||m.name.toLocaleLowerCase().includes(u)))},Q=l=>l.split(`
`).map(n=>n.trim()).filter(Boolean),Ne=(l,n,a)=>!!(l&&Q(n).length>0&&!a),F=(l,n,a,u)=>l===n&&a===u,q=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),D=(l,n)=>l instanceof Error?l.message:n,ve=({cards:l,loadCards:n})=>{const[a,u]=i.useState(!1),[m,_]=i.useState(!1),[f,j]=i.useState(null),[d,A]=i.useState({}),[c,y]=i.useState(q),[N,b]=i.useState(""),[r,x]=i.useState(""),s=i.useMemo(()=>l.filter(o=>o.type==="data"),[l]),h=i.useMemo(()=>je(l,N,r),[l,r,N]),E=i.useCallback(o=>{var t,g,k,S,C;j(o),A({id:o.id,name:o.name||"",type:o.type||"text",api_url:((t=o.api_config)==null?void 0:t.url)||"",api_method:((g=o.api_config)==null?void 0:g.method)||"GET",api_timeout:((k=o.api_config)==null?void 0:k.timeout)||10,api_headers:((S=o.api_config)==null?void 0:S.headers)||"",api_params:((C=o.api_config)==null?void 0:C.params)||"",text_content:o.text_content||"",data_content:o.data_content||"",image_url:o.image_url||"",delay_seconds:o.delay_seconds||0,description:o.description||"",enabled:o.enabled}),u(!0)},[]),M=i.useCallback(async()=>{var o,t,g,k,S,C,p,B;if(f){if(!((o=d.name)!=null&&o.trim())){alert("请输入卡密名称");return}if(!d.type){alert("请选择卡密类型");return}try{const w={name:d.name.trim(),type:d.type,description:(t=d.description)==null?void 0:t.trim(),delay_seconds:d.delay_seconds||0,enabled:d.enabled??!0};d.type==="api"?w.api_config={url:((g=d.api_url)==null?void 0:g.trim())||"",method:d.api_method||"GET",timeout:d.api_timeout||10,headers:((k=d.api_headers)==null?void 0:k.trim())||void 0,params:((S=d.api_params)==null?void 0:S.trim())||void 0}:d.type==="text"?w.text_content=((C=d.text_content)==null?void 0:C.trim())||"":d.type==="data"?w.data_content=((p=d.data_content)==null?void 0:p.trim())||"":d.type==="image"&&(w.image_url=((B=d.image_url)==null?void 0:B.trim())||""),await J(f.id,w),u(!1),await n()}catch(w){console.error("更新卡密失败:",w),alert(D(w,"更新失败,请重试"))}}},[d,n,f]),R=i.useCallback(async o=>{if(confirm("确认删除该卡密吗?"))try{await ge(o),await n()}catch(t){console.error("删除卡密失败:",t),alert(D(t,"删除失败,请重试"))}},[n]),v=i.useCallback(async()=>{if(!c.name.trim()){alert("请输入卡密名称");return}if(!c.content.trim()){alert(c.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const o={name:c.name.trim(),type:c.type,description:c.description.trim(),enabled:c.enabled,delay_seconds:c.delay_seconds};c.type==="text"&&(o.text_content=c.content.trim()),c.type==="data"&&(o.data_content=c.content.trim()),c.type==="image"&&(o.image_url=c.content.trim()),c.type==="api"&&(o.api_config={url:c.content.trim(),method:c.api_method,timeout:c.api_timeout,headers:c.api_headers.trim()||void 0,params:c.api_params.trim()||void 0}),await be(o),_(!1),y(q()),await n()}catch(o){console.error("添加卡密失败:",o),alert(D(o,"添加失败,请重试"))}},[c,n]),T=i.useCallback(async o=>{try{await J(o.id,{...o,enabled:!o.enabled}),await n()}catch(t){console.error("切换状态失败:",t)}},[n]),P=i.useCallback(async o=>{try{await navigator.clipboard.writeText(String(o)),alert(`已复制卡密组ID:${o}`)}catch{prompt("复制卡密组ID",String(o))}},[]),$=i.useCallback(()=>{const g=[["名称","类型","内容","描述","启用","延迟秒","多规格","规格名","规格值"],...[["VIP月卡","data",`VIP-MONTH-001 `).map(n=>n.trim()).filter(Boolean),Ne=(l,n,a)=>!!(l&&Q(n).length>0&&!a),F=(l,n,a,u)=>l===n&&a===u,q=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),D=(l,n)=>l instanceof Error?l.message:n,ve=({cards:l,loadCards:n})=>{const[a,u]=i.useState(!1),[m,_]=i.useState(!1),[f,j]=i.useState(null),[d,A]=i.useState({}),[c,y]=i.useState(q),[N,b]=i.useState(""),[r,x]=i.useState(""),s=i.useMemo(()=>l.filter(o=>o.type==="data"),[l]),h=i.useMemo(()=>je(l,N,r),[l,r,N]),E=i.useCallback(o=>{var t,g,k,S,C;j(o),A({id:o.id,name:o.name||"",type:o.type||"text",api_url:((t=o.api_config)==null?void 0:t.url)||"",api_method:((g=o.api_config)==null?void 0:g.method)||"GET",api_timeout:((k=o.api_config)==null?void 0:k.timeout)||10,api_headers:((S=o.api_config)==null?void 0:S.headers)||"",api_params:((C=o.api_config)==null?void 0:C.params)||"",text_content:o.text_content||"",data_content:o.data_content||"",image_url:o.image_url||"",delay_seconds:o.delay_seconds||0,description:o.description||"",enabled:o.enabled}),u(!0)},[]),M=i.useCallback(async()=>{var o,t,g,k,S,C,p,B;if(f){if(!((o=d.name)!=null&&o.trim())){alert("请输入卡密名称");return}if(!d.type){alert("请选择卡密类型");return}try{const w={name:d.name.trim(),type:d.type,description:(t=d.description)==null?void 0:t.trim(),delay_seconds:d.delay_seconds||0,enabled:d.enabled??!0};d.type==="api"?w.api_config={url:((g=d.api_url)==null?void 0:g.trim())||"",method:d.api_method||"GET",timeout:d.api_timeout||10,headers:((k=d.api_headers)==null?void 0:k.trim())||void 0,params:((S=d.api_params)==null?void 0:S.trim())||void 0}:d.type==="text"?w.text_content=((C=d.text_content)==null?void 0:C.trim())||"":d.type==="data"?w.data_content=((p=d.data_content)==null?void 0:p.trim())||"":d.type==="image"&&(w.image_url=((B=d.image_url)==null?void 0:B.trim())||""),await J(f.id,w),u(!1),await n()}catch(w){console.error("更新卡密失败:",w),alert(D(w,"更新失败,请重试"))}}},[d,n,f]),R=i.useCallback(async o=>{if(confirm("确认删除该卡密吗?"))try{await ge(o),await n()}catch(t){console.error("删除卡密失败:",t),alert(D(t,"删除失败,请重试"))}},[n]),v=i.useCallback(async()=>{if(!c.name.trim()){alert("请输入卡密名称");return}if(!c.content.trim()){alert(c.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const o={name:c.name.trim(),type:c.type,description:c.description.trim(),enabled:c.enabled,delay_seconds:c.delay_seconds};c.type==="text"&&(o.text_content=c.content.trim()),c.type==="data"&&(o.data_content=c.content.trim()),c.type==="image"&&(o.image_url=c.content.trim()),c.type==="api"&&(o.api_config={url:c.content.trim(),method:c.api_method,timeout:c.api_timeout,headers:c.api_headers.trim()||void 0,params:c.api_params.trim()||void 0}),await be(o),_(!1),y(q()),await n()}catch(o){console.error("添加卡密失败:",o),alert(D(o,"添加失败,请重试"))}},[c,n]),T=i.useCallback(async o=>{try{await J(o.id,{...o,enabled:!o.enabled}),await n()}catch(t){console.error("切换状态失败:",t)}},[n]),P=i.useCallback(async o=>{try{await navigator.clipboard.writeText(String(o)),alert(`已复制卡密组ID:${o}`)}catch{prompt("复制卡密组ID",String(o))}},[]),$=i.useCallback(()=>{const g=[["名称","类型","内容","描述","启用","延迟秒","多规格","规格名","规格值"],...[["VIP月卡","data",`VIP-MONTH-001
VIP-MONTH-002 VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(p=>p.map(B=>`"${String(B).replace(/"/g,'""')}"`).join(",")).join(` VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(p=>p.map(B=>`"${String(B).replace(/"/g,'""')}"`).join(",")).join(`
@@ -1 +1 @@
import{j as e,c as x0,r as i}from"./react-vendor-C_od1ZSF.js";import{L as re}from"./vendor-Es4K8PXl.js";import{e as M0,f as le,h as F0,m as P0,s as ce,i as oe,j as pe,k as me,l as z0}from"./index-KV7tSL6x.js";import{L as X,ak as ge,al as de,M as B0,I as xe,R as ue,ad as U0,k as he,am as _e,t as J0,an as be,ao as fe,ah as Q0,X as je}from"./icons-vendor-DwxdQTKt.js";const Z0=[["尊嘟假嘟","https://img.alicdn.com/imgextra/i2/O1CN01hWzOgD1KcmFEIaGwE_!!6000000001185-2-tps-64-64.png_110x10000.jpg_.webp"],["鸡哔你","https://img.alicdn.com/imgextra/i1/O1CN01P9TVJl1JCqCZcQIdW_!!6000000000993-2-tps-64-64.png_110x10000.jpg_.webp"],["谁懂啊","https://img.alicdn.com/imgextra/i1/O1CN01r9qUnx1g3tcrtSmcs_!!6000000004087-2-tps-64-64.png_110x10000.jpg_.webp"],["吗喽","https://img.alicdn.com/imgextra/i4/O1CN01dTynZh1LnbIYTHI1D_!!6000000001344-2-tps-64-64.png_110x10000.jpg_.webp"],["功德+1","https://img.alicdn.com/imgextra/i1/O1CN01l1G5pS1IVn37pfQJi_!!6000000000899-2-tps-64-64.png_110x10000.jpg_.webp"],["city不city啊","https://img.alicdn.com/imgextra/i2/O1CN01zRjPTR29lWHqabmDA_!!6000000008108-2-tps-64-64.png_110x10000.jpg_.webp"],["激推","https://img.alicdn.com/imgextra/i3/O1CN01ADTJ6u1khypfxbfnQ_!!6000000004716-2-tps-64-64.png_110x10000.jpg_.webp"],["微笑","https://img.alicdn.com/imgextra/i1/O1CN017b61R51wRk2lVV7vx_!!6000000006305-2-tps-980-980.png_110x10000.jpg_.webp"],["龇牙","https://img.alicdn.com/imgextra/i2/O1CN01nmOh4S22Yxz8IdEVf_!!6000000007133-2-tps-980-980.png_110x10000.jpg_.webp"],["流泪","https://img.alicdn.com/imgextra/i2/O1CN01Ec1EaL1zqQETcM2dX_!!6000000006765-2-tps-980-980.png_110x10000.jpg_.webp"],["尴尬","https://img.alicdn.com/imgextra/i2/O1CN01UrWH7a1ZVBrgRYXlc_!!6000000003199-2-tps-980-980.png_110x10000.jpg_.webp"],["撇嘴","https://img.alicdn.com/imgextra/i2/O1CN01Sr7o2b1lUWg5KfOD8_!!6000000004822-2-tps-980-980.png_110x10000.jpg_.webp"],["破涕为笑","https://img.alicdn.com/imgextra/i4/O1CN01pPetah1gkwndfn7Fs_!!6000000004181-2-tps-980-980.png_110x10000.jpg_.webp"],["捂脸哭","https://img.alicdn.com/imgextra/i2/O1CN0170KgpE1dE1TuQgd66_!!6000000003703-2-tps-980-980.png_110x10000.jpg_.webp"],["害羞","https://img.alicdn.com/imgextra/i3/O1CN01ZoB0Lb1ps7XpqP8PQ_!!6000000005415-2-tps-980-980.png_110x10000.jpg_.webp"],["感动","https://img.alicdn.com/imgextra/i2/O1CN01wqD4ly29yndR3Qp3A_!!6000000008137-2-tps-980-980.png_110x10000.jpg_.webp"],["滴泪","https://img.alicdn.com/imgextra/i1/O1CN01MpkJ3L1oUTTqfryOn_!!6000000005228-2-tps-980-980.png_110x10000.jpg_.webp"],["暗中观察","https://img.alicdn.com/imgextra/i1/O1CN010LO9yj272W07GlLls_!!6000000007739-2-tps-980-980.png_110x10000.jpg_.webp"],["偷笑","https://img.alicdn.com/imgextra/i4/O1CN01vJtO031g818IuYO7x_!!6000000004096-2-tps-980-980.png_110x10000.jpg_.webp"],["ok","https://img.alicdn.com/imgextra/i3/O1CN01QRkqDF25tz0WcANje_!!6000000007585-2-tps-980-980.png_110x10000.jpg_.webp"],["送花","https://img.alicdn.com/imgextra/i2/O1CN01PpzBNX1JNpeJBWnvr_!!6000000001017-2-tps-980-980.png_110x10000.jpg_.webp"],["大哭","https://img.alicdn.com/imgextra/i4/O1CN014TiaNb1ViEgNvRrTB_!!6000000002686-2-tps-980-980.png_110x10000.jpg_.webp"],["色","https://img.alicdn.com/imgextra/i2/O1CN01840t1B1JaCLGvHnBK_!!6000000001044-2-tps-980-980.png_110x10000.jpg_.webp"],["惊慌","https://img.alicdn.com/imgextra/i1/O1CN01mnqO7G1LAfUnfAN2U_!!6000000001259-2-tps-980-980.png_110x10000.jpg_.webp"],["惊讶","https://img.alicdn.com/imgextra/i3/O1CN0127IeyS1Kw0p0P4jzI_!!6000000001227-2-tps-980-980.png_110x10000.jpg_.webp"],["得意","https://img.alicdn.com/imgextra/i4/O1CN018QUnFv1WpOUES9POZ_!!6000000002837-2-tps-980-980.png_110x10000.jpg_.webp"],["睡","https://img.alicdn.com/imgextra/i2/O1CN01RprGZl1lqVgnEJLCx_!!6000000004870-2-tps-980-980.png_110x10000.jpg_.webp"],["不好意思","https://img.alicdn.com/imgextra/i3/O1CN01rMJJgn1SUXzuVpUhO_!!6000000002250-2-tps-980-980.png_110x10000.jpg_.webp"],["托腮","https://img.alicdn.com/imgextra/i1/O1CN01w3reBU1d3wlgOBtyZ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["发怒","https://img.alicdn.com/imgextra/i2/O1CN013Wzy8d2A8PxGJZPpT_!!6000000008158-2-tps-980-980.png_110x10000.jpg_.webp"],["难过","https://img.alicdn.com/imgextra/i2/O1CN01zcwaSh1G9gZCFuFal_!!6000000000580-2-tps-980-980.png_110x10000.jpg_.webp"],["调皮","https://img.alicdn.com/imgextra/i3/O1CN01Zd1YHi1TI0lwpBe8c_!!6000000002358-2-tps-980-980.png_110x10000.jpg_.webp"],["愉快","https://img.alicdn.com/imgextra/i2/O1CN0145wDk21SWpyjTvsvA_!!6000000002255-2-tps-980-980.png_110x10000.jpg_.webp"],["白眼","https://img.alicdn.com/imgextra/i4/O1CN01nexGth1hwEAT1SHO2_!!6000000004341-2-tps-980-980.png_110x10000.jpg_.webp"],["拒绝","https://img.alicdn.com/imgextra/i2/O1CN01nqusqS1uHXzoUcpXr_!!6000000006012-2-tps-980-980.png_110x10000.jpg_.webp"],["期待","https://img.alicdn.com/imgextra/i3/O1CN01M44QY11Oh8Q5PdMIx_!!6000000001736-2-tps-980-980.png_110x10000.jpg_.webp"],["困","https://img.alicdn.com/imgextra/i4/O1CN01J4hFFz1Y9pmNdBq76_ Line truncated import{j as e,c as x0,r as i}from"./react-vendor-C_od1ZSF.js";import{L as re}from"./vendor-Es4K8PXl.js";import{e as M0,f as le,h as F0,m as P0,s as ce,i as oe,j as pe,k as me,l as z0}from"./index-zEvleK2K.js";import{L as X,ak as ge,al as de,M as B0,I as xe,R as ue,ad as U0,k as he,am as _e,t as J0,an as be,ao as fe,ah as Q0,X as je}from"./icons-vendor-DwxdQTKt.js";const Z0=[["尊嘟假嘟","https://img.alicdn.com/imgextra/i2/O1CN01hWzOgD1KcmFEIaGwE_!!6000000001185-2-tps-64-64.png_110x10000.jpg_.webp"],["鸡哔你","https://img.alicdn.com/imgextra/i1/O1CN01P9TVJl1JCqCZcQIdW_!!6000000000993-2-tps-64-64.png_110x10000.jpg_.webp"],["谁懂啊","https://img.alicdn.com/imgextra/i1/O1CN01r9qUnx1g3tcrtSmcs_!!6000000004087-2-tps-64-64.png_110x10000.jpg_.webp"],["吗喽","https://img.alicdn.com/imgextra/i4/O1CN01dTynZh1LnbIYTHI1D_!!6000000001344-2-tps-64-64.png_110x10000.jpg_.webp"],["功德+1","https://img.alicdn.com/imgextra/i1/O1CN01l1G5pS1IVn37pfQJi_!!6000000000899-2-tps-64-64.png_110x10000.jpg_.webp"],["city不city啊","https://img.alicdn.com/imgextra/i2/O1CN01zRjPTR29lWHqabmDA_!!6000000008108-2-tps-64-64.png_110x10000.jpg_.webp"],["激推","https://img.alicdn.com/imgextra/i3/O1CN01ADTJ6u1khypfxbfnQ_!!6000000004716-2-tps-64-64.png_110x10000.jpg_.webp"],["微笑","https://img.alicdn.com/imgextra/i1/O1CN017b61R51wRk2lVV7vx_!!6000000006305-2-tps-980-980.png_110x10000.jpg_.webp"],["龇牙","https://img.alicdn.com/imgextra/i2/O1CN01nmOh4S22Yxz8IdEVf_!!6000000007133-2-tps-980-980.png_110x10000.jpg_.webp"],["流泪","https://img.alicdn.com/imgextra/i2/O1CN01Ec1EaL1zqQETcM2dX_!!6000000006765-2-tps-980-980.png_110x10000.jpg_.webp"],["尴尬","https://img.alicdn.com/imgextra/i2/O1CN01UrWH7a1ZVBrgRYXlc_!!6000000003199-2-tps-980-980.png_110x10000.jpg_.webp"],["撇嘴","https://img.alicdn.com/imgextra/i2/O1CN01Sr7o2b1lUWg5KfOD8_!!6000000004822-2-tps-980-980.png_110x10000.jpg_.webp"],["破涕为笑","https://img.alicdn.com/imgextra/i4/O1CN01pPetah1gkwndfn7Fs_!!6000000004181-2-tps-980-980.png_110x10000.jpg_.webp"],["捂脸哭","https://img.alicdn.com/imgextra/i2/O1CN0170KgpE1dE1TuQgd66_!!6000000003703-2-tps-980-980.png_110x10000.jpg_.webp"],["害羞","https://img.alicdn.com/imgextra/i3/O1CN01ZoB0Lb1ps7XpqP8PQ_!!6000000005415-2-tps-980-980.png_110x10000.jpg_.webp"],["感动","https://img.alicdn.com/imgextra/i2/O1CN01wqD4ly29yndR3Qp3A_!!6000000008137-2-tps-980-980.png_110x10000.jpg_.webp"],["滴泪","https://img.alicdn.com/imgextra/i1/O1CN01MpkJ3L1oUTTqfryOn_!!6000000005228-2-tps-980-980.png_110x10000.jpg_.webp"],["暗中观察","https://img.alicdn.com/imgextra/i1/O1CN010LO9yj272W07GlLls_!!6000000007739-2-tps-980-980.png_110x10000.jpg_.webp"],["偷笑","https://img.alicdn.com/imgextra/i4/O1CN01vJtO031g818IuYO7x_!!6000000004096-2-tps-980-980.png_110x10000.jpg_.webp"],["ok","https://img.alicdn.com/imgextra/i3/O1CN01QRkqDF25tz0WcANje_!!6000000007585-2-tps-980-980.png_110x10000.jpg_.webp"],["送花","https://img.alicdn.com/imgextra/i2/O1CN01PpzBNX1JNpeJBWnvr_!!6000000001017-2-tps-980-980.png_110x10000.jpg_.webp"],["大哭","https://img.alicdn.com/imgextra/i4/O1CN014TiaNb1ViEgNvRrTB_!!6000000002686-2-tps-980-980.png_110x10000.jpg_.webp"],["色","https://img.alicdn.com/imgextra/i2/O1CN01840t1B1JaCLGvHnBK_!!6000000001044-2-tps-980-980.png_110x10000.jpg_.webp"],["惊慌","https://img.alicdn.com/imgextra/i1/O1CN01mnqO7G1LAfUnfAN2U_!!6000000001259-2-tps-980-980.png_110x10000.jpg_.webp"],["惊讶","https://img.alicdn.com/imgextra/i3/O1CN0127IeyS1Kw0p0P4jzI_!!6000000001227-2-tps-980-980.png_110x10000.jpg_.webp"],["得意","https://img.alicdn.com/imgextra/i4/O1CN018QUnFv1WpOUES9POZ_!!6000000002837-2-tps-980-980.png_110x10000.jpg_.webp"],["睡","https://img.alicdn.com/imgextra/i2/O1CN01RprGZl1lqVgnEJLCx_!!6000000004870-2-tps-980-980.png_110x10000.jpg_.webp"],["不好意思","https://img.alicdn.com/imgextra/i3/O1CN01rMJJgn1SUXzuVpUhO_!!6000000002250-2-tps-980-980.png_110x10000.jpg_.webp"],["托腮","https://img.alicdn.com/imgextra/i1/O1CN01w3reBU1d3wlgOBtyZ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["发怒","https://img.alicdn.com/imgextra/i2/O1CN013Wzy8d2A8PxGJZPpT_!!6000000008158-2-tps-980-980.png_110x10000.jpg_.webp"],["难过","https://img.alicdn.com/imgextra/i2/O1CN01zcwaSh1G9gZCFuFal_!!6000000000580-2-tps-980-980.png_110x10000.jpg_.webp"],["调皮","https://img.alicdn.com/imgextra/i3/O1CN01Zd1YHi1TI0lwpBe8c_!!6000000002358-2-tps-980-980.png_110x10000.jpg_.webp"],["愉快","https://img.alicdn.com/imgextra/i2/O1CN0145wDk21SWpyjTvsvA_!!6000000002255-2-tps-980-980.png_110x10000.jpg_.webp"],["白眼","https://img.alicdn.com/imgextra/i4/O1CN01nexGth1hwEAT1SHO2_!!6000000004341-2-tps-980-980.png_110x10000.jpg_.webp"],["拒绝","https://img.alicdn.com/imgextra/i2/O1CN01nqusqS1uHXzoUcpXr_!!6000000006012-2-tps-980-980.png_110x10000.jpg_.webp"],["期待","https://img.alicdn.com/imgextra/i3/O1CN01M44QY11Oh8Q5PdMIx_!!6000000001736-2-tps-980-980.png_110x10000.jpg_.webp"],["困","https://img.alicdn.com/imgextra/i4/O1CN01J4hFFz1Y9pmNdBq76_ Line truncated
@@ -1 +1 @@
import{j as e,r as c}from"./react-vendor-C_od1ZSF.js";import{f as me}from"./dateTime-DDi7rqpW.js";import{j as de,k as ge,l as te,D as he,c as pe,P as be,m as se,E as fe,T as ye}from"./icons-vendor-DwxdQTKt.js";import{R as E,B as je,X as ae,Y as re,T as F,a as ve,C as U,A as Ne,b as we,c as _e,P as ne,d as le,L as ke}from"./charts-vendor-deWqkrdG.js";import{g as q,c as xe,o as De}from"./index-KV7tSL6x.js";import"./vendor-Es4K8PXl.js";const M=t=>{const a=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),l=String(t.getDate()).padStart(2,"0");return`${a}-${s}-${l}`},H=(t,a)=>{const s=new Date(t);return s.setHours(12,0,0,0),s.setDate(s.getDate()+a),s},X=(t,a)=>({startDate:M(H(t,-(a-1))),endDate:M(t)}),ue=(t,a=new Date,s="",l="")=>{if(t==="custom"&&s&&l){if(s>l)throw new Error("开始日期不能晚于结束日期");return{startDate:s,endDate:l}}return t==="yesterday"?X(H(a,-1),1):X(a,t==="3days"?3:t==="30days"?30:t==="today"?1:7)},Se=t=>{const a=new Date(`${t.startDate}T12:00:00`),s=new Date(`${t.endDate}T12:00:00`),l=Math.round((s.getTime()-a.getTime())/864e5)+1,n=H(a,-1);return X(n,l)},i=(t,a)=>a===void 0?`rgb(var(--color-${t}))`:`rgb(var(--color-${t}) / ${a})`,Ce=({chartData:t,selectedRangeLabel:a,totalAmount:s})=>e.jsxs("div",{className:"ios-card p-8 rounded-xl",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("h3",{className:"text-xl font-bold text-gray-900",children:"营收趋势分析"}),e.jsxs("p",{className:"text-sm text-gray-400 mt-1",children:[a,"的销售额走势"]})]}),e.jsx("div",{className:"dashboard-revenue-chart h-[350px] w-full",children:t.length===0||s===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(de,{className:"w-16 h-16 mb-4 opacity-20"}),e.jsx("p",{className:"text-lg font-medium",children:"暂无营收数据"}),e.jsx("p",{className:"text-sm mt-2",children:"所选时间范围内暂无订单记录"})]}):t.length<=2?e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(je,{data:t,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(ae,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-700"),fontSize:14,fontWeight:600},dy:10}),e.jsx(re,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},tickFormatter:(l=>`¥${l}`)}),e.jsx(F,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{fill:i("brand",.08)},formatter:(l=>[`¥${Number(l).toFixed(2)}`,"营收"])}),e.jsx(ve,{dataKey:"amount",fill:i("brand"),maxBarSize:72,radius:[12,12,0,0],activeBar:!1,stroke:"none",strokeWidth:0,children:t.map((l,n)=>e.jsx(U,{fill:i("brand"),stroke:"none",strokeWidth:0},`cell-${n}`))})]})}):e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(Ne,{data:t,margin:{top:10,right:10,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorAmount",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:i("brand"),stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:i("brand"),stopOpacity:0})]})}),e.jsx(ae,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},dy:15}),e.jsx(re,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500}}),e.jsx(we,{vertical:!1,stroke:i("neutral-100"),strokeDasharray:"3 3"}),e.jsx(F,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{stroke:i("brand"),strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(_e,{type:"monotone",dataKey:"amount",stroke:i("brand"),strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:i("white"),stroke:i("brand"),strokeWidth:2}})]})})})]}),oe=t=>{const a=String(t||"");return a==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(a)?a:"unknown"},$e=async t=>q("/api/v1/analytics/dashboard",void 0,t),Re=async(t,a)=>{const s=await q("/api/v1/items",void 0,a);return xe(s,["items","data","results"]).map(n=>({...n,id:n.id||`${n.cookie_id}-${n.item_id}`,is_multi_spec:n.is_multi_spec===!0||n.is_multi_spec===1,multi_quantity_delivery:n.multi_quantity_delivery===!0||n.multi_quantity_delivery===1}))},ie=async(t=7,a)=>{let s;if(typeof t=="number"){const l=new Date,n=new Date;n.setDate(n.getDate()-t),s={start_date:M(n),end_date:M(l)}}else s=t;return q("/api/v1/analytics/orders",{...s,timezone_offset_minutes:-new Date().getTimezoneOffset()},a)},Le=async(t,a)=>{const s=await q("/api/v1/analytics/orders/valid",{...t,timezone_offset_minutes:-new Date().getTimezoneOffset()},a),l=De(s,["data","result"])||{},o=xe(s,["orders","data","items"]).map(b=>({...b,id:b.order_id,status:oe(b.statusLine truncated import{j as e,r as c}from"./react-vendor-C_od1ZSF.js";import{f as me}from"./dateTime-DDi7rqpW.js";import{j as de,k as ge,l as te,D as he,c as pe,P as be,m as se,E as fe,T as ye}from"./icons-vendor-DwxdQTKt.js";import{R as E,B as je,X as ae,Y as re,T as F,a as ve,C as U,A as Ne,b as we,c as _e,P as ne,d as le,L as ke}from"./charts-vendor-deWqkrdG.js";import{g as q,c as xe,o as De}from"./index-zEvleK2K.js";import"./vendor-Es4K8PXl.js";const M=t=>{const a=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),l=String(t.getDate()).padStart(2,"0");return`${a}-${s}-${l}`},H=(t,a)=>{const s=new Date(t);return s.setHours(12,0,0,0),s.setDate(s.getDate()+a),s},X=(t,a)=>({startDate:M(H(t,-(a-1))),endDate:M(t)}),ue=(t,a=new Date,s="",l="")=>{if(t==="custom"&&s&&l){if(s>l)throw new Error("开始日期不能晚于结束日期");return{startDate:s,endDate:l}}return t==="yesterday"?X(H(a,-1),1):X(a,t==="3days"?3:t==="30days"?30:t==="today"?1:7)},Se=t=>{const a=new Date(`${t.startDate}T12:00:00`),s=new Date(`${t.endDate}T12:00:00`),l=Math.round((s.getTime()-a.getTime())/864e5)+1,n=H(a,-1);return X(n,l)},i=(t,a)=>a===void 0?`rgb(var(--color-${t}))`:`rgb(var(--color-${t}) / ${a})`,Ce=({chartData:t,selectedRangeLabel:a,totalAmount:s})=>e.jsxs("div",{className:"ios-card p-8 rounded-xl",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("h3",{className:"text-xl font-bold text-gray-900",children:"营收趋势分析"}),e.jsxs("p",{className:"text-sm text-gray-400 mt-1",children:[a,"的销售额走势"]})]}),e.jsx("div",{className:"dashboard-revenue-chart h-[350px] w-full",children:t.length===0||s===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(de,{className:"w-16 h-16 mb-4 opacity-20"}),e.jsx("p",{className:"text-lg font-medium",children:"暂无营收数据"}),e.jsx("p",{className:"text-sm mt-2",children:"所选时间范围内暂无订单记录"})]}):t.length<=2?e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(je,{data:t,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(ae,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-700"),fontSize:14,fontWeight:600},dy:10}),e.jsx(re,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},tickFormatter:(l=>`¥${l}`)}),e.jsx(F,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{fill:i("brand",.08)},formatter:(l=>[`¥${Number(l).toFixed(2)}`,"营收"])}),e.jsx(ve,{dataKey:"amount",fill:i("brand"),maxBarSize:72,radius:[12,12,0,0],activeBar:!1,stroke:"none",strokeWidth:0,children:t.map((l,n)=>e.jsx(U,{fill:i("brand"),stroke:"none",strokeWidth:0},`cell-${n}`))})]})}):e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(Ne,{data:t,margin:{top:10,right:10,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorAmount",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:i("brand"),stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:i("brand"),stopOpacity:0})]})}),e.jsx(ae,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},dy:15}),e.jsx(re,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500}}),e.jsx(we,{vertical:!1,stroke:i("neutral-100"),strokeDasharray:"3 3"}),e.jsx(F,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{stroke:i("brand"),strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(_e,{type:"monotone",dataKey:"amount",stroke:i("brand"),strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:i("white"),stroke:i("brand"),strokeWidth:2}})]})})})]}),oe=t=>{const a=String(t||"");return a==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(a)?a:"unknown"},$e=async t=>q("/api/v1/analytics/dashboard",void 0,t),Re=async(t,a)=>{const s=await q("/api/v1/items",void 0,a);return xe(s,["items","data","results"]).map(n=>({...n,id:n.id||`${n.cookie_id}-${n.item_id}`,is_multi_spec:n.is_multi_spec===!0||n.is_multi_spec===1,multi_quantity_delivery:n.multi_quantity_delivery===!0||n.multi_quantity_delivery===1}))},ie=async(t=7,a)=>{let s;if(typeof t=="number"){const l=new Date,n=new Date;n.setDate(n.getDate()-t),s={start_date:M(n),end_date:M(l)}}else s=t;return q("/api/v1/analytics/orders",{...s,timezone_offset_minutes:-new Date().getTimezoneOffset()},a)},Le=async(t,a)=>{const s=await q("/api/v1/analytics/orders/valid",{...t,timezone_offset_minutes:-new Date().getTimezoneOffset()},a),l=De(s,["data","result"])||{},o=xe(s,["orders","data","items"]).map(b=>({...b,id:b.order_id,status:oe(b.statusLine truncated
@@ -1,2 +1,2 @@
import{j as e,r,b as we}from"./react-vendor-C_od1ZSF.js";import{g as je,c as Qe,a as ce,b as et,d as tt,A as yt,p as ft}from"./index-KV7tSL6x.js";import{a3 as jt,U as De,R as Se,N as Te,a4 as Pe,a5 as _e,V as vt,y as Nt,B as wt,a6 as Ue,a7 as _t,a8 as kt,A as Ct,d as It,X as be,o as St,a9 as ze,I as Oe}from"./icons-vendor-DwxdQTKt.js";const Ke="ydisks-amap-js-api",Pt="c9b68d4ce9a2a97f22a4a439404488ca";let ye=null;const Bt=()=>Pt,qt=()=>window.AMap?Promise.resolve(window.AMap):ye||(ye=new Promise((s,l)=>{const i=document.getElementById(Ke),m=i||document.createElement("script"),u=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(R)},f=()=>{window.AMap?(u(),s(window.AMap)):(u(),l(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},R=window.setTimeout(()=>{u(),l(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=f,m.id=Ke,m.async=!0,m.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(Bt())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,m.onerror=()=>{u(),l(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},i||document.head.appendChild(m)}).catch(s=>{throw ye=null,s}),ye),ke=s=>Number.isFinite(s)&&s!==0,Lt=s=>{var u,f;const l=Number((u=s.location)==null?void 0:u.lng),i=Number((f=s.location)==null?void 0:f.lat),m={area:String(s.adname||"").trim(),city:String(s.cityname||"").trim(),division_id:String(s.adcode||"").trim(),longitude:l,latitude:i,poi_id:String(s.id||"").trim(),poi_name:String(s.name||"").trim(),province:String(s.pname||"").trim()};return!m.division_id||!m.province||!m.city||!m.poi_id||!m.poi_name||!ke(l)||!ke(i)||l<-180||l>180||i<-90||i>90?null:m},At=async(s,l,i={})=>{if(!ke(s)||!ke(l)||s<-180||s>180||l<-90||l>90)throw new Error("经纬度无效");const m=await qt();return new Promise((u,f)=>{var G,E;let R=!1;const k=Math.max(1,i.timeoutMs??1e4),A=M=>{var p;R||(R=!0,globalThis.clearTimeout(Z),(p=i.signal)==null||p.removeEventListener("abort",I),M())},I=()=>A(()=>f(new DOMException("aborted","AbortError"))),Z=globalThis.setTimeout(()=>A(()=>f(new Error("高德地图附近地址查询超时,请稍后重试"))),k);if((G=i.signal)!=null&&G.aborted){I();return}(E=i.signal)==null||E.addEventListener("abort",I,{once:!0}),new m.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[s,l],1e3,(M,p)=>{var d;if(R)return;if(M!=="complete"){if(M==="no_data"){A(()=>u([]));return}A(()=>f(new Error("高德地图附近地址查询失败,请稍后重试")));return}const B=(((d=p==null?void 0:p.poiList)==null?void 0:d.pois)||[]).map(Lt).filter(j=>j!==null);A(()=>u(B))})})},Et=async s=>je("/api/v1/accounts/details",void 0,s),Je=async s=>je("/api/v1/automation-rules",void 0,s),Mt=(s,l,i)=>At(s,l,i),Be=(s,l)=>{if(s instanceof yt)switch(s.code){case"stock_permission_missing":return"发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。";case"conflict":case"item_conflict":return"商品状态已发生变化,请刷新后重试。";case"external_result_unknown":case"manual_review_required":return"平台结果暂时无法确认,请先人工核对闲鱼状态,再决定是否重试。";case"retryable":case"temporarily_unavailable":return"平台暂时不可用,请稍后重试。";default:return s.message||l}if(s instanceof Error)return s.message;const i=typeof s=="object"&&s!==null&&"message"in s?s.message:void 0;return typeof i=="string"?i:l},qe=s=>s===!0||s===1||s==="1",Ze=async(s,l)=>{const i=await je("/api/v1/items",void 0,l);return Qe(i,["items","data","results"]).map(u=>({...u,id:u.id||`${u.cookie_id}-${u.item_id}`,is_multi_spec:qe(u.is_multi_spec),is_multi_qty_ship:qe(u.is_multi_qty_ship??u.multi_quantity_delivery),multi_quantity_delivery:qe(u.multi_quantity_delivery??u.is_multi_qty_ship)}))},Rt=async s=>ce("/api/v1/items/get-all-from-account",{cookie_id:s}),Ft=async(s,l)=>tt(`/api/v1/items/${s}/${l}`),Gt=async(s,l)=>ce(`/api/v1/items/${s}`,l),$t=async s=>{const l=new FormData;l.set("cookie_id",s.cookie_id),l.set("title",s.title),l.set("description",s.description),l.set("price",s.price),l.set("original_price",s.original_price||""),l.set("quantity",String(s.quantity)),l.set("postage_mode",s.postage_mode),l.set("postage",s.postage||""),s.location&&l.set("location",JSON.stringify(s.location));for(const i of s.images)l.append("images",i);return et("/api/v1/items/publish",l)},Dt=async(s,l,i)=>ce("/api/v1/items/publish-categories/recommend",{cookie_id:s,keyword:l},i),Tt=async(s,l)=>{const i=new FormData;return i.set("file",s.file),s.imagesZip&&i.set("images_zip",s.imagesZip),s.defaultCookieId&&i.set("default_cookie_id",s.defaultCookieId),i.set("fallback_category_id",s.fallbackCategory.catId),i.set("fallback_category_name",s.fallbackCategory.catName),i.set("fallback_channel_category_id",s.fallbackCategory.channelCatId||""),i.set("fallback_tb_category_id",s.fallbackCategory.tbCatLine truncated import{j as e,r,b as we}from"./react-vendor-C_od1ZSF.js";import{g as je,c as Qe,a as ce,b as et,d as tt,A as yt,p as ft}from"./index-zEvleK2K.js";import{a3 as jt,U as De,R as Se,N as Te,a4 as Pe,a5 as _e,V as vt,y as Nt,B as wt,a6 as Ue,a7 as _t,a8 as kt,A as Ct,d as It,X as be,o as St,a9 as ze,I as Oe}from"./icons-vendor-DwxdQTKt.js";const Ke="ydisks-amap-js-api",Pt="c9b68d4ce9a2a97f22a4a439404488ca";let ye=null;const Bt=()=>Pt,qt=()=>window.AMap?Promise.resolve(window.AMap):ye||(ye=new Promise((s,l)=>{const i=document.getElementById(Ke),m=i||document.createElement("script"),u=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(R)},f=()=>{window.AMap?(u(),s(window.AMap)):(u(),l(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},R=window.setTimeout(()=>{u(),l(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=f,m.id=Ke,m.async=!0,m.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(Bt())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,m.onerror=()=>{u(),l(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},i||document.head.appendChild(m)}).catch(s=>{throw ye=null,s}),ye),ke=s=>Number.isFinite(s)&&s!==0,Lt=s=>{var u,f;const l=Number((u=s.location)==null?void 0:u.lng),i=Number((f=s.location)==null?void 0:f.lat),m={area:String(s.adname||"").trim(),city:String(s.cityname||"").trim(),division_id:String(s.adcode||"").trim(),longitude:l,latitude:i,poi_id:String(s.id||"").trim(),poi_name:String(s.name||"").trim(),province:String(s.pname||"").trim()};return!m.division_id||!m.province||!m.city||!m.poi_id||!m.poi_name||!ke(l)||!ke(i)||l<-180||l>180||i<-90||i>90?null:m},At=async(s,l,i={})=>{if(!ke(s)||!ke(l)||s<-180||s>180||l<-90||l>90)throw new Error("经纬度无效");const m=await qt();return new Promise((u,f)=>{var G,E;let R=!1;const k=Math.max(1,i.timeoutMs??1e4),A=M=>{var p;R||(R=!0,globalThis.clearTimeout(Z),(p=i.signal)==null||p.removeEventListener("abort",I),M())},I=()=>A(()=>f(new DOMException("aborted","AbortError"))),Z=globalThis.setTimeout(()=>A(()=>f(new Error("高德地图附近地址查询超时,请稍后重试"))),k);if((G=i.signal)!=null&&G.aborted){I();return}(E=i.signal)==null||E.addEventListener("abort",I,{once:!0}),new m.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[s,l],1e3,(M,p)=>{var d;if(R)return;if(M!=="complete"){if(M==="no_data"){A(()=>u([]));return}A(()=>f(new Error("高德地图附近地址查询失败,请稍后重试")));return}const B=(((d=p==null?void 0:p.poiList)==null?void 0:d.pois)||[]).map(Lt).filter(j=>j!==null);A(()=>u(B))})})},Et=async s=>je("/api/v1/accounts/details",void 0,s),Je=async s=>je("/api/v1/automation-rules",void 0,s),Mt=(s,l,i)=>At(s,l,i),Be=(s,l)=>{if(s instanceof yt)switch(s.code){case"stock_permission_missing":return"发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。";case"conflict":case"item_conflict":return"商品状态已发生变化,请刷新后重试。";case"external_result_unknown":case"manual_review_required":return"平台结果暂时无法确认,请先人工核对闲鱼状态,再决定是否重试。";case"retryable":case"temporarily_unavailable":return"平台暂时不可用,请稍后重试。";default:return s.message||l}if(s instanceof Error)return s.message;const i=typeof s=="object"&&s!==null&&"message"in s?s.message:void 0;return typeof i=="string"?i:l},qe=s=>s===!0||s===1||s==="1",Ze=async(s,l)=>{const i=await je("/api/v1/items",void 0,l);return Qe(i,["items","data","results"]).map(u=>({...u,id:u.id||`${u.cookie_id}-${u.item_id}`,is_multi_spec:qe(u.is_multi_spec),is_multi_qty_ship:qe(u.is_multi_qty_ship??u.multi_quantity_delivery),multi_quantity_delivery:qe(u.multi_quantity_delivery??u.is_multi_qty_ship)}))},Rt=async s=>ce("/api/v1/items/get-all-from-account",{cookie_id:s}),Ft=async(s,l)=>tt(`/api/v1/items/${s}/${l}`),Gt=async(s,l)=>ce(`/api/v1/items/${s}`,l),$t=async s=>{const l=new FormData;l.set("cookie_id",s.cookie_id),l.set("title",s.title),l.set("description",s.description),l.set("price",s.price),l.set("original_price",s.original_price||""),l.set("quantity",String(s.quantity)),l.set("postage_mode",s.postage_mode),l.set("postage",s.postage||""),s.location&&l.set("location",JSON.stringify(s.location));for(const i of s.images)l.append("images",i);return et("/api/v1/items/publish",l)},Dt=async(s,l,i)=>ce("/api/v1/items/publish-categories/recommend",{cookie_id:s,keyword:l},i),Tt=async(s,l)=>{const i=new FormData;return i.set("file",s.file),s.imagesZip&&i.set("images_zip",s.imagesZip),s.defaultCookieId&&i.set("default_cookie_id",s.defaultCookieId),i.set("fallback_category_id",s.fallbackCategory.catId),i.set("fallback_category_name",s.fallbackCategory.catName),i.set("fallback_channel_category_id",s.fallbackCategory.channelCatId||""),i.set("fallback_tb_category_id",s.fallbackCategory.tbCatLine truncated
`),X=new Blob(["\uFEFF"+L],{type:"text/csv;charset=utf-8"}),F=URL.createObjectURL(X),P=document.createElement("a");P.href=F,P.download="批量铺货模板.csv",document.body.appendChild(P),P.click(),P.remove(),URL.revokeObjectURL(F)},[]),n=r.useCallback(()=>{y(o=>({...o,cookie_id:s||o.cookie_id})),p(!0)},[s]),h=r.useCallback(()=>{v(o=>({...o,cookie_id:s||o.cookie_id})),d(!0)},[s]),q=r.useCallback(async o=>{if(!(o?s:b.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");D();const L=new AbortController;H.current=L;const X=++z.current;S(!0);try{const F=await new Promise((ue,me)=>{const Ce=Q=>ue(Q),re=Q=>me(Q);navigator.geolocation.getCurrentPosition(Ce,re,{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})});if(L.signal.aborted||X!==z.current)return;const P=await Mt(F.coords.longitude,F.coords.latitude,{signal:L.signal});if(L.signal.aborted||X!==z.current)return;if(!P.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");o?(R(P),k(P[0])):(W(P),U(P[0]))}catch(F){if(L.signal.aborted||X!==z.current)return;if(typeof F=="object"&&F!==null&&"code"in F){const P=F;alert(P.code===P.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")}else alert(Be(F,"获取发货地失败"))}finally{X===z.current&&(H.current=null,S(!1))}},[D,b.cookie_id,s,k,R]);return{selectedAccount:s,setSelectedAccount:l,loading:A,publishing:Z,showEditModal:G,setShowEditModal:E,showAddModal:M,setShowAddModal:p,showPublishModal:B,setShowPublishModal:d,locationLoading:j,publishLocations:V,setPublishLocations:W,publishLocation:Y,setPublishLocation:U,selectedItem:$,editForm:C,setEditForm:se,addForm:g,setAddForm:y,publishForm:b,setPublishForm:v,publishImagePreviews:x,handleSync:te,handleEdit:oe,handleSaveEdit:le,handleDelete:de,handleAddItem:xe,handlePublishItem:ve,downloadPublishTemplate:a,openAddModal:n,openPublishModal:h,locateForPublish:q}},Qt=s=>{const l=String(s||"").trim();return l?/^[¥¥]/.test(l)?l:`¥${l}`:"-"},as=({onConfigureDelivery:s})=>{const[l,i]=r.useState([]),[m,u]=r.useState([]),[f,R]=r.useState([]),[k,A]=r.useState(""),[I,Z]=r.useState(""),T=r.useRef(0),G=r.useRef(0),E=r.useCallback(async()=>{const t=++T.current,c=await Ze();t===T.current&&i(c)},[]),M=r.useCallback(async()=>{const t=++G.current,c=await Je();t===G.current&&u(c)},[]),p=Ht({selectedAccount:k,loadItems:E,loadShippingRules:M}),{showBatchModal:B,batchLoading:d,batchPhase:j,batchFile:S,setBatchFile:V,batchImagesZip:W,setBatchImagesZip:Y,batchCategoryKeyword:U,setBatchCategoryKeyword:$,batchCategoryLoading:K,batchFallbackCategory:C,setBatchFallbackCategory:se,batchPreview:g,batchDetail:y,recentBatch:b,setRecentBatch:v,batchLocations:x,batchLocation:ae,batchPublishIntervalSeconds:H,setBatchPublishIntervalSeconds:z,setBatchLocations:D,setBatchLocation:te,openBatchModal:oe,handleRecommendBatchCategory:le,openRecentBatchResult:de,handlePreviewBatch:xe,handleStartBatch:ve,handleCancelBatch:a,abandonBatchPreview:n,closeBatchModal:h,handleRetryBatchFailed:q}=p,o=Xt({selectedAccount:k,setSelectedAccount:A,setItems:i,loadItems:E,loadShippingRules:M,onConfigureDelivery:s,setBatchLocations:D,setBatchLocation:te}),{loading:N,publishing:L,showEditModal:X,setShowEditModal:F,showAddModal:P,setShowAddModal:ue,showPublishModal:me,setShowPublishModal:Ce,locationLoading:re,publishLocations:Q,setPublishLocations:at,publishLocation:lt,setPublishLocation:Le,selectedItem:Ae,editForm:ee,setEditForm:Ne,addForm:O,setAddForm:he,publishForm:w,setPublishForm:J,publishImagePreviews:Ee,handleSync:rt,handleEdit:nt,handleSaveEdit:it,handleDelete:ct,handleAddItem:ot,handlePublishItem:dt,downloadPublishTemplate:xt,openAddModal:ut,openPublishModal:mt,locateForPublish:Me}=o;r.useEffect(()=>{const t=new AbortController,c=++T.current,_=++G.current;let ge=!0;return Promise.all([Et({signal:t.signal}),Ze(void 0,{signal:t.signal}),Je({signal:t.signal}),st(20,{signal:t.signal})]).then(([ne,pt,gt,$e])=>{if(!ge||t.signal.aborted||c!==T.current||_!==G.current)return;R(ne),i(pt),u(gt);const bt=$e.find(Ie=>["running","canceling"].includes(Ie.status))||$e.find(Ie=>Ie.status!=="preview");v(bt||null)}).catch(ne=>{t.signal.aborted||console.error("加载商品配置失败:",ne)}),(()=>{ge=!1,t.abort()})},[]);const ht=t=>m.filter(c=>c.cookie_id===t.cookie_id&&c.item_id===t.item_id).length>0?m.filter(c=>c.cookie_id===t.cookie_id&&c.item_id===t.item_id):m.filter(c=>c.cookie_id===t.cookie_id&&!c.item_id),Re=r.useMemo(()=>new Map(f.map(t=>[t.id,t])),[f]),Fe=r.useMemo(()=>I?l.filter(t=>t.cookie_id===I):l,[I,l]),pe=t=>{const c=Re.get(t),_=(c==null?void 0:c.remark)||(c==null?void 0:c.nickname);return _?`${_} · ${t.slice(0,6)}`:`账号 ${t.slice(0,8)}`},Ge=t=>{const c=Re.get(t);return(c==null?void 0:c.remark)||(c==null?void 0:c.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"fl Line truncated `),X=new Blob(["\uFEFF"+L],{type:"text/csv;charset=utf-8"}),F=URL.createObjectURL(X),P=document.createElement("a");P.href=F,P.download="批量铺货模板.csv",document.body.appendChild(P),P.click(),P.remove(),URL.revokeObjectURL(F)},[]),n=r.useCallback(()=>{y(o=>({...o,cookie_id:s||o.cookie_id})),p(!0)},[s]),h=r.useCallback(()=>{v(o=>({...o,cookie_id:s||o.cookie_id})),d(!0)},[s]),q=r.useCallback(async o=>{if(!(o?s:b.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");D();const L=new AbortController;H.current=L;const X=++z.current;S(!0);try{const F=await new Promise((ue,me)=>{const Ce=Q=>ue(Q),re=Q=>me(Q);navigator.geolocation.getCurrentPosition(Ce,re,{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})});if(L.signal.aborted||X!==z.current)return;const P=await Mt(F.coords.longitude,F.coords.latitude,{signal:L.signal});if(L.signal.aborted||X!==z.current)return;if(!P.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");o?(R(P),k(P[0])):(W(P),U(P[0]))}catch(F){if(L.signal.aborted||X!==z.current)return;if(typeof F=="object"&&F!==null&&"code"in F){const P=F;alert(P.code===P.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")}else alert(Be(F,"获取发货地失败"))}finally{X===z.current&&(H.current=null,S(!1))}},[D,b.cookie_id,s,k,R]);return{selectedAccount:s,setSelectedAccount:l,loading:A,publishing:Z,showEditModal:G,setShowEditModal:E,showAddModal:M,setShowAddModal:p,showPublishModal:B,setShowPublishModal:d,locationLoading:j,publishLocations:V,setPublishLocations:W,publishLocation:Y,setPublishLocation:U,selectedItem:$,editForm:C,setEditForm:se,addForm:g,setAddForm:y,publishForm:b,setPublishForm:v,publishImagePreviews:x,handleSync:te,handleEdit:oe,handleSaveEdit:le,handleDelete:de,handleAddItem:xe,handlePublishItem:ve,downloadPublishTemplate:a,openAddModal:n,openPublishModal:h,locateForPublish:q}},Qt=s=>{const l=String(s||"").trim();return l?/^[¥¥]/.test(l)?l:`¥${l}`:"-"},as=({onConfigureDelivery:s})=>{const[l,i]=r.useState([]),[m,u]=r.useState([]),[f,R]=r.useState([]),[k,A]=r.useState(""),[I,Z]=r.useState(""),T=r.useRef(0),G=r.useRef(0),E=r.useCallback(async()=>{const t=++T.current,c=await Ze();t===T.current&&i(c)},[]),M=r.useCallback(async()=>{const t=++G.current,c=await Je();t===G.current&&u(c)},[]),p=Ht({selectedAccount:k,loadItems:E,loadShippingRules:M}),{showBatchModal:B,batchLoading:d,batchPhase:j,batchFile:S,setBatchFile:V,batchImagesZip:W,setBatchImagesZip:Y,batchCategoryKeyword:U,setBatchCategoryKeyword:$,batchCategoryLoading:K,batchFallbackCategory:C,setBatchFallbackCategory:se,batchPreview:g,batchDetail:y,recentBatch:b,setRecentBatch:v,batchLocations:x,batchLocation:ae,batchPublishIntervalSeconds:H,setBatchPublishIntervalSeconds:z,setBatchLocations:D,setBatchLocation:te,openBatchModal:oe,handleRecommendBatchCategory:le,openRecentBatchResult:de,handlePreviewBatch:xe,handleStartBatch:ve,handleCancelBatch:a,abandonBatchPreview:n,closeBatchModal:h,handleRetryBatchFailed:q}=p,o=Xt({selectedAccount:k,setSelectedAccount:A,setItems:i,loadItems:E,loadShippingRules:M,onConfigureDelivery:s,setBatchLocations:D,setBatchLocation:te}),{loading:N,publishing:L,showEditModal:X,setShowEditModal:F,showAddModal:P,setShowAddModal:ue,showPublishModal:me,setShowPublishModal:Ce,locationLoading:re,publishLocations:Q,setPublishLocations:at,publishLocation:lt,setPublishLocation:Le,selectedItem:Ae,editForm:ee,setEditForm:Ne,addForm:O,setAddForm:he,publishForm:w,setPublishForm:J,publishImagePreviews:Ee,handleSync:rt,handleEdit:nt,handleSaveEdit:it,handleDelete:ct,handleAddItem:ot,handlePublishItem:dt,downloadPublishTemplate:xt,openAddModal:ut,openPublishModal:mt,locateForPublish:Me}=o;r.useEffect(()=>{const t=new AbortController,c=++T.current,_=++G.current;let ge=!0;return Promise.all([Et({signal:t.signal}),Ze(void 0,{signal:t.signal}),Je({signal:t.signal}),st(20,{signal:t.signal})]).then(([ne,pt,gt,$e])=>{if(!ge||t.signal.aborted||c!==T.current||_!==G.current)return;R(ne),i(pt),u(gt);const bt=$e.find(Ie=>["running","canceling"].includes(Ie.status))||$e.find(Ie=>Ie.status!=="preview");v(bt||null)}).catch(ne=>{t.signal.aborted||console.error("加载商品配置失败:",ne)}),(()=>{ge=!1,t.abort()})},[]);const ht=t=>m.filter(c=>c.cookie_id===t.cookie_id&&c.item_id===t.item_id).length>0?m.filter(c=>c.cookie_id===t.cookie_id&&c.item_id===t.item_id):m.filter(c=>c.cookie_id===t.cookie_id&&!c.item_id),Re=r.useMemo(()=>new Map(f.map(t=>[t.id,t])),[f]),Fe=r.useMemo(()=>I?l.filter(t=>t.cookie_id===I):l,[I,l]),pe=t=>{const c=Re.get(t),_=(c==null?void 0:c.remark)||(c==null?void 0:c.nickname);return _?`${_} · ${t.slice(0,6)}`:`账号 ${t.slice(0,8)}`},Ge=t=>{const c=Re.get(t);return(c==null?void 0:c.remark)||(c==null?void 0:c.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"fl Line truncated
@@ -1 +1 @@
import{j as e,b as _e,r as d}from"./react-vendor-C_od1ZSF.js";import{ai as ee,ah as se,aj as Ne,u as K,e as W,L as I,w as ve,y as ke,t as Q,X as te,z as ae,F as ne,o as we,R as Se,N as Ce}from"./icons-vendor-DwxdQTKt.js";import{g as re,p as le,a as oe,d as Te}from"./index-KV7tSL6x.js";const H=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],G=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},ie=s=>{const t=Object.prototype.hasOwnProperty.call(s,"use_custom_smtp"),a=H.some(n=>String(s[n]??"").trim()!=="");return{...s,use_custom_smtp:t?G(s.use_custom_smtp,!1):a}},ce=(s,t)=>{const a={...s,use_custom_smtp:!0};for(const n of H)String(a[n]??"").trim()===""&&t[n]!==void 0&&(a[n]=t[n]);return a.smtp_port||(a.smtp_port=587),a.smtp_from_address||(a.smtp_from_address=a.smtp_user||""),a.smtp_use_tls=G(a.smtp_use_tls,!0),a.smtp_use_ssl=G(a.smtp_use_ssl,!1),a},de=s=>{const t=ie(s),a={to_email:String(t.to_email??"").trim(),use_custom_smtp:t.use_custom_smtp===!0};if(a.use_custom_smtp)for(const n of H)a[n]=t[n];return a},B={bark:{label:"Bark",icon:W,fields:[{key:"server_url",label:"Bark 服务器",placeholder:"https://api.day.app",required:!0},{key:"device_key",label:"Device Key",placeholder:"你的 Bark 设备 Key",required:!0},{key:"title",label:"标题(可选)",placeholder:"Ydisks闲鱼助手"},{key:"sound",label:"铃声(可选)",placeholder:"default"},{key:"group",label:"分组(可选)",placeholder:"xianyu"}],guide:{steps:["App Store 搜索并安装 Bark(免费)","打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app/<key>/这是测试推送内容","URL 路径里 <key> 那一段就是 Device Key,复制填入","服务器地址默认 https://api.day.app,自建服务端则填自建域名"],urlFormat:"https://api.day.app/<你的key>/测试内容",note:"不需要 secret,Device Key 本身就是唯一凭证。"}},dingtalk:{label:"钉钉机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://oapi.dingtalk.com/robot/send?access_token=...",required:!0},{key:"secret",label:"加签密钥",placeholder:"SEC...",help:"安全设置勾选「加签」后生成,SEC 开头"}],guide:{steps:["钉钉进入一个群(可建单人群)→ 右上角 群设置","机器人 → 添加机器人 → 选择「自定义机器人」","安全设置勾选「加签」","完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制","Webhook URL 填上面,Secret 填加签密钥"],urlFormat:"https://oapi.dingtalk.com/robot/send?access_token=XXX",note:"加签密钥可选,但强烈建议启用,否则机器人可能被滥用。"}},feishu:{label:"飞书机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://open.feishu.cn/open-apis/bot/v2/hook/...",required:!0},{key:"secret",label:"签名校验密钥",placeholder:"sec-...",help:"安全设置选「签名校验」后生成"}],guide:{steps:["飞书进入目标群 → 右上角 更多 → 设置","群机器人 → 添加机器人 → 自定义机器人","安全设置选择「签名校验」,复制生成的秘钥","完成会给 Webhook 地址,复制","Webhook URL 填上面,秘钥填签名校验密钥"],urlFormat:"https://open.feishu.cn/open-apis/bot/v2/hook/xxx",note:"签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。"}},wechat:{label:"企业微信机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...",required:!0}],guide:{steps:["企业微信进入一个内部群 → 右上角 … → 群设置","找到「群机器人」(新版可能叫「消息推送」)","添加 → 选择自定义机器人","完成给 Webhook 地址(含 ?key=),复制填入"],urlFormat:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX",note:"不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。"}},webhook:{label:"自定义 Webhook",icon:Ne,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://your-server/notify",required:!0}],guide:{steps:["仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON","系统会 POST 这个 URL,Content-Type: application/json","请求体固定为右侧 JSON 格式,按需解析 message 字段"],urlFormat:'{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',note:"若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。"}},telegram:{label:"Telegram",icon:se,fields:[{key:"bot_token",label:"Bot Token",placeholder:"123456:ABC-DEF...",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"-1001234567890 或你的用户 ID",Line truncated import{j as e,b as _e,r as d}from"./react-vendor-C_od1ZSF.js";import{ai as ee,ah as se,aj as Ne,u as K,e as W,L as I,w as ve,y as ke,t as Q,X as te,z as ae,F as ne,o as we,R as Se,N as Ce}from"./icons-vendor-DwxdQTKt.js";import{g as le,p as re,a as oe,d as Te}from"./index-zEvleK2K.js";const H=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],G=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},ie=s=>{const t=Object.prototype.hasOwnProperty.call(s,"use_custom_smtp"),a=H.some(n=>String(s[n]??"").trim()!=="");return{...s,use_custom_smtp:t?G(s.use_custom_smtp,!1):a}},ce=(s,t)=>{const a={...s,use_custom_smtp:!0};for(const n of H)String(a[n]??"").trim()===""&&t[n]!==void 0&&(a[n]=t[n]);return a.smtp_port||(a.smtp_port=587),a.smtp_from_address||(a.smtp_from_address=a.smtp_user||""),a.smtp_use_tls=G(a.smtp_use_tls,!0),a.smtp_use_ssl=G(a.smtp_use_ssl,!1),a},de=s=>{const t=ie(s),a={to_email:String(t.to_email??"").trim(),use_custom_smtp:t.use_custom_smtp===!0};if(a.use_custom_smtp)for(const n of H)a[n]=t[n];return a},B={bark:{label:"Bark",icon:W,fields:[{key:"server_url",label:"Bark 服务器",placeholder:"https://api.day.app",required:!0},{key:"device_key",label:"Device Key",placeholder:"你的 Bark 设备 Key",required:!0},{key:"title",label:"标题(可选)",placeholder:"Ydisks闲鱼助手"},{key:"sound",label:"铃声(可选)",placeholder:"default"},{key:"group",label:"分组(可选)",placeholder:"xianyu"}],guide:{steps:["App Store 搜索并安装 Bark(免费)","打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app/<key>/这是测试推送内容","URL 路径里 <key> 那一段就是 Device Key,复制填入","服务器地址默认 https://api.day.app,自建服务端则填自建域名"],urlFormat:"https://api.day.app/<你的key>/测试内容",note:"不需要 secret,Device Key 本身就是唯一凭证。"}},dingtalk:{label:"钉钉机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://oapi.dingtalk.com/robot/send?access_token=...",required:!0},{key:"secret",label:"加签密钥",placeholder:"SEC...",help:"安全设置勾选「加签」后生成,SEC 开头"}],guide:{steps:["钉钉进入一个群(可建单人群)→ 右上角 群设置","机器人 → 添加机器人 → 选择「自定义机器人」","安全设置勾选「加签」","完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制","Webhook URL 填上面,Secret 填加签密钥"],urlFormat:"https://oapi.dingtalk.com/robot/send?access_token=XXX",note:"加签密钥可选,但强烈建议启用,否则机器人可能被滥用。"}},feishu:{label:"飞书机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://open.feishu.cn/open-apis/bot/v2/hook/...",required:!0},{key:"secret",label:"签名校验密钥",placeholder:"sec-...",help:"安全设置选「签名校验」后生成"}],guide:{steps:["飞书进入目标群 → 右上角 更多 → 设置","群机器人 → 添加机器人 → 自定义机器人","安全设置选择「签名校验」,复制生成的秘钥","完成会给 Webhook 地址,复制","Webhook URL 填上面,秘钥填签名校验密钥"],urlFormat:"https://open.feishu.cn/open-apis/bot/v2/hook/xxx",note:"签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。"}},wechat:{label:"企业微信机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...",required:!0}],guide:{steps:["企业微信进入一个内部群 → 右上角 … → 群设置","找到「群机器人」(新版可能叫「消息推送」)","添加 → 选择自定义机器人","完成给 Webhook 地址(含 ?key=),复制填入"],urlFormat:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX",note:"不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。"}},webhook:{label:"自定义 Webhook",icon:Ne,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://your-server/notify",required:!0}],guide:{steps:["仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON","系统会 POST 这个 URL,Content-Type: application/json","请求体固定为右侧 JSON 格式,按需解析 message 字段"],urlFormat:'{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',note:"若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。"}},telegram:{label:"Telegram",icon:se,fields:[{key:"bot_token",label:"Bot Token",placeholder:"123456:ABC-DEF...",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"-1001234567890 或你的用户 ID",Line truncated
@@ -1 +1 @@
import{j as e,b as X,r as a}from"./react-vendor-C_od1ZSF.js";import{f as Z}from"./dateTime-DDi7rqpW.js";import{U as re,I as ie,X as H,J as ce,R as K,N as oe,O as ee,m as se,E as de,F as xe,V as me,y as ue,h as he,g as ge,o as pe}from"./icons-vendor-DwxdQTKt.js";import{g as U,o as be,c as ye,b as le,a as Y,p as fe,d as ne}from"./index-KV7tSL6x.js";const ve=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],je=s=>{const t=typeof s=="object"&&s!==null?s:{},i=Array.isArray(t.results)?t.results:[];return{total:Number(t.total||0),success_count:Number(t.success_count||0),failed_count:Number(t.failed_count||0),results:i.map(Ne)}},Ne=s=>{const t=typeof s=="object"&&s!==null?s:{};return{order_id:String(t.order_id||"unknown"),success:t.success===!0,message:String(t.message||"")}},we=s=>(s==null?void 0:s.results.filter(_e))||[],_e=s=>!s.success,ke=(s,t)=>s!==null&&!t,Ce=s=>{if(!s)return"请选择订单文件";const t=s.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(t)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},T=(s,t)=>s===t,Se=(s,t)=>s instanceof Error&&s.message?s.message:t,Ee=({filter:s,onFilterChange:t,accountFilter:i,onAccountFilterChange:u,accounts:b,accountName:m,searchText:h,onSearchChange:N})=>{const g=l=>t(l.currentTarget.dataset.status||"all"),f=l=>u(l.target.value),y=l=>N(l.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:ve.map(l=>e.jsx("button",{"data-status":l.key,onClick:g,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${s===l.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:l.label},l.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(re,{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:i,onChange:f,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:"全部账号"}),b.map(l=>e.jsx("option",{value:l.id,children:m(l.id)},l.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(ie,{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:h,onChange:y,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Oe=s=>{const t=m=>{var h;s.setImportFile(((h=m.target.files)==null?void 0:h[0])||null)},i=()=>s.closeImportModal(),u=()=>void s.handleImportOrders(),b=()=>void s.handleRetryImport();return s.showImportModal?X.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:i,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{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:t,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:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),s.importFile&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ce,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:s.importFile.name})]})}),s.importError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-100 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.importError}),e.jsx("button",{type:"button",onClick:b,disabled:s.importing||!s.importFile,className:"font-bold whitespace-nowrap",children:"重试"})]}),s.importResult&&s.importResult.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:成功 ",s.importResult.success_count," 条,失败 ",s.iLine truncated import{j as e,b as X,r as a}from"./react-vendor-C_od1ZSF.js";import{f as Z}from"./dateTime-DDi7rqpW.js";import{U as re,I as ie,X as H,J as ce,R as K,N as oe,O as ee,m as se,E as de,F as xe,V as me,y as ue,h as he,g as ge,o as pe}from"./icons-vendor-DwxdQTKt.js";import{g as U,o as be,c as ye,b as le,a as Y,p as fe,d as ne}from"./index-zEvleK2K.js";const ve=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],je=s=>{const t=typeof s=="object"&&s!==null?s:{},i=Array.isArray(t.results)?t.results:[];return{total:Number(t.total||0),success_count:Number(t.success_count||0),failed_count:Number(t.failed_count||0),results:i.map(Ne)}},Ne=s=>{const t=typeof s=="object"&&s!==null?s:{};return{order_id:String(t.order_id||"unknown"),success:t.success===!0,message:String(t.message||"")}},we=s=>(s==null?void 0:s.results.filter(_e))||[],_e=s=>!s.success,ke=(s,t)=>s!==null&&!t,Ce=s=>{if(!s)return"请选择订单文件";const t=s.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(t)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},T=(s,t)=>s===t,Se=(s,t)=>s instanceof Error&&s.message?s.message:t,Ee=({filter:s,onFilterChange:t,accountFilter:i,onAccountFilterChange:u,accounts:b,accountName:m,searchText:h,onSearchChange:N})=>{const g=l=>t(l.currentTarget.dataset.status||"all"),f=l=>u(l.target.value),y=l=>N(l.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:ve.map(l=>e.jsx("button",{"data-status":l.key,onClick:g,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${s===l.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:l.label},l.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(re,{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:i,onChange:f,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:"全部账号"}),b.map(l=>e.jsx("option",{value:l.id,children:m(l.id)},l.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(ie,{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:h,onChange:y,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Oe=s=>{const t=m=>{var h;s.setImportFile(((h=m.target.files)==null?void 0:h[0])||null)},i=()=>s.closeImportModal(),u=()=>void s.handleImportOrders(),b=()=>void s.handleRetryImport();return s.showImportModal?X.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:i,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{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:t,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:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),s.importFile&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ce,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:s.importFile.name})]})}),s.importError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-100 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.importError}),e.jsx("button",{type:"button",onClick:b,disabled:s.importing||!s.importFile,className:"font-bold whitespace-nowrap",children:"重试"})]}),s.importResult&&s.importResult.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:成功 ",s.importResult.success_count," 条,失败 ",s.iLine truncated
@@ -1 +1 @@
import{j as e,r as o,b as Fe}from"./react-vendor-C_od1ZSF.js";import{k as Je,ae as it,af as vt,m as Nt,R as Te,N as Ye,Z as He,u as wt,n as et,I as kt,a1 as Ct,X as ke,V as ze,y as Ce,h as St,g as Rt,a6 as At,ag as $t,o as tt,ah as Mt}from"./icons-vendor-DwxdQTKt.js";import{g as Z,o as Ae,c as Ge,p as Ke,a as fe,d as Ue}from"./index-KV7tSL6x.js";const Ee=(t,a)=>t.allowed_resolutions.includes(a),Pt=(t,a)=>({runs:t.runs.filter(i=>!a||i.cookie_id===a),pending_tasks:t.pending_tasks.filter(i=>!a||i.cookie_id===a)}),Lt=t=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[t]||"自动化异常",It=({runs:t,pendingTasks:a,onResolveRun:i,onResolveDeferredTask:u})=>e.jsxs("section",{className:"rounded-2xl border border-red-200 bg-red-50 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-black text-red-900",children:"需要人工处理的自动化任务"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。"})]})]}),e.jsxs("div",{className:"space-y-3",children:[t.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 订单 ",r.order_id||"-"," · 已记录发送 ",r.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:Lt(r.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[Ee(r,"continue")&&e.jsx("button",{onClick:(()=>i(r.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),Ee(r,"retry")&&e.jsx("button",{onClick:(()=>i(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),Ee(r,"cancel")&&e.jsx("button",{onClick:(()=>i(r.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${r.id}`)),a.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 延迟任务重试已达 ",r.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:(()=>u(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:(()=>u(r.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${r.id}`))]})]}),Dt=async t=>Z("/api/v1/accounts/details",void 0,t),ot=async t=>Z("/api/v1/cards",void 0,t),dt=async(t,a)=>Z("/api/v1/items",void 0,a),ct=t=>t.map(a=>{var i,u;return{id:String(a.id),name:a.name||"",trigger_type:a.trigger_type||"order_paid",item_keyword:a.item_title||a.item_id||"",cookie_id:a.cookie_id||"",item_id:a.item_id||"",item_title:a.item_title||"",card_group_id:Number(((i=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:i.card_id)||0),card_group_name:((u=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:u.card_name)||"",priority:a.priority||100,enabled:a.enabled||!1,config_json:a.config_json||"{}",actions:(a.actions||[]).map(r=>({id:r.id?String(r.id):void 0,action_type:r.action_type,card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),message_template:r.message_template||"",delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}",enabled:r.enabled!==!1,sort_order:Number(r.sort_order||0)})),variants:(a.actions||[]).filter(r=>r.action_type==="send_card").map(r=>{let y={};try{y=JSON.parse(r.config_json||"{}")}catch{}return{id:r.id?String(r.id):void 0,spec_name:y.spec_name||"",spec_value:y.spec_value||"",card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),enabled:r.enabled!==!1,delay_override:y.delay_override===!0,delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}"}})}}),Ft=async()=>{const t=await Z("/api/v1/automation-rules"),a=Ge(t,["data","rules","items"]);return ct(a)},Tt=async({cookieId:t,triggerType:a,enabled:i,search:u,page:r=1,pageSize:y=10}={})=>{const A=await Z("/api/vLine truncated import{j as e,r as o,b as Fe}from"./react-vendor-C_od1ZSF.js";import{k as Je,ae as it,af as vt,m as Nt,R as Te,N as Ye,Z as He,u as wt,n as et,I as kt,a1 as Ct,X as ke,V as ze,y as Ce,h as St,g as Rt,a6 as At,ag as $t,o as tt,ah as Mt}from"./icons-vendor-DwxdQTKt.js";import{g as Z,o as Ae,c as Ge,p as Ke,a as fe,d as Ue}from"./index-zEvleK2K.js";const Ee=(t,a)=>t.allowed_resolutions.includes(a),Pt=(t,a)=>({runs:t.runs.filter(i=>!a||i.cookie_id===a),pending_tasks:t.pending_tasks.filter(i=>!a||i.cookie_id===a)}),Lt=t=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[t]||"自动化异常",It=({runs:t,pendingTasks:a,onResolveRun:i,onResolveDeferredTask:u})=>e.jsxs("section",{className:"rounded-2xl border border-red-200 bg-red-50 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-black text-red-900",children:"需要人工处理的自动化任务"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。"})]})]}),e.jsxs("div",{className:"space-y-3",children:[t.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 订单 ",r.order_id||"-"," · 已记录发送 ",r.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:Lt(r.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[Ee(r,"continue")&&e.jsx("button",{onClick:(()=>i(r.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),Ee(r,"retry")&&e.jsx("button",{onClick:(()=>i(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),Ee(r,"cancel")&&e.jsx("button",{onClick:(()=>i(r.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${r.id}`)),a.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 延迟任务重试已达 ",r.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:(()=>u(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:(()=>u(r.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${r.id}`))]})]}),Dt=async t=>Z("/api/v1/accounts/details",void 0,t),ot=async t=>Z("/api/v1/cards",void 0,t),dt=async(t,a)=>Z("/api/v1/items",void 0,a),ct=t=>t.map(a=>{var i,u;return{id:String(a.id),name:a.name||"",trigger_type:a.trigger_type||"order_paid",item_keyword:a.item_title||a.item_id||"",cookie_id:a.cookie_id||"",item_id:a.item_id||"",item_title:a.item_title||"",card_group_id:Number(((i=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:i.card_id)||0),card_group_name:((u=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:u.card_name)||"",priority:a.priority||100,enabled:a.enabled||!1,config_json:a.config_json||"{}",actions:(a.actions||[]).map(r=>({id:r.id?String(r.id):void 0,action_type:r.action_type,card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),message_template:r.message_template||"",delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}",enabled:r.enabled!==!1,sort_order:Number(r.sort_order||0)})),variants:(a.actions||[]).filter(r=>r.action_type==="send_card").map(r=>{let y={};try{y=JSON.parse(r.config_json||"{}")}catch{}return{id:r.id?String(r.id):void 0,spec_name:y.spec_name||"",spec_value:y.spec_value||"",card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),enabled:r.enabled!==!1,delay_override:y.delay_override===!0,delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}"}})}}),Ft=async()=>{const t=await Z("/api/v1/automation-rules"),a=Ge(t,["data","rules","items"]);return ct(a)},Tt=async({cookieId:t,triggerType:a,enabled:i,search:u,page:r=1,pageSize:y=10}={})=>{const A=await Z("/api/vLine truncated
@@ -1 +1 @@
import{r,j as e}from"./react-vendor-C_od1ZSF.js";import{a as xe,g as re,p as le}from"./index-KV7tSL6x.js";import{f as ue,R as se,aa as pe,r as me,z as R,F as O,ab as he,t as ge,S as te,ac as ae,ad as ye,o as fe}from"./icons-vendor-DwxdQTKt.js";const ne="https://dashscope.aliyuncs.com/compatible-mode/v1",be=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],we=new Set(["ai_api_key_configured","smtp_password_configured","qq_reply_secret_key_configured","captcha.remote_secret_key_configured","smtp_server","smtp_port","smtp_user","smtp_password","smtp_from","smtp_from_name","smtp_from_address","registration_enabled","show_default_login_info","login_captcha_enabled","item_sync_enabled","item_sync_interval","item_sync_max_pages","default_reply"]),oe=new Set(["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"]),je=s=>{if("values"in s||"secrets"in s)return s;const a={},o={};for(const[d,h]of Object.entries(s))if(h!=null){if(oe.has(d)){o[d]=h===""?{action:"clear"}:{action:"replace",value:String(h)};continue}a[d]=h}return Object.keys(o).length>0?{values:a,secrets:o}:a},ve=s=>{const a={...s};for(const o of oe){const d=`${o}_configured`;d in a&&(a[d]=a[d]===!0||a[d]==="true")}if("renewal_log_retention_days"in a){const o=Number(a.renewal_log_retention_days);a.renewal_log_retention_days=Number.isFinite(o)?o:10}return a},_e=async(s,a)=>le("/api/v1/session/credentials",s,a),Ne=async s=>{const a=await re("/api/v1/settings/system",void 0,s),o=a.data||a.settings||a;return ve(o)},Se=async(s,a)=>le("/api/v1/settings/system",je(s),a),ke=async(s,a="",o)=>{const d=await xe("/api/v1/settings/ai-models",{base_url:s,api_key:a},o);return Array.isArray(d.models)?d.models:[]},Ce=async s=>re("/api/v1/session",void 0,s),Ee=s=>Object.fromEntries(Object.entries(s).filter(([a,o])=>!we.has(a)&&o!==void 0&&o!==null)),Ae=s=>s.new_username.trim().length<3?"用户名至少需要 3 个字符":s.current_password?s.new_password&&s.new_password.length<8?"新密码至少需要 8 个字符":s.new_password!==s.confirm_password?"两次输入的新密码不一致":"":"请输入当前密码确认身份",f=(s,a,o)=>s===a&&!o.aborted,D=s=>s instanceof Error&&s.message==="请求已取消",K=(s,a)=>s instanceof Error?s.message:a,Ie=(s="")=>({new_username:s,current_password:"",new_password:"",confirm_password:""}),T=(s,a)=>({type:s,text:a}),Me=()=>{const[s,a]=r.useState(null),[o,d]=r.useState(!1),[h,p]=r.useState(""),[S,A]=r.useState(!1),[P,k]=r.useState(""),[C,w]=r.useState([]),[j,I]=r.useState(!1),[M,x]=r.useState(""),[$,v]=r.useState(!1),[z,q]=r.useState(!1),[U,u]=r.useState(!1),[b,F]=r.useState(!1),[G,V]=r.useState(!1),[Y,_]=r.useState(!1),[L,y]=r.useState(null),[t,X]=r.useState(()=>Ie()),[ce,J]=r.useState("idle"),Z=r.useRef(null),ee=r.useRef(null),m=r.useRef(0),W=r.useRef(null);ee.current=s;const E=r.useCallback(()=>{var c;(c=W.current)==null||c.abort();const n=new AbortController;return W.current=n,m.current+=1,{controller:n,sequence:m.current}},[]),B=r.useCallback(async(n,c=!1,l)=>{const i=n||ee.current,g=(i==null?void 0:i.ai_api_url)||(i==null?void 0:i.ai_base_url)||ne;I(!0),x("");try{const N=await ke(g,(i==null?void 0:i.ai_api_key)||"",{signal:l});if(l!=null&&l.aborted)return;w(N),v(c&&N.length>0),!(i!=null&&i.ai_model)&&N.length>0&&a(Q=>Q&&{...Q,ai_model:N[0]})}catch(N){if(l!=null&&l.aborted||D(N))return;w([]),v(!1),x(K(N,"读取模型失败"))}finally{l!=null&&l.aborted||I(!1)}},[]),H=r.useCallback(()=>{const{controller:n,sequence:c}=E();d(!0),J("loading"),p(""),Promise.all([Ne({signal:n.signal}),Ce({signal:n.signal})]).then(([l,i])=>{f(m.current,c,n.signal)&&(a(l),i.username&&X(g=>({...g,new_username:i.username||""})),B(l,!1,n.signal),J("success"))}).catch(l=>{!f(m.current,c,n.signal)||D(l)||(a(null),p(K(l,"加载配置失败")),J("error"))}).finally(()=>{f(m.current,c,n.signal)&&d(!1)})},[E,B]);r.useEffect(()=>(H(),(()=>{var n;return(n=W.current)==null?void 0:n.abort()})),[H]),r.useEffect(()=>{const n=c=>{var l;(l=Z.current)!=null&&l.contains(c.target)||v(!1)};return document.addEventListener("mousedown",n),(()=>document.removeEventListener("mousedown",n))},[]);const ie=r.useCallback(async()=>{if(!s||S)return;const{controller:n,sequence:c}=E();A(!0),k("");try{if(await Se(Ee(s),{signal:n.signal}),!f(m.current,c,n.signal))return;window.alert("系统配置已保存")}catch(l){if(!f(m.current,c,n.signal)||D(l))return;k(K(l,"保存配置失败"))}finally{f(m.current,c,n.signal)&&A(!1)}},[E,S,s]),de=r.useCallback(async n=>{n.preventDefault(),y(null);const c=Ae(t);if(c){y(T("error",c));return}const{controller:l,sequence:i}=E();_(!0);try{const g=await _e({current_password:t.current_password,new_username:t.new_username.trim(),new_password:t.new_password||void 0},{signal:l.signal});if(!f(m.current,i,l.signal))return;if(!g.success){y(T("error",g.message||"登录凭据更新失败"));return}y(T("success",g.message||"登录凭据已更新")),window.setTimeout(()=>windLine truncated import{r,j as e}from"./react-vendor-C_od1ZSF.js";import{a as xe,g as re,p as le}from"./index-zEvleK2K.js";import{f as ue,R as se,aa as pe,r as me,z as R,F as O,ab as he,t as ge,S as te,ac as ae,ad as ye,o as fe}from"./icons-vendor-DwxdQTKt.js";const ne="https://dashscope.aliyuncs.com/compatible-mode/v1",be=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],we=new Set(["ai_api_key_configured","smtp_password_configured","qq_reply_secret_key_configured","captcha.remote_secret_key_configured","smtp_server","smtp_port","smtp_user","smtp_password","smtp_from","smtp_from_name","smtp_from_address","registration_enabled","show_default_login_info","login_captcha_enabled","item_sync_enabled","item_sync_interval","item_sync_max_pages","default_reply"]),oe=new Set(["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"]),je=s=>{if("values"in s||"secrets"in s)return s;const a={},o={};for(const[d,h]of Object.entries(s))if(h!=null){if(oe.has(d)){o[d]=h===""?{action:"clear"}:{action:"replace",value:String(h)};continue}a[d]=h}return Object.keys(o).length>0?{values:a,secrets:o}:a},ve=s=>{const a={...s};for(const o of oe){const d=`${o}_configured`;d in a&&(a[d]=a[d]===!0||a[d]==="true")}if("renewal_log_retention_days"in a){const o=Number(a.renewal_log_retention_days);a.renewal_log_retention_days=Number.isFinite(o)?o:10}return a},_e=async(s,a)=>le("/api/v1/session/credentials",s,a),Ne=async s=>{const a=await re("/api/v1/settings/system",void 0,s),o=a.data||a.settings||a;return ve(o)},Se=async(s,a)=>le("/api/v1/settings/system",je(s),a),ke=async(s,a="",o)=>{const d=await xe("/api/v1/settings/ai-models",{base_url:s,api_key:a},o);return Array.isArray(d.models)?d.models:[]},Ce=async s=>re("/api/v1/session",void 0,s),Ee=s=>Object.fromEntries(Object.entries(s).filter(([a,o])=>!we.has(a)&&o!==void 0&&o!==null)),Ae=s=>s.new_username.trim().length<3?"用户名至少需要 3 个字符":s.current_password?s.new_password&&s.new_password.length<8?"新密码至少需要 8 个字符":s.new_password!==s.confirm_password?"两次输入的新密码不一致":"":"请输入当前密码确认身份",f=(s,a,o)=>s===a&&!o.aborted,D=s=>s instanceof Error&&s.message==="请求已取消",K=(s,a)=>s instanceof Error?s.message:a,Ie=(s="")=>({new_username:s,current_password:"",new_password:"",confirm_password:""}),T=(s,a)=>({type:s,text:a}),Me=()=>{const[s,a]=r.useState(null),[o,d]=r.useState(!1),[h,p]=r.useState(""),[S,A]=r.useState(!1),[P,k]=r.useState(""),[C,w]=r.useState([]),[j,I]=r.useState(!1),[M,x]=r.useState(""),[$,v]=r.useState(!1),[z,q]=r.useState(!1),[U,u]=r.useState(!1),[b,F]=r.useState(!1),[G,V]=r.useState(!1),[Y,_]=r.useState(!1),[L,y]=r.useState(null),[t,X]=r.useState(()=>Ie()),[ce,J]=r.useState("idle"),Z=r.useRef(null),ee=r.useRef(null),m=r.useRef(0),W=r.useRef(null);ee.current=s;const E=r.useCallback(()=>{var c;(c=W.current)==null||c.abort();const n=new AbortController;return W.current=n,m.current+=1,{controller:n,sequence:m.current}},[]),B=r.useCallback(async(n,c=!1,l)=>{const i=n||ee.current,g=(i==null?void 0:i.ai_api_url)||(i==null?void 0:i.ai_base_url)||ne;I(!0),x("");try{const N=await ke(g,(i==null?void 0:i.ai_api_key)||"",{signal:l});if(l!=null&&l.aborted)return;w(N),v(c&&N.length>0),!(i!=null&&i.ai_model)&&N.length>0&&a(Q=>Q&&{...Q,ai_model:N[0]})}catch(N){if(l!=null&&l.aborted||D(N))return;w([]),v(!1),x(K(N,"读取模型失败"))}finally{l!=null&&l.aborted||I(!1)}},[]),H=r.useCallback(()=>{const{controller:n,sequence:c}=E();d(!0),J("loading"),p(""),Promise.all([Ne({signal:n.signal}),Ce({signal:n.signal})]).then(([l,i])=>{f(m.current,c,n.signal)&&(a(l),i.username&&X(g=>({...g,new_username:i.username||""})),B(l,!1,n.signal),J("success"))}).catch(l=>{!f(m.current,c,n.signal)||D(l)||(a(null),p(K(l,"加载配置失败")),J("error"))}).finally(()=>{f(m.current,c,n.signal)&&d(!1)})},[E,B]);r.useEffect(()=>(H(),(()=>{var n;return(n=W.current)==null?void 0:n.abort()})),[H]),r.useEffect(()=>{const n=c=>{var l;(l=Z.current)!=null&&l.contains(c.target)||v(!1)};return document.addEventListener("mousedown",n),(()=>document.removeEventListener("mousedown",n))},[]);const ie=r.useCallback(async()=>{if(!s||S)return;const{controller:n,sequence:c}=E();A(!0),k("");try{if(await Se(Ee(s),{signal:n.signal}),!f(m.current,c,n.signal))return;window.alert("系统配置已保存")}catch(l){if(!f(m.current,c,n.signal)||D(l))return;k(K(l,"保存配置失败"))}finally{f(m.current,c,n.signal)&&A(!1)}},[E,S,s]),de=r.useCallback(async n=>{n.preventDefault(),y(null);const c=Ae(t);if(c){y(T("error",c));return}const{controller:l,sequence:i}=E();_(!0);try{const g=await _e({current_password:t.current_password,new_username:t.new_username.trim(),new_password:t.new_password||void 0},{signal:l.signal});if(!f(m.current,i,l.signal))return;if(!g.success){y(T("error",g.message||"登录凭据更新失败"));return}y(T("success",g.message||"登录凭据已更新")),window.setTimeout(()=>windLine truncated
@@ -1,2 +1,2 @@
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-B9IAsTbK.js","assets/react-vendor-C_od1ZSF.js","assets/dateTime-DDi7rqpW.js","assets/icons-vendor-DwxdQTKt.js","assets/charts-vendor-deWqkrdG.js","assets/vendor-Es4K8PXl.js","assets/vendor-DUblxfbA.css","assets/AccountList-cIlnZ13o.js","assets/OrderList-BEavERdn.js","assets/CardList-CcZPotoH.js","assets/ItemList-CyILtubM.js","assets/Settings-eSrR2WFx.js","assets/Rules-DyCI8Yz_.js","assets/Notifications-CusLu0iM.js","assets/Chat-Dnvr2e7q.js"])))=>i.map(i=>d[i]); const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-C9RwPfK-.js","assets/react-vendor-C_od1ZSF.js","assets/dateTime-DDi7rqpW.js","assets/icons-vendor-DwxdQTKt.js","assets/charts-vendor-deWqkrdG.js","assets/vendor-Es4K8PXl.js","assets/vendor-DUblxfbA.css","assets/AccountList-bbR-Z2_J.js","assets/OrderList-Dma_R9-T.js","assets/CardList-CvCo2zF6.js","assets/ItemList-CZPbhJDg.js","assets/Settings-BmdW4Gos.js","assets/Rules-CeggCy2B.js","assets/Notifications-DUiNU4WL.js","assets/Chat-CKN6Wl0-.js"])))=>i.map(i=>d[i]);
import{c as R,j as t,r as l,d as te}from"./react-vendor-C_od1ZSF.js";import{L as U,a as O,S as se,U as ne,A as re,b as ae,c as oe,M as ie,C as ce,B as le,d as de,Z as ue,e as he,f as me,G as M,g as fe,h as pe,i as xe}from"./icons-vendor-DwxdQTKt.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))o(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&o(a)}).observe(document,{childList:!0,subtree:!0});function s(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function o(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();class ge extends R.Component{constructor(){super(...arguments),this.state={hasError:!1},this.handleReload=()=>{window.location.reload()}}static getDerivedStateFromError(){return{hasError:!0}}render(){const{hasError:n}=this.state,{children:s}=this.props;return n?t.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-6 text-ink",children:t.jsxs("section",{className:"max-w-md text-center",children:[t.jsx("h1",{className:"text-xl font-semibold",children:"页面暂时无法显示"}),t.jsx("button",{className:"ios-btn-primary mt-6 px-4 py-2",type:"button",onClick:this.handleReload,children:"重新加载"})]})}):s}}const be=3e4,ye=10*6e4;let P=!1;class q extends Error{constructor(n,s){super(je(s,n)),this.name="ApiError",this.status=n,this.code=E(s)?s.code:`http_${n}`,this.requestId=E(s)?s.request_id:void 0,this.request_id=this.requestId,this.details=E(s)?s.details:void 0,this.payload=s}}const F=()=>{P||typeof window>"u"||(P=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{P=!1}))},ve=e=>{if(!e)return"";const n=new URLSearchParams;for(const[o,r]of Object.entries(e))r!=null&&n.set(o,String(r));const s=n.toString();return s?`?${s}`:""},A=async(e,n,s={})=>{var d;const o=ve(s.params),r=`${n}${o}`,i=B(s.signal,s.timeoutMs??be);let a;try{a=await fetch(r,{method:e,credentials:"include",signal:i.signal,headers:{...s.body===void 0?{}:{"Content-Type":"application/json"}},body:s.body===void 0?void 0:JSON.stringify(s.body)})}catch(h){throw i.signal.aborted?new Error((d=s.signal)!=null&&d.aborted?"请求已取消":"请求超时,请稍后重试"):h}finally{i.cleanup()}const u=(a.headers.get("content-type")||"").includes("application/json");if(!a.ok){a.status===401&&!s.skipAuthLogout&&F();const h=await V(a,u);throw new q(a.status,h)}return u?await a.json():await a.text()},j=async(e,n,s)=>A("GET",e,{params:n,...s}),L=async(e,n,s)=>A("POST",e,{body:n,...s}),ot=async(e,n,s)=>A("PUT",e,{body:n,...s}),it=async(e,n,s)=>A("DELETE",e,{params:n,...s}),we=async(e,n,s={})=>{var u;const o=B(s.signal,s.timeoutMs??ye);let r;try{r=await fetch(e,{method:"POST",credentials:"include",signal:o.signal,body:n})}catch(d){throw o.signal.aborted?new Error((u=s.signal)!=null&&u.aborted?"请求已取消":"上传超时,请稍后重试"):d}finally{o.cleanup()}const a=(r.headers.get("content-type")||"").includes("application/json"),c=await V(r,a);if(!r.ok)throw r.status===401&&F(),new q(r.status,c);return c},B=(e,n)=>{const s=new AbortController,o=()=>s.abort(e==null?void 0:e.reason);e!=null&&e.aborted?o():e==null||e.addEventListener("abort",o,{once:!0});const r=globalThis.setTimeout(()=>s.abort(new DOMException("timeout","TimeoutError")),Math.max(1,n));return{signal:s.signal,cleanup:()=>{globalThis.clearTimeout(r),e==null||e.removeEventListener("abort",o)}}},V=async(e,n)=>n?e.json().catch(()=>{}):e.text().catch(()=>{}),E=e=>{if(typeof e!="object"||e===null)return!1;const n=e;return typeof n.code=="string"&&typeof n.message=="string"},je=(e,n)=>typeof e=="string"?e:E(e)?e.message:`请求失败: ${n}`,Le=async e=>L("/api/v1/session/login",e,{skipAuthLogout:!0}),Ce=async e=>L("/api/v1/session/initialize",{password:e},{skipAuthLogout:!0}),Ne=async e=>j("/api/v1/session",void 0,e),Ee=async()=>L("/api/v1/session/logout",{}),G=l.createContext(void 0),Se=({children:e})=>{const[n,s]=l.useState(!1),[o,r]=l.useState(!1),[i,a]=l.useState(!0),[c,u]=l.useState(!1),d=()=>{s(!1),r(!1)};l.useEffect(()=>{const x=new AbortController;let p=!0;Ne({signal:x.signal}).then(b=>{if(p){if((b==null?void 0:b.initialized)===!1){u(!0),d();return}u(!1),b!=null&&b.authenticated?(s(!0),r(b.is_admin===!0)):d()}}).catch(b=>{!p||b instanceof DOMException&&b.name==="AbortError"||(u(!1),d())}).finally(()=>{p&&a(!1)});const m=()=>d();return window.addEventListener("auth:logout",m),(()=>{p=!1,x.abort(),window.removeEventListener("auth:logout",m)})},[]);const h=async x=>{const p=await Le(x);return p.success&&(u(!1),s(!0),r(p.is_admin===!0)),p},g=async x=>{const p=await Ce(x);return p.success&&(u(!1),s(!0Line truncated import{c as R,j as t,r as l,d as te}from"./react-vendor-C_od1ZSF.js";import{L as U,a as O,S as se,U as ne,A as re,b as ae,c as oe,M as ie,C as ce,B as le,d as de,Z as ue,e as he,f as me,G as M,g as fe,h as pe,i as xe}from"./icons-vendor-DwxdQTKt.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))o(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&o(a)}).observe(document,{childList:!0,subtree:!0});function s(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function o(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();class ge extends R.Component{constructor(){super(...arguments),this.state={hasError:!1},this.handleReload=()=>{window.location.reload()}}static getDerivedStateFromError(){return{hasError:!0}}render(){const{hasError:n}=this.state,{children:s}=this.props;return n?t.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-6 text-ink",children:t.jsxs("section",{className:"max-w-md text-center",children:[t.jsx("h1",{className:"text-xl font-semibold",children:"页面暂时无法显示"}),t.jsx("button",{className:"ios-btn-primary mt-6 px-4 py-2",type:"button",onClick:this.handleReload,children:"重新加载"})]})}):s}}const be=3e4,ye=10*6e4;let P=!1;class q extends Error{constructor(n,s){super(je(s,n)),this.name="ApiError",this.status=n,this.code=E(s)?s.code:`http_${n}`,this.requestId=E(s)?s.request_id:void 0,this.request_id=this.requestId,this.details=E(s)?s.details:void 0,this.payload=s}}const F=()=>{P||typeof window>"u"||(P=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{P=!1}))},ve=e=>{if(!e)return"";const n=new URLSearchParams;for(const[o,r]of Object.entries(e))r!=null&&n.set(o,String(r));const s=n.toString();return s?`?${s}`:""},A=async(e,n,s={})=>{var d;const o=ve(s.params),r=`${n}${o}`,i=B(s.signal,s.timeoutMs??be);let a;try{a=await fetch(r,{method:e,credentials:"include",signal:i.signal,headers:{...s.body===void 0?{}:{"Content-Type":"application/json"}},body:s.body===void 0?void 0:JSON.stringify(s.body)})}catch(h){throw i.signal.aborted?new Error((d=s.signal)!=null&&d.aborted?"请求已取消":"请求超时,请稍后重试"):h}finally{i.cleanup()}const u=(a.headers.get("content-type")||"").includes("application/json");if(!a.ok){a.status===401&&!s.skipAuthLogout&&F();const h=await V(a,u);throw new q(a.status,h)}return u?await a.json():await a.text()},j=async(e,n,s)=>A("GET",e,{params:n,...s}),L=async(e,n,s)=>A("POST",e,{body:n,...s}),ot=async(e,n,s)=>A("PUT",e,{body:n,...s}),it=async(e,n,s)=>A("DELETE",e,{params:n,...s}),we=async(e,n,s={})=>{var u;const o=B(s.signal,s.timeoutMs??ye);let r;try{r=await fetch(e,{method:"POST",credentials:"include",signal:o.signal,body:n})}catch(d){throw o.signal.aborted?new Error((u=s.signal)!=null&&u.aborted?"请求已取消":"上传超时,请稍后重试"):d}finally{o.cleanup()}const a=(r.headers.get("content-type")||"").includes("application/json"),c=await V(r,a);if(!r.ok)throw r.status===401&&F(),new q(r.status,c);return c},B=(e,n)=>{const s=new AbortController,o=()=>s.abort(e==null?void 0:e.reason);e!=null&&e.aborted?o():e==null||e.addEventListener("abort",o,{once:!0});const r=globalThis.setTimeout(()=>s.abort(new DOMException("timeout","TimeoutError")),Math.max(1,n));return{signal:s.signal,cleanup:()=>{globalThis.clearTimeout(r),e==null||e.removeEventListener("abort",o)}}},V=async(e,n)=>n?e.json().catch(()=>{}):e.text().catch(()=>{}),E=e=>{if(typeof e!="object"||e===null)return!1;const n=e;return typeof n.code=="string"&&typeof n.message=="string"},je=(e,n)=>typeof e=="string"?e:E(e)?e.message:`请求失败: ${n}`,Le=async e=>L("/api/v1/session/login",e,{skipAuthLogout:!0}),Ce=async e=>L("/api/v1/session/initialize",{password:e},{skipAuthLogout:!0}),Ne=async e=>j("/api/v1/session",void 0,e),Ee=async()=>L("/api/v1/session/logout",{}),G=l.createContext(void 0),Se=({children:e})=>{const[n,s]=l.useState(!1),[o,r]=l.useState(!1),[i,a]=l.useState(!0),[c,u]=l.useState(!1),d=()=>{s(!1),r(!1)};l.useEffect(()=>{const x=new AbortController;let p=!0;Ne({signal:x.signal}).then(b=>{if(p){if((b==null?void 0:b.initialized)===!1){u(!0),d();return}u(!1),b!=null&&b.authenticated?(s(!0),r(b.is_admin===!0)):d()}}).catch(b=>{!p||b instanceof DOMException&&b.name==="AbortError"||(u(!1),d())}).finally(()=>{p&&a(!1)});const m=()=>d();return window.addEventListener("auth:logout",m),(()=>{p=!1,x.abort(),window.removeEventListener("auth:logout",m)})},[]);const h=async x=>{const p=await Le(x);return p.success&&(u(!1),s(!0),r(p.is_admin===!0)),p},g=async x=>{const p=await Ce(x);return p.success&&(u(!1),s(!0Line truncated
+1 -1
View File
@@ -6,7 +6,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ydisks闲鱼助手 - 自动发货与管家系统</title> <title>Ydisks闲鱼助手 - 自动发货与管家系统</title>
<meta name="description" content="Ydisks闲鱼助手 - 自动回复、自动发货、订单管理、AI智能议价一体化解决方案" /> <meta name="description" content="Ydisks闲鱼助手 - 自动回复、自动发货、订单管理、AI智能议价一体化解决方案" />
<script type="module" crossorigin src="/static/assets/index-KV7tSL6x.js"></script> <script type="module" crossorigin src="/static/assets/index-zEvleK2K.js"></script>
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-C_od1ZSF.js"> <link rel="modulepreload" crossorigin href="/static/assets/react-vendor-C_od1ZSF.js">
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-DwxdQTKt.js"> <link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-DwxdQTKt.js">
<link rel="stylesheet" crossorigin href="/static/assets/index-D5pYdG6n.css"> <link rel="stylesheet" crossorigin href="/static/assets/index-D5pYdG6n.css">
@@ -0,0 +1,565 @@
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
)
// frontendDTOContractSpec 描述共享前端传输 DTO 与 Server 具名响应 DTO 的字段契约。
type frontendDTOContractSpec struct {
// frontendPath 是 DTO 所在的前端源码相对路径;为空时使用共享 transport 文件。
frontendPath string
// frontendType 是 frontend/shared/api-contract/transport.ts 中的导出接口名称。
frontendType string
// backendType 是 internal/server 中实际写入 JSON 的具名响应类型名称;为空表示仅由 feature 归一的组合类型。
backendType string
// rationale 说明没有一一对应 Server DTO 的组合类型为何仍允许存在。
rationale string
}
// frontendDTOContractSpecs 覆盖共享 transport 文件全部导出的对象 DTO。直接 HTTP DTO 必须指定 Server DTO;
// 只有 feature 对多个响应、动态设置或嵌套行 DTO 归一后产生的类型可以不指定后端类型。
var frontendDTOContractSpecs = []frontendDTOContractSpec{
{frontendPath: "frontend/app/features/session/api.ts", frontendType: "SessionStatusResponse", backendType: "sessionVerificationResponse"},
{frontendPath: "frontend/app/features/accounts/api.ts", frontendType: "AccountRuntimeStatus", rationale: "运行状态接口返回按账号 ID 索引的应用层状态映射,feature 只定义映射值形状。"},
{frontendPath: "frontend/app/features/accounts/api.ts", frontendType: "LongLoginSettings", backendType: "longLoginResponse"},
{frontendPath: "frontend/app/features/accounts/api.ts", frontendType: "PasswordLoginStartResponse", rationale: "密码登录兼容接口已永久禁用,实际响应使用统一错误信封;该类型仅保留历史调用编译兼容。"},
{frontendPath: "frontend/app/features/accounts/api.ts", frontendType: "PasswordLoginStatusResponse", rationale: "密码登录兼容接口已永久禁用,实际响应使用统一错误信封;该类型仅保留历史调用编译兼容。"},
{frontendPath: "frontend/app/features/chat/api.ts", frontendType: "ChatSessionPage", backendType: "chatSessionPageResponse"},
{frontendPath: "frontend/app/features/chat/api.ts", frontendType: "ChatMessagePage", backendType: "chatMessagePageResponse"},
{frontendPath: "frontend/app/features/dashboard/api.ts", frontendType: "ValidOrdersResult", rationale: "dashboard adapter 从 ValidOrdersResponse 归一订单状态并派生 orders/truncated。"},
{frontendPath: "frontend/app/features/rules/api.ts", frontendType: "AutomationRunIssue", backendType: "automationRunIssueDTO"},
{frontendPath: "frontend/app/features/rules/api.ts", frontendType: "DeferredAutomationIssue", backendType: "deferredAutomationIssueDTO"},
{frontendPath: "frontend/app/features/settings/api.ts", frontendType: "SettingsSessionStatusResponse", backendType: "sessionVerificationResponse"},
{frontendPath: "frontend/app/features/system/types.ts", frontendType: "BuildInfo", backendType: "healthResponse"},
{frontendType: "PublishLocation", rationale: "发货地由 items feature 的高德地图适配器获取,不经过本服务 HTTP Server。"},
{frontendType: "AccountDetail", rationale: "账号页面 UI 模型由 AccountSummaryResponse 和运行状态索引归一,包含前端派生状态而非单一 Server 响应。"},
{frontendType: "AccountTaskSettings", backendType: "accountTaskSettingsResponse"},
{frontendType: "AccountTaskSummary", backendType: "accountTaskSummaryResponse"},
{frontendType: "ChatSession", backendType: "chatSessionDTO"},
{frontendType: "ChatMessage", backendType: "chatMessageDTO"},
{frontendType: "Order", rationale: "订单列表 feature 由 orderDTO 归一,补充本地 id 并将数量和状态转换为 UI 值。"},
{frontendType: "Card", backendType: "cardResponse"},
{frontendType: "Item", backendType: "itemListResponse"},
{frontendType: "ShippingRule", rationale: "规则编辑器从 AutomationRuleResponse 解析动作配置并派生 card_group 与 variants。"},
{frontendType: "AutomationAction", backendType: "automationActionResponse"},
{frontendType: "ShippingVariant", rationale: "规格变体由自动化动作的 config_json 解码后产生,不是独立 HTTP DTO。"},
{frontendType: "ReplyRule", rationale: "关键词接口的 KeywordTypedResponse 在 feature adapter 中转换为回复规则 UI 模型。"},
{frontendType: "AdminStats", backendType: "adminStatsResponse"},
{frontendType: "DashboardStats", backendType: "dashboardStatsResponse"},
{frontendType: "OrderAnalytics", backendType: "orderAnalyticsResponse"},
{frontendType: "SystemSettings", rationale: "设置接口保留历史动态键形状,且 adapter 将敏感值归一为已配置状态,不能静态映射到单一结构体。"},
{frontendType: "AIReplySettings", backendType: "aiReplySettingsResponse"},
{frontendType: "DefaultReply", backendType: "defaultReplyResponse"},
{frontendType: "NotificationChannel", rationale: "通知编辑器 UI 模型不会接收渠道秘密配置;adapter 为新建/编辑表单构造空配置。"},
{frontendType: "SessionResponse", backendType: "loginResponse"},
{frontendType: "PaginatedResponse", rationale: "分页泛型由订单和自动化规则等不同 Server 响应复用,feature adapter 负责按端点归一。"},
{frontendType: "ApiErrorResponse", rationale: "统一错误信封由 internal/httpapi 写入,不属于 internal/server 的成功响应 DTO。"},
{frontendType: "AccountSummaryResponse", backendType: "cookieSummaryResponse"},
{frontendType: "CookieSettingsResponse", backendType: "cookieSettingsResponse"},
{frontendType: "CookieProfileResponse", backendType: "cookieProfileResponse"},
{frontendType: "PauseDurationResponse", backendType: "pauseDurationResponse"},
{frontendType: "ItemDetailResponse", backendType: "itemDetailResponse"},
{frontendType: "ItemPublishResponse", backendType: "itemPublishResponse"},
{frontendType: "ItemSyncResponse", backendType: "itemSyncResponse"},
{frontendType: "ItemPageSyncResponse", backendType: "itemPageSyncResponse"},
{frontendType: "OrderDTOResponse", backendType: "orderDTO"},
{frontendType: "OrderDetailResponse", backendType: "orderDetailResponse"},
{frontendType: "OrderRefreshDetailResponse", backendType: "orderRefreshDetailResponse"},
{frontendType: "OrderSingleRefreshResponse", backendType: "orderSingleRefreshResponse"},
{frontendType: "AutomationActionResponse", backendType: "automationActionResponse"},
{frontendType: "AutomationRuleResponse", backendType: "automationRuleResponse"},
{frontendType: "AutomationRulePageResponse", backendType: "automationRulePageResponse"},
{frontendType: "AIReplySettingsResponse", backendType: "aiReplySettingsResponse"},
{frontendType: "AIModelsResponse", backendType: "aiModelsResponse"},
{frontendType: "UserSettingResponse", backendType: "userSettingResponse"},
{frontendType: "CardBatchResponse", backendType: "cardBatchResponse"},
{frontendType: "CardBatchResult", backendType: "cardBatchResultRow"},
{frontendType: "CardAppendResponse", backendType: "cardAppendResponse"},
{frontendType: "NotificationBinding", rationale: "消息通知接口以账号 ID 为外层动态键,adapter 展平列表时将该键补为 cookie_id。"},
{frontendType: "AccountBindingsResponse", backendType: "accountBindingsResponse"},
{frontendType: "CategoryRecommendationResponse", backendType: "categoryRecommendationResponse"},
{frontendType: "ItemPublishBatchPreviewRow", backendType: "publishBatchPreviewRow"},
{frontendType: "ItemPublishBatchPreviewResponse", backendType: "itemPublishBatchPreviewResponse"},
{frontendType: "BatchIDResponse", backendType: "batchIDResponse"},
{frontendType: "BatchCancelResponse", backendType: "batchCancelResponse"},
{frontendType: "ItemPublishBatchRowResponse", backendType: "itemPublishBatchRowResponse"},
{frontendType: "ItemPublishBatchResponse", backendType: "itemPublishBatchResponse"},
{frontendType: "ItemPublishBatchListResponse", backendType: "itemPublishBatchListResponse"},
{frontendType: "MutationIDResponse", backendType: "mutationIDResponse"},
{frontendType: "OperationResponse", backendType: "operationResponse"},
{frontendType: "NotificationChannelResponse", backendType: "notificationChannelResponse"},
{frontendType: "KeywordBasicResponse", backendType: "keywordBasicResponse"},
{frontendType: "KeywordItemResponse", backendType: "keywordItemResponse"},
{frontendType: "KeywordTypedResponse", backendType: "keywordTypedResponse"},
{frontendType: "ItemReplyResponse", backendType: "itemReplyResponse"},
{frontendType: "DefaultReplyResponse", backendType: "defaultReplyResponse"},
{frontendType: "AccountTaskSettingsResponse", backendType: "accountTaskSettingsResponse"},
{frontendType: "AccountTaskRunResponse", backendType: "accountTaskRunResponse"},
{frontendType: "AccountTaskRunsResponse", backendType: "accountTaskRunsResponse"},
{frontendType: "AccountTaskSummaryResponse", backendType: "accountTaskSummaryResponse"},
{frontendType: "AccountTaskRunResponseEnvelope", backendType: "accountTaskRunResponseEnvelope"},
{frontendType: "AdminUserResponse", backendType: "adminUserResponse"},
{frontendType: "AdminCookieResponse", backendType: "adminCookieResponse"},
{frontendType: "AdminStatsResponse", backendType: "adminStatsResponse"},
{frontendType: "DashboardStatsResponse", backendType: "dashboardStatsResponse"},
{frontendType: "AnalyticsRevenueStatsResponse", backendType: "analyticsRevenueStatsResponse"},
{frontendType: "AnalyticsDailyStatsResponse", backendType: "analyticsDailyStatsResponse"},
{frontendType: "AnalyticsStatusStatsResponse", backendType: "analyticsStatusStatsResponse"},
{frontendType: "AnalyticsCityStatsResponse", backendType: "analyticsCityStatsResponse"},
{frontendType: "AnalyticsItemStatsResponse", backendType: "analyticsItemStatsResponse"},
{frontendType: "OrderAnalyticsResponse", backendType: "orderAnalyticsResponse"},
{frontendType: "ValidOrderResponse", backendType: "validOrderResponse"},
{frontendType: "ValidOrdersResponse", backendType: "validOrdersResponse"},
{frontendType: "QRLoginGenerateResponse", backendType: "qrLoginGenerateResponse"},
{frontendType: "QRLoginStatusResponse", backendType: "qrLoginStatusResponse"},
{frontendType: "QRLoginVerificationResponse", backendType: "qrLoginVerificationResponse"},
{frontendType: "OrderRefreshResultResponse", backendType: "orderRefreshResultDTO"},
{frontendType: "OrderRefreshSummaryResponse", backendType: "orderRefreshSummary"},
{frontendType: "OrderRefreshResponse", backendType: "orderRefreshResponse"},
{frontendType: "OrderRefreshJobStartResponse", backendType: "orderRefreshJobStartResponse"},
{frontendType: "OrderRefreshJobStatusResponse", backendType: "orderRefreshJobStatusResponse"},
{frontendType: "OrderRefreshJobCancelResponse", backendType: "orderRefreshJobCancelResponse"},
{frontendType: "CardListResponse", rationale: "卡券接口直接返回 cardResponse 数组,前端仅用此类型表达历史包装。"},
{frontendType: "OrderBatchResponse", rationale: "导入与发货端点使用不同 Server 响应 DTO,feature 将其归一为同一批量结果。"},
{frontendType: "OrderBatchResult", rationale: "批量发货与导入的逐行 DTO 不同,feature 只保留共同展示字段。"},
{frontendType: "ItemListEnvelope", rationale: "商品列表兼容端点同时支持数组和历史包装,feature adapter 负责归一。"},
{frontendType: "AutomationIssuesEnvelope", rationale: "自动化问题响应由两个 Server 行 DTO 组合,feature adapter 不直接透传。"},
}
// checkFrontendDTOFieldContracts 验证前端共享对象 DTO 已登记,且直接 HTTP DTO 的每个字段都由 Server 显式提供。
func checkFrontendDTOFieldContracts(root string) []violation {
// frontendPath 是共享前端传输契约的唯一源文件。
frontendPath := filepath.Join(root, "frontend", "shared", "api-contract", "transport.ts")
// frontendRaw、frontendReadErr 分别是前端契约源码及其读取错误。
frontendRaw, frontendReadErr := os.ReadFile(frontendPath)
if frontendReadErr != nil {
return []violation{{file: "frontend/shared/api-contract/transport.ts", line: 1, message: fmt.Sprintf("无法读取前端 DTO 契约: %v", frontendReadErr)}}
}
// frontendFields、frontendLines 分别保存 TypeScript 对象 DTO 字段和其声明行。
frontendFields, frontendLines := parseFrontendResponseFields(string(frontendRaw))
// frontendPaths 保存每个已解析 DTO 对应的实际源码路径。
frontendPaths := make(map[string]string, len(frontendFields))
// typeName 是共享契约中的当前 DTO 名称。
for typeName := range frontendFields {
frontendPaths[typeName] = "frontend/shared/api-contract/transport.ts"
}
// featureSources 保存全部 feature API DTO 源码及注册表中的额外 DTO 源码。
featureSources := make(map[string]struct{})
// featureAPIFiles 是所有 feature API 适配器路径;新增响应 DTO 必须自动进入门禁。
featureAPIFiles, featureGlobErr := filepath.Glob(filepath.Join(root, "frontend", "app", "features", "*", "api.ts"))
if featureGlobErr != nil {
return []violation{{file: "frontend/app/features", line: 1, message: fmt.Sprintf("无法枚举 feature DTO 契约: %v", featureGlobErr)}}
}
// featureAPIFile 是当前需要纳入扫描的 feature API 文件绝对路径。
for _, featureAPIFile := range featureAPIFiles {
// relativePath 是当前 feature API 文件相对于仓库根的稳定路径。
relativePath, relativeErr := filepath.Rel(root, featureAPIFile)
if relativeErr != nil {
return []violation{{file: "frontend/app/features", line: 1, message: fmt.Sprintf("无法规范 feature DTO 路径: %v", relativeErr)}}
}
featureSources[filepath.ToSlash(relativePath)] = struct{}{}
}
// spec 是当前可能额外声明 feature DTO 源码的契约登记项。
for _, spec := range frontendDTOContractSpecs {
if spec.frontendPath != "" {
featureSources[spec.frontendPath] = struct{}{}
}
}
// featureSource 是当前需要读取的局部 feature DTO 源码路径。
for featureSource := range featureSources {
// featureRaw、featureReadErr 分别是局部 DTO 源码和读取错误。
featureRaw, featureReadErr := os.ReadFile(filepath.Join(root, featureSource))
if featureReadErr != nil {
return []violation{{file: featureSource, line: 1, message: fmt.Sprintf("无法读取 feature DTO 契约: %v", featureReadErr)}}
}
// featureFields、featureLines 分别保存局部 DTO 字段和声明行号。
featureFields, featureLines := parseFrontendResponseFields(string(featureRaw))
// typeName、fields 分别是当前局部 DTO 名称和其顶层字段集合。
for typeName, fields := range featureFields {
if !isFeatureResponseDTOName(typeName) && !isExplicitFrontendDTO(featureSource, typeName) {
continue
}
frontendFields[typeName] = fields
frontendLines[typeName] = featureLines[typeName]
frontendPaths[typeName] = featureSource
}
}
// backendFields、backendLines 分别保存 Server 具名结构体的 JSON 字段和其声明行。
backendFields, backendLines, backendErr := parseServerResponseFields(root)
if backendErr != nil {
return []violation{{file: "internal/server", line: 1, message: fmt.Sprintf("无法解析 Server DTO: %v", backendErr)}}
}
// registered 保存已在注册表登记的前端响应类型,避免新增 DTO 漏检。
registered := make(map[string]frontendDTOContractSpec, len(frontendDTOContractSpecs))
// violations 保存字段遗漏、未知 DTO 和无效登记。
var violations []violation
// spec 是当前前后端 DTO 对照规则。
for _, spec := range frontendDTOContractSpecs {
// duplicated 表示相同前端 DTO 是否已经登记过。
if _, duplicated := registered[spec.frontendType]; duplicated {
violations = append(violations, violation{file: "tools/architecturecheck/dto_field_contract.go", line: 1, message: fmt.Sprintf("前端 DTO %s 在字段契约注册表中重复登记", spec.frontendType)})
continue
}
registered[spec.frontendType] = spec
// frontendTypeFields、exists 分别是当前前端 DTO 的字段集合和是否存在。
frontendTypeFields, exists := frontendFields[spec.frontendType]
if !exists {
violations = append(violations, violation{file: "tools/architecturecheck/dto_field_contract.go", line: 1, message: fmt.Sprintf("字段契约登记的前端 DTO %s 不存在", spec.frontendType)})
continue
}
if spec.backendType == "" {
if strings.TrimSpace(spec.rationale) == "" {
violations = append(violations, violation{file: "tools/architecturecheck/dto_field_contract.go", line: 1, message: fmt.Sprintf("组合 DTO %s 必须说明不直接对应 Server DTO 的原因", spec.frontendType)})
}
continue
}
// backendTypeFields、backendExists 分别是 Server DTO 的 JSON 字段集合和是否存在。
backendTypeFields, backendExists := backendFields[spec.backendType]
if !backendExists {
violations = append(violations, violation{file: "tools/architecturecheck/dto_field_contract.go", line: 1, message: fmt.Sprintf("前端 DTO %s 对应的 Server DTO %s 不存在", spec.frontendType, spec.backendType)})
continue
}
// field 是前端声明为可消费的当前字段。
for field := range frontendTypeFields {
// provided 表示后端具名 DTO 是否显式提供当前前端字段。
if _, provided := backendTypeFields[field]; provided {
continue
}
violations = append(violations, violation{file: frontendPaths[spec.frontendType], line: frontendLines[spec.frontendType], message: fmt.Sprintf("前端 DTO %s 需要字段 %q,但 Server DTO %s 未提供;请补齐具名响应字段或移除未使用契约", spec.frontendType, field, spec.backendType)})
}
_ = backendLines
}
// frontendType 是当前需要强制登记的共享或 feature 响应 DTO。
for frontendType := range parseTransportDTOTypeNames(string(frontendRaw)) {
// exists 表示共享 DTO 是否已有字段契约登记。
if _, exists := registered[frontendType]; exists {
continue
}
violations = append(violations, violation{file: "frontend/shared/api-contract/transport.ts", line: frontendLines[frontendType], message: fmt.Sprintf("前端对象 DTO %s 未登记到字段契约门禁", frontendType)})
}
// frontendType、frontendPath 分别是局部响应 DTO 名称和其声明文件。
for frontendType, frontendPath := range frontendPaths {
if frontendPath == "frontend/shared/api-contract/transport.ts" {
continue
}
// exists 表示局部响应 DTO 是否已有字段契约登记。
if _, exists := registered[frontendType]; exists {
continue
}
violations = append(violations, violation{file: frontendPath, line: frontendLines[frontendType], message: fmt.Sprintf("前端对象 DTO %s 未登记到字段契约门禁", frontendType)})
}
return violations
}
// isFeatureResponseDTOName 判断 feature 局部接口是否表达 HTTP 响应或其响应行 DTO。
func isFeatureResponseDTOName(typeName string) bool {
// suffix 是当前接口名称可证明为响应 DTO 的后缀。
for _, suffix := range []string{"Response", "Page", "Status", "Settings", "Result", "Issue", "RuntimeStatus"} {
if strings.HasSuffix(typeName, suffix) {
return true
}
}
return false
}
// isExplicitFrontendDTO 判断当前路径和类型是否由登记表显式纳入,例如健康检查 BuildInfo。
func isExplicitFrontendDTO(frontendPath, typeName string) bool {
// spec 是当前字段契约登记项。
for _, spec := range frontendDTOContractSpecs {
if spec.frontendPath == frontendPath && spec.frontendType == typeName {
return true
}
}
return false
}
// parseTransportDTOTypeNames 返回共享 transport 中需要强制登记的全部导出对象 DTO 名称。
func parseTransportDTOTypeNames(source string) map[string]struct{} {
// fields 是 transport DTO 的解析结果;只需其类型名称。
fields, _ := parseFrontendResponseFields(source)
// names 保存所有待检查的共享 DTO 名称。
names := make(map[string]struct{}, len(fields))
// typeName 是当前共享 DTO 名称。
for typeName := range fields {
names[typeName] = struct{}{}
}
return names
}
// parseFrontendResponseFields 从共享 TypeScript transport 文件读取全部导出对象 DTO 的顶层字段和 extends 字段。
func parseFrontendResponseFields(source string) (map[string]map[string]struct{}, map[string]int) {
// declarationPattern 匹配导出的对象接口声明;字符串和联合类型不是可逐字段校验的 DTO。
declarationPattern := regexp.MustCompile(`(?m)^export interface ([A-Za-z][A-Za-z0-9]*)[^\{]*\{`)
// extendsPattern 匹配接口继承的单个对象 DTO;当前契约不使用交叉继承。
extendsPattern := regexp.MustCompile(`\bextends\s+([A-Za-z][A-Za-z0-9]*)`)
// fieldPattern 匹配接口体顶层的普通属性;索引签名不表示固定 HTTP 字段。
fieldPattern := regexp.MustCompile(`(?m)^\s*([A-Za-z_][A-Za-z0-9_]*)\??\s*:`)
// fields 保存每个响应接口声明的固定字段集合。
fields := make(map[string]map[string]struct{})
// lines 保存接口声明的 1-based 行号,供失败信息定位。
lines := make(map[string]int)
// parents 保存接口的直接父 DTO,供后续合并继承字段。
parents := make(map[string]string)
// matches 保存所有响应接口声明的位置和类型名称。
matches := declarationPattern.FindAllStringSubmatchIndex(source, -1)
// match 是当前响应接口声明的位置元组。
for _, match := range matches {
// typeName 是当前响应接口名称。
typeName := source[match[2]:match[3]]
// bodyStart 是声明中第一个左花括号的下标。
bodyStart := strings.Index(source[match[0]:match[1]], "{") + match[0]
// bodyEnd 是配对右花括号的下标;异常源码由 TypeScript 类型检查另行报告。
bodyEnd := matchingBrace(source, bodyStart)
if bodyEnd < 0 {
continue
}
// body 是不含外层花括号的接口字段文本。
body := source[bodyStart+1 : bodyEnd]
// typeFields 保存当前接口的顶层字段,嵌套对象字段不属于当前 Server DTO 的直接字段。
typeFields := topLevelFrontendFields(body, fieldPattern)
fields[typeName] = typeFields
lines[typeName] = strings.Count(source[:match[0]], "\n") + 1
// parentMatch 是当前接口继承的父 DTO 名称。
if parentMatch := extendsPattern.FindStringSubmatch(source[match[0]:match[1]]); len(parentMatch) == 2 {
parents[typeName] = parentMatch[1]
}
}
// resolved 保存已展开继承字段的 DTO 集合。
resolved := make(map[string]map[string]struct{}, len(fields))
// resolving 保存当前 DFS 路径,防止异常源码中的循环继承无限递归。
resolving := make(map[string]bool, len(fields))
// resolve 返回当前 DTO 自身及所有父 DTO 的字段集合。
var resolve func(string) map[string]struct{}
resolve = func(typeName string) map[string]struct{} {
// resolvedFields、ok 分别是已缓存的继承字段和其命中标记。
if resolvedFields, ok := resolved[typeName]; ok {
return resolvedFields
}
if resolving[typeName] {
return fields[typeName]
}
resolving[typeName] = true
// merged 是当前 DTO 合并父级后的独立字段集合。
merged := make(map[string]struct{}, len(fields[typeName]))
// field 是当前 DTO 自身声明的字段。
for field := range fields[typeName] {
merged[field] = struct{}{}
}
// parentType、hasParent 分别是当前 DTO 的父接口名称和继承标记。
if parentType, hasParent := parents[typeName]; hasParent {
// field 是从父接口继承的字段。
for field := range resolve(parentType) {
merged[field] = struct{}{}
}
}
delete(resolving, typeName)
resolved[typeName] = merged
return merged
}
// typeName 是当前需要展开继承字段的 DTO 名称。
for typeName := range fields {
fields[typeName] = resolve(typeName)
}
return fields, lines
}
// topLevelFrontendFields 只提取 TypeScript 接口第一层字段,跳过嵌套对象和数组元素的属性。
func topLevelFrontendFields(body string, fieldPattern *regexp.Regexp) map[string]struct{} {
// fields 保存当前接口顶层可由 HTTP 响应直接提供的字段。
fields := make(map[string]struct{})
// depth 保存当前行开始时所处的嵌套花括号层级。
depth := 0
// line 是当前待检查的源码行。
for _, line := range strings.Split(body, "\n") {
if depth == 0 {
// match 是当前顶层属性名的正则匹配位置。
if match := fieldPattern.FindStringSubmatch(line); len(match) == 2 {
fields[match[1]] = struct{}{}
}
}
// character 是当前行的单个字符;嵌套字段将在下一行因 depth 非零被跳过。
for _, character := range line {
switch character {
case '{':
depth++
case '}':
depth--
}
}
}
return fields
}
// matchingBrace 返回 source 中指定左花括号对应右花括号的位置,不把对象字面量嵌套误认为接口结束。
func matchingBrace(source string, start int) int {
// depth 保存当前花括号嵌套层级。
depth := 0
// index 是当前扫描的字节位置。
for index := start; index < len(source); index++ {
switch source[index] {
case '{':
depth++
case '}':
depth--
if depth == 0 {
return index
}
}
}
return -1
}
// parseServerResponseFields 收集 internal/server 生产源码中全部具名结构体的 JSON 字段。
func parseServerResponseFields(root string) (map[string]map[string]struct{}, map[string]int, error) {
// fields 保存每个 Server 结构体暴露的 JSON 字段集合。
fields := make(map[string]map[string]struct{})
// lines 保存结构体声明所在行,供后续诊断扩展使用。
lines := make(map[string]int)
// embedded 保存结构体匿名嵌入的 DTO 类型,编码时会提升这些字段。
embedded := make(map[string][]string)
// fset 为 Go AST 节点提供稳定行号。
fset := token.NewFileSet()
// serverRoot 是 HTTP transport 源码目录。
serverRoot := filepath.Join(root, "internal", "server")
// walkErr 表示遍历或解析 Server DTO 时发生的错误。
walkErr := filepath.WalkDir(serverRoot, func(path string, entry os.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if entry.IsDir() || !strings.HasSuffix(path, ".go") || strings.HasSuffix(path, "_test.go") {
return nil
}
// syntax、parseErr 分别是当前 Server 源码的 AST 与解析错误。
syntax, parseErr := parser.ParseFile(fset, path, nil, 0)
if parseErr != nil {
return parseErr
}
// declaration 是当前文件的顶层声明。
for _, declaration := range syntax.Decls {
// general、ok 分别是类型声明块及其断言结果。
general, ok := declaration.(*ast.GenDecl)
if !ok || general.Tok != token.TYPE {
continue
}
// specification 是类型声明块中的单个类型。
for _, specification := range general.Specs {
// typeSpec、ok 分别是具名类型规格及其断言结果。
typeSpec, ok := specification.(*ast.TypeSpec)
if !ok {
continue
}
// structure、ok 分别是具名结构体及其断言结果。
structure, ok := typeSpec.Type.(*ast.StructType)
if !ok {
continue
}
// jsonFields 保存当前结构体可编码的固定 JSON 字段。
jsonFields := make(map[string]struct{})
// field 是当前结构体字段声明。
for _, field := range structure.Fields.List {
if len(field.Names) == 0 {
// embeddedType 是匿名嵌入结构体的类型名;指针嵌入与值嵌入都会提升 JSON 字段。
embeddedType := embeddedStructTypeName(field.Type)
if embeddedType != "" {
embedded[typeSpec.Name.Name] = append(embedded[typeSpec.Name.Name], embeddedType)
}
continue
}
if field.Tag == nil {
continue
}
// tag 是去除反引号后的结构体标签文本。
tag := strings.Trim(field.Tag.Value, "`")
// jsonName 是 json 标签的字段名;空名和 - 不属于响应字段。
jsonName := strings.Split(strings.TrimPrefix(tag, "json:\""), "\"")[0]
jsonName = strings.Split(jsonName, ",")[0]
if jsonName != "" && jsonName != "-" {
jsonFields[jsonName] = struct{}{}
}
}
fields[typeSpec.Name.Name] = jsonFields
lines[typeSpec.Name.Name] = fset.Position(typeSpec.Pos()).Line
}
}
return nil
})
if walkErr != nil {
return fields, lines, walkErr
}
// resolved 保存已经展开匿名嵌入字段的 Server DTO 集合。
resolved := make(map[string]map[string]struct{}, len(fields))
// resolving 保存当前 DFS 路径,避免异常源码出现循环嵌入时无限递归。
resolving := make(map[string]bool, len(fields))
// resolve 返回当前 DTO 自身及所有匿名嵌入 DTO 的 JSON 字段。
var resolve func(string) map[string]struct{}
resolve = func(typeName string) map[string]struct{} {
// resolvedFields、ok 分别是已缓存的匿名嵌入字段和其命中标记。
if resolvedFields, ok := resolved[typeName]; ok {
return resolvedFields
}
if resolving[typeName] {
return fields[typeName]
}
resolving[typeName] = true
// merged 是当前 DTO 合并匿名嵌入字段后的独立集合。
merged := make(map[string]struct{}, len(fields[typeName]))
// field 是当前 Server DTO 自身声明的 JSON 字段。
for field := range fields[typeName] {
merged[field] = struct{}{}
}
// embeddedType 是当前 Server DTO 匿名嵌入的字段来源类型。
for _, embeddedType := range embedded[typeName] {
// field 是匿名嵌入类型提升到当前 DTO 的 JSON 字段。
for field := range resolve(embeddedType) {
merged[field] = struct{}{}
}
}
delete(resolving, typeName)
resolved[typeName] = merged
return merged
}
// typeName 是当前需要展开匿名嵌入字段的 Server DTO 名称。
for typeName := range fields {
fields[typeName] = resolve(typeName)
}
return fields, lines, walkErr
}
// embeddedStructTypeName 返回匿名嵌入字段引用的本包结构体类型名;匿名基本类型不会提升 JSON DTO 字段。
func embeddedStructTypeName(expression ast.Expr) string {
// identifier、ok 分别是匿名值嵌入的类型名及其断言结果。
if identifier, ok := expression.(*ast.Ident); ok {
return identifier.Name
}
// pointer、ok 分别是匿名指针嵌入及其断言结果。
pointer, ok := expression.(*ast.StarExpr)
if !ok {
return ""
}
// identifier、ok 分别是指针指向的本包类型名及其断言结果。
identifier, ok := pointer.X.(*ast.Ident)
if !ok {
return ""
}
return identifier.Name
}
// sortedFieldNames 返回稳定排序的字段名列表,供测试失败输出保持可复现。
func sortedFieldNames(fields map[string]struct{}) []string {
// names 保存待排序字段名。
names := make([]string, 0, len(fields))
// field 是当前字段集合成员。
for field := range fields {
names = append(names, field)
}
sort.Strings(names)
return names
}
+108
View File
@@ -5,9 +5,117 @@ import (
"go/token" "go/token"
"os" "os"
"path/filepath" "path/filepath"
"strings"
"testing" "testing"
) )
// TestFrontendDTOFieldParserRejectsNestedProperties 验证 DTO 字段解析只比较 HTTP 响应的顶层字段。
func TestFrontendDTOFieldParserRejectsNestedProperties(t *testing.T) {
// source 是同时包含直接字段和嵌套对象字段的最小前端响应 DTO。
source := `export interface CategoryResponse {
success: boolean;
category: {
cat_id: string;
};
}`
// fields、lines 分别是解析出的字段集合和接口声明行号。
fields, lines := parseFrontendResponseFields(source)
// categoryFields 是 CategoryResponse 的顶层字段集合。
categoryFields := fields["CategoryResponse"]
// exists 表示 success 是否被正确识别为顶层字段。
if _, exists := categoryFields["success"]; !exists {
t.Fatalf("顶层 success 字段未被识别: %v", sortedFieldNames(categoryFields))
}
// exists 表示 category 是否被正确识别为顶层字段。
if _, exists := categoryFields["category"]; !exists {
t.Fatalf("顶层 category 字段未被识别: %v", sortedFieldNames(categoryFields))
}
// exists 表示嵌套 cat_id 是否被错误提升为顶层字段。
if _, exists := categoryFields["cat_id"]; exists {
t.Fatalf("嵌套 cat_id 不应被视为外层 DTO 字段: %v", sortedFieldNames(categoryFields))
}
if lines["CategoryResponse"] != 1 {
t.Fatalf("接口声明行=%d want=1", lines["CategoryResponse"])
}
}
// TestFrontendDTOFieldContractReportsMissingBackendField 验证真实 DTO 夹具缺少后端字段时字段门禁会失败。
func TestFrontendDTOFieldContractReportsMissingBackendField(t *testing.T) {
// root 是本测试隔离出的最小仓库根目录。
root := t.TempDir()
// frontendDir、serverDir 分别是前端传输契约和服务端 DTO 的夹具目录。
frontendDir := filepath.Join(root, "frontend", "shared", "api-contract")
// serverDir 是服务端 DTO 夹具目录。
serverDir := filepath.Join(root, "internal", "server")
// err 是创建前端夹具目录失败的原因。
if err := os.MkdirAll(frontendDir, 0o755); err != nil {
t.Fatal(err)
}
// err 是创建服务端夹具目录失败的原因。
if err := os.MkdirAll(serverDir, 0o755); err != nil {
t.Fatal(err)
}
// frontendSource 是要求 required 字段的最小前端 DTO。
frontendSource := []byte("export interface ExampleResponse {\n required: string;\n}\n")
// err 是写入前端 DTO 夹具失败的原因。
if err := os.WriteFile(filepath.Join(frontendDir, "transport.ts"), frontendSource, 0o600); err != nil {
t.Fatal(err)
}
// serverSource 故意不提供 required 字段,用来验证真实扫描链路。
serverSource := []byte("package server\ntype exampleResponse struct { Provided string `json:\"provided\"` }\n")
// err 是写入服务端 DTO 夹具失败的原因。
if err := os.WriteFile(filepath.Join(serverDir, "response.go"), serverSource, 0o600); err != nil {
t.Fatal(err)
}
// originalSpecs 保存测试前的全局登记表,结束后必须恢复避免污染其他门禁测试。
originalSpecs := frontendDTOContractSpecs
frontendDTOContractSpecs = []frontendDTOContractSpec{{frontendType: "ExampleResponse", backendType: "exampleResponse"}}
defer func() { frontendDTOContractSpecs = originalSpecs }()
// violations 是执行真实字段门禁后得到的违规集合。
violations := checkFrontendDTOFieldContracts(root)
if len(violations) != 1 {
t.Fatalf("violations=%+v", violations)
}
// message 是字段缺失诊断,应稳定指明双方 DTO 和遗漏字段。
message := violations[0].message
if !strings.Contains(message, "ExampleResponse") || !strings.Contains(message, "required") || !strings.Contains(message, "exampleResponse") {
t.Fatalf("缺失字段诊断不完整: %s", message)
}
}
// TestServerDTOFieldParserIncludesEmbeddedDTO 验证匿名嵌入 DTO 提升的 JSON 字段不会被字段门禁误判遗漏。
func TestServerDTOFieldParserIncludesEmbeddedDTO(t *testing.T) {
// root 是本测试隔离出的最小仓库根目录。
root := t.TempDir()
// serverDir 是服务端 DTO 夹具目录。
serverDir := filepath.Join(root, "internal", "server")
// err 是创建服务端匿名嵌入夹具目录失败的原因。
if err := os.MkdirAll(serverDir, 0o755); err != nil {
t.Fatal(err)
}
// source 使用 Go 的匿名嵌入模拟 orderDetailResponse 兼容顶层字段行为。
source := []byte("package server\ntype baseDTO struct { ID string `json:\"id\"` }\ntype detailResponse struct { baseDTO; Success bool `json:\"success\"` }\n")
// err 是写入匿名嵌入 DTO 夹具失败的原因。
if err := os.WriteFile(filepath.Join(serverDir, "response.go"), source, 0o600); err != nil {
t.Fatal(err)
}
// fields、_、err 分别是解析出的 DTO 字段、未使用的行号和解析错误。
fields, _, err := parseServerResponseFields(root)
if err != nil {
t.Fatal(err)
}
// detailFields 是含匿名嵌入字段的详情 DTO 字段集合。
detailFields := fields["detailResponse"]
// exists 表示匿名嵌入的 id 是否已提升。
if _, exists := detailFields["id"]; !exists {
t.Fatalf("匿名嵌入 id 字段未被解析: %v", sortedFieldNames(detailFields))
}
// exists 表示详情 DTO 的直接 success 字段是否已保留。
if _, exists := detailFields["success"]; !exists {
t.Fatalf("直接 success 字段未被解析: %v", sortedFieldNames(detailFields))
}
}
// TestHTTPResponseContractBoundary 验证 HTTP 契约扫描会拒绝动态 map 和直接 map 响应。 // TestHTTPResponseContractBoundary 验证 HTTP 契约扫描会拒绝动态 map 和直接 map 响应。
func TestHTTPResponseContractBoundary(t *testing.T) { func TestHTTPResponseContractBoundary(t *testing.T) {
// fset 是模拟 Server 源码的文件位置集合。 // fset 是模拟 Server 源码的文件位置集合。
+1
View File
@@ -100,6 +100,7 @@ func checkActivatedRepositoryGates(root string, activeStage int) []violation {
} }
if architectureStageEnabled(activeStage, architectureStageClosure) { if architectureStageEnabled(activeStage, architectureStageClosure) {
violations = append(violations, checkQualityArchitecture(root)...) violations = append(violations, checkQualityArchitecture(root)...)
violations = append(violations, checkFrontendDTOFieldContracts(root)...)
} }
return violations return violations
} }