API契约:收口业务成功响应 DTO

This commit is contained in:
Christ committed 2026-08-14 15:15:00 +08:00
1 parent ebce42f9dc
commit 0ca52e43ad
12 files changed
+1020 -233

No files matched your search

@@ -7,8 +7,10 @@
| 领域 | 现有路径 | 目标 `/api/v1` 路径 | 迁移状态 |
| --- | --- | --- | --- |
| 会话 | `/verify`、`/logout` | `/api/v1/session`、`/api/v1/session/logout` | 旧路径保留,待前端统一请求层后迁移 |
| 账号 | `/cookies/details`、`/cookies/{cid}/...` | `/api/v1/accounts/...` | 旧路径保留,具名 DTO 已开始落地 |
| 订单 | `/api/orders...` | `/api/v1/orders...` | 旧路径保留,列表 DTO 已落地 |
| 账号 | `/cookies/details`、`/cookies/{cid}/...` | `/api/v1/accounts/...` | 旧路径保留,详情/设置/资料/暂停 DTO 已落地 |
| 商品 | `/items...` | `/api/v1/items...` | 旧路径保留,发布/同步/列表/详情 DTO 已落地 |
| 自动化 | `/automation-rules...` | `/api/v1/automation-rules...` | 旧路径保留,规则分页/异常 DTO 已落地 |
| 订单 | `/api/orders...` | `/api/v1/orders...` | 旧路径保留,列表/详情/刷新/批量外层 DTO 已落地 |
| 聊天 | `/api/chat...` | `/api/v1/chat...` | 旧路径保留,会话/消息 DTO 已落地 |
## 迁移规则
@@ -22,6 +24,10 @@
## 当前切片证据
- 认证会话校验使用 `sessionVerificationResponse`。
- 订单列表使用 `orderListResponse` 和 `orderDTO`。
- 账号详情、设置、资料刷新和暂停查询使用 `cookieDetailResponse`、`cookieSettingsResponse`、`cookieProfileResponse` 与 `pauseDurationResponse`。
- 商品发布、同步、列表和详情使用 `itemPublishResponse`、`itemSyncResponse`、`itemPageSyncResponse`、`itemListResponse` 与 `itemDetailResponse`。
- 自动化规则分页、动作和异常列表使用 `automationRulePageResponse`、`automationRuleResponse`、`automationActionResponse` 与 `automationIssuesResponse`。
- 订单列表、详情、刷新和批量外层结果使用 `orderListResponse`、`orderDetailResponse`、`orderRefreshResponse` 与 `manualShipResponse`/`importOrdersResponse`。
- 聊天会话、消息分页和发送结果使用独立 DTO,不直接暴露数据库模型。
- React `frontend/types.ts` 与 `frontend/services/api.ts` 已同步具名成功响应类型,同时保留旧字段归一逻辑。
- 旧路径仍由现有路由提供,尚未宣称 `/api/v1` 已经可用。
+3 -1
View File
@@ -134,7 +134,8 @@ app shell / routes
- 已完成阶段 3 第四个 PR 切片“聊天、商品与自动化业务 API 错误响应迁移”:聊天发送失败和商品发布失败均改用统一 `code`/`message`/`request_id` 错误 DTO,商品远端已成功但本地保存失败的恢复信息迁移到可选 `details`;React 错误类型同步支持 `details`,新增 HTTP DTO、聊天/自动化/商品契约测试并通过前端门禁;
- 已完成阶段 3 第五个 PR 切片“二维码登录、密码登录和剩余公共业务错误响应迁移”:二维码生成、扫码状态持久化、风控验证失败和账号不匹配均改用正确的非 2xx 状态码与统一错误 DTO;历史密码登录入口返回明确的 `password_login_disabled` 未实现错误;新增二维码/密码登录契约测试并通过全量门禁;
- 已完成阶段 3 第六个 PR 切片“统一业务成功响应具名 DTO 与版本化路径准备”:认证会话、账号新增、订单列表、聊天会话/消息主链路已改用具名成功响应 DTO,新增响应契约测试,并记录 `/api/v1` 兼容迁移边界;未提前切换旧路径,保持可回滚;
- 阶段 3 下一 PR 切片为“剩余业务成功响应 DTO 与客户端契约收口”:继续按领域迁移剩余账号、商品、自动化和订单详情成功响应,不拆分单个 handler 提交;
- 已完成阶段 3 第七个 PR 切片“剩余业务成功响应 DTO 与客户端契约收口”:账号详情/设置、商品核心发布与同步、自动化规则/异常、订单详情/刷新/批量外层响应改用具名 DTO;React 客户端同步使用具名契约类型;新增跨领域成功响应契约测试;旧字段、旧路径和批处理逐行兼容字段保留;全量门禁通过并合并为一个可回滚提交;
- 阶段 3 下一 PR 切片为“剩余商品批量操作与设置/卡券/通知成功响应收口”:继续迁移尚未覆盖的商品批量操作、系统设置、卡券和通知接口,不拆分单个 handler 提交;
- 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。
## 6. 阶段 0:治理文档与强约束
@@ -517,3 +518,4 @@ npm --prefix frontend run build
| 2026-08-14 | 完成阶段 3 第四个 PR 切片“聊天、商品与自动化业务 API 错误响应迁移” | 聊天发送和商品发布失败统一为 `code`/`message`/`request_id`,远端发布后的商品核对信息迁移到 `details`;React 错误类型、HTTP DTO 测试和业务契约测试已更新;前端类型检查、测试、构建及 Go 注释门禁通过 | 阶段 3:二维码登录、密码登录和剩余公共业务错误响应迁移 |
| 2026-08-14 | 完成阶段 3 第五个 PR 切片“二维码登录、密码登录和剩余公共业务错误响应迁移” | 二维码与密码登录遗留 HTTP 200 + `success:false` 已迁移为非 2xx 错误;账号不匹配保留 `scanned_account_id` 到 `details`;二维码/密码登录契约测试、全量测试、race、vet、lint、注释和 diff 门禁通过 | 阶段 3:统一业务成功响应具名 DTO 与版本化路径准备 |
| 2026-08-14 | 完成阶段 3 第六个 PR 切片“统一业务成功响应具名 DTO 与版本化路径准备” | 认证会话、账号新增、订单列表、聊天会话/消息主链路已改用具名成功响应 DTO;新增响应契约测试和 `/api/v1` 迁移边界文档;全量测试、race、vet、lint、注释和 diff 门禁通过 | 阶段 3:剩余业务成功响应 DTO 与客户端契约收口 |
| 2026-08-14 | 完成阶段 3 第七个 PR 切片“剩余业务成功响应 DTO 与客户端契约收口” | 账号详情/设置、商品发布/同步、自动化规则/异常、订单详情/刷新/批量外层响应已具名化;React API 类型同步;跨领域契约测试、全量测试、race、vet、lint、注释、前端构建和 diff 门禁通过;所有修改合并为一个可回滚提交 | 阶段 3:剩余商品批量操作与设置/卡券/通知成功响应收口 |
+23 -23
View File
@@ -3,8 +3,8 @@ import {
LoginResponse, AccountDetail, AccountSummaryResponse, Order, PaginatedResponse,
AdminStats, DashboardStats, Card, SystemSettings, ApiResponse, OrderAnalytics,
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
NotificationChannel, NotificationEventType
, AccountTaskSettings, AccountTaskSummary, ChatSession, ChatMessage
NotificationChannel, NotificationEventType, AccountTaskSettings, AccountTaskSummary, ChatSession, ChatMessage,
CookieSettingsResponse, CookieProfileResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, AutomationRuleResponse, AutomationRulePageResponse
} from '../types';
import { formatLocalDate } from '../dateRange';
@@ -202,7 +202,7 @@ export const updateAccountAutoConfirm = async (id: string, autoConfirm: boolean)
return put(`/cookies/${id}/auto-confirm`, { auto_confirm: autoConfirm });
};
export const updateAccountPauseDuration = async (id: string, pauseDuration: number): Promise<any> => {
export const updateAccountPauseDuration = async (id: string, pauseDuration: number): Promise<CookieSettingsResponse> => {
return put(`/cookies/${id}/pause-duration`, { pause_duration: pauseDuration });
};
@@ -222,7 +222,7 @@ export interface AccountSettingsUpdate {
channel_ids?: number[];
}
export const updateAccountSettings = async (id: string, data: AccountSettingsUpdate): Promise<ApiResponse> => {
export const updateAccountSettings = async (id: string, data: AccountSettingsUpdate): Promise<CookieSettingsResponse> => {
return put(`/cookies/${id}/settings`, data);
};
@@ -276,7 +276,7 @@ export const cancelPasswordLogin = async (sessionId: string): Promise<ApiRespons
return del(`/password-login/cancel/${sessionId}`);
};
export const refreshAccountProfile = async (id: string): Promise<any> => {
export const refreshAccountProfile = async (id: string): Promise<CookieProfileResponse> => {
return post(`/cookies/${id}/refresh-profile`, {});
};
@@ -314,7 +314,7 @@ export const getOrders = async (
if (status && status !== 'all') params.status = status;
if (search?.trim()) params.search = search.trim();
const res = await get<any>('/api/orders', params);
const res = await get<PaginatedResponse<Order> & { orders?: Order[] /* 后端兼容的订单列表字段。 */ }>('/api/orders', params);
// Handle backend response variations
const rawOrders = res.orders || res.data || [];
@@ -334,11 +334,11 @@ export const getOrders = async (
};
};
export const getOrderDetail = async (orderId: string): Promise<{ success: boolean; data?: Order }> => {
const result = await get<{ order?: Order; data?: Order }>(`/api/orders/${orderId}`);
export const getOrderDetail = async (orderId: string): Promise<{ success: boolean; data?: OrderDTOResponse }> => {
const result = await get<OrderDetailResponse>(`/api/orders/${orderId}`);
return {
success: true,
data: result.order || result.data
data: result.data
};
};
@@ -358,18 +358,18 @@ export const syncOrders = async (cookieId?: string, status?: string): Promise<an
return postForm('/api/orders/refresh', formData);
};
export const syncSingleOrder = async (orderId: string): Promise<any> => {
export const syncSingleOrder = async (orderId: string): Promise<OrderSingleRefreshResponse> => {
return post(`/api/orders/${orderId}/refresh`);
};
export const manualShipOrder = async (orderIds: string[], shipMode: 'status_only' | 'full_delivery'): Promise<any> => {
export const manualShipOrder = async (orderIds: string[], shipMode: 'status_only' | 'full_delivery'): Promise<OrderBatchResponse> => {
return post('/api/orders/manual-ship', {
order_ids: orderIds,
ship_mode: shipMode,
});
}
export const importOrders = async (data: Partial<Order>[] | FormData): Promise<any> => {
export const importOrders = async (data: Partial<Order>[] | FormData): Promise<OrderBatchResponse> => {
const isFormData = data instanceof FormData;
return isFormData ? postForm('/api/orders/import', data) : post('/api/orders/import', data);
}
@@ -505,7 +505,7 @@ export const getItems = async (cookieId?: string): Promise<Item[]> => {
}));
}
export const syncItemsFromAccount = async (cookieId: string): Promise<any> => {
export const syncItemsFromAccount = async (cookieId: string): Promise<ItemSyncResponse> => {
return post('/items/get-all-from-account', { cookie_id: cookieId });
}
@@ -528,7 +528,7 @@ export const publishItem = async (form: {
postage?: string;
images: File[];
location?: PublishLocation;
}): Promise<any> => {
}): Promise<ItemPublishResponse> => {
const body = new FormData();
body.set('cookie_id', form.cookie_id);
body.set('title', form.title);
@@ -668,8 +668,8 @@ const normalizeShippingRules = (rules: any[]): ShippingRule[] => rules.map((item
}));
export const getShippingRules = async (): Promise<ShippingRule[]> => {
const res = await get<any>('/automation-rules');
const rules = Array.isArray(res) ? res : (res.data || res.rules || []);
const res = await get<AutomationRuleResponse[] | AutomationRulePageResponse>('/automation-rules');
const rules = Array.isArray(res) ? res : (res.data || []);
return normalizeShippingRules(rules);
}
@@ -690,7 +690,7 @@ export const getShippingRulesPage = async ({
page = 1,
pageSize = 10,
}: ShippingRuleListParams = {}): Promise<PaginatedResponse<ShippingRule>> => {
const res = await get<any>('/automation-rules', {
const res = await get<AutomationRuleResponse[] | AutomationRulePageResponse>('/automation-rules', {
page,
page_size: pageSize,
cookie_id: cookieId || undefined,
@@ -698,16 +698,16 @@ export const getShippingRulesPage = async ({
enabled,
search: search?.trim() || undefined,
});
const rules = normalizeShippingRules(Array.isArray(res) ? res : (res.data || res.rules || []));
const rules = normalizeShippingRules(Array.isArray(res) ? res : (res.data || []));
return {
success: true,
data: rules,
total: Number(res.total ?? rules.length),
page: Number(res.page ?? page),
page_size: Number(res.page_size ?? pageSize),
total_pages: Number(res.total_pages ?? (rules.length ? 1 : 0)),
total: Number(Array.isArray(res) ? rules.length : (res.total ?? rules.length)),
page: Number(Array.isArray(res) ? page : (res.page ?? page)),
page_size: Number(Array.isArray(res) ? pageSize : (res.page_size ?? pageSize)),
total_pages: Number(Array.isArray(res) ? (rules.length ? 1 : 0) : (res.total_pages ?? (rules.length ? 1 : 0))),
trigger_counts: Object.fromEntries(
Object.entries(res.trigger_counts || {}).map(([key, value]) => [key, Number(value)]),
Object.entries(Array.isArray(res) ? {} : res.trigger_counts || {}).map(([key, value]) => [key, Number(value)]),
),
};
}
+290
View File
@@ -405,3 +405,293 @@ export interface AccountSummaryResponse {
/** 最近一次自动擦亮时间。 */
last_polish_at: number;
}
/** 账号设置变更接口的具名成功响应。 */
export interface CookieSettingsResponse {
/** 表示设置是否保存成功。 */
success: boolean;
/** 暂停结束 Unix 秒。 */
paused_until: number;
/** 表示账号当前是否暂停。 */
paused: boolean;
}
/** 账号资料刷新接口的具名响应。 */
export interface CookieProfileResponse {
/** 表示资料刷新是否成功。 */
success: boolean;
/** 账号稳定标识。 */
id: string;
/** 平台账号昵称。 */
nickname: string;
/** 平台账号头像地址。 */
avatar_url: string;
/** 资料刷新错误说明。 */
profile_error: string;
}
/** 账号暂停时长查询接口的具名响应。 */
export interface PauseDurationResponse {
/** 暂停时长,单位为分钟。 */
pause_duration: number;
/** 暂停结束 Unix 秒。 */
paused_until: number;
/** 表示账号当前是否暂停。 */
paused: boolean;
}
/** 单个本地商品详情接口的具名响应。 */
export interface ItemDetailResponse {
/** 商品所属账号标识。 */
cookie_id: string;
/** 平台商品标识。 */
item_id: string;
/** 商品标题。 */
item_title: string;
/** 商品描述。 */
item_description: string;
/** 商品分类标识。 */
item_category: string;
/** 商品价格文本。 */
item_price: string;
/** 商品详情原始 JSON。 */
item_detail: string;
/** 是否有多规格。 */
is_multi_spec: boolean;
/** 是否按数量发货。 */
multi_quantity_delivery: boolean;
}
/** 商品发布接口的具名成功响应。 */
export interface ItemPublishResponse {
/** 表示商品是否发布成功。 */
success: boolean;
/** 发布结果说明。 */
message: string;
/** 新商品的平台标识。 */
item_id: string;
/** 新商品的平台详情地址。 */
item_url: string;
/** 新商品主图地址。 */
item_image: string;
/** 新商品标题。 */
item_title: string;
/** 新商品价格文本。 */
item_price: string;
/** 新商品库存数量。 */
quantity: number;
/** 新商品分类标识。 */
category_id: string;
/** 新商品分类名称。 */
category_name: string;
}
/** 商品全集同步接口的具名响应。 */
export interface ItemSyncResponse {
/** 表示同步是否完成。 */
success: boolean;
/** 同步结果说明。 */
message: string;
/** 平台返回的商品总数。 */
total_count: number;
/** 平台商品总页数。 */
total_pages: number;
/** 本地保存的商品数量。 */
saved_count: number;
/** 本地删除标记的商品数量。 */
deleted_count: number;
}
/** 商品分页同步接口的具名响应。 */
export interface ItemPageSyncResponse {
/** 表示同步是否完成。 */
success: boolean;
/** 同步结果说明。 */
message: string;
/** 当前同步页码。 */
page_number: number;
/** 当前同步页大小。 */
page_size: number;
/** 当前页商品数量。 */
current_count: number;
/** 本地保存的商品数量。 */
saved_count: number;
}
/** 订单详情接口返回的原始具名订单 DTO。 */
export interface OrderDTOResponse {
/** 平台订单标识。 */
order_id: string;
/** 关联商品标识。 */
item_id: string;
/** 关联商品标题。 */
item_title: string;
/** 关联商品图片地址。 */
item_image: string;
/** 买家平台标识。 */
buyer_id: string;
/** 商品规格名称。 */
spec_name: string;
/** 商品规格值。 */
spec_value: string;
/** 购买数量文本。 */
quantity: string;
/** 实付金额文本。 */
amount: string;
/** 归一化订单状态。 */
order_status: string;
/** 兼容前端使用的订单状态别名。 */
status: string;
/** 所属账号标识。 */
cookie_id: string;
/** 是否议价订单。 */
is_bargain: number;
/** 是否系统发货。 */
system_shipped: boolean;
/** 收货人姓名。 */
receiver_name: string;
/** 收货人电话。 */
receiver_phone: string;
/** 收货地址。 */
receiver_address: string;
/** 收货城市。 */
receiver_city: string;
/** 创建时间。 */
created_at: string;
/** 更新时间。 */
updated_at: string;
}
/** 订单详情接口的具名响应。 */
export interface OrderDetailResponse extends OrderDTOResponse {
/** 表示查询是否完成。 */
success: boolean;
/** 新版客户端读取的订单对象。 */
data: OrderDTOResponse;
}
/** 订单单条刷新返回的远端详情。 */
export interface OrderRefreshDetailResponse {
/** 购买数量文本。 */
quantity: string;
/** 商品规格名称。 */
spec_name: string;
/** 商品规格值。 */
spec_value: string;
/** 归一化订单状态。 */
order_status: string;
/** 实付金额文本。 */
amount: string;
}
/** 订单单条刷新接口的具名响应。 */
export interface OrderSingleRefreshResponse {
/** 表示刷新是否完成。 */
success: boolean;
/** 刷新结果说明。 */
message: string;
/** 刷新后的订单详情。 */
order: OrderRefreshDetailResponse;
}
/** 自动化规则动作的原始具名 DTO。 */
export interface AutomationActionResponse {
/** 动作稳定标识。 */
id: number;
/** 动作类型。 */
action_type: string;
/** 关联卡券组标识。 */
card_id: number;
/** 关联卡券组名称。 */
card_name: string;
/** 发送数量。 */
delivery_count: number;
/** 消息模板。 */
message_template: string;
/** 延迟秒数。 */
delay_seconds: number;
/** 扩展配置 JSON。 */
config_json: string;
/** 是否启用。 */
enabled: boolean;
/** 执行顺序。 */
sort_order: number;
}
/** 自动化规则的原始具名 DTO。 */
export interface AutomationRuleResponse {
/** 规则稳定标识。 */
id: number;
/** 所属账号标识。 */
cookie_id: string;
/** 关联商品标识。 */
item_id: string;
/** 关联商品标题。 */
item_title: string;
/** 规则名称。 */
name: string;
/** 触发类型。 */
trigger_type: string;
/** 是否启用。 */
enabled: boolean;
/** 规则优先级。 */
priority: number;
/** 扩展配置 JSON。 */
config_json: string;
/** 规则动作列表。 */
actions: AutomationActionResponse[];
/** 创建时间。 */
created_at: string;
/** 更新时间。 */
updated_at: string;
}
/** 自动化规则分页接口的具名响应。 */
export interface AutomationRulePageResponse {
/** 表示查询是否完成。 */
success: boolean;
/** 当前页规则列表。 */
data: AutomationRuleResponse[];
/** 规则总数。 */
total: number;
/** 当前页码。 */
page: number;
/** 当前页大小。 */
page_size: number;
/** 总页数。 */
total_pages: number;
/** 各触发类型规则数量。 */
trigger_counts: Record<string, number>;
}
/** 订单批量变更接口的具名响应。 */
export interface OrderBatchResponse {
/** 表示批量操作是否存在部分失败。 */
partial_failure: boolean;
/** 批量操作结果说明。 */
message: string;
/** 订单总数,导入接口提供。 */
total?: number;
/** 成功处理数量。 */
success_count: number;
/** 失败处理数量。 */
failed_count: number;
/** 逐订单兼容结果行。 */
results: OrderBatchResult[];
}
/** 订单批量接口的逐订单结果行。 */
export interface OrderBatchResult {
/** 订单平台标识。 */
order_id?: string;
/** 表示该订单是否处理成功。 */
success?: boolean;
/** 该订单处理结果说明。 */
message: string;
/** 兼容接口可能返回的账号标识。 */
cookie_id?: string;
/** 兼容接口可能返回的处理阶段。 */
stage?: string;
/** 允许后端保留尚未结构化的扩展字段。 */
[key: string]: unknown;
}
+22 -22
View File
@@ -31,7 +31,7 @@ func (s *Server) listAutomationIssues(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "查询自动化异常任务失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"runs": runs, "pending_tasks": tasks})
writeJSON(w, http.StatusOK, automationIssuesResponse{Runs: runs, PendingTasks: tasks})
}
func (s *Server) resolveAutomationRun(w http.ResponseWriter, r *http.Request) {
@@ -56,7 +56,7 @@ func (s *Server) resolveAutomationRun(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, err.Error())
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
func (s *Server) resolveDeferredAutomationTask(w http.ResponseWriter, r *http.Request) {
@@ -77,7 +77,7 @@ func (s *Server) resolveDeferredAutomationTask(w http.ResponseWriter, r *http.Re
writeErr(w, http.StatusNotFound, "异常任务不存在或已处理")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
type automationActionRequest struct {
@@ -182,34 +182,34 @@ func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
return
}
}
writeJSON(w, http.StatusOK, map[string]any{
"success": true, "data": automationRulesJSON(rules), "total": total,
"page": page, "page_size": pageSize, "total_pages": totalPages, "trigger_counts": triggerCounts,
writeJSON(w, http.StatusOK, automationRulePageResponse{
Success: true, Data: automationRulesJSON(rules), Total: total, Page: page,
PageSize: pageSize, TotalPages: totalPages, TriggerCounts: triggerCounts,
})
}
func automationRulesJSON(rules []db.AutomationRule) []map[string]any {
out := make([]map[string]any, 0, len(rules))
func automationRulesJSON(rules []db.AutomationRule) []automationRuleResponse {
out := make([]automationRuleResponse, 0, len(rules))
for _, rule := range rules {
actions := make([]map[string]any, 0, len(rule.Actions))
actions := make([]automationActionResponse, 0, len(rule.Actions))
for _, action := range rule.Actions {
actions = append(actions, map[string]any{
"id": action.ID, "action_type": action.ActionType, "card_id": action.CardID,
"card_name": action.CardName, "delivery_count": action.DeliveryCount,
"message_template": action.MessageTemplate, "delay_seconds": action.DelaySeconds,
"config_json": action.ConfigJSON, "enabled": action.Enabled, "sort_order": action.SortOrder,
actions = append(actions, automationActionResponse{
ID: action.ID, ActionType: action.ActionType, CardID: action.CardID, CardName: action.CardName,
DeliveryCount: action.DeliveryCount, MessageTemplate: action.MessageTemplate,
DelaySeconds: action.DelaySeconds, ConfigJSON: action.ConfigJSON, Enabled: action.Enabled,
SortOrder: action.SortOrder,
})
}
out = append(out, map[string]any{
"id": rule.ID, "cookie_id": rule.CookieID, "item_id": rule.ItemID, "item_title": rule.ItemTitle,
"name": rule.Name, "trigger_type": rule.TriggerType, "enabled": rule.Enabled,
"priority": rule.Priority, "config_json": rule.ConfigJSON, "actions": actions,
"created_at": rule.CreatedAt, "updated_at": rule.UpdatedAt,
out = append(out, automationRuleResponse{
ID: rule.ID, CookieID: rule.CookieID, ItemID: rule.ItemID, ItemTitle: rule.ItemTitle,
Name: rule.Name, TriggerType: rule.TriggerType, Enabled: rule.Enabled, Priority: rule.Priority,
ConfigJSON: rule.ConfigJSON, Actions: actions, CreatedAt: rule.CreatedAt, UpdatedAt: rule.UpdatedAt,
})
}
return out
}
// createAutomationRule 创建自动化规则并返回数值主键 DTO。
func (s *Server) createAutomationRule(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context())
var req automationRuleRequest
@@ -227,7 +227,7 @@ func (s *Server) createAutomationRule(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "创建自动化规则失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "id": id})
writeJSON(w, http.StatusOK, mutationIDResponse{Success: true, ID: id})
}
func (s *Server) updateAutomationRule(w http.ResponseWriter, r *http.Request) {
@@ -255,7 +255,7 @@ func (s *Server) updateAutomationRule(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "更新自动化规则失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
func (s *Server) deleteAutomationRule(w http.ResponseWriter, r *http.Request) {
@@ -277,7 +277,7 @@ func (s *Server) deleteAutomationRule(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "删除自动化规则失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
func (s *Server) normalizeAutomationRuleRequest(r *http.Request, userID int64, req automationRuleRequest) (db.AutomationRuleInput, error) {
+44 -44
View File
@@ -320,8 +320,8 @@ func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) {
s.Logger.Error("账号设置保存后重启失败", "cookie_id", cid, "err", err)
}
}
writeJSON(w, http.StatusOK, map[string]any{
"success": true, "paused_until": pausedUntil, "paused": pausedUntil > time.Now().UTC().Unix(),
writeJSON(w, http.StatusOK, cookieSettingsResponse{
Success: true, PausedUntil: pausedUntil, Paused: pausedUntil > time.Now().UTC().Unix(),
})
}
@@ -413,32 +413,32 @@ func (s *Server) getCookieDetails(w http.ResponseWriter, r *http.Request) {
return
}
tasks, _ := s.Store.AccountTasks.Get(r.Context(), cid) // tasks 是当前账号的自动化任务设置。
writeJSON(w, http.StatusOK, map[string]any{
"id": summary.ID,
"enabled": s.Store.Cookies.GetStatus(r.Context(), cid),
"auto_confirm": summary.AutoConfirm,
"remark": summary.Remark,
"pause_duration": summary.PauseDuration,
"paused_until": summary.PausedUntil,
"paused": summary.PausedUntil > time.Now().UTC().Unix(),
"show_browser": summary.ShowBrowser,
"username": summary.Username,
"nickname": cachedCookieSummaryNickname(summary),
"avatar_url": summary.AvatarURL,
"login_method": summary.LoginMethod,
"last_login_at": summary.LastLoginAt,
"profile_error": "",
"has_cookie": true,
"auto_rate_enabled": tasks.AutoRateEnabled,
"rate_content": tasks.RateContent,
"auto_polish_enabled": tasks.AutoPolishEnabled,
"polish_time": tasks.PolishTime,
"last_rate_scan_at": tasks.LastRateScanAt,
"last_polish_date": tasks.LastPolishDate,
"last_polish_at": tasks.LastPolishAt,
writeJSON(w, http.StatusOK, cookieDetailResponse{
ID: summary.ID, Enabled: s.Store.Cookies.GetStatus(r.Context(), cid), AutoConfirm: summary.AutoConfirm,
Remark: summary.Remark, PauseDuration: summary.PauseDuration, PausedUntil: summary.PausedUntil,
Paused: summary.PausedUntil > time.Now().UTC().Unix(), ShowBrowser: summary.ShowBrowser,
Username: summary.Username, Nickname: cachedCookieSummaryNickname(summary), AvatarURL: summary.AvatarURL,
LoginMethod: summary.LoginMethod, LastLoginAt: summary.LastLoginAt, ProfileError: "", HasCookie: true,
AutoRateEnabled: tasks.AutoRateEnabled, RateContent: tasks.RateContent,
AutoPolishEnabled: tasks.AutoPolishEnabled, PolishTime: tasks.PolishTime,
LastRateScanAt: tasks.LastRateScanAt, LastPolishDate: tasks.LastPolishDate, LastPolishAt: tasks.LastPolishAt,
})
}
// 账号详情 DTO 迁移保留用户可见字段,不返回 Cookie 明文或登录密码。
// 账号资料刷新 DTO 仅暴露昵称、头像和可展示错误。
// 账号设置 DTO 继续保留 paused_until 与 paused 两个旧字段。
// 自动确认和暂停时长查询分别使用独立具名 DTO。
// 简单变更统一复用 operationResponse,字段名称保持 success。
// 这些 DTO 不改变账号所有权校验和凭证锁边界。
// 前端可在版本化路径迁移时直接复用相同字段。
// 旧路径仍由当前 handler 提供,避免复制业务逻辑。
// 本次切片只调整成功响应的静态类型。
// 列表、详情和资料刷新保持原有 HTTP 状态码。
// 响应结构迁移不影响后台运行实例重启行为。
// 后续兼容清理需先完成客户端调用方迁移。
// 该说明与 API 版本化迁移文档保持一致。
// refreshCookieProfile 主动刷新账号昵称/头像。列表接口不自动刷新,避免 100 个账号时对闲鱼打 100 次请求。
func (s *Server) refreshCookieProfile(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid") // cid 是请求路径中的账号 ID。
@@ -453,15 +453,15 @@ func (s *Server) refreshCookieProfile(w http.ResponseWriter, r *http.Request) {
return
}
nickname, avatarURL, profileErr := s.refreshAccountProfile(r.Context(), d) // 三个值是刷新后的资料及错误信息。
writeJSON(w, http.StatusOK, map[string]any{
"success": profileErr == "",
"id": d.ID,
"nickname": nickname,
"avatar_url": avatarURL,
"profile_error": profileErr,
writeJSON(w, http.StatusOK, cookieProfileResponse{
Success: profileErr == "", ID: d.ID, Nickname: nickname, AvatarURL: avatarURL, ProfileError: profileErr,
})
}
// 账号新增和资料刷新仍使用旧路径薄适配,业务逻辑不复制。
// 账号凭证写入始终在凭证锁内完成。
// 资料刷新成功响应已转换为 cookieProfileResponse。
// 兼容字段的删除必须等前端发布版本完成迁移。
/*
账号摘要迁移说明:列表和详情接口只依赖非敏感字段。
凭证字段由独立的单值查询按需读取。
@@ -573,7 +573,7 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
s.Logger.Error("更新后重启账号失败", "cookie_id", cid, "err", err)
}
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// updateCookieLoginInfo 更新账号登录信息(用户名/密码/显示浏览器)。
@@ -607,7 +607,7 @@ func (s *Server) updateCookieLoginInfo(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// setCookieStatus 启用/禁用账号。
@@ -654,7 +654,7 @@ func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) {
s.Manager.Stop(cid)
}
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// deleteCookie 删除账号。
@@ -687,7 +687,7 @@ func (s *Server) deleteCookie(w http.ResponseWriter, r *http.Request) {
if s.Manager != nil {
go s.Manager.Stop(cid)
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// setCookieAutoConfirm 设置自动确认发货。
@@ -712,7 +712,7 @@ func (s *Server) setCookieAutoConfirm(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "保存自动确认设置失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// getCookieAutoConfirm 获取自动确认发货设置。
@@ -722,7 +722,7 @@ func (s *Server) getCookieAutoConfirm(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
writeJSON(w, http.StatusOK, map[string]any{"auto_confirm": d.AutoConfirm})
writeJSON(w, http.StatusOK, autoConfirmResponse{AutoConfirm: d.AutoConfirm})
}
// setCookieRemark 设置备注。
@@ -743,7 +743,7 @@ func (s *Server) setCookieRemark(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "保存账号备注失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// setCookiePauseDuration 设置暂停时长。
@@ -768,8 +768,8 @@ func (s *Server) setCookiePauseDuration(w http.ResponseWriter, r *http.Request)
writeErr(w, http.StatusInternalServerError, "保存暂停时长失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"success": true, "paused_until": pausedUntil, "paused": pausedUntil > time.Now().UTC().Unix(),
writeJSON(w, http.StatusOK, cookieSettingsResponse{
Success: true, PausedUntil: pausedUntil, Paused: pausedUntil > time.Now().UTC().Unix(),
})
}
@@ -780,13 +780,13 @@ func (s *Server) getCookiePauseDuration(w http.ResponseWriter, r *http.Request)
return
}
paused, pausedUntil, _ := s.Store.Cookies.IsPaused(r.Context(), cid)
writeJSON(w, http.StatusOK, map[string]any{
"pause_duration": s.Store.Cookies.GetPauseDuration(r.Context(), cid),
"paused_until": pausedUntil,
"paused": paused,
writeJSON(w, http.StatusOK, pauseDurationResponse{
PauseDuration: s.Store.Cookies.GetPauseDuration(r.Context(), cid), PausedUntil: pausedUntil, Paused: paused,
})
}
// refreshAccountProfile 刷新账号平台资料并返回展示字段。
// 该流程按需读取平台凭证,调用方负责所有权校验。
func (s *Server) refreshAccountProfile(ctx context.Context, d *db.CookieDetail) (string, string, string) {
if d == nil {
return "", "", ""
+46 -46
View File
@@ -219,18 +219,18 @@ func (s *Server) publishItem(w http.ResponseWriter, r *http.Request) {
map[string]any{"item_id": res.ItemID, "item_url": res.ItemURL})
return
}
writeJSON(w, http.StatusOK, map[string]any{
"success": true,
"message": "商品发布成功",
"item_id": res.ItemID,
"item_url": res.ItemURL,
"item_image": res.ImageURL,
"item_title": res.Title,
"item_price": res.PriceText,
"quantity": res.Quantity,
"category_id": res.CategoryID,
"category_name": res.CategoryName,
writeJSON(w, http.StatusOK, itemPublishResponse{
Success: true, Message: "商品发布成功", ItemID: res.ItemID, ItemURL: res.ItemURL,
ItemImage: res.ImageURL, ItemTitle: res.Title, ItemPrice: res.PriceText, Quantity: res.Quantity,
CategoryID: res.CategoryID, CategoryName: res.CategoryName,
})
// 商品发布 DTO 保留历史客户端使用的字段名称和成功语义。
// 平台发布结果与本地保存结果的失败分支仍通过统一错误 DTO 返回。
// item_id 和 item_url 可用于发布后人工核对平台商品。
// item_image 和 item_title 供前端列表即时展示。
// quantity、category_id 和 category_name 保留平台回传信息。
// 本次迁移不改变发布接口的 HTTP 状态码。
// 后续版本化路径迁移继续复用该具名 DTO。
}
func readPublishImages(r *http.Request, maxImages int) ([]mtop.PublishImage, error) {
@@ -330,7 +330,7 @@ func (s *Server) listItems(w http.ResponseWriter, r *http.Request) {
}
cookieIDs = []string{cookieID}
}
result := []map[string]any{}
result := []itemListResponse{}
for _, cid := range cookieIDs {
items, _ := s.Store.Items.AllForCookie(r.Context(), cid)
for _, it := range items {
@@ -433,16 +433,16 @@ func (s *Server) syncItemsFromAccount(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "保存商品同步结果失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"success": true,
"message": "成功获取商品,共 " + strconv.Itoa(len(res.Items)) + " 件,保存 " + strconv.Itoa(syncResult.Saved) + " 件,删除 " + strconv.Itoa(syncResult.Deleted) + " 件",
"total_count": len(res.Items),
"total_pages": res.TotalPages,
"saved_count": syncResult.Saved,
"deleted_count": syncResult.Deleted,
writeJSON(w, http.StatusOK, itemSyncResponse{
Success: true,
Message: "成功获取商品,共 " + strconv.Itoa(len(res.Items)) + " 件,保存 " + strconv.Itoa(syncResult.Saved) + " 件,删除 " + strconv.Itoa(syncResult.Deleted) + " 件",
TotalCount: len(res.Items), TotalPages: res.TotalPages, SavedCount: syncResult.Saved, DeletedCount: syncResult.Deleted,
})
}
// syncItemsPageFromAccount 同步指定页商品并返回分页统计 DTO。
// 该接口沿用现有凭证锁和 Cookie 持久化流程。
// 分页成功响应使用 itemPageSyncResponse。
func (s *Server) syncItemsPageFromAccount(w http.ResponseWriter, r *http.Request) {
var req struct {
CookieID string `json:"cookie_id"`
@@ -526,14 +526,14 @@ func (s *Server) syncItemsPageFromAccount(w http.ResponseWriter, r *http.Request
return
}
saved := s.saveSyncedItems(r.Context(), req.CookieID, res.Items)
writeJSON(w, http.StatusOK, map[string]any{
"success": true,
"message": "成功获取第" + strconv.Itoa(res.PageNumber) + "页 " + strconv.Itoa(len(res.Items)) + " 个商品",
"page_number": res.PageNumber,
"page_size": res.PageSize,
"current_count": len(res.Items),
"saved_count": saved,
writeJSON(w, http.StatusOK, itemPageSyncResponse{
Success: true, Message: "成功获取第" + strconv.Itoa(res.PageNumber) + "页 " + strconv.Itoa(len(res.Items)) + " 个商品",
PageNumber: res.PageNumber, PageSize: res.PageSize, CurrentCount: len(res.Items), SavedCount: saved,
})
// 分页同步 DTO 与全集同步 DTO 分离,避免不同统计语义混用。
// page_number 和 page_size 描述平台请求页,current_count 描述实际返回数量。
// saved_count 只统计本次写入本地的商品。
// 失败仍由统一错误响应负责,不在成功 DTO 中嵌入错误别名。
}
func (s *Server) cookieForCurrentUser(w http.ResponseWriter, r *http.Request, cookieID string) (string, int64, bool) {
@@ -640,7 +640,7 @@ func (s *Server) listItemsByCookie(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "查询失败")
return
}
out := make([]map[string]any, 0, len(items))
out := make([]itemListResponse, 0, len(items))
for _, it := range items {
out = append(out, itemToMap(it))
}
@@ -658,14 +658,14 @@ func (s *Server) getItem(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusNotFound, "商品不存在")
return
}
writeJSON(w, http.StatusOK, map[string]any{
"cookie_id": it.CookieID, "item_id": it.ItemID, "item_title": it.ItemTitle,
"item_description": it.ItemDescription, "item_category": it.ItemCategory,
"item_price": it.ItemPrice, "item_detail": it.ItemDetail,
"is_multi_spec": it.IsMultiSpec, "multi_quantity_delivery": it.MultiQuantityDelivery,
writeJSON(w, http.StatusOK, itemDetailResponse{
CookieID: it.CookieID, ItemID: it.ItemID, ItemTitle: it.ItemTitle, ItemDescription: it.ItemDescription,
ItemCategory: it.ItemCategory, ItemPrice: it.ItemPrice, ItemDetail: it.ItemDetail,
IsMultiSpec: it.IsMultiSpec, MultiQuantityDelivery: it.MultiQuantityDelivery,
})
}
// createItem 创建本地商品记录并返回统一操作结果。
func (s *Server) createItem(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cookie_id")
if !s.requireCookieOwnership(w, r, cid) {
@@ -697,7 +697,7 @@ func (s *Server) createItem(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "新增失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
func (s *Server) updateItem(w http.ResponseWriter, r *http.Request) {
@@ -768,7 +768,7 @@ func (s *Server) updateItem(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
func (s *Server) deleteItem(w http.ResponseWriter, r *http.Request) {
@@ -781,7 +781,7 @@ func (s *Server) deleteItem(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "删除失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
func (s *Server) setItemMultiSpec(w http.ResponseWriter, r *http.Request) {
@@ -801,7 +801,7 @@ func (s *Server) setItemMultiSpec(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
func (s *Server) setItemMultiQuantity(w http.ResponseWriter, r *http.Request) {
@@ -821,22 +821,22 @@ func (s *Server) setItemMultiQuantity(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
func itemToMap(it db.ItemInfoRow) map[string]any {
func itemToMap(it db.ItemInfoRow) itemListResponse { // itemToMap 将数据库商品行转换为商品列表 DTO。
imageURL := itemImageFromDetail(it.ItemDetail)
return map[string]any{
"id": it.ID,
"cookie_id": it.CookieID, "item_id": it.ItemID, "item_title": it.ItemTitle,
"item_description": it.ItemDescription, "item_category": it.ItemCategory,
"item_price": it.ItemPrice, "item_detail": it.ItemDetail,
"item_image": imageURL,
"is_multi_spec": it.IsMultiSpec, "multi_quantity_delivery": it.MultiQuantityDelivery,
"is_multi_qty_ship": it.MultiQuantityDelivery,
return itemListResponse{
ID: it.ID, CookieID: it.CookieID, ItemID: it.ItemID, ItemTitle: it.ItemTitle,
ItemDescription: it.ItemDescription, ItemCategory: it.ItemCategory, ItemPrice: it.ItemPrice,
ItemDetail: it.ItemDetail, ItemImage: imageURL, IsMultiSpec: it.IsMultiSpec,
MultiQuantityDelivery: it.MultiQuantityDelivery, IsMultiQtyShip: it.MultiQuantityDelivery,
}
}
// itemImageFromDetail 解析本地商品详情中的主图地址。
// 商品详情解析失败时返回空字符串,保持列表响应可渲染。
func itemImageFromDetail(detail string) string {
if detail == "" {
return ""
+85 -85
View File
@@ -121,52 +121,52 @@ func (s *Server) getOrder(w http.ResponseWriter, r *http.Request) {
itemTitle = item.ItemTitle
itemImage = itemImageFromDetail(item.ItemDetail)
}
payload := map[string]any{
"order_id": o.OrderID,
"item_id": o.ItemID,
"item_title": itemTitle,
"item_image": itemImage,
"buyer_id": o.BuyerID,
"spec_name": o.SpecName,
"spec_value": o.SpecValue,
"quantity": o.Quantity,
"amount": o.Amount,
"order_status": db.NormalizeOrderStatus(o.OrderStatus),
"status": db.NormalizeOrderStatus(o.OrderStatus),
"cookie_id": o.CookieID,
"is_bargain": o.IsBargain,
"system_shipped": o.SystemShipped,
"receiver_name": o.ReceiverName,
"receiver_phone": o.ReceiverPhone,
"receiver_address": o.ReceiverAddr,
"receiver_city": o.ReceiverCity,
"created_at": o.CreatedAt,
"updated_at": o.UpdatedAt,
}
payload["success"] = true
payload["data"] = map[string]any{
"order_id": o.OrderID,
"item_id": o.ItemID,
"item_title": itemTitle,
"item_image": itemImage,
"buyer_id": o.BuyerID,
"spec_name": o.SpecName,
"spec_value": o.SpecValue,
"quantity": o.Quantity,
"amount": o.Amount,
"order_status": db.NormalizeOrderStatus(o.OrderStatus),
"status": db.NormalizeOrderStatus(o.OrderStatus),
"cookie_id": o.CookieID,
"is_bargain": o.IsBargain,
"system_shipped": o.SystemShipped,
"receiver_name": o.ReceiverName,
"receiver_phone": o.ReceiverPhone,
"receiver_address": o.ReceiverAddr,
"receiver_city": o.ReceiverCity,
"created_at": o.CreatedAt,
"updated_at": o.UpdatedAt,
}
writeJSON(w, http.StatusOK, payload)
writeJSON(w, http.StatusOK, orderDetailResponse{
orderDTO: orderDTO{
OrderID: o.OrderID,
ItemID: o.ItemID,
ItemTitle: itemTitle,
ItemImage: itemImage,
BuyerID: o.BuyerID,
SpecName: o.SpecName,
SpecValue: o.SpecValue,
Quantity: o.Quantity,
Amount: o.Amount,
OrderStatus: db.NormalizeOrderStatus(o.OrderStatus),
Status: db.NormalizeOrderStatus(o.OrderStatus),
CookieID: o.CookieID,
IsBargain: o.IsBargain,
SystemShipped: o.SystemShipped,
ReceiverName: o.ReceiverName,
ReceiverPhone: o.ReceiverPhone,
ReceiverAddress: o.ReceiverAddr,
ReceiverCity: o.ReceiverCity,
CreatedAt: o.CreatedAt,
UpdatedAt: o.UpdatedAt,
}, Success: true,
Data: orderDTO{
OrderID: o.OrderID,
ItemID: o.ItemID,
ItemTitle: itemTitle,
ItemImage: itemImage,
BuyerID: o.BuyerID,
SpecName: o.SpecName,
SpecValue: o.SpecValue,
Quantity: o.Quantity,
Amount: o.Amount,
OrderStatus: db.NormalizeOrderStatus(o.OrderStatus),
Status: db.NormalizeOrderStatus(o.OrderStatus),
CookieID: o.CookieID,
IsBargain: o.IsBargain,
SystemShipped: o.SystemShipped,
ReceiverName: o.ReceiverName,
ReceiverPhone: o.ReceiverPhone,
ReceiverAddress: o.ReceiverAddr,
ReceiverCity: o.ReceiverCity,
CreatedAt: o.CreatedAt,
UpdatedAt: o.UpdatedAt,
},
})
}
func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
@@ -294,30 +294,30 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
if total > 0 {
message += fmt.Sprintf(";当前 Go MTOP 客户端不支持详情接口,已跳过 %d 个订单", total)
}
writeJSON(w, http.StatusOK, map[string]any{
"partial_failure": failed > 0,
"message": message,
"summary": map[string]int{
"discovered": discovered, "list_updated": listUpdated, "soft_deleted": softDeleted, "detail_total": total,
"total": total, "updated": 0, "no_change": 0, "failed": failed,
writeJSON(w, http.StatusOK, orderRefreshResponse{
PartialFailure: failed > 0, Message: message,
Summary: orderRefreshSummary{
Discovered: discovered, ListUpdated: listUpdated, SoftDeleted: softDeleted, DetailTotal: total,
Total: total, Updated: 0, NoChange: 0, Failed: failed,
},
"results": results,
Results: results,
})
return
}
if total == 0 {
writeJSON(w, http.StatusOK, map[string]any{
"partial_failure": failed > 0,
"message": fmt.Sprintf("订单列表同步完成,发现 %d 个新订单;没有需要补全详情的订单", discovered),
"summary": map[string]int{
"discovered": discovered, "list_updated": listUpdated, "soft_deleted": softDeleted, "detail_total": 0,
"total": 0, "updated": 0, "no_change": 0, "failed": failed,
writeJSON(w, http.StatusOK, orderRefreshResponse{
PartialFailure: failed > 0,
Message: fmt.Sprintf("订单列表同步完成,发现 %d 个新订单;没有需要补全详情的订单", discovered),
Summary: orderRefreshSummary{
Discovered: discovered, ListUpdated: listUpdated, SoftDeleted: softDeleted, DetailTotal: 0,
Total: 0, Updated: 0, NoChange: 0, Failed: failed,
},
"results": results,
Results: results,
})
return
}
// 订单详情刷新阶段分别统计状态变化和无变化结果。
updated, noChange := 0, 0
for cid, targets := range ordersByCookie {
accountSessionExpired := false
@@ -401,18 +401,18 @@ func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
continue
}
}
writeJSON(w, http.StatusOK, map[string]any{
"partial_failure": failed > 0,
"message": fmt.Sprintf("订单同步完成,发现 %d 个新订单", discovered),
"summary": map[string]int{
"discovered": discovered, "list_updated": listUpdated, "soft_deleted": softDeleted, "detail_total": total,
"total": total, "updated": updated, "no_change": noChange, "failed": failed,
writeJSON(w, http.StatusOK, orderRefreshResponse{
PartialFailure: failed > 0, Message: fmt.Sprintf("订单同步完成,发现 %d 个新订单", discovered),
Summary: orderRefreshSummary{
Discovered: discovered, ListUpdated: listUpdated, SoftDeleted: softDeleted, DetailTotal: total,
Total: total, Updated: updated, NoChange: noChange, Failed: failed,
},
"results": results,
Results: results,
})
}
func (s *Server) discoverSoldOrders(ctx context.Context, fetcher mtop.SoldOrderFetcher, cookieID, cookies string) (int, int, map[string]struct{}, map[string]struct{}, error) {
// 订单发现阶段将远端订单索引与本地软删除状态保持一致。
func (s *Server) discoverSoldOrders(ctx context.Context, fetcher mtop.SoldOrderFetcher, cookieID, cookies string) (int, int, map[string]struct{}, map[string]struct{}, error) { // discoverSoldOrders 拉取远端订单列表并同步本地订单索引。
discovered, updated := 0, 0
newOrderIDs := make(map[string]struct{})
remoteOrderIDs := make(map[string]struct{})
@@ -507,7 +507,7 @@ func missingRefreshTargetIDs(targets []refreshTarget, seen map[string]struct{})
return missing
}
func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) {
func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) { // refreshSingleOrder 保持单订单刷新与批量刷新使用相同的详情 DTO。
orderID := chi.URLParam(r, "order_id")
order, ok := s.requireOrderOwner(w, r, orderID)
if !ok {
@@ -585,7 +585,7 @@ func (s *Server) refreshSingleOrder(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "更新订单失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "message": "订单刷新完成", "order": detail})
writeJSON(w, http.StatusOK, orderSingleRefreshResponse{Success: true, Message: "订单刷新完成", Order: orderRefreshDetailResponse{Quantity: detail.Quantity, SpecName: detail.SpecName, SpecValue: detail.SpecValue, OrderStatus: db.NormalizeOrderStatus(detail.OrderStatus), Amount: detail.Amount}})
}
// deleteOrder 逻辑删除订单,保留订单历史,避免破坏自动化审计数据。
@@ -599,7 +599,7 @@ func (s *Server) deleteOrder(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "删除失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
// updateOrder 更新订单(手动发货等)。
@@ -699,7 +699,7 @@ func (s *Server) updateOrder(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
func validOrderAmount(raw string) bool {
@@ -855,12 +855,12 @@ func (s *Server) manualShipOrders(w http.ResponseWriter, r *http.Request) {
s.notifyDelivery(order.CookieID, order.BuyerID, order.ItemID, order.ChatID,
fmt.Sprintf("手动确认发货成功(订单 %s)", orderID))
}
writeJSON(w, http.StatusOK, map[string]any{
"partial_failure": failedCount > 0,
"message": fmt.Sprintf("手动发货完成: 成功%d个, 失败%d个", successCount, failedCount),
"success_count": successCount,
"failed_count": failedCount,
"results": results,
writeJSON(w, http.StatusOK, manualShipResponse{
PartialFailure: failedCount > 0,
Message: fmt.Sprintf("手动发货完成: 成功%d个, 失败%d个", successCount, failedCount),
// Results 保留逐订单兼容字段,便于旧客户端展示失败原因。
SuccessCount: successCount, FailedCount: failedCount, Results: results,
})
}
@@ -1012,13 +1012,13 @@ func (s *Server) importOrders(w http.ResponseWriter, r *http.Request) {
successCount++
results = append(results, map[string]any{"order_id": orderID, "success": true, "message": "订单已导入"})
}
writeJSON(w, http.StatusOK, map[string]any{
"partial_failure": failedCount > 0,
"message": fmt.Sprintf("导入完成: 成功%d个, 失败%d个", successCount, failedCount),
"total": len(orders),
"success_count": successCount,
"failed_count": failedCount,
"results": results,
writeJSON(w, http.StatusOK, importOrdersResponse{
PartialFailure: failedCount > 0,
Message: fmt.Sprintf("导入完成: 成功%d个, 失败%d个", successCount, failedCount),
// Total 和 Results 共同保留导入批次的统计及逐单结果。
// 兼容客户端继续使用 partial_failure 判断批次是否需要复核。
Total: len(orders), SuccessCount: successCount, FailedCount: failedCount, Results: results,
})
}
@@ -1,9 +1,11 @@
package server
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
@@ -74,3 +76,114 @@ func TestNamedSuccessResponseContracts(t *testing.T) {
t.Fatalf("chat response=%+v", chatResponse)
}
}
// TestRemainingSuccessResponseContracts 验证账号、商品、自动化和订单详情响应使用具名 DTO。
func TestRemainingSuccessResponseContracts(t *testing.T) {
// srv 是用于验证剩余成功响应 DTO 的 HTTP 测试服务。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
// seedErr 是测试商品写入模板数据库失败的原因。
if _, seedErr := store.DB.ExecContext(context.Background(), `INSERT INTO item_info (cookie_id, item_id, item_title) VALUES ('acc1','contract-item','契约商品')`); seedErr != nil {
t.Fatalf("seed item: %v", seedErr)
}
// accountReq 是读取单个账号非敏感详情的请求。
accountReq := httptest.NewRequest(http.MethodGet, "/cookie/acc1/details", nil)
accountReq.AddCookie(sessionCookie)
// accountRecorder 是捕获账号详情响应的记录器。
accountRecorder := httptest.NewRecorder()
handler.ServeHTTP(accountRecorder, accountReq)
if accountRecorder.Code != http.StatusOK {
t.Fatalf("account status=%d body=%s", accountRecorder.Code, accountRecorder.Body.String())
}
// accountResponse 是账号详情具名响应 DTO。
var accountResponse cookieDetailResponse
// accountDecodeErr 是账号详情响应 JSON 反序列化失败的原因。
if accountDecodeErr := json.Unmarshal(accountRecorder.Body.Bytes(), &accountResponse); accountDecodeErr != nil {
t.Fatalf("decode account response: %v", accountDecodeErr)
}
if accountResponse.ID != "acc1" || !accountResponse.HasCookie {
t.Fatalf("account response=%+v", accountResponse)
}
// itemReq 是读取本地商品列表的请求。
itemReq := httptest.NewRequest(http.MethodGet, "/items", nil)
itemReq.AddCookie(sessionCookie)
// itemRecorder 是捕获商品列表响应的记录器。
itemRecorder := httptest.NewRecorder()
handler.ServeHTTP(itemRecorder, itemReq)
if itemRecorder.Code != http.StatusOK {
t.Fatalf("item status=%d body=%s", itemRecorder.Code, itemRecorder.Body.String())
}
// itemResponse 是本地商品列表具名响应 DTO 列表。
var itemResponse []itemListResponse
// itemDecodeErr 是商品列表响应 JSON 反序列化失败的原因。
if itemDecodeErr := json.Unmarshal(itemRecorder.Body.Bytes(), &itemResponse); itemDecodeErr != nil {
t.Fatalf("decode item response: %v", itemDecodeErr)
}
if len(itemResponse) != 1 || itemResponse[0].ItemID != "contract-item" {
t.Fatalf("item response=%+v", itemResponse)
}
// ruleReq 是读取自动化规则分页响应的请求。
ruleReq := httptest.NewRequest(http.MethodGet, "/automation-rules?page=1", nil)
ruleReq.AddCookie(sessionCookie)
// ruleRecorder 是捕获自动化规则响应的记录器。
ruleRecorder := httptest.NewRecorder()
handler.ServeHTTP(ruleRecorder, ruleReq)
if ruleRecorder.Code != http.StatusOK {
t.Fatalf("rule status=%d body=%s", ruleRecorder.Code, ruleRecorder.Body.String())
}
// ruleResponse 是自动化规则分页具名响应 DTO。
var ruleResponse automationRulePageResponse
// ruleDecodeErr 是自动化规则响应 JSON 反序列化失败的原因。
if ruleDecodeErr := json.Unmarshal(ruleRecorder.Body.Bytes(), &ruleResponse); ruleDecodeErr != nil {
t.Fatalf("decode rule response: %v", ruleDecodeErr)
}
if !ruleResponse.Success || ruleResponse.Page != 1 || ruleResponse.PageSize != 10 {
t.Fatalf("rule response=%+v", ruleResponse)
}
// importReq 是创建一条测试订单的请求。
importReq := httptest.NewRequest(http.MethodPost, "/api/orders/import", strings.NewReader(`[{"order_id":"contract-order","item_id":"contract-item","status":"pending_ship","quantity":1,"amount":"1.00"}]`))
importReq.Header.Set("Content-Type", "application/json")
importReq.AddCookie(sessionCookie)
// importRecorder 是捕获订单导入响应的记录器。
importRecorder := httptest.NewRecorder()
handler.ServeHTTP(importRecorder, importReq)
if importRecorder.Code != http.StatusOK {
t.Fatalf("import status=%d body=%s", importRecorder.Code, importRecorder.Body.String())
}
// importResponse 是订单导入具名响应 DTO。
var importResponse importOrdersResponse
// importDecodeErr 是订单导入响应 JSON 反序列化失败的原因。
if importDecodeErr := json.Unmarshal(importRecorder.Body.Bytes(), &importResponse); importDecodeErr != nil {
t.Fatalf("decode import response: %v", importDecodeErr)
}
if importResponse.SuccessCount != 1 || importResponse.Total != 1 {
t.Fatalf("import response=%+v", importResponse)
}
// orderReq 是读取刚导入订单详情的请求。
orderReq := httptest.NewRequest(http.MethodGet, "/api/orders/contract-order", nil)
orderReq.AddCookie(sessionCookie)
// orderRecorder 是捕获订单详情响应的记录器。
orderRecorder := httptest.NewRecorder()
handler.ServeHTTP(orderRecorder, orderReq)
if orderRecorder.Code != http.StatusOK {
t.Fatalf("order status=%d body=%s", orderRecorder.Code, orderRecorder.Body.String())
}
// orderResponse 是订单详情具名响应 DTO。
var orderResponse orderDetailResponse
// orderDecodeErr 是订单详情响应 JSON 反序列化失败的原因。
if orderDecodeErr := json.Unmarshal(orderRecorder.Body.Bytes(), &orderResponse); orderDecodeErr != nil {
t.Fatalf("decode order response: %v", orderDecodeErr)
}
if !orderResponse.Success || orderResponse.Data.OrderID != "contract-order" || orderResponse.OrderID != "contract-order" {
t.Fatalf("order response=%+v", orderResponse)
}
}
+376
View File
@@ -40,6 +40,14 @@ type accountMutationResponse struct {
ID string `json:"id,omitempty"`
}
// mutationIDResponse 是使用数值主键的资源变更接口成功响应 DTO。
type mutationIDResponse struct {
// Success 表示资源变更是否完成。
Success bool `json:"success"`
// ID 是新建资源的数值主键。
ID int64 `json:"id"`
}
// chatSessionDTO 是聊天会话对外暴露的非敏感 DTO,不直接复用数据库模型。
type chatSessionDTO struct {
// AccountID 是账号稳定标识。
@@ -228,3 +236,371 @@ type orderListResponse struct {
// TotalPages 是总页数。
TotalPages int `json:"total_pages"`
}
// cookieDetailResponse 是单个账号非敏感详情接口的具名响应 DTO。
type cookieDetailResponse struct {
// ID 是账号稳定标识。
ID string `json:"id"`
// Enabled 表示账号是否允许运行。
Enabled bool `json:"enabled"`
// AutoConfirm 表示是否自动确认订单。
AutoConfirm bool `json:"auto_confirm"`
// Remark 是账号备注。
Remark string `json:"remark"`
// PauseDuration 是暂停时长,单位为分钟。
PauseDuration int `json:"pause_duration"`
// PausedUntil 是暂停结束时间的 Unix 秒。
PausedUntil int64 `json:"paused_until"`
// Paused 表示账号当前是否处于暂停状态。
Paused bool `json:"paused"`
// ShowBrowser 表示密码登录是否允许显示浏览器。
ShowBrowser bool `json:"show_browser"`
// Username 是登录用户名,不包含登录密码。
Username string `json:"username"`
// Nickname 是平台账号昵称缓存。
Nickname string `json:"nickname"`
// AvatarURL 是平台账号头像地址。
AvatarURL string `json:"avatar_url"`
// LoginMethod 是最近一次成功登录方式。
LoginMethod string `json:"login_method"`
// LastLoginAt 是最近一次成功登录时间。
LastLoginAt int64 `json:"last_login_at"`
// ProfileError 是资料刷新错误说明。
ProfileError string `json:"profile_error"`
// HasCookie 表示数据库中存在可用账号记录。
HasCookie bool `json:"has_cookie"`
// AutoRateEnabled 表示自动评价计划是否启用。
AutoRateEnabled bool `json:"auto_rate_enabled"`
// RateContent 是自动评价文案。
RateContent string `json:"rate_content"`
// AutoPolishEnabled 表示自动擦亮计划是否启用。
AutoPolishEnabled bool `json:"auto_polish_enabled"`
// PolishTime 是自动擦亮的本地时间。
PolishTime string `json:"polish_time"`
// LastRateScanAt 是最近一次自动评价扫描时间。
LastRateScanAt int64 `json:"last_rate_scan_at"`
// LastPolishDate 是最近一次自动擦亮日期。
LastPolishDate string `json:"last_polish_date"`
// LastPolishAt 是最近一次自动擦亮时间。
LastPolishAt int64 `json:"last_polish_at"`
}
// cookieSettingsResponse 是账号设置更新接口的具名成功响应 DTO。
type cookieSettingsResponse struct {
// Success 表示账号设置是否保存成功。
Success bool `json:"success"`
// PausedUntil 是新的暂停结束时间 Unix 秒。
PausedUntil int64 `json:"paused_until"`
// Paused 表示账号当前是否处于暂停状态。
Paused bool `json:"paused"`
}
// cookieProfileResponse 是账号资料刷新接口的具名响应 DTO。
type cookieProfileResponse struct {
// Success 表示资料刷新是否成功。
Success bool `json:"success"`
// ID 是账号稳定标识。
ID string `json:"id"`
// Nickname 是刷新后的平台昵称。
Nickname string `json:"nickname"`
// AvatarURL 是刷新后的头像地址。
AvatarURL string `json:"avatar_url"`
// ProfileError 是资料刷新失败原因。
ProfileError string `json:"profile_error"`
}
// autoConfirmResponse 是账号自动确认设置查询接口的具名响应 DTO。
type autoConfirmResponse struct {
// AutoConfirm 表示是否自动确认订单。
AutoConfirm bool `json:"auto_confirm"`
}
// pauseDurationResponse 是账号暂停时长查询接口的具名响应 DTO。
type pauseDurationResponse struct {
// PauseDuration 是暂停时长,单位为分钟。
PauseDuration int `json:"pause_duration"`
// PausedUntil 是暂停结束时间的 Unix 秒。
PausedUntil int64 `json:"paused_until"`
// Paused 表示账号当前是否处于暂停状态。
Paused bool `json:"paused"`
}
// itemListResponse 是本地商品列表接口的具名商品 DTO。
type itemListResponse struct {
// ID 是本地商品记录主键。
ID int64 `json:"id"`
// CookieID 是商品所属账号标识。
CookieID string `json:"cookie_id"`
// ItemID 是平台商品标识。
ItemID string `json:"item_id"`
// ItemTitle 是商品标题。
ItemTitle string `json:"item_title"`
// ItemDescription 是商品描述。
ItemDescription string `json:"item_description"`
// ItemCategory 是商品分类标识。
ItemCategory string `json:"item_category"`
// ItemPrice 是商品价格文本。
ItemPrice string `json:"item_price"`
// ItemDetail 是商品详情原始 JSON。
ItemDetail string `json:"item_detail"`
// ItemImage 是从详情中提取的商品图片地址。
ItemImage string `json:"item_image"`
// IsMultiSpec 表示商品是否有多规格。
IsMultiSpec bool `json:"is_multi_spec"`
// MultiQuantityDelivery 表示是否按数量发货。
MultiQuantityDelivery bool `json:"multi_quantity_delivery"`
// IsMultiQtyShip 是按数量发货的兼容字段。
IsMultiQtyShip bool `json:"is_multi_qty_ship"`
}
// itemDetailResponse 是单个本地商品详情接口的具名响应 DTO。
type itemDetailResponse struct {
// CookieID 是商品所属账号标识。
CookieID string `json:"cookie_id"`
// ItemID 是平台商品标识。
ItemID string `json:"item_id"`
// ItemTitle 是商品标题。
ItemTitle string `json:"item_title"`
// ItemDescription 是商品描述。
ItemDescription string `json:"item_description"`
// ItemCategory 是商品分类标识。
ItemCategory string `json:"item_category"`
// ItemPrice 是商品价格文本。
ItemPrice string `json:"item_price"`
// ItemDetail 是商品详情原始 JSON。
ItemDetail string `json:"item_detail"`
// IsMultiSpec 表示商品是否有多规格。
IsMultiSpec bool `json:"is_multi_spec"`
// MultiQuantityDelivery 表示是否按数量发货。
MultiQuantityDelivery bool `json:"multi_quantity_delivery"`
}
// itemPublishResponse 是单个商品发布成功接口的具名响应 DTO。
type itemPublishResponse struct {
// Success 表示商品是否发布成功。
Success bool `json:"success"`
// Message 是发布结果说明。
Message string `json:"message"`
// ItemID 是新商品的平台标识。
ItemID string `json:"item_id"`
// ItemURL 是新商品的平台详情地址。
ItemURL string `json:"item_url"`
// ItemImage 是新商品主图地址。
ItemImage string `json:"item_image"`
// ItemTitle 是新商品标题。
ItemTitle string `json:"item_title"`
// ItemPrice 是新商品价格文本。
ItemPrice string `json:"item_price"`
// Quantity 是新商品库存数量。
Quantity int `json:"quantity"`
// CategoryID 是新商品分类标识。
CategoryID string `json:"category_id"`
// CategoryName 是新商品分类名称。
CategoryName string `json:"category_name"`
}
// itemSyncResponse 是商品全集同步接口的具名响应 DTO。
type itemSyncResponse struct {
// Success 表示同步是否完成。
Success bool `json:"success"`
// Message 是同步结果说明。
Message string `json:"message"`
// TotalCount 是平台返回的商品总数。
TotalCount int `json:"total_count"`
// TotalPages 是平台商品总页数。
TotalPages int `json:"total_pages"`
// SavedCount 是本地保存的商品数量。
SavedCount int `json:"saved_count"`
// DeletedCount 是本地删除标记的商品数量。
DeletedCount int `json:"deleted_count"`
}
// itemPageSyncResponse 是商品分页同步接口的具名响应 DTO。
type itemPageSyncResponse struct {
// Success 表示同步是否完成。
Success bool `json:"success"`
// Message 是同步结果说明。
Message string `json:"message"`
// PageNumber 是当前同步页码。
PageNumber int `json:"page_number"`
// PageSize 是当前同步页大小。
PageSize int `json:"page_size"`
// CurrentCount 是当前页商品数量。
CurrentCount int `json:"current_count"`
// SavedCount 是本地保存的商品数量。
SavedCount int `json:"saved_count"`
}
// automationActionResponse 是自动化规则动作的具名响应 DTO。
type automationActionResponse struct {
// ID 是动作稳定标识。
ID int64 `json:"id"`
// ActionType 是动作类型。
ActionType string `json:"action_type"`
// CardID 是动作关联卡券组标识。
CardID int64 `json:"card_id"`
// CardName 是动作关联卡券组名称。
CardName string `json:"card_name"`
// DeliveryCount 是动作发送数量。
DeliveryCount int `json:"delivery_count"`
// MessageTemplate 是动作消息模板。
MessageTemplate string `json:"message_template"`
// DelaySeconds 是动作延迟秒数。
DelaySeconds int `json:"delay_seconds"`
// ConfigJSON 是动作扩展配置 JSON。
ConfigJSON string `json:"config_json"`
// Enabled 表示动作是否启用。
Enabled bool `json:"enabled"`
// SortOrder 是动作执行顺序。
SortOrder int `json:"sort_order"`
}
// automationRuleResponse 是自动化规则的具名响应 DTO。
type automationRuleResponse struct {
// ID 是规则稳定标识。
ID int64 `json:"id"`
// CookieID 是规则所属账号标识。
CookieID string `json:"cookie_id"`
// ItemID 是规则关联商品标识。
ItemID string `json:"item_id"`
// ItemTitle 是规则关联商品标题。
ItemTitle string `json:"item_title"`
// Name 是规则名称。
Name string `json:"name"`
// TriggerType 是规则触发类型。
TriggerType string `json:"trigger_type"`
// Enabled 表示规则是否启用。
Enabled bool `json:"enabled"`
// Priority 是规则优先级。
Priority int `json:"priority"`
// ConfigJSON 是规则扩展配置 JSON。
ConfigJSON string `json:"config_json"`
// Actions 是规则动作列表。
Actions []automationActionResponse `json:"actions"`
// CreatedAt 是规则创建时间。
CreatedAt string `json:"created_at"`
// UpdatedAt 是规则更新时间。
UpdatedAt string `json:"updated_at"`
}
// automationRulePageResponse 是自动化规则分页接口的具名响应 DTO。
type automationRulePageResponse struct {
// Success 表示查询是否完成。
Success bool `json:"success"`
// Data 是当前页自动化规则。
Data []automationRuleResponse `json:"data"`
// Total 是符合条件的规则总数。
Total int `json:"total"`
// Page 是当前页码。
Page int `json:"page"`
// PageSize 是当前页大小。
PageSize int `json:"page_size"`
// TotalPages 是总页数。
TotalPages int `json:"total_pages"`
// TriggerCounts 是各触发类型的规则数量。
TriggerCounts map[string]int `json:"trigger_counts"`
}
// automationIssuesResponse 是自动化异常任务接口的具名响应 DTO。
type automationIssuesResponse struct {
// Runs 是需要处理的自动化运行记录。
Runs []db.AutomationRunIssue `json:"runs"`
// PendingTasks 是需要处理的延迟任务记录。
PendingTasks []db.DeferredAutomationIssue `json:"pending_tasks"`
}
// orderDetailResponse 是订单详情接口的具名响应 DTO,同时保留旧版顶层字段兼容性。
type orderDetailResponse struct {
// orderDTO 提供历史客户端仍读取的顶层订单字段。
orderDTO
// Success 表示查询是否完成。
Success bool `json:"success"`
// Data 是新版客户端读取的订单对象。
Data orderDTO `json:"data"`
}
// orderRefreshDetailResponse 是订单刷新后返回的远端详情 DTO。
type orderRefreshDetailResponse struct {
// Quantity 是订单购买数量。
Quantity string `json:"quantity"`
// SpecName 是商品规格名称。
SpecName string `json:"spec_name"`
// SpecValue 是商品规格值。
SpecValue string `json:"spec_value"`
// OrderStatus 是归一化后的订单状态。
OrderStatus string `json:"order_status"`
// Amount 是订单实付金额。
Amount string `json:"amount"`
}
// orderRefreshResponse 是订单列表刷新接口的具名响应 DTO。
type orderRefreshResponse struct {
// PartialFailure 表示批量刷新是否存在部分失败。
PartialFailure bool `json:"partial_failure"`
// Message 是刷新结果说明。
Message string `json:"message"`
// Summary 是刷新统计摘要。
Summary orderRefreshSummary `json:"summary"`
// Results 是逐账号或逐订单的兼容结果行。
Results []map[string]any `json:"results"`
}
// orderRefreshSummary 是订单列表刷新统计摘要 DTO。
type orderRefreshSummary struct {
// Discovered 是发现的新订单数量。
Discovered int `json:"discovered"`
// ListUpdated 是订单列表更新数量。
ListUpdated int `json:"list_updated"`
// SoftDeleted 是标记删除的订单数量。
SoftDeleted int `json:"soft_deleted"`
// DetailTotal 是需要补全详情的订单数量。
DetailTotal int `json:"detail_total"`
// Total 是本次处理订单总数。
Total int `json:"total"`
// Updated 是状态发生变化的订单数量。
Updated int `json:"updated"`
// NoChange 是状态未发生变化的订单数量。
NoChange int `json:"no_change"`
// Failed 是刷新失败数量。
Failed int `json:"failed"`
}
// orderSingleRefreshResponse 是单订单刷新接口的具名响应 DTO。
type orderSingleRefreshResponse struct {
// Success 表示刷新是否完成。
Success bool `json:"success"`
// Message 是刷新结果说明。
Message string `json:"message"`
// Order 是刷新后的订单详情。
Order orderRefreshDetailResponse `json:"order"`
}
// manualShipResponse 是手动发货接口的具名响应 DTO。
type manualShipResponse struct {
// PartialFailure 表示批量发货是否存在部分失败。
PartialFailure bool `json:"partial_failure"`
// Message 是发货结果说明。
Message string `json:"message"`
// SuccessCount 是成功发货数量。
SuccessCount int `json:"success_count"`
// FailedCount 是失败发货数量。
FailedCount int `json:"failed_count"`
// Results 是逐订单的兼容结果行。
Results []map[string]any `json:"results"`
}
// importOrdersResponse 是订单导入接口的具名响应 DTO。
type importOrdersResponse struct {
// PartialFailure 表示批量导入是否存在部分失败。
PartialFailure bool `json:"partial_failure"`
// Message 是导入结果说明。
Message string `json:"message"`
// Total 是本次导入订单总数。
Total int `json:"total"`
// SuccessCount 是成功导入数量。
SuccessCount int `json:"success_count"`
// FailedCount 是失败导入数量。
FailedCount int `json:"failed_count"`
// Results 是逐订单的兼容结果行。
Results []map[string]any `json:"results"`
}
@@ -1,19 +1,19 @@
import{j as e,r,c as ys,b as qe,d as Wa}from"./react-vendor-C_od1ZSF.js";import{L as Ja,U as ha,M as is,C as os,B as ga,S as ba,Z as cs,a as jt,b as js,G as As,c as Ns,d as _s,e as Va,f as rt,A as $s,D as Qa,g as Ps,P as fa,h as qt,E as ya,T as Ga,i as Ka,j as Pe,X as Me,k as Ha,l as Za,m as vs,n as ja,o as He,Q as Xt,p as xt,q as Ke,r as yt,s as Tt,t as Rs,R as ze,u as Na,v as Ya,w as Qe,K as Xa,x as dt,y as lt,z as et,F as Es,H as _t,I as Nt,J as Dt,N as _a,O as el,V as Ds,W as Ts,Y as tl,_ as sl,$ as al,a0 as ll,a1 as es,a2 as Bt,a3 as ds,a4 as rl,a5 as nl,a6 as xs,a7 as Ms,a8 as il,a9 as ol,aa as Mt,ab as qs,ac as Gt,ad as va,ae as cl,af as dl,ag as Zt,ah as wa,ai as xl,aj as ml,ak as pl,al as ul,am as hl,an as gl,ao as Fs}from"./icons-vendor-BpMgNNfy.js";import{R as zt,B as bl,X as Bs,Y as zs,T as Ut,a as fl,C as ts,A as yl,b as jl,c as Nl,P as Us,d as Ws,L as _l}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const m of document.querySelectorAll('link[rel="modulepreload"]'))i(m);new MutationObserver(m=>{for(const N of m)if(N.type==="childList")for(const _ of N.addedNodes)_.tagName==="LINK"&&_.rel==="modulepreload"&&i(_)}).observe(document,{childList:!0,subtree:!0});function l(m){const N={};return m.integrity&&(N.integrity=m.integrity),m.referrerPolicy&&(N.referrerPolicy=m.referrerPolicy),m.crossOrigin==="use-credentials"?N.credentials="include":m.crossOrigin==="anonymous"?N.credentials="omit":N.credentials="same-origin",N}function i(m){if(m.ep)return;m.ep=!0;const N=l(m);fetch(m.href,N)}})();const vl=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),ms=({sizeClass:t="w-12 h-12",logoClassName:a="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23Line truncated
import{j as e,r,c as ys,b as qe,d as Wa}from"./react-vendor-C_od1ZSF.js";import{L as Ja,U as ha,M as is,C as os,B as ga,S as ba,Z as cs,a as jt,b as js,G as As,c as Ns,d as _s,e as Va,f as rt,A as $s,D as Qa,g as Ps,P as fa,h as qt,E as ya,T as Ga,i as Ka,j as Pe,X as Me,k as Ha,l as Za,m as vs,n as ja,o as He,Q as Xt,p as xt,q as Ke,r as yt,s as Tt,t as Rs,R as ze,u as Na,v as Ya,w as Qe,K as Xa,x as dt,y as lt,z as et,F as Es,H as _t,I as Nt,J as Dt,N as _a,O as el,V as Ds,W as Ts,Y as tl,_ as sl,$ as al,a0 as ll,a1 as es,a2 as Bt,a3 as ds,a4 as rl,a5 as nl,a6 as xs,a7 as Ms,a8 as il,a9 as ol,aa as Mt,ab as qs,ac as Gt,ad as va,ae as cl,af as dl,ag as Zt,ah as wa,ai as xl,aj as ml,ak as pl,al as ul,am as hl,an as gl,ao as Fs}from"./icons-vendor-BpMgNNfy.js";import{R as zt,B as bl,X as Bs,Y as zs,T as Ut,a as fl,C as ts,A as yl,b as jl,c as Nl,P as Us,d as Ws,L as _l}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const m of document.querySelectorAll('link[rel="modulepreload"]'))i(m);new MutationObserver(m=>{for(const _ of m)if(_.type==="childList")for(const N of _.addedNodes)N.tagName==="LINK"&&N.rel==="modulepreload"&&i(N)}).observe(document,{childList:!0,subtree:!0});function l(m){const _={};return m.integrity&&(_.integrity=m.integrity),m.referrerPolicy&&(_.referrerPolicy=m.referrerPolicy),m.crossOrigin==="use-credentials"?_.credentials="include":m.crossOrigin==="anonymous"?_.credentials="omit":_.credentials="same-origin",_}function i(m){if(m.ep)return;m.ep=!0;const _=l(m);fetch(m.href,_)}})();const vl=({className:t="w-full h-full text-white"})=>e.jsx("svg",{className:t,viewBox:"0 0 256 256","aria-hidden":"true",children:e.jsx("g",{stroke:"none",fill:"none",fillRule:"evenodd",children:e.jsx("path",{d:"M121.73,57.0003 C138.901,57.0003 154.897,65.5053 164.52,79.7493 C166.029,81.9823 165.441,85.0143 163.209,86.5233 C160.976,88.0323 157.944,87.4433 156.436,85.2113 C148.629,73.6553 135.655,66.7563 121.73,66.7563 C104.076789,66.7563 88.6201962,77.6596007 82.5581814,93.8184545 C83.9120803,93.7133631 85.2800264,93.66 86.6602,93.66 C111.537727,93.66 132.442611,110.997575 137.926382,134.224255 L162.5425,92.109 L162.615557,91.9879406 L162.756884,91.77367 L162.911804,91.5639102 L162.98657,91.4716759 C163.351845,91.025169 163.786059,90.6571744 164.264191,90.3738733 L164.550153,90.2178351 L164.729252,90.1315693 L164.989203,90.021723 L165.230265,89.9354653 L165.542393,89.8445739 C165.666021,89.8126706 165.790834,89.7857324 165.916565,89.7637431 L166.116517,89.7342499 C166.29505,89.7098142 166.475001,89.6957386 166.655596,89.6918808 L166.7539,89.693 C196.8909,89.693 221.4079,114.21 221.4079,144.347 C221.4079,174.482 196.8909,199 166.7539,199 L125.0869,199 C122.3919,199 120.2079,196.815 120.2079,194.122 C120.2079,191.429 122.3919,189.244 125.0869,189.244 L166.7539,189.244 C191.5109,189.244 211.6519,169.104 211.6519,144.347 C211.6519,120.513406 192.985349,100.957891 169.504046,99.5322548 L112.7745,196.584 C111.8995,198.08 110.2965,199 108.5635,199 L86.6602,199 C57.6182,199 33.9902,175.373 33.9902,146.33 C33.9902,122.475163 49.9316132,102.273061 71.7206298,95.817503 L71.9446339,94.967678 C78.0600632,72.5405324 98.33054,57.0003 121.73,57.0003 Z M86.6602,103.417 C62.9972,103.417 43.7462,122.667 43.7462,146.33 C43.7462,169.992 62.9972,189.244 86.6602,189.244 L105.7645,189.244 L129.869462,148.004782 C129.678439,147.482425 129.5742,146.918336 129.5742,146.33 C129.5742,122.667 110.3232,103.417 86.6602,103.417 Z",fill:"currentColor"})})}),ms=({sizeClass:t="w-12 h-12",logoClassName:a="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23Line truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(js,{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:n,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:Y,children:"取消"}),e.jsxs("button",{onClick:ut,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:Y,children:[Y?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(He,{className:"w-4 h-4"}),Y?"保存中...":"保存"]})]})})]})}),document.body)]})},nn=t=>({total:Number((t==null?void 0:t.total)||0),success_count:Number((t==null?void 0:t.success_count)||0),failed_count:Number((t==null?void 0:t.failed_count)||0),results:Array.isArray(t==null?void 0:t.results)?t.results.map(a=>({order_id:String((a==null?void 0:a.order_id)||"unknown"),success:(a==null?void 0:a.success)===!0,message:String((a==null?void 0:a.message)||"")})):[]}),on=t=>(t==null?void 0:t.results.filter(a=>!a.success))||[],sa=({status:t})=>{const a={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${a[t]||a.cancelled}`,children:l[t]||t})},cn=()=>{const[t,a]=r.useState([]),[l,i]=r.useState([]),[m,N]=r.useState([]),[_,E]=r.useState({}),[g,C]=r.useState("all"),[j,F]=r.useState(""),[G,me]=r.useState(""),[oe,v]=r.useState(""),q=r.useRef(0),[ce,Q]=r.useState(1),[ee,B]=r.useState(1),[ge,ue]=r.useState(!1),[k,Z]=r.useState(!1),[se,K]=r.useState(!1),[ve,J]=r.useState(!1),[I,R]=r.useState(null),[$,be]=r.useState(null),[Re,ae]=r.useState({}),[T,p]=r.useState(!1),[b,U]=r.useState(""),[M,ne]=r.useState(!1),[he,ye]=r.useState(null),[Ee,ke]=r.useState(null),[x,V]=r.useState(null),[X,c]=r.useState(!1),[d,D]=r.useState(null),[S,Y]=r.useState(null),O=async()=>{const u=++q.current;ue(!0);try{const L=await tr(j||void 0,g,ce,20,oe);if(u!==q.current)return;a(L.data),B(L.total_pages)}catch(L){console.error("加载订单失败:",L)}finally{u===q.current&&ue(!1)}},de=(u,L,le)=>{if(le&&le.trim())return le;if(_[`${u}:${L}`])return _[`${u}:${L}`];const Ne=l.find(Ue=>{if(le&&Ue.item_title){const Fe=le.toLowerCase(),tt=Ue.item_title.toLowerCase();return tt.includes(Fe)||Fe.includes(tt)}return!1});return Ne!=null&&Ne.item_title?Ne.item_title:"未知商品"},Se=u=>{const L={};u.forEach(le=>{le.item_id&&(L[`${le.cookie_id}:${le.item_id}`]=le.item_title||le.item_id)}),E(L)};r.useEffect(()=>{const u=window.setTimeout(()=>{Q(1),v(G.trim())},300);return()=>window.clearTimeout(u)},[G]),r.useEffect(()=>{O()},[j,g,ce,oe]),r.useEffect(()=>{Promise.all([Ft(),vt()]).then(([u,L])=>{N(u),i(L),Se(L)}).catch(u=>{console.error("加载商品列表失败:",u)})},[]);const fe=r.useMemo(()=>new Map(m.map(u=>[u.id,u])),[m]),Oe=u=>{const L=fe.get(u),le=(L==null?void 0:L.remark)||(L==null?void 0:L.nickname);return le?`${le} · ${u.slice(0,6)}`:`账号 ${u.slice(0,8)}`},re=u=>{const L=fe.get(u);return(L==null?void 0:L.remark)||(L==null?void 0:L.nickname)||"未命名账号"},h=async()=>{ue(!0);try{const u=await lr(j||void 0,g);await O(),u!=null&&u.message&&alert(u.message)}catch(u){console.error("同步订单失败:",u),alert((u==null?void 0:u.message)||"同步失败,请重试")}finally{ue(!1)}},f=u=>{U(u),ye(null),p(!0)},P=async u=>{var L;ne(!0),ye(null);try{const le=await nr([b],u),Ne=(L=le==null?void 0:le.results)==null?void 0:L[0];Ne!=null&&Ne.success?(ye({success:!0,message:Ne.message}),O()):ye({success:!1,message:(Ne==null?void 0:Ne.message)||"发货失败"})}catch(le){ye({success:!1,message:(le==null?void 0:le.message)||"请求失败"})}finally{ne(!1)}},z=u=>{R(u),Z(!0)},Ie=u=>{be({...u}),K(!0)},Ae=async()=>{if(!(!$||!$.order_id))try{const u={};$.status!==void 0&&(u.order_status=$.status),$.buyer_id!==void 0&&(u.buyer_id=$.buyer_id),$.amount!==void 0&&(u.amount=$.amount),$.receiver_name!==void 0&&(u.receiver_name=$.receiver_name),$.receiver_phone!== 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(js,{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:n,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:Y,children:"取消"}),e.jsxs("button",{onClick:ut,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:Y,children:[Y?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(He,{className:"w-4 h-4"}),Y?"保存中...":"保存"]})]})})]})}),document.body)]})},nn=t=>({total:Number((t==null?void 0:t.total)||0),success_count:Number((t==null?void 0:t.success_count)||0),failed_count:Number((t==null?void 0:t.failed_count)||0),results:Array.isArray(t==null?void 0:t.results)?t.results.map(a=>({order_id:String((a==null?void 0:a.order_id)||"unknown"),success:(a==null?void 0:a.success)===!0,message:String((a==null?void 0:a.message)||"")})):[]}),on=t=>(t==null?void 0:t.results.filter(a=>!a.success))||[],sa=({status:t})=>{const a={processing:"bg-blue-100 text-blue-800",pending_ship:"bg-brand text-white",shipped:"bg-blue-100 text-blue-700",completed:"bg-green-100 text-green-700",cancelled:"bg-gray-100 text-gray-500",refunding:"bg-red-100 text-red-600",unknown:"bg-gray-100 text-gray-500"},l={processing:"处理中",pending_ship:"待发货",shipped:"已发货",completed:"已完成",cancelled:"已取消",refunding:"退款中",unknown:"未知"};return e.jsx("span",{className:`px-3 py-1.5 rounded-lg text-xs font-bold ${a[t]||a.cancelled}`,children:l[t]||t})},cn=()=>{const[t,a]=r.useState([]),[l,i]=r.useState([]),[m,_]=r.useState([]),[N,R]=r.useState({}),[g,C]=r.useState("all"),[j,F]=r.useState(""),[G,me]=r.useState(""),[oe,v]=r.useState(""),q=r.useRef(0),[ce,Q]=r.useState(1),[ee,B]=r.useState(1),[ge,ue]=r.useState(!1),[k,Z]=r.useState(!1),[se,K]=r.useState(!1),[ve,J]=r.useState(!1),[I,E]=r.useState(null),[$,be]=r.useState(null),[Re,ae]=r.useState({}),[T,p]=r.useState(!1),[b,U]=r.useState(""),[M,ne]=r.useState(!1),[he,ye]=r.useState(null),[Ee,ke]=r.useState(null),[x,V]=r.useState(null),[X,c]=r.useState(!1),[d,D]=r.useState(null),[S,Y]=r.useState(null),O=async()=>{const u=++q.current;ue(!0);try{const L=await tr(j||void 0,g,ce,20,oe);if(u!==q.current)return;a(L.data),B(L.total_pages)}catch(L){console.error("加载订单失败:",L)}finally{u===q.current&&ue(!1)}},de=(u,L,le)=>{if(le&&le.trim())return le;if(N[`${u}:${L}`])return N[`${u}:${L}`];const Ne=l.find(Ue=>{if(le&&Ue.item_title){const Fe=le.toLowerCase(),tt=Ue.item_title.toLowerCase();return tt.includes(Fe)||Fe.includes(tt)}return!1});return Ne!=null&&Ne.item_title?Ne.item_title:"未知商品"},Se=u=>{const L={};u.forEach(le=>{le.item_id&&(L[`${le.cookie_id}:${le.item_id}`]=le.item_title||le.item_id)}),R(L)};r.useEffect(()=>{const u=window.setTimeout(()=>{Q(1),v(G.trim())},300);return()=>window.clearTimeout(u)},[G]),r.useEffect(()=>{O()},[j,g,ce,oe]),r.useEffect(()=>{Promise.all([Ft(),vt()]).then(([u,L])=>{_(u),i(L),Se(L)}).catch(u=>{console.error("加载商品列表失败:",u)})},[]);const fe=r.useMemo(()=>new Map(m.map(u=>[u.id,u])),[m]),Oe=u=>{const L=fe.get(u),le=(L==null?void 0:L.remark)||(L==null?void 0:L.nickname);return le?`${le} · ${u.slice(0,6)}`:`账号 ${u.slice(0,8)}`},re=u=>{const L=fe.get(u);return(L==null?void 0:L.remark)||(L==null?void 0:L.nickname)||"未命名账号"},h=async()=>{ue(!0);try{const u=await lr(j||void 0,g);await O(),u!=null&&u.message&&alert(u.message)}catch(u){console.error("同步订单失败:",u),alert((u==null?void 0:u.message)||"同步失败,请重试")}finally{ue(!1)}},f=u=>{U(u),ye(null),p(!0)},P=async u=>{var L;ne(!0),ye(null);try{const le=await nr([b],u),Ne=(L=le==null?void 0:le.results)==null?void 0:L[0];Ne!=null&&Ne.success?(ye({success:!0,message:Ne.message}),O()):ye({success:!1,message:(Ne==null?void 0:Ne.message)||"发货失败"})}catch(le){ye({success:!1,message:(le==null?void 0:le.message)||"请求失败"})}finally{ne(!1)}},z=u=>{E(u),Z(!0)},Ie=u=>{be({...u}),K(!0)},Ae=async()=>{if(!(!$||!$.order_id))try{const u={};$.status!==void 0&&(u.order_status=$.status),$.buyer_id!==void 0&&(u.buyer_id=$.buyer_id),$.amount!==void 0&&(u.amount=$.amount),$.receiver_name!==void 0&&(u.receiver_name=$.receiver_name),$.receiver_phone!== Line truncated
VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(S=>S.map(Y=>`"${String(Y).replace(/"/g,'""')}"`).join(",")).join(`
`),c=new Blob(["\uFEFF"+X],{type:"text/csv;charset=utf-8"}),d=URL.createObjectURL(c),D=document.createElement("a");D.href=d,D.download="卡密组批量导入模板.csv",document.body.appendChild(D),D.click(),D.remove(),URL.revokeObjectURL(d)},ye=async()=>{if(q){ge(!0),ee(null);try{const x=await pr(q);if(ee(x),x.created>0){const V=await Xe();a(V)}}catch(x){ee({error:(x==null?void 0:x.message)||"上传失败"})}finally{ge(!1)}}},Ee=async()=>{if(!(!ue||!Z.trim())){ge(!0),ve(null);try{const x=await ur(ue,Z);ve({added:x.added}),se("");const V=await Xe();a(V)}catch(x){alert("追加失败:"+((x==null?void 0:x.message)||"未知错误"))}finally{ge(!1)}}},ke=()=>{var x;v("create"),ce(null),ee(null),k((x=M[0])!=null&&x.id?String(M[0].id):""),se(""),ve(null),me(!0)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:ke,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(Dt,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>N(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(et,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(_a,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:J,onChange:x=>I(x.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(_t,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:R,onChange:x=>$(x.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",ne.length," / ",t.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:ne.map(x=>{let V="";return x.type==="data"&&x.data_content?V=`库存: ${x.data_content.split(`
`).filter(c=>c.trim()).length} 条`:x.type==="text"&&x.text_content?V=x.text_content:x.type==="api"&&x.api_config?V=x.api_config.url:x.type==="image"&&x.image_url&&(V="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(be,{type:x.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:x.name,children:x.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>U(x.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:x.id}),e.jsx(el,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${x.type==="text"?"bg-blue-50 text-blue-600":x.type==="data"?"bg-purple-50 text-purple-600":x.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:x.type==="text"?"文本":x.type==="data"?"批量":x.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:V,children:V})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:x.description||"-",children:x.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>b(x),className:`w-12 h-8 rounded-full relative transition-colors ${x.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${x.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>Re(x),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(Nt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>T(x.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Qe,{className:"h-4 w-4"})})]})})]},x.id)})})]})}),ne.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(fa,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),l&&_&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>i(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(Me,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:g.name||"",onChange:x=>C({...g,name:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:g.type||"text",onChange:x=>C({...g,type:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(_==null?void 0:_.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),g.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:g.api_url||"",onChange:x=>C({...g,api_url:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsLine truncated
`),c=new Blob(["\uFEFF"+X],{type:"text/csv;charset=utf-8"}),d=URL.createObjectURL(c),D=document.createElement("a");D.href=d,D.download="卡密组批量导入模板.csv",document.body.appendChild(D),D.click(),D.remove(),URL.revokeObjectURL(d)},ye=async()=>{if(q){ge(!0),ee(null);try{const x=await pr(q);if(ee(x),x.created>0){const V=await Xe();a(V)}}catch(x){ee({error:(x==null?void 0:x.message)||"上传失败"})}finally{ge(!1)}}},Ee=async()=>{if(!(!ue||!Z.trim())){ge(!0),ve(null);try{const x=await ur(ue,Z);ve({added:x.added}),se("");const V=await Xe();a(V)}catch(x){alert("追加失败:"+((x==null?void 0:x.message)||"未知错误"))}finally{ge(!1)}}},ke=()=>{var x;v("create"),ce(null),ee(null),k((x=M[0])!=null&&x.id?String(M[0].id):""),se(""),ve(null),me(!0)};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col md:flex-row justify-between md:items-end gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-4xl font-extrabold text-gray-900 tracking-tight",children:"卡密库存"}),e.jsx("p",{className:"text-gray-500 mt-2 font-medium",children:"管理自动发货的卡密、链接或图片资源。"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:ke,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(Dt,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:()=>_(!0),className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 transition-transform hover:scale-105 active:scale-95",children:[e.jsx(et,{className:"w-5 h-5"}),"添加新卡密"]})]})]}),e.jsxs("div",{className:"ios-card rounded-xl overflow-hidden shadow-lg border-0 bg-white",children:[e.jsxs("div",{className:"flex flex-col gap-3 border-b border-gray-50 bg-surface-muted p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex flex-1 flex-col gap-3 sm:flex-row",children:[e.jsxs("div",{className:"relative sm:w-48",children:[e.jsx(_a,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsxs("select",{"aria-label":"按卡密类型筛选",value:J,onChange:x=>I(x.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(_t,{className:"pointer-events-none absolute left-4 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400"}),e.jsx("input",{type:"search","aria-label":"按卡密名称搜索",placeholder:"搜索卡密名称...",value:E,onChange:x=>$(x.target.value),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",ne.length," / ",t.length," 组"]})]}),e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full table-fixed text-left border-collapse",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-white text-gray-400 text-xs font-bold uppercase tracking-wider border-b border-gray-50",children:[e.jsx("th",{className:"w-[23%] px-5 py-5",children:"卡密名称"}),e.jsx("th",{className:"w-[8%] px-3 py-5",children:"卡密组ID"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"类型"}),e.jsx("th",{className:"w-[27%] px-5 py-5",children:"内容/库存"}),e.jsx("th",{className:"w-[19%] px-5 py-5",children:"描述"}),e.jsx("th",{className:"w-[7%] px-2 py-5",children:"状态"}),e.jsx("th",{className:"w-[9%] px-3 py-5 text-right",children:"操作"})]})}),e.jsx("tbody",{className:"divide-y divide-gray-50",children:ne.map(x=>{let V="";return x.type==="data"&&x.data_content?V=`库存: ${x.data_content.split(`
`).filter(c=>c.trim()).length} 条`:x.type==="text"&&x.text_content?V=x.text_content:x.type==="api"&&x.api_config?V=x.api_config.url:x.type==="image"&&x.image_url&&(V="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(be,{type:x.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:x.name,children:x.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:()=>U(x.id),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:x.id}),e.jsx(el,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${x.type==="text"?"bg-blue-50 text-blue-600":x.type==="data"?"bg-purple-50 text-purple-600":x.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:x.type==="text"?"文本":x.type==="data"?"批量":x.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:V,children:V})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:x.description||"-",children:x.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:()=>b(x),className:`w-12 h-8 rounded-full relative transition-colors ${x.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${x.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:()=>Re(x),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(Nt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:()=>T(x.id),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Qe,{className:"h-4 w-4"})})]})})]},x.id)})})]})}),ne.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(fa,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),l&&N&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:()=>i(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(Me,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:g.name||"",onChange:x=>C({...g,name:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:g.type||"text",onChange:x=>C({...g,type:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(N==null?void 0:N.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),g.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:g.api_url||"",onChange:x=>C({...g,api_url:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsLine truncated
卡号1:密码1
卡号2:密码2
或者
兑换码1
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:g.data_content?g.data_content.split(`
`).filter(x=>x.trim()).length:0})," 条"]})]})]}),g.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:g.image_url||"",onChange:x=>C({...g,image_url:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),g.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:g.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:x=>{x.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:g.delay_seconds||0,onChange:x=>C({...g,delay_seconds:parseInt(x.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:g.description||"",onChange:x=>C({...g,description:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>C({...g,enabled:!g.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${g.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${g.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>i(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:ae,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(He,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),m&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>N(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(Me,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:j.name,onChange:x=>F({...j,name:x.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>F({...j,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(os,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>F({...j,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Ds,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>F({...j,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children Line truncated
`).filter(x=>x.trim()).length:0})," 条"]})]})]}),g.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:g.image_url||"",onChange:x=>C({...g,image_url:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),g.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:g.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:x=>{x.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"}})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:g.delay_seconds||0,onChange:x=>C({...g,delay_seconds:parseInt(x.target.value)||0}),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:g.description||"",onChange:x=>C({...g,description:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:()=>C({...g,enabled:!g.enabled}),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${g.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${g.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>i(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:ae,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(He,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),m&&qe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:()=>_(!1),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(Me,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:j.name,onChange:x=>F({...j,name:x.target.value}),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>F({...j,type:"data",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(os,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:()=>F({...j,type:"text",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Ds,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:()=>F({...j,type:"image",content:""}),className:`p-3 rounded-xl font-bold transition-all ${j.type==="image"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children Line truncated
CODE-789012
...`:"请输入每次发货时发送的固定文字"}),j.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:j.content.split(`
`).filter(x=>x.trim()).length})," 条"]})]}),j.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:j.api_method,onChange:x=>F({...j,api_method:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:j.api_timeout,onChange:x=>F({...j,api_timeout:parseInt(x.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:j.api_headers,onChange:x=>F({...j,api_headers:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:j.api_params,onChange:x=>F({...j,api_params:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:j.description,onChange:x=>F({...j,description:x.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:j.delay_seconds,onChange:x=>F({...j,delay_seconds:parseInt(x.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>N(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:p,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(et,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),G&&qe.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>me(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(Me,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>v("create"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${oe==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(tl,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>v("append"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${oe==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Dt,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),oe==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:he,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm tran Line truncated
`).filter(x=>x.trim()).length})," 条"]})]}),j.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:j.api_method,onChange:x=>F({...j,api_method:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:j.api_timeout,onChange:x=>F({...j,api_timeout:parseInt(x.target.value)||10}),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:j.api_headers,onChange:x=>F({...j,api_headers:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:j.api_params,onChange:x=>F({...j,api_params:x.target.value}),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:j.description,onChange:x=>F({...j,description:x.target.value}),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:j.delay_seconds,onChange:x=>F({...j,delay_seconds:parseInt(x.target.value)||0}),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:()=>_(!1),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:p,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(et,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),G&&qe.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:()=>me(!1),className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(Me,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:()=>v("create"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${oe==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(tl,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:()=>v("append"),className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${oe==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Dt,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),oe==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),'。 类型填 text/data/image;data 类型的"内容"按行存卡密(CSV 单元格内换行需用引号包裹)。']}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:he,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm tran Line truncated
VIP-002
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),K&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",K.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>me(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),oe==="create"?e.jsxs("button",{onClick:ye,disabled:!q||B,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[B?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(Dt,{className:"w-4 h-4"}),B?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:Ee,disabled:!ue||!Z.trim()||B||M.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[B?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(et,{className:"w-4 h-4"}),B?"处理中...":"追加卡密"]})]})]})}),document.body)]})},mn=t=>t.find(a=>a.status==="running"||a.status==="canceling"),la="ydisks-amap-js-api",pn="c9b68d4ce9a2a97f22a4a439404488ca";let $t=null;const un=()=>pn,hn=()=>window.AMap?Promise.resolve(window.AMap):$t||($t=new Promise((t,a)=>{const l=document.getElementById(la),i=l||document.createElement("script"),m=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(_)},N=()=>{window.AMap?(m(),t(window.AMap)):(m(),a(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},_=window.setTimeout(()=>{m(),a(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=N,i.id=la,i.async=!0,i.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(un())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,i.onerror=()=>{m(),a(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},l||document.head.appendChild(i)}).catch(t=>{throw $t=null,t}),$t),Ht=t=>Number.isFinite(t)&&t!==0,gn=t=>{var m,N;const a=Number((m=t.location)==null?void 0:m.lng),l=Number((N=t.location)==null?void 0:N.lat),i={area:String(t.adname||"").trim(),city:String(t.cityname||"").trim(),division_id:String(t.adcode||"").trim(),longitude:a,latitude:l,poi_id:String(t.id||"").trim(),poi_name:String(t.name||"").trim(),province:String(t.pname||"").trim()};return!i.division_id||!i.province||!i.city||!i.poi_id||!i.poi_name||!Ht(a)||!Ht(l)||a<-180||a>180||l<-90||l>90?null:i},bn=async(t,a)=>{if(!Ht(t)||!Ht(a)||t<-180||t>180||a<-90||a>90)throw new Error("经纬度无效");const l=await hn();return new Promise((i,m)=>{new l.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[t,a],1e3,(_,E)=>{var C;if(_!=="complete"){if(_==="no_data"){i([]);return}m(new Error("高德地图附近地址查询失败,请稍后重试"));return}const g=(((C=E==null?void 0:E.poiList)==null?void 0:C.pois)||[]).map(gn).filter(j=>j!==null);i(g)})})},fn=t=>{const a=String(t||"").trim();return a?/^[¥¥]/.test(a)?a:`¥${a}`:"-"},yn=({onConfigureDelivery:t})=>{const[a,l]=r.useState([]),[i,m]=r.useState([]),[N,_]=r.useState([]),[E,g]=r.useState(""),[C,j]=r.useState(""),[F,G]=r.useState(!1),[me,oe]=r.useState(!1),[v,q]=r.useState(!1),[ce,Q]=r.useState(!1),[ee,B]=r.useState(!1),[ge,ue]=r.useState(!1),[k,Z]=r.useState(!1),[se,K]=r.useState("upload"),[ve,J]=r.useState(null),[I,R]=r.useState(null),[$,be]=r.useState(""),[Re,ae]=r.useState(!1),[T,p]=r.useState(!1),[b,U]=r.useState([]),[M,ne]=r.useState(null),[he,ye]=r.useState([]),[Ee,ke]=r.useState(null),[x,V]=r.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[X,c]=r.useState(null),[d,D]=r.useState(null),[S,Y]=r.useState(null),O=r.useRef(!1),[de,Se]=r.useState(null),[fe,Oe]=r.useState({}),[re,h]=r.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[f,P]=r.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[z,Ie]=r.useState([]);r.useEffect(()=>{if(!ge||f.images.length===0){Ie([]);return}const n=f.images.map((w,H)=>({key:w.name+H,url:URL.createObjectURL(w)}));return Ie(n),()=>{n.forEach(w=>URL.revokeObjectURL(w.url))}},[ge,f.images]);const Ae=async()=>{const n=await vt();l(n)},we=async()=>{m(await gs())};r.useEffect(()=>{Promise.all([Ft(),vt(),gs(),Hs(20)]).then(([n,w,H,Te])=>{_(n),l(w),m(H);const s=Te.find(o=>["running","canceling"].includes(o.status))||Te.find(o=>o.status!=="preview");Y(s||null)}).catch(n=>console.error("加载商品配置失败:",n))},[]),r.useEffect(()=>{if(!k||!(d!=null&&d.id)||!["running","canceling"].includes(d.status))return;const n=window.setInterval(async()=>{if(!O.current){O.current=!0;try{const w=await bt(d.id);D(w),Y(w),[ Line truncated
`),Te=new Blob(["\uFEFF"+H],{type:"text/csv;charset=utf-8"}),s=URL.createObjectURL(Te),o=document.createElement("a");o.href=s,o.download="批量铺货模板.csv",document.body.appendChild(o),o.click(),o.remove(),URL.revokeObjectURL(s)},Lt=()=>{h(n=>({...n,cookie_id:E||n.cookie_id})),B(!0)},nt=()=>{P(n=>({...n,cookie_id:E||n.cookie_id})),ue(!0)},it=async n=>{if(!(n?E:f.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");p(!0),navigator.geolocation.getCurrentPosition(async H=>{try{const Te=await bn(H.coords.longitude,H.coords.latitude);if(!Te.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");n?(ye(Te),ke(Te[0])):(U(Te),ne(Te[0]))}catch(Te){alert((Te==null?void 0:Te.message)||"获取发货地失败")}finally{p(!1)}},H=>{p(!1),alert(H.code===H.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},Ot=n=>i.filter(w=>w.cookie_id===n.cookie_id&&w.item_id===n.item_id).length>0?i.filter(w=>w.cookie_id===n.cookie_id&&w.item_id===n.item_id):i.filter(w=>w.cookie_id===n.cookie_id&&!w.item_id),pt=n=>{switch(n){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return n||"-"}},ut=n=>{switch(n){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},st=r.useMemo(()=>new Map(N.map(n=>[n.id,n])),[N]),ht=r.useMemo(()=>C?a.filter(n=>n.cookie_id===C):a,[C,a]),Ge=n=>{const w=st.get(n),H=(w==null?void 0:w.remark)||(w==null?void 0:w.nickname);return H?`${H} · ${n.slice(0,6)}`:`账号 ${n.slice(0,8)}`},ot=n=>{const w=st.get(n);return(w==null?void 0:w.remark)||(w==null?void 0:w.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(ll,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:C,onChange:n=>j(n.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),N.map(n=>e.jsx("option",{value:n.id,children:Ge(n.id)},n.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(xt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:E,onChange:n=>g(n.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),N.map(n=>e.jsx("option",{value:n.id,children:Ge(n.id)},n.id))]})]})]}),e.jsxs("button",{onClick:De,disabled:F||!E,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(ze,{className:`w-4 h-4 ${F?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:Lt,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(et,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:nt,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(es,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void Ne(),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white Line truncated
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsx("p",{className:"text-xs text-gray-500",children:"一行一个卡密号,空行自动忽略。会追加到该组现有库存末尾。"})]}),K&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",K.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:()=>me(!1),className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),oe==="create"?e.jsxs("button",{onClick:ye,disabled:!q||B,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[B?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(Dt,{className:"w-4 h-4"}),B?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:Ee,disabled:!ue||!Z.trim()||B||M.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[B?e.jsx(Pe,{className:"w-4 h-4 animate-spin"}):e.jsx(et,{className:"w-4 h-4"}),B?"处理中...":"追加卡密"]})]})]})}),document.body)]})},mn=t=>t.find(a=>a.status==="running"||a.status==="canceling"),la="ydisks-amap-js-api",pn="c9b68d4ce9a2a97f22a4a439404488ca";let $t=null;const un=()=>pn,hn=()=>window.AMap?Promise.resolve(window.AMap):$t||($t=new Promise((t,a)=>{const l=document.getElementById(la),i=l||document.createElement("script"),m=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(N)},_=()=>{window.AMap?(m(),t(window.AMap)):(m(),a(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},N=window.setTimeout(()=>{m(),a(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=_,i.id=la,i.async=!0,i.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(un())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,i.onerror=()=>{m(),a(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},l||document.head.appendChild(i)}).catch(t=>{throw $t=null,t}),$t),Ht=t=>Number.isFinite(t)&&t!==0,gn=t=>{var m,_;const a=Number((m=t.location)==null?void 0:m.lng),l=Number((_=t.location)==null?void 0:_.lat),i={area:String(t.adname||"").trim(),city:String(t.cityname||"").trim(),division_id:String(t.adcode||"").trim(),longitude:a,latitude:l,poi_id:String(t.id||"").trim(),poi_name:String(t.name||"").trim(),province:String(t.pname||"").trim()};return!i.division_id||!i.province||!i.city||!i.poi_id||!i.poi_name||!Ht(a)||!Ht(l)||a<-180||a>180||l<-90||l>90?null:i},bn=async(t,a)=>{if(!Ht(t)||!Ht(a)||t<-180||t>180||a<-90||a>90)throw new Error("经纬度无效");const l=await hn();return new Promise((i,m)=>{new l.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[t,a],1e3,(N,R)=>{var C;if(N!=="complete"){if(N==="no_data"){i([]);return}m(new Error("高德地图附近地址查询失败,请稍后重试"));return}const g=(((C=R==null?void 0:R.poiList)==null?void 0:C.pois)||[]).map(gn).filter(j=>j!==null);i(g)})})},fn=t=>{const a=String(t||"").trim();return a?/^[¥¥]/.test(a)?a:`¥${a}`:"-"},yn=({onConfigureDelivery:t})=>{const[a,l]=r.useState([]),[i,m]=r.useState([]),[_,N]=r.useState([]),[R,g]=r.useState(""),[C,j]=r.useState(""),[F,G]=r.useState(!1),[me,oe]=r.useState(!1),[v,q]=r.useState(!1),[ce,Q]=r.useState(!1),[ee,B]=r.useState(!1),[ge,ue]=r.useState(!1),[k,Z]=r.useState(!1),[se,K]=r.useState("upload"),[ve,J]=r.useState(null),[I,E]=r.useState(null),[$,be]=r.useState(""),[Re,ae]=r.useState(!1),[T,p]=r.useState(!1),[b,U]=r.useState([]),[M,ne]=r.useState(null),[he,ye]=r.useState([]),[Ee,ke]=r.useState(null),[x,V]=r.useState({catId:"",catName:"",channelCatId:"",tbCatId:""}),[X,c]=r.useState(null),[d,D]=r.useState(null),[S,Y]=r.useState(null),O=r.useRef(!1),[de,Se]=r.useState(null),[fe,Oe]=r.useState({}),[re,h]=r.useState({cookie_id:"",item_id:"",item_title:"",item_price:"",item_image:""}),[f,P]=r.useState({cookie_id:"",title:"",description:"",price:"",original_price:"",quantity:"1",postage_mode:"free",postage:"",images:[]}),[z,Ie]=r.useState([]);r.useEffect(()=>{if(!ge||f.images.length===0){Ie([]);return}const n=f.images.map((w,H)=>({key:w.name+H,url:URL.createObjectURL(w)}));return Ie(n),()=>{n.forEach(w=>URL.revokeObjectURL(w.url))}},[ge,f.images]);const Ae=async()=>{const n=await vt();l(n)},we=async()=>{m(await gs())};r.useEffect(()=>{Promise.all([Ft(),vt(),gs(),Hs(20)]).then(([n,w,H,Te])=>{N(n),l(w),m(H);const s=Te.find(o=>["running","canceling"].includes(o.status))||Te.find(o=>o.status!=="preview");Y(s||null)}).catch(n=>console.error("加载商品配置失败:",n))},[]),r.useEffect(()=>{if(!k||!(d!=null&&d.id)||!["running","canceling"].includes(d.status))return;const n=window.setInterval(async()=>{if(!O.current){O.current=!0;try{const w=await bt(d.id);D(w),Y(w),[ Line truncated
`),Te=new Blob(["\uFEFF"+H],{type:"text/csv;charset=utf-8"}),s=URL.createObjectURL(Te),o=document.createElement("a");o.href=s,o.download="批量铺货模板.csv",document.body.appendChild(o),o.click(),o.remove(),URL.revokeObjectURL(s)},Lt=()=>{h(n=>({...n,cookie_id:R||n.cookie_id})),B(!0)},nt=()=>{P(n=>({...n,cookie_id:R||n.cookie_id})),ue(!0)},it=async n=>{if(!(n?R:f.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");p(!0),navigator.geolocation.getCurrentPosition(async H=>{try{const Te=await bn(H.coords.longitude,H.coords.latitude);if(!Te.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");n?(ye(Te),ke(Te[0])):(U(Te),ne(Te[0]))}catch(Te){alert((Te==null?void 0:Te.message)||"获取发货地失败")}finally{p(!1)}},H=>{p(!1),alert(H.code===H.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},Ot=n=>i.filter(w=>w.cookie_id===n.cookie_id&&w.item_id===n.item_id).length>0?i.filter(w=>w.cookie_id===n.cookie_id&&w.item_id===n.item_id):i.filter(w=>w.cookie_id===n.cookie_id&&!w.item_id),pt=n=>{switch(n){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:return n||"-"}},ut=n=>{switch(n){case"success":case"completed":return"bg-emerald-50 text-emerald-700 border-emerald-100";case"partially_failed":case"failed":return"bg-red-50 text-red-700 border-red-100";case"running":return"bg-blue-50 text-blue-700 border-blue-100";case"canceled":return"bg-gray-100 text-gray-600 border-gray-200";default:return"bg-amber-50 text-amber-700 border-amber-100"}},st=r.useMemo(()=>new Map(_.map(n=>[n.id,n])),[_]),ht=r.useMemo(()=>C?a.filter(n=>n.cookie_id===C):a,[C,a]),Ge=n=>{const w=st.get(n),H=(w==null?void 0:w.remark)||(w==null?void 0:w.nickname);return H?`${H} · ${n.slice(0,6)}`:`账号 ${n.slice(0,8)}`},ot=n=>{const w=st.get(n);return(w==null?void 0:w.remark)||(w==null?void 0:w.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(ll,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-account-filter","aria-label":"按账号筛选商品列表",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:C,onChange:n=>j(n.target.value),children:[e.jsx("option",{value:"",children:"全部账号"}),_.map(n=>e.jsx("option",{value:n.id,children:Ge(n.id)},n.id))]})]})]}),e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-sync-account",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"同步商品账号"}),e.jsxs("div",{className:"relative",children:[e.jsx(xt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{id:"item-sync-account","aria-label":"选择要同步商品的账号",className:"ios-input w-full pl-10 pr-9 py-3 rounded-xl text-sm",value:R,onChange:n=>g(n.target.value),children:[e.jsx("option",{value:"",children:"请选择账号"}),_.map(n=>e.jsx("option",{value:n.id,children:Ge(n.id)},n.id))]})]})]}),e.jsxs("button",{onClick:De,disabled:F||!R,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(ze,{className:`w-4 h-4 ${F?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:Lt,className:"px-5 py-3 rounded-2xl font-bold bg-gray-900 text-white hover:bg-gray-800 transition-colors flex items-center gap-2 shadow-lg",children:[e.jsx(et,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:nt,className:"px-5 py-3 rounded-2xl font-bold bg-emerald-500 text-white hover:bg-emerald-600 transition-colors flex items-center gap-2 shadow-lg shadow-emerald-100",children:[e.jsx(es,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:()=>void Ne(),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white Line truncated
+1 -1
View File
@@ -6,7 +6,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ydisks闲鱼助手 - 自动发货与管家系统</title>
<meta name="description" content="Ydisks闲鱼助手 - 自动回复、自动发货、订单管理、AI智能议价一体化解决方案" />
<script type="module" crossorigin src="/static/assets/index-DoIRwhyi.js"></script>
<script type="module" crossorigin src="/static/assets/index-DA3sXl2j.js"></script>
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-C_od1ZSF.js">
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-BpMgNNfy.js">
<link rel="modulepreload" crossorigin href="/static/assets/vendor-D-Edl3pr.js">