将订单刷新改为持久化后台任务

This commit is contained in:
Christ committed 2026-08-15 16:35:08 +08:00
1 parent 6bc29829ba
commit 5b30551694
22 files changed
+883 -99

No files matched your search

+1
View File
@@ -334,6 +334,7 @@ func runServer(parent context.Context, opts serverOptions) error {
}
srv.StartPublishBatchRecovery(ctx)
srv.StartOrderReconciliationRecovery(ctx)
srv.StartOrderRefreshRecovery(ctx)
// err 是 HTTP 服务显式启动失败的原因。
if err := srv.Start(ctx); err != nil {
return fmt.Errorf("启动 HTTP 服务失败: %w", err)
@@ -745,3 +745,4 @@ npm --prefix frontend run build
| 2026-08-15 | P2 商品多规格探测批量与并发边界切片 | 已完成 | 商品同步先用 `MultiSpecFlags` 一次读取本地多规格标记,消除逐商品数据库查询;剩余远端详情探测使用 4 路有界并发,Session 过期可取消同批次探测,普通单项失败保留告警并继续;新增批量标记和并发上限回归测试,定向测试与中文注释门禁通过。跨请求缓存、跨批次去重、平台限流指标和 MySQL/Postgres 查询计划仍待完成,P2 批量同步保持“进行中” |
| 2026-08-15 | P2 商品多规格跨请求缓存切片 | 已完成 | Server 新增按账号/商品隔离的 10 分钟 TTL 多规格缓存;同步成功结果(含 false)均缓存,后续同步命中缓存时跳过远端探测,过期项自动清理;新增缓存命中、过期和并发探测回归测试,注释门禁通过。跨实例共享缓存、主动失效通知、平台限流指标和 MySQL/Postgres 查询计划仍待完成,P2 批量同步保持“进行中” |
| 2026-08-15 | P2 订单复合游标索引与查询计划切片 | 已完成 | SQLite/MySQL/Postgres 新增 `idx_orders_cursor(cookie_id, deleted_at, created_at, order_id)` 复合索引;新增 SQLite `EXPLAIN QUERY PLAN` 回归,确认订单游标查询使用该索引;迁移、订单扫描和中文注释门禁通过。MySQL/Postgres 实际执行计划仍需外部数据库环境验证,P2 批量同步保持“进行中” |
| 2026-08-15 | P1 订单刷新持久化后台任务切片 | 已完成 | 新增 SQLite/MySQL/Postgres `order_refresh_jobs` 迁移及应用层 `RefreshJobRepository` Port;订单刷新 HTTP 端点改为 202 + 用户隔离的状态查询,后台 worker 受 Server 生命周期管理,使用 worker token/lease fencing,并提供过期任务恢复扫描;React 客户端改为可取消的状态轮询;新增任务生命周期、跨用户隔离、旧 worker 拒绝写入、成功/失败/取消和 HTTP/前端契约回归;Go 全量测试、架构/中文注释门禁、前端 317 测试、类型检查和生产构建通过。仍待补充取消端点、进度事件、MySQL/Postgres 实际任务迁移回归与统一运维查询,阶段 4/5/8/9 继续保持“进行中” |
+28 -2
View File
@@ -172,12 +172,38 @@ test('automation issue APIs expose and resolve quarantined work', async () => {
} /* 回调函数负责当前业务流程。 */);
test('order multipart requests use the shared authenticated form request path', async () => {
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
const fetchMock = vi.fn()
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-1', status: 'running' }))
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-1', status: 'succeeded', result: { partial_failure: false, message: '同步完成', summary: { discovered: 0, list_updated: 0, soft_deleted: 0, detail_total: 0, total: 0, updated: 0, no_change: 0, failed: 0 }, results: [] } }))
.mockResolvedValueOnce(jsonResponse({ success: true })); /* fetchMock 表示fetchMock。 */
vi.stubGlobal('fetch', fetchMock);
await syncOrders('acc1', 'pending_ship');
await importOrders(new FormData());
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/orders/refresh', expect.objectContaining({ method: 'POST', credentials: 'include', body: expect.any(FormData) }));
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/orders/import', expect.objectContaining({ method: 'POST', credentials: 'include', body: expect.any(FormData) }));
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/orders/refresh/job-1', expect.objectContaining({ method: 'GET', credentials: 'include' }));
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/orders/import', expect.objectContaining({ method: 'POST', credentials: 'include', body: expect.any(FormData) }));
} /* 回调函数负责当前业务流程。 */);
test('syncOrders surfaces failed persisted job status', async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-failed', status: 'running' }))
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-failed', status: 'failed', error_message: '平台会话已过期' })); /* fetchMock 表示fetchMock。 */
vi.stubGlobal('fetch', fetchMock);
await expect(syncOrders()).rejects.toThrow('平台会话已过期');
} /* 回调函数负责当前业务流程。 */);
test('syncOrders aborts while waiting for persisted job status', async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-running', status: 'running' }))
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-running', status: 'running' })); /* fetchMock 表示fetchMock。 */
vi.stubGlobal('fetch', fetchMock);
// controller 控制订单刷新轮询的取消信号。
const controller = new AbortController();
// pending 保存等待取消结果的订单刷新请求。
const pending = syncOrders(undefined, undefined, { signal: controller.signal });
await Promise.resolve();
controller.abort();
await expect(pending).rejects.toThrow('请求已取消');
} /* 回调函数负责当前业务流程。 */);
test('legacy notification channel aliases are normalized for the editor', async () => {
+37 -3
View File
@@ -4,7 +4,7 @@ import {
AdminStats, DashboardStats, Card, SystemSettings, OrderAnalytics,
Item, AIReplySettings, ShippingRule, ReplyRule, DefaultReply, AutomationAction, AutomationTriggerType,
NotificationChannel, NotificationEventType, AccountTaskSettings, ChatSession, ChatMessage, ItemListEnvelope, AutomationIssuesEnvelope,
CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse
CookieSettingsResponse, CookieProfileResponse, ItemDetailResponse, ItemPublishResponse, ItemSyncResponse, OrderDTOResponse, OrderDetailResponse, OrderSingleRefreshResponse, OrderBatchResponse, OrderRefreshResponse, OrderRefreshJobStartResponse, OrderRefreshJobStatusResponse, AutomationRuleResponse, AutomationRulePageResponse, AIReplySettingsResponse, AIModelsResponse, UserSettingResponse, CardBatchResponse, CardAppendResponse, CategoryRecommendationResponse, ItemPublishBatchPreviewResponse, ItemPublishBatchListResponse, BatchIDResponse, ItemPublishBatchResponse, BatchCancelResponse, MutationIDResponse, OperationResponse, NotificationChannelResponse, NotificationBinding, AccountBindingsResponse, CardListResponse, KeywordTypedResponse, DefaultReplyResponse, AccountTaskSettingsResponse, AccountTaskRunResponseEnvelope, AdminStatsResponse, DashboardStatsResponse, OrderAnalyticsResponse, QRLoginGenerateResponse, QRLoginStatusResponse, QRLoginVerificationResponse, ValidOrderResponse, ValidOrdersResponse
} from '../types';
import { formatLocalDate } from '../dateRange';
@@ -423,13 +423,47 @@ export const deleteOrder = async (orderId: string): Promise<OperationResponse> =
};
// syncOrders 同步订单。
export const syncOrders = async (cookieId?: string, status?: string): Promise<OrderRefreshResponse> => {
export const syncOrders = async (cookieId?: string, status?: string, options?: RequestControlOptions): Promise<OrderRefreshResponse> => {
// formData 表单数据,用于当前 API 处理流程。
const formData = new FormData();
if (cookieId) formData.append('cookie_id', cookieId);
if (status) formData.append('status', status);
return postForm('/api/v1/orders/refresh', formData);
// start 表示后台订单刷新任务创建响应。
const start = await postForm<OrderRefreshJobStartResponse>('/api/v1/orders/refresh', formData, options);
// pollLimit 限制前端等待后台任务的轮询次数。
const pollLimit = 180;
// pollIndex 表示当前订单刷新任务状态轮询次数。
let pollIndex = 0;
while (pollIndex < pollLimit) {
// job 表示当前轮询得到的后台任务状态。
const job = await get<OrderRefreshJobStatusResponse>(`/api/v1/orders/refresh/${start.job_id}`, undefined, options);
if (job.status === 'succeeded' && job.result) {
return job.result;
}
if (job.status === 'failed' || job.status === 'cancelled') {
throw new Error(job.error_message || '订单刷新任务失败');
}
// waitMs 是下一次任务状态轮询前的等待时间。
const waitMs = 500;
await new Promise<void>(/* 轮询等待器负责等待下一次任务状态查询。 */ (resolve, reject) => {
// abort 负责响应调用方取消轮询。
const abort = () => {
globalThis.clearTimeout(timer);
reject(new Error('请求已取消'));
};
// timer 表示当前轮询等待定时器。
const timer = globalThis.setTimeout(/* 轮询完成回调清理取消监听并结束等待。 */ () => {
options?.signal?.removeEventListener('abort', abort);
resolve();
}, waitMs);
if (!options?.signal) return;
if (options.signal.aborted) abort();
else options.signal.addEventListener('abort', abort, { once: true });
});
pollIndex += 1;
}
throw new Error('订单刷新任务等待超时');
};
// syncSingleOrder 同步单个订单。
+24
View File
@@ -1561,6 +1561,30 @@ export interface OrderRefreshResponse {
results: OrderRefreshResultResponse[];
}
/** 创建订单刷新后台任务的响应。 */
export interface OrderRefreshJobStartResponse {
/** 任务是否创建成功。 */
success: boolean;
/** 后台任务标识。 */
job_id: string;
/** 任务当前状态。 */
status: 'queued' | 'running';
}
/** 查询订单刷新后台任务的响应。 */
export interface OrderRefreshJobStatusResponse {
/** 查询是否成功。 */
success: boolean;
/** 后台任务标识。 */
job_id: string;
/** 任务当前状态。 */
status: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled';
/** 任务失败原因。 */
error_message?: string;
/** 任务成功后的订单刷新结果。 */
result?: OrderRefreshResponse;
}
// ItemListEnvelope 是商品列表接口的兼容分页响应。
export interface ItemListEnvelope {
/** items 是兼容分页响应中的商品列表。 */
@@ -0,0 +1,51 @@
package orders
import (
"context"
"errors"
)
// ErrRefreshJobNotFound 表示当前用户无法读取指定订单刷新任务。
var ErrRefreshJobNotFound = errors.New("订单刷新任务不存在")
// RefreshJob 是订单刷新后台任务的应用层模型,不暴露数据库类型。
type RefreshJob struct {
// ID 是任务唯一标识。
ID string
// UserID 是任务所属用户标识。
UserID int64
// CookieID 是可选的目标账号标识。
CookieID string
// FilterStatus 是订单状态筛选条件。
FilterStatus string
// Status 是 queued/running/succeeded/failed/cancelled 之一。
Status string
// ResultJSON 保存成功后的具名刷新结果 JSON。
ResultJSON string
// ErrorMessage 保存任务失败原因。
ErrorMessage string
// WorkerToken 是当前执行者租约令牌。
WorkerToken string
// LeaseExpiresAt 是租约过期 Unix 秒时间戳。
LeaseExpiresAt int64
// CreatedAt 是任务创建时间。
CreatedAt string
// UpdatedAt 是任务最后更新时间。
UpdatedAt string
}
// RefreshJobRepository 定义订单刷新任务需要的持久化能力。
type RefreshJobRepository interface {
// Create 创建一个 queued 状态的订单刷新任务。
Create(ctx context.Context, job *RefreshJob) error
// Get 按用户读取订单刷新任务。
Get(ctx context.Context, userID int64, id string) (*RefreshJob, error)
// Claim 原子抢占 queued 任务并写入租约令牌。
Claim(ctx context.Context, id, token string, leaseExpiresAt int64) (bool, error)
// Complete 在租约令牌匹配时写入任务终态。
Complete(ctx context.Context, id, token, status, resultJSON, errorMessage string) (bool, error)
// Recoverable 返回租约已过期的 running 任务。
Recoverable(ctx context.Context, now int64, limit int) ([]RefreshJob, error)
// RequeueExpired 将过期运行任务恢复为 queued。
RequeueExpired(ctx context.Context, id string, now int64) (bool, error)
}
@@ -0,0 +1,20 @@
-- +goose Up
CREATE TABLE IF NOT EXISTS order_refresh_jobs (
id VARCHAR(64) PRIMARY KEY,
user_id BIGINT NOT NULL,
cookie_id VARCHAR(255) NOT NULL DEFAULT '',
filter_status VARCHAR(64) NOT NULL DEFAULT '',
status VARCHAR(32) NOT NULL DEFAULT 'queued',
result_json LONGTEXT NOT NULL,
error_message TEXT NOT NULL,
worker_token VARCHAR(128) NOT NULL DEFAULT '',
lease_expires_at BIGINT NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT fk_order_refresh_jobs_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE,
INDEX idx_order_refresh_jobs_user (user_id, created_at, id),
INDEX idx_order_refresh_jobs_lease (status, lease_expires_at)
);
-- +goose Down
DROP TABLE IF EXISTS order_refresh_jobs;
@@ -0,0 +1,21 @@
-- +goose Up
CREATE TABLE IF NOT EXISTS order_refresh_jobs (
id TEXT PRIMARY KEY,
user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE CASCADE,
cookie_id TEXT NOT NULL DEFAULT '',
filter_status TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'queued',
result_json TEXT NOT NULL DEFAULT '{}',
error_message TEXT NOT NULL DEFAULT '',
worker_token TEXT NOT NULL DEFAULT '',
lease_expires_at BIGINT NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_user ON order_refresh_jobs(user_id, created_at DESC, id DESC);
CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_lease ON order_refresh_jobs(status, lease_expires_at);
-- +goose Down
DROP INDEX IF EXISTS idx_order_refresh_jobs_lease;
DROP INDEX IF EXISTS idx_order_refresh_jobs_user;
DROP TABLE IF EXISTS order_refresh_jobs;
@@ -0,0 +1,21 @@
-- +goose Up
CREATE TABLE IF NOT EXISTS order_refresh_jobs (
id TEXT PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
cookie_id TEXT NOT NULL DEFAULT '',
filter_status TEXT NOT NULL DEFAULT '',
status TEXT NOT NULL DEFAULT 'queued',
result_json TEXT NOT NULL DEFAULT '{}',
error_message TEXT NOT NULL DEFAULT '',
worker_token TEXT NOT NULL DEFAULT '',
lease_expires_at INTEGER NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
);
CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_user ON order_refresh_jobs(user_id, created_at DESC, id DESC);
CREATE INDEX IF NOT EXISTS idx_order_refresh_jobs_lease ON order_refresh_jobs(status, lease_expires_at);
-- +goose Down
DROP INDEX IF EXISTS idx_order_refresh_jobs_lease;
DROP INDEX IF EXISTS idx_order_refresh_jobs_user;
DROP TABLE IF EXISTS order_refresh_jobs;
+153
View File
@@ -0,0 +1,153 @@
package db
import (
"context"
"database/sql"
"errors"
)
// OrderRefreshJobs 持久化订单刷新后台任务及其租约状态。
type OrderRefreshJobs struct {
// DB 保存任务表使用的数据库连接。
DB *sql.DB
}
// OrderRefreshJob 是订单刷新任务的持久化模型。
type OrderRefreshJob struct {
// ID 是任务唯一标识。
ID string
// UserID 是任务所属用户标识。
UserID int64
// CookieID 是可选的目标账号标识。
CookieID string
// FilterStatus 是订单状态筛选条件。
FilterStatus string
// Status 是 queued/running/succeeded/failed/cancelled 之一。
Status string
// ResultJSON 保存成功后的具名刷新结果 JSON。
ResultJSON string
// ErrorMessage 保存任务失败原因。
ErrorMessage string
// WorkerToken 是当前执行者租约令牌。
WorkerToken string
// LeaseExpiresAt 是租约过期 Unix 秒时间戳。
LeaseExpiresAt int64
// CreatedAt 是任务创建时间。
CreatedAt string
// UpdatedAt 是任务最后更新时间。
UpdatedAt string
}
// Create 创建一个 queued 状态的订单刷新任务。
func (j *OrderRefreshJobs) Create(ctx context.Context, job *OrderRefreshJob) error {
if job.Status == "" {
job.Status = "queued"
}
if job.ResultJSON == "" {
job.ResultJSON = "{}"
}
// err 表示创建订单刷新任务的数据库错误。
_, err := j.DB.ExecContext(ctx,
`INSERT INTO order_refresh_jobs
(id,user_id,cookie_id,filter_status,status,result_json,error_message,worker_token,lease_expires_at)
VALUES (?,?,?,?,?,?,?,?,?)`,
job.ID, job.UserID, job.CookieID, job.FilterStatus, job.Status, job.ResultJSON,
job.ErrorMessage, job.WorkerToken, job.LeaseExpiresAt)
return err
}
// Get 按用户读取订单刷新任务,防止跨用户查询任务结果。
func (j *OrderRefreshJobs) Get(ctx context.Context, userID int64, id string) (*OrderRefreshJob, error) {
// job 保存读取到的任务模型。
job := &OrderRefreshJob{}
// err 保存任务查询错误。
err := j.DB.QueryRowContext(ctx,
`SELECT id,user_id,cookie_id,filter_status,status,COALESCE(result_json,'{}'),
COALESCE(error_message,''),COALESCE(worker_token,''),COALESCE(lease_expires_at,0),created_at,updated_at
FROM order_refresh_jobs WHERE id=? AND user_id=?`, id, userID).Scan(
&job.ID, &job.UserID, &job.CookieID, &job.FilterStatus, &job.Status, &job.ResultJSON,
&job.ErrorMessage, &job.WorkerToken, &job.LeaseExpiresAt, &job.CreatedAt, &job.UpdatedAt)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrNotFound
}
if err != nil {
return nil, err
}
return job, nil
}
// Claim 将 queued 任务原子切换为 running 并写入租约。
func (j *OrderRefreshJobs) Claim(ctx context.Context, id, token string, leaseExpiresAt int64) (bool, error) {
// result、err 保存抢占更新结果及错误。
result, err := j.DB.ExecContext(ctx,
`UPDATE order_refresh_jobs
SET status='running',worker_token=?,lease_expires_at=?,updated_at=CURRENT_TIMESTAMP
WHERE id=? AND status='queued'`, token, leaseExpiresAt, id)
if err != nil {
return false, err
}
// affected、err 保存抢占更新影响行数及错误。
affected, err := result.RowsAffected()
return affected == 1, err
}
// Complete 在租约令牌匹配时写入任务终态,过期 worker 不能覆盖新执行者结果。
func (j *OrderRefreshJobs) Complete(ctx context.Context, id, token, status, resultJSON, errorMessage string) (bool, error) {
// result、err 保存任务终态更新结果及错误。
result, err := j.DB.ExecContext(ctx,
`UPDATE order_refresh_jobs
SET status=?,result_json=?,error_message=?,worker_token='',lease_expires_at=0,updated_at=CURRENT_TIMESTAMP
WHERE id=? AND status='running' AND worker_token=?`, status, resultJSON, errorMessage, id, token)
if err != nil {
return false, err
}
// affected、err 保存终态更新影响行数及错误。
affected, err := result.RowsAffected()
return affected == 1, err
}
// Recoverable 返回租约已过期的 running 任务,供恢复扫描器重新排队。
func (j *OrderRefreshJobs) Recoverable(ctx context.Context, now int64, limit int) ([]OrderRefreshJob, error) {
if limit <= 0 || limit > 100 {
limit = 20
}
// rows、err 保存可恢复任务查询结果及错误。
rows, err := j.DB.QueryContext(ctx,
`SELECT id,user_id,cookie_id,filter_status,status,COALESCE(result_json,'{}'),
COALESCE(error_message,''),COALESCE(worker_token,''),COALESCE(lease_expires_at,0),created_at,updated_at
FROM order_refresh_jobs
WHERE status='running' AND lease_expires_at>0 AND lease_expires_at<=?
ORDER BY updated_at ASC,id ASC LIMIT ?`, now, limit)
if err != nil {
return nil, err
}
defer rows.Close()
// jobs 保存可恢复任务列表。
jobs := make([]OrderRefreshJob, 0, limit)
for rows.Next() {
// job 保存当前可恢复任务。
var job OrderRefreshJob
// err 表示扫描可恢复任务的数据库错误。
if err := rows.Scan(&job.ID, &job.UserID, &job.CookieID, &job.FilterStatus, &job.Status,
&job.ResultJSON, &job.ErrorMessage, &job.WorkerToken, &job.LeaseExpiresAt, &job.CreatedAt, &job.UpdatedAt); err != nil {
return nil, err
}
jobs = append(jobs, job)
}
return jobs, rows.Err()
}
// RequeueExpired 将过期运行任务恢复为 queued,并清理旧 worker 租约。
func (j *OrderRefreshJobs) RequeueExpired(ctx context.Context, id string, now int64) (bool, error) {
// result、err 保存任务重新入队结果及错误。
result, err := j.DB.ExecContext(ctx,
`UPDATE order_refresh_jobs
SET status='queued',worker_token='',lease_expires_at=0,updated_at=CURRENT_TIMESTAMP
WHERE id=? AND status='running' AND lease_expires_at>0 AND lease_expires_at<=?`, id, now)
if err != nil {
return false, err
}
// affected、err 保存重新入队影响行数及错误。
affected, err := result.RowsAffected()
return affected == 1, err
}
+81
View File
@@ -0,0 +1,81 @@
package db
import (
"context"
"errors"
"testing"
"time"
)
// TestOrderRefreshJobsLifecycle 验证订单刷新任务的创建、租约、终态和过期恢复生命周期。
func TestOrderRefreshJobsLifecycle(t *testing.T) {
// store、cleanup 保存当前测试数据库及清理函数。
store, cleanup := newTestDB(t)
defer cleanup()
// ctx 保存当前任务测试使用的上下文。
ctx := context.Background()
// userID、cookieID 保存测试账号归属信息。
userID, cookieID := seedAccount(t, store)
// job 保存待测试的订单刷新任务。
job := &OrderRefreshJob{ID: "refresh-job-1", UserID: userID, CookieID: cookieID, FilterStatus: "pending_ship"}
// err 表示创建任务的数据库错误。
if err := store.OrderRefreshJobs.Create(ctx, job); err != nil {
t.Fatalf("create job: %v", err)
}
// loaded、err 保存创建后的任务读取结果及错误。
loaded, err := store.OrderRefreshJobs.Get(ctx, userID, job.ID)
if err != nil || loaded.Status != "queued" || loaded.ResultJSON != "{}" {
t.Fatalf("created job=%+v err=%v", loaded, err)
}
// claimed、err 保存首次租约抢占结果及错误。
claimed, err := store.OrderRefreshJobs.Claim(ctx, job.ID, "worker-1", time.Now().Add(time.Minute).Unix())
if err != nil || !claimed {
t.Fatalf("claim job: claimed=%v err=%v", claimed, err)
}
// err 表示重复抢占的数据库错误。
if claimed, err = store.OrderRefreshJobs.Claim(ctx, job.ID, "worker-2", time.Now().Add(time.Minute).Unix()); err != nil || claimed {
t.Fatalf("duplicate claim should fail: claimed=%v err=%v", claimed, err)
}
// completed、err 表示错误 worker 的终态写入结果及错误。
if completed, err := store.OrderRefreshJobs.Complete(ctx, job.ID, "worker-2", "succeeded", `{"message":"wrong worker"}`, ""); err != nil || completed {
t.Fatalf("wrong worker must not complete: completed=%v err=%v", completed, err)
}
// completed、err 表示合法 worker 的终态写入结果及错误。
if completed, err := store.OrderRefreshJobs.Complete(ctx, job.ID, "worker-1", "succeeded", `{"message":"ok"}`, ""); err != nil || !completed {
t.Fatalf("complete job: completed=%v err=%v", completed, err)
}
// completedJob、err 保存成功任务的终态读取结果及错误。
completedJob, err := store.OrderRefreshJobs.Get(ctx, userID, job.ID)
if err != nil || completedJob.Status != "succeeded" || completedJob.WorkerToken != "" {
t.Fatalf("completed job=%+v err=%v", completedJob, err)
}
// expiredJob 保存用于验证租约过期恢复的任务。
expiredJob := &OrderRefreshJob{ID: "refresh-job-expired", UserID: userID, CookieID: cookieID}
// err 表示创建过期任务的数据库错误。
if err := store.OrderRefreshJobs.Create(ctx, expiredJob); err != nil {
t.Fatalf("create expired job: %v", err)
}
// claimed、err 表示过期任务的租约抢占结果及错误。
if claimed, err := store.OrderRefreshJobs.Claim(ctx, expiredJob.ID, "worker-old", time.Now().Add(-time.Minute).Unix()); err != nil || !claimed {
t.Fatalf("claim expired job: claimed=%v err=%v", claimed, err)
}
// recoverable、err 保存过期任务扫描结果及错误。
recoverable, err := store.OrderRefreshJobs.Recoverable(ctx, time.Now().Unix(), 10)
if err != nil || len(recoverable) != 1 || recoverable[0].ID != expiredJob.ID {
t.Fatalf("recoverable=%+v err=%v", recoverable, err)
}
// requeued、err 表示过期任务重新入队结果及错误。
if requeued, err := store.OrderRefreshJobs.RequeueExpired(ctx, expiredJob.ID, time.Now().Unix()); err != nil || !requeued {
t.Fatalf("requeue expired job: requeued=%v err=%v", requeued, err)
}
// requeuedJob、err 保存重新入队后的任务及错误。
requeuedJob, err := store.OrderRefreshJobs.Get(ctx, userID, expiredJob.ID)
if err != nil || requeuedJob.Status != "queued" || requeuedJob.WorkerToken != "" {
t.Fatalf("requeued job=%+v err=%v", requeuedJob, err)
}
// err 表示跨用户读取任务的查询错误。
if _, err := store.OrderRefreshJobs.Get(ctx, userID+1, job.ID); !errors.Is(err, ErrNotFound) {
t.Fatalf("cross-user job lookup should be hidden, err=%v", err)
}
}
+57 -55
View File
@@ -7,33 +7,34 @@ import (
// Store 聚合各 repository,供上层(HTTP server、account supervisor 等)统一持有。
type Store struct {
DB *sql.DB
Dialect Dialect
Users *Users
Sessions *Sessions
Cookies *Cookies
Items *Items
Cards *Cards
Automation *AutomationRules
Orders *Orders
Reconciliations *OrderReconciliations
Keywords *Keywords
DefaultReps *DefaultReplies
ItemReps *ItemReplies
AIReply *AIReply
Notifications *Notifications
Settings *SystemSettings
UserSettings *UserSettings
WSMessages *WSMessageStore
PublishBatches *ItemPublishBatches
Tokens *AccountTokens
Renewal *RenewalStore
LoginLogs *AccountLoginLogs
RiskLogs *RiskControlLogs
Chats *ChatStore
AccountTasks *AccountTaskStore
Admin *AdminQueries
Analytics *AnalyticsQueries
DB *sql.DB
Dialect Dialect
Users *Users
Sessions *Sessions
Cookies *Cookies
Items *Items
Cards *Cards
Automation *AutomationRules
Orders *Orders
Reconciliations *OrderReconciliations
OrderRefreshJobs *OrderRefreshJobs
Keywords *Keywords
DefaultReps *DefaultReplies
ItemReps *ItemReplies
AIReply *AIReply
Notifications *Notifications
Settings *SystemSettings
UserSettings *UserSettings
WSMessages *WSMessageStore
PublishBatches *ItemPublishBatches
Tokens *AccountTokens
Renewal *RenewalStore
LoginLogs *AccountLoginLogs
RiskLogs *RiskControlLogs
Chats *ChatStore
AccountTasks *AccountTaskStore
Admin *AdminQueries
Analytics *AnalyticsQueries
credentialMu sync.Mutex
credentialLocks map[string]*credentialLockEntry
@@ -52,34 +53,35 @@ func NewStore(db *sql.DB, dialect Dialect) *Store {
// codec 保存codec,供当前处理流程使用
codec := secretCodecFromEnvironment()
return &Store{
DB: db,
Dialect: dialect,
Users: &Users{DB: db},
Sessions: &Sessions{DB: db},
Cookies: &Cookies{DB: db, Dialect: dialect, codec: codec},
Items: &Items{DB: db, Dialect: dialect},
Cards: &Cards{DB: db, Dialect: dialect},
Automation: &AutomationRules{DB: db, Dialect: dialect},
Orders: &Orders{DB: db, Dialect: dialect},
Reconciliations: &OrderReconciliations{DB: db},
Keywords: &Keywords{DB: db, Dialect: dialect},
DefaultReps: &DefaultReplies{DB: db, Dialect: dialect},
ItemReps: &ItemReplies{DB: db, Dialect: dialect},
AIReply: &AIReply{DB: db, Dialect: dialect, codec: codec},
Notifications: &Notifications{DB: db, Dialect: dialect, codec: codec},
Settings: &SystemSettings{DB: db, Dialect: dialect, codec: codec},
UserSettings: &UserSettings{DB: db, Dialect: dialect},
WSMessages: &WSMessageStore{DB: db},
PublishBatches: &ItemPublishBatches{DB: db},
Tokens: &AccountTokens{DB: db, Dialect: dialect, codec: codec},
Renewal: &RenewalStore{DB: db, Dialect: dialect},
LoginLogs: &AccountLoginLogs{DB: db},
RiskLogs: &RiskControlLogs{DB: db, Dialect: dialect},
Chats: &ChatStore{DB: db, Dialect: dialect},
AccountTasks: &AccountTaskStore{DB: db, Dialect: dialect},
Admin: &AdminQueries{DB: db},
Analytics: &AnalyticsQueries{DB: db},
credentialLocks: make(map[string]*credentialLockEntry),
DB: db,
Dialect: dialect,
Users: &Users{DB: db},
Sessions: &Sessions{DB: db},
Cookies: &Cookies{DB: db, Dialect: dialect, codec: codec},
Items: &Items{DB: db, Dialect: dialect},
Cards: &Cards{DB: db, Dialect: dialect},
Automation: &AutomationRules{DB: db, Dialect: dialect},
Orders: &Orders{DB: db, Dialect: dialect},
Reconciliations: &OrderReconciliations{DB: db},
OrderRefreshJobs: &OrderRefreshJobs{DB: db},
Keywords: &Keywords{DB: db, Dialect: dialect},
DefaultReps: &DefaultReplies{DB: db, Dialect: dialect},
ItemReps: &ItemReplies{DB: db, Dialect: dialect},
AIReply: &AIReply{DB: db, Dialect: dialect, codec: codec},
Notifications: &Notifications{DB: db, Dialect: dialect, codec: codec},
Settings: &SystemSettings{DB: db, Dialect: dialect, codec: codec},
UserSettings: &UserSettings{DB: db, Dialect: dialect},
WSMessages: &WSMessageStore{DB: db},
PublishBatches: &ItemPublishBatches{DB: db},
Tokens: &AccountTokens{DB: db, Dialect: dialect, codec: codec},
Renewal: &RenewalStore{DB: db, Dialect: dialect},
LoginLogs: &AccountLoginLogs{DB: db},
RiskLogs: &RiskControlLogs{DB: db, Dialect: dialect},
Chats: &ChatStore{DB: db, Dialect: dialect},
AccountTasks: &AccountTaskStore{DB: db, Dialect: dialect},
Admin: &AdminQueries{DB: db},
Analytics: &AnalyticsQueries{DB: db},
credentialLocks: make(map[string]*credentialLockEntry),
}
}
+1 -1
View File
@@ -17,7 +17,7 @@ type applicationServices struct {
// newApplicationServices 为指定 Server 装配全部应用服务实例。
func newApplicationServices(server *Server) *applicationServices {
return &applicationServices{
orders: &orderApplicationService{server: newServerOrderRuntime(server), repository: newStoreOrderRepository(server.Store)},
orders: &orderApplicationService{server: newServerOrderRuntime(server), repository: newStoreOrderRepository(server.Store), refreshJobs: newStoreOrderRefreshJobRepository(server.Store)},
itemPublish: &itemPublishService{server: server, repository: newStoreItemPublishRepository(server.Store)},
accountLogin: &accountLoginService{server: server, repository: newStoreAccountLoginRepository(server.Store)},
communication: &communicationService{server: server, repository: newStoreCommunicationRepository(server.Store)},
+1 -18
View File
@@ -36,7 +36,7 @@ type orderDetailMTop interface {
func (s *Server) mountOrdersReal(r chi.Router) {
r.Get("/api/orders", s.listOrders)
r.Get("/api/orders/{order_id}", s.getOrder)
r.Post("/api/orders/refresh", s.refreshOrders)
s.mountOrderRefreshJobRoutes(r, "/api")
r.Post("/api/orders/{order_id}/refresh", s.refreshSingleOrder)
r.Post("/api/orders/manual-ship", s.manualShipOrders)
r.Post("/api/orders/import", s.importOrders)
@@ -93,23 +93,6 @@ func (s *Server) getOrder(w http.ResponseWriter, r *http.Request) {
})
}
// refreshOrders 将 HTTP 请求转换为订单刷新应用服务调用并编码兼容响应。
func (s *Server) refreshOrders(w http.ResponseWriter, r *http.Request) {
// sess 保存sess,供当前处理流程使用
sess := auth.SessionFromContext(r.Context())
// result、err 保存result、err,供当前处理流程使用
result, err := s.orders().Refresh(r.Context(), sess.UserID, r.FormValue("cookie_id"), r.FormValue("status"))
if errors.Is(err, db.ErrForbidden) {
writeErr(w, http.StatusForbidden, "Cookie不存在或无权访问")
return
}
if err != nil {
writeErr(w, http.StatusInternalServerError, "查询账号失败")
return
}
writeJSON(w, http.StatusOK, result)
}
// 订单发现阶段将远端订单索引与本地软删除状态保持一致。
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
+72 -3
View File
@@ -15,6 +15,42 @@ import (
"xianyu-go/internal/db"
)
// waitOrderRefreshJob 等待订单刷新后台任务完成并返回具名刷新结果。
func waitOrderRefreshJob(t *testing.T, handler http.Handler, cookie *http.Cookie, jobID string) orderRefreshResponse {
t.Helper()
// deadline 保存测试任务允许的最长等待时间。
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
// req 保存当前任务状态查询请求。
req := httptest.NewRequest(http.MethodGet, "/api/orders/refresh/"+jobID, nil)
req.AddCookie(cookie)
// rec 保存当前任务状态响应。
rec := httptest.NewRecorder()
handler.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("refresh job status=%d body=%s", rec.Code, rec.Body.String())
}
// status 保存任务状态响应。
var status orderRefreshJobStatusResponse
// err 表示任务状态 JSON 解析错误。
if err := json.Unmarshal(rec.Body.Bytes(), &status); err != nil {
t.Fatalf("decode refresh job status: %v", err)
}
if status.Status == "succeeded" {
if status.Result == nil {
t.Fatalf("succeeded refresh job has no result: %+v", status)
}
return *status.Result
}
if status.Status == "failed" {
t.Fatalf("refresh job failed: %+v", status)
}
time.Sleep(10 * time.Millisecond)
}
t.Fatalf("refresh job %s did not complete", jobID)
return orderRefreshResponse{}
}
// TestRefreshOrdersNoBrowser 浏览器未启用时仍应完成订单列表发现。
func TestRefreshOrdersNoBrowser(t *testing.T) {
// srv、cleanup 保存srv、cleanup,供当前处理流程使用
@@ -31,9 +67,20 @@ func TestRefreshOrdersNoBrowser(t *testing.T) {
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "订单列表同步完成") {
if rec.Code != http.StatusAccepted {
t.Fatalf("无浏览器仍应同步列表,got %d body=%s", rec.Code, rec.Body.String())
}
// start 保存后台任务创建响应。
var start orderRefreshJobStartResponse
// err 表示任务创建响应 JSON 解析错误。
if err := json.Unmarshal(rec.Body.Bytes(), &start); err != nil {
t.Fatal(err)
}
// result 保存完成后的订单刷新结果。
result := waitOrderRefreshJob(t, h, cookie, start.JobID)
if !strings.Contains(result.Message, "订单列表同步完成") {
t.Fatalf("refresh result=%+v", result)
}
}
// TestRefreshOrdersDiscoversNewOrdersWithoutBrowser 负责TestRefresh订单列表DiscoversNew订单列表Without浏览器相关处理。
@@ -65,9 +112,20 @@ func TestRefreshOrdersDiscoversNewOrdersWithoutBrowser(t *testing.T) {
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"discovered":1`) {
if rec.Code != http.StatusAccepted {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// start 保存后台任务创建响应。
var start orderRefreshJobStartResponse
// err 表示任务创建响应 JSON 解析错误。
if err := json.Unmarshal(rec.Body.Bytes(), &start); err != nil {
t.Fatal(err)
}
// result 保存完成后的订单刷新结果。
result := waitOrderRefreshJob(t, h, cookie, start.JobID)
if result.Summary.Discovered != 1 {
t.Fatalf("refresh result=%+v", result)
}
// order、err 保存order、err,供当前处理流程使用
order, err := store.Orders.Get(context.Background(), "sold-new-1")
if err != nil {
@@ -168,9 +226,20 @@ func TestRefreshOrdersSoftDeletesOrdersMissingFromSellerList(t *testing.T) {
// rec 保存rec,供当前处理流程使用
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"soft_deleted":1`) {
if rec.Code != http.StatusAccepted {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
// start 保存后台任务创建响应。
var start orderRefreshJobStartResponse
// err 表示任务创建响应 JSON 解析错误。
if err := json.Unmarshal(rec.Body.Bytes(), &start); err != nil {
t.Fatal(err)
}
// result 保存完成后的订单刷新结果。
result := waitOrderRefreshJob(t, h, cookie, start.JobID)
if result.Summary.SoftDeleted != 1 {
t.Fatalf("refresh result=%+v", result)
}
// deletedAt 保存deletedAt,供当前处理流程使用
var deletedAt string
if // err 保存err,供当前处理流程使用
@@ -0,0 +1,204 @@
package server
import (
"context"
"encoding/json"
"errors"
"net/http"
"time"
"github.com/go-chi/chi/v5"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/auth"
)
// orderRefreshJobTimeout 限制单个订单刷新后台任务的最长执行时间。
const orderRefreshJobTimeout = 30 * time.Minute
// orderRefreshJobLease 为运行中的订单刷新任务提供可恢复租约。
const orderRefreshJobLease = orderRefreshJobTimeout + time.Minute
// orderRefreshJobStartResponse 是创建订单刷新任务后的响应 DTO。
type orderRefreshJobStartResponse struct {
// Success 表示任务是否成功创建。
Success bool `json:"success"`
// JobID 是后台任务标识。
JobID string `json:"job_id"`
// Status 是任务初始状态。
Status string `json:"status"`
}
// orderRefreshJobStatusResponse 是订单刷新任务查询响应 DTO。
type orderRefreshJobStatusResponse struct {
// Success 表示查询是否成功。
Success bool `json:"success"`
// JobID 是后台任务标识。
JobID string `json:"job_id"`
// Status 是 queued/running/succeeded/failed 任务状态。
Status string `json:"status"`
// ErrorMessage 是任务失败原因。
ErrorMessage string `json:"error_message,omitempty"`
// Result 是任务成功后的订单刷新结果。
Result *orderRefreshResponse `json:"result,omitempty"`
}
// mountOrderRefreshJobRoutes 挂载订单刷新后台任务端点。
func (s *Server) mountOrderRefreshJobRoutes(r chi.Router, prefix string) {
r.Post(prefix+"/orders/refresh", s.startOrderRefreshJob)
r.Get(prefix+"/orders/refresh/{job_id}", s.getOrderRefreshJob)
}
// startOrderRefreshJob 创建订单刷新任务并立即返回任务标识。
func (s *Server) startOrderRefreshJob(w http.ResponseWriter, r *http.Request) {
// sess 保存当前认证会话。
sess := auth.SessionFromContext(r.Context())
// cookieID、filterStatus 保存订单刷新筛选条件。
cookieID, filterStatus := r.FormValue("cookie_id"), r.FormValue("status")
if cookieID != "" && !s.orders().orderOwnedByUser(r.Context(), sess.UserID, cookieID) {
writeErr(w, http.StatusForbidden, "Cookie不存在或无权访问")
return
}
// job 保存待持久化的订单刷新任务。
job := &orderapp.RefreshJob{
ID: "order-refresh-" + randomHex(16), UserID: sess.UserID,
CookieID: cookieID, FilterStatus: filterStatus,
}
// err 表示创建任务的数据库错误。
if err := s.orders().refreshJobs.Create(r.Context(), job); err != nil {
writeErr(w, http.StatusInternalServerError, "创建订单刷新任务失败")
return
}
// token 保存本次执行者的租约令牌。
token := randomHex(16)
// claimed、claimErr 保存任务抢占结果及错误。
claimed, claimErr := s.orders().refreshJobs.Claim(r.Context(), job.ID, token, time.Now().Add(orderRefreshJobLease).Unix())
if claimErr != nil || !claimed {
writeErr(w, http.StatusInternalServerError, "启动订单刷新任务失败")
return
}
s.startOrderRefreshWorker(job, token)
writeJSON(w, http.StatusAccepted, orderRefreshJobStartResponse{Success: true, JobID: job.ID, Status: "running"})
}
// getOrderRefreshJob 返回当前用户拥有的订单刷新任务状态和结果。
func (s *Server) getOrderRefreshJob(w http.ResponseWriter, r *http.Request) {
// sess 保存当前认证会话。
sess := auth.SessionFromContext(r.Context())
// jobID 保存路径中的订单刷新任务标识。
jobID := chi.URLParam(r, "job_id")
// job、err 保存任务读取结果及错误。
job, err := s.orders().refreshJobs.Get(r.Context(), sess.UserID, jobID)
if errors.Is(err, orderapp.ErrRefreshJobNotFound) {
writeErr(w, http.StatusNotFound, "订单刷新任务不存在")
return
}
if err != nil {
writeErr(w, http.StatusInternalServerError, "读取订单刷新任务失败")
return
}
// response 保存任务状态响应 DTO。
response := orderRefreshJobStatusResponse{Success: true, JobID: job.ID, Status: job.Status, ErrorMessage: job.ErrorMessage}
if job.ResultJSON != "" && job.ResultJSON != "{}" {
// result 保存成功任务的具名刷新结果。
var result orderRefreshResponse
// err 表示任务结果 JSON 解析错误。
if err := json.Unmarshal([]byte(job.ResultJSON), &result); err != nil {
if s.Logger != nil {
s.Logger.Error("解析订单刷新任务结果失败", "job_id", job.ID, "err", err)
}
writeErr(w, http.StatusInternalServerError, "读取订单刷新结果失败")
return
}
response.Result = &result
}
writeJSON(w, http.StatusOK, response)
}
// startOrderRefreshWorker 启动受 Server 生命周期管理的订单刷新 worker。
func (s *Server) startOrderRefreshWorker(job *orderapp.RefreshJob, token string) {
if job == nil {
return
}
s.startBackgroundTask("订单刷新任务", func() {
// parent 保存 Server 生命周期上下文,避免 HTTP 请求结束取消后台任务。
parent := s.lifecycleContext()
// jobCtx、cancel 限制后台任务执行时间。
jobCtx, cancel := context.WithTimeout(parent, orderRefreshJobTimeout)
defer cancel()
s.runOrderRefreshJob(jobCtx, job, token)
})
}
// runOrderRefreshJob 执行订单刷新并以租约令牌写入成功或失败终态。
func (s *Server) runOrderRefreshJob(ctx context.Context, job *orderapp.RefreshJob, token string) {
// result、err 保存订单刷新业务结果及错误。
result, err := s.orders().Refresh(ctx, job.UserID, job.CookieID, job.FilterStatus)
if err != nil {
// completeErr 表示失败终态写入错误。
if _, completeErr := s.orders().refreshJobs.Complete(context.Background(), job.ID, token, "failed", "{}", err.Error()); completeErr != nil && s.Logger != nil {
s.Logger.Warn("写入订单刷新失败终态失败", "job_id", job.ID, "err", completeErr)
}
return
}
// resultJSON、marshalErr 保存具名刷新结果 JSON 及序列化错误。
resultJSON, marshalErr := json.Marshal(result)
if marshalErr != nil {
_, _ = s.orders().refreshJobs.Complete(context.Background(), job.ID, token, "failed", "{}", marshalErr.Error())
return
}
// completeErr 表示成功终态写入错误。
if _, completeErr := s.orders().refreshJobs.Complete(context.Background(), job.ID, token, "succeeded", string(resultJSON), ""); completeErr != nil && s.Logger != nil {
s.Logger.Warn("写入订单刷新成功终态失败", "job_id", job.ID, "err", completeErr)
}
}
// RunOrderRefreshRecovery 扫描并重新执行租约过期的订单刷新任务。
func (s *Server) RunOrderRefreshRecovery(ctx context.Context) {
s.recoverOrderRefreshJobsOnce(ctx)
// ticker 保存恢复扫描间隔计时器。
ticker := time.NewTicker(time.Minute)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
s.recoverOrderRefreshJobsOnce(ctx)
}
}
}
// StartOrderRefreshRecovery 启动受 Server 生命周期管理的订单刷新恢复扫描器。
func (s *Server) StartOrderRefreshRecovery(ctx context.Context) {
s.startBackgroundTask("订单刷新恢复扫描器", func() {
s.RunOrderRefreshRecovery(ctx)
})
}
// recoverOrderRefreshJobsOnce 将过期任务重新入队并启动新的 worker。
func (s *Server) recoverOrderRefreshJobsOnce(ctx context.Context) {
// jobs、err 保存可恢复任务及扫描错误。
jobs, err := s.orders().refreshJobs.Recoverable(ctx, time.Now().Unix(), 20)
if err != nil {
if s.Logger != nil {
s.Logger.Warn("扫描订单刷新恢复任务失败", "err", err)
}
return
}
// job 表示当前待恢复的订单刷新任务。
for _, job := range jobs {
// requeued、requeueErr 保存重新入队结果及错误。
requeued, requeueErr := s.orders().refreshJobs.RequeueExpired(ctx, job.ID, time.Now().Unix())
if requeueErr != nil || !requeued {
continue
}
// token 保存恢复 worker 的新租约令牌。
token := randomHex(16)
// claimed、claimErr 保存恢复任务抢占结果及错误。
claimed, claimErr := s.orders().refreshJobs.Claim(ctx, job.ID, token, time.Now().Add(orderRefreshJobLease).Unix())
if claimErr == nil && claimed {
s.startOrderRefreshWorker(&job, token)
}
}
}
+82
View File
@@ -3,6 +3,7 @@ package server
import (
"context"
"database/sql"
"errors"
orderapp "xianyu-go/internal/application/orders"
"xianyu-go/internal/db"
)
@@ -234,6 +235,78 @@ func (r storeOrderRepository) ListOrdersByCookieCursor(ctx context.Context, cook
return orderRowsFromDB(rows), nil
}
// Create 创建订单刷新后台任务并同步应用层模型默认值。
func (r storeOrderRepository) Create(ctx context.Context, job *orderapp.RefreshJob) error {
// dbJob 保存待写入的数据库任务模型。
dbJob := &db.OrderRefreshJob{
ID: job.ID, UserID: job.UserID, CookieID: job.CookieID, FilterStatus: job.FilterStatus,
Status: job.Status, ResultJSON: job.ResultJSON, ErrorMessage: job.ErrorMessage,
WorkerToken: job.WorkerToken, LeaseExpiresAt: job.LeaseExpiresAt,
}
// err 表示数据库任务创建错误。
if err := r.store.OrderRefreshJobs.Create(ctx, dbJob); err != nil {
return err
}
job.Status, job.ResultJSON = dbJob.Status, dbJob.ResultJSON
return nil
}
// Get 按用户读取订单刷新后台任务并转换为应用层模型。
func (r storeOrderRepository) Get(ctx context.Context, userID int64, id string) (*orderapp.RefreshJob, error) {
// job、err 保存数据库任务读取结果及错误。
job, err := r.store.OrderRefreshJobs.Get(ctx, userID, id)
if errors.Is(err, db.ErrNotFound) {
return nil, orderapp.ErrRefreshJobNotFound
}
if err != nil {
return nil, err
}
return refreshJobFromDB(job), nil
}
// Claim 原子抢占订单刷新后台任务。
func (r storeOrderRepository) Claim(ctx context.Context, id, token string, leaseExpiresAt int64) (bool, error) {
return r.store.OrderRefreshJobs.Claim(ctx, id, token, leaseExpiresAt)
}
// Complete 以租约令牌安全写入订单刷新后台任务终态。
func (r storeOrderRepository) Complete(ctx context.Context, id, token, status, resultJSON, errorMessage string) (bool, error) {
return r.store.OrderRefreshJobs.Complete(ctx, id, token, status, resultJSON, errorMessage)
}
// Recoverable 查询租约过期的订单刷新后台任务。
func (r storeOrderRepository) Recoverable(ctx context.Context, now int64, limit int) ([]orderapp.RefreshJob, error) {
// jobs、err 保存数据库层可恢复任务及查询错误。
jobs, err := r.store.OrderRefreshJobs.Recoverable(ctx, now, limit)
if err != nil {
return nil, err
}
// converted 保存转换后的应用层任务列表。
converted := make([]orderapp.RefreshJob, 0, len(jobs))
for _, job := range jobs { // job 表示当前待转换的数据库任务。
converted = append(converted, *refreshJobFromDB(&job))
}
return converted, nil
}
// RequeueExpired 将过期订单刷新后台任务恢复为 queued。
func (r storeOrderRepository) RequeueExpired(ctx context.Context, id string, now int64) (bool, error) {
return r.store.OrderRefreshJobs.RequeueExpired(ctx, id, now)
}
// refreshJobFromDB 将数据库任务模型转换为应用层任务模型。
func refreshJobFromDB(job *db.OrderRefreshJob) *orderapp.RefreshJob {
if job == nil {
return nil
}
return &orderapp.RefreshJob{
ID: job.ID, UserID: job.UserID, CookieID: job.CookieID, FilterStatus: job.FilterStatus,
Status: job.Status, ResultJSON: job.ResultJSON, ErrorMessage: job.ErrorMessage,
WorkerToken: job.WorkerToken, LeaseExpiresAt: job.LeaseExpiresAt,
CreatedAt: job.CreatedAt, UpdatedAt: job.UpdatedAt,
}
}
// newStoreOrderRepository 从完整 Store 构造订单应用服务窄 repository。
func newStoreOrderRepository(store *db.Store) orderapp.Repository {
if store == nil || store.Cookies == nil || store.Orders == nil || store.Items == nil {
@@ -242,7 +315,16 @@ func newStoreOrderRepository(store *db.Store) orderapp.Repository {
return storeOrderRepository{store: store}
}
// newStoreOrderRefreshJobRepository 构造订单刷新任务持久化适配器。
func newStoreOrderRefreshJobRepository(store *db.Store) orderapp.RefreshJobRepository {
if store == nil || store.OrderRefreshJobs == nil {
return nil
}
return storeOrderRepository{store: store}
}
// 确保 Store 适配器始终覆盖订单应用服务所需的全部能力。
var _ orderapp.Repository = storeOrderRepository{}
var _ orderapp.UnitOfWork = storeOrderRepository{}
var _ orderapp.Writer = storeOrderWriter{}
var _ orderapp.RefreshJobRepository = storeOrderRepository{}
+2
View File
@@ -146,6 +146,8 @@ type orderApplicationService struct {
server orderRuntimePort
// repository 提供订单用例所需的应用层持久化与凭证锁 Port。
repository orderapp.Repository
// refreshJobs 提供订单刷新后台任务的持久化 Port。
refreshJobs orderapp.RefreshJobRepository
}
// orderRefreshWrite 保存已从平台成功获取、等待同一事务批量写入的订单详情。
@@ -124,15 +124,17 @@ func TestVersionedOrderRefreshAndBatchRoutesPreserveLegacyContracts(t *testing.T
// refreshRecorder 是捕获版本化刷新响应的记录器。
refreshRecorder := httptest.NewRecorder()
handler.ServeHTTP(refreshRecorder, refreshReq)
if refreshRecorder.Code != http.StatusOK {
if refreshRecorder.Code != http.StatusAccepted {
t.Fatalf("versioned order refresh status=%d body=%s", refreshRecorder.Code, refreshRecorder.Body.String())
}
// refreshValue 是版本化刷新响应 DTO。
var refreshValue orderRefreshResponse
// refreshDecodeErr 是刷新响应反序列化失败的原因。
if refreshDecodeErr := json.Unmarshal(refreshRecorder.Body.Bytes(), &refreshValue); refreshDecodeErr != nil {
// refreshStart 是版本化刷新任务创建响应 DTO。
var refreshStart orderRefreshJobStartResponse
// refreshDecodeErr 是刷新任务创建响应反序列化失败的原因。
if refreshDecodeErr := json.Unmarshal(refreshRecorder.Body.Bytes(), &refreshStart); refreshDecodeErr != nil {
t.Fatalf("decode versioned order refresh: %v", refreshDecodeErr)
}
// refreshValue 是版本化刷新任务完成后的具名结果。
refreshValue := waitOrderRefreshJob(t, handler, sessionCookie, refreshStart.JobID)
if refreshValue.Message == "" {
t.Fatalf("versioned order refresh should preserve a named success response: %+v", refreshValue)
}
@@ -143,9 +145,16 @@ func TestVersionedOrderRefreshAndBatchRoutesPreserveLegacyContracts(t *testing.T
// legacyRefreshRecorder 是捕获旧刷新响应的记录器。
legacyRefreshRecorder := httptest.NewRecorder()
handler.ServeHTTP(legacyRefreshRecorder, legacyRefreshReq)
if legacyRefreshRecorder.Code != http.StatusOK {
if legacyRefreshRecorder.Code != http.StatusAccepted {
t.Fatalf("legacy order refresh status=%d body=%s", legacyRefreshRecorder.Code, legacyRefreshRecorder.Body.String())
}
// legacyRefreshStart 是旧路径刷新任务创建响应 DTO。
var legacyRefreshStart orderRefreshJobStartResponse
// err 表示旧路径任务创建响应解析错误。
if err := json.Unmarshal(legacyRefreshRecorder.Body.Bytes(), &legacyRefreshStart); err != nil {
t.Fatalf("decode legacy order refresh: %v", err)
}
waitOrderRefreshJob(t, handler, sessionCookie, legacyRefreshStart.JobID)
// singleInsertErr 是单订单刷新夹具写入失败的原因。
_, singleInsertErr := store.DB.ExecContext(ctx, `INSERT INTO orders (order_id, item_id, buyer_id, order_status, cookie_id) VALUES ('order-single-v1','item-v1','buyer-v1','pending_ship','acc1')`)
+1 -1
View File
@@ -15,7 +15,7 @@ func (s *Server) mountVersionedOrders(r chi.Router) {
r.Get("/api/v1/orders/{order_id}", s.getOrder)
r.Put("/api/v1/orders/{order_id}", s.updateOrder)
r.Delete("/api/v1/orders/{order_id}", s.deleteOrder)
r.Post("/api/v1/orders/refresh", s.refreshOrders)
s.mountOrderRefreshJobRoutes(r, "/api/v1")
r.Post("/api/v1/orders/manual-ship", s.manualShipOrders)
r.Post("/api/v1/orders/import", s.importOrders)
r.Post("/api/v1/orders/{order_id}/refresh", s.refreshSingleOrder)
@@ -1,20 +1,20 @@
import{j as e,r,c as Is,b as Oe,d as ir}from"./react-vendor-C_od1ZSF.js";import{L as or,U as va,M as ys,C as Os,B as Na,S as _a,Z as js,a as Rt,b as Ps,G as Bs,c as Ts,d as Es,e as cr,f as wa,g as ut,A as Fs,D as dr,P as ka,h as Bt,E as Ca,T as xr,i as mr,j as _e,X as ke,k as ur,l as pr,m as Ds,n as Sa,o as lt,p as Ye,q as La,K as hr,r as bt,s as mt,Q as rs,t as yt,u as wt,v as $t,R as We,w as Ra,x as gr,y as Ze,z as St,F as Mt,H as nt,I as zs,J as kt,N as br,O as fr,V as yr,W as Aa,Y as Ia,_ as Oa,$ as jr,a0 as vr,a1 as ls,a2 as Wt,a3 as vs,a4 as Nr,a5 as _r,a6 as Ns,a7 as Us,a8 as wr,a9 as kr,aa as qt,ab as Ws,ac as Zt,ad as Pa,ae as Cr,af as Sr,ag as ss,ah as Ta,ai as Lr,aj as Rr,ak as Ar,al as Ir,am as Or,an as Pr,ao as Js}from"./icons-vendor-i_74xDZy.js";import{R as Yt,B as Tr,X as Gs,Y as Ks,T as Xt,a as Er,C as _s,A as Dr,b as $r,c as Mr,P as Vs,d as Qs,L as qr}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))l(n);new MutationObserver(n=>{for(const c of n)if(c.type==="childList")for(const u of c.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&l(u)}).observe(document,{childList:!0,subtree:!0});function a(n){const c={};return n.integrity&&(c.integrity=n.integrity),n.referrerPolicy&&(c.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?c.credentials="include":n.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function l(n){if(n.ep)return;n.ep=!0;const c=a(n);fetch(n.href,c)}})();const Br=({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"})})}),ws=({sizeClass:t="w-12 h-12",logoClassName:s="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23Line truncated
import{j as e,r,c as As,b as Oe,d as ir}from"./react-vendor-C_od1ZSF.js";import{L as or,U as va,M as ys,C as Os,B as Na,S as _a,Z as js,a as Rt,b as Ps,G as Bs,c as Ts,d as Es,e as cr,f as wa,g as ut,A as Fs,D as dr,P as ka,h as Bt,E as Ca,T as xr,i as mr,j as _e,X as ke,k as ur,l as pr,m as Ds,n as Sa,o as lt,p as Ye,q as La,K as hr,r as bt,s as mt,Q as rs,t as yt,u as wt,v as $t,R as We,w as Ra,x as gr,y as Ze,z as St,F as Mt,H as nt,I as zs,J as kt,N as br,O as fr,V as yr,W as Ia,Y as Aa,_ as Oa,$ as jr,a0 as vr,a1 as ls,a2 as Wt,a3 as vs,a4 as Nr,a5 as _r,a6 as Ns,a7 as Us,a8 as wr,a9 as kr,aa as qt,ab as Ws,ac as Zt,ad as Pa,ae as Cr,af as Sr,ag as ss,ah as Ta,ai as Lr,aj as Rr,ak as Ir,al as Ar,am as Or,an as Pr,ao as Js}from"./icons-vendor-i_74xDZy.js";import{R as Yt,B as Tr,X as Gs,Y as Ks,T as Xt,a as Er,C as _s,A as Dr,b as $r,c as Mr,P as Vs,d as Qs,L as qr}from"./charts-vendor-BxxJOyEX.js";import"./vendor-D-Edl3pr.js";(function(){const s=document.createElement("link").relList;if(s&&s.supports&&s.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))l(n);new MutationObserver(n=>{for(const c of n)if(c.type==="childList")for(const u of c.addedNodes)u.tagName==="LINK"&&u.rel==="modulepreload"&&l(u)}).observe(document,{childList:!0,subtree:!0});function a(n){const c={};return n.integrity&&(c.integrity=n.integrity),n.referrerPolicy&&(c.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?c.credentials="include":n.crossOrigin==="anonymous"?c.credentials="omit":c.credentials="same-origin",c}function l(n){if(n.ep)return;n.ep=!0;const c=a(n);fetch(n.href,c)}})();const Br=({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"})})}),ws=({sizeClass:t="w-12 h-12",logoClassName:s="w-full h-full text-white"})=>e.jsxs("div",{className:"relative z-10 flex items-center justify-center",children:[e.jsx("div",{className:"absolute -inset-1 bg-blue-500/20 rounded-xl blur opacity-25"}),e.jsxs("div",{className:`relative ${t} rounded-xl flex items-center justify-center group-hover:scale-105 transition-transform duration-300`,children:[e.jsxs("svg",{className:"absolute inset-0 w-full h-full",viewBox:"0 0 120 120","aria-hidden":"true",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"login-squircle-gradient",x1:"0",y1:"0",x2:"1",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(var(--color-brand))"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(var(--color-brand-light))"})]})}),e.jsx("path",{d:"M 114.00 60.00 L 113.83 71.48 L 113.31 78.16 L 112.44 83.67 L 111.22 88.46 L 109.66 92.71 L 107.75 96.49 L 105.48 99.87 L 102.86 102.86 L 99.87 105.48 L 96.49 107.75 L 92.71 109.66 L 88.46 111.22 L 83.67 112.44 L 78.16 113.31 L 71.48 113.83 L 60.00 114.00 L 48.52 113.83 L 41.84 113.31 L 36.33 112.44 L 31.54 111.22 L 27.29 109.66 L 23.51 107.75 L 20.13 105.48 L 17.14 102.86 L 14.52 99.87 L 12.25 96.49 L 10.34 92.71 L 8.78 88.46 L 7.56 83.67 L 6.69 78.16 L 6.17 71.48 L 6.00 60.00 L 6.17 48.52 L 6.69 41.84 L 7.56 36.33 L 8.78 31.54 L 10.34 27.29 L 12.25 23.51 L 14.52 20.13 L 17.14 17.14 L 20.13 14.52 L 23Line truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(Ps,{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:g,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:V,children:"取消"}),e.jsxs("button",{onClick:de,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:V,children:[V?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(lt,{className:"w-4 h-4"}),V?"保存中...":"保存"]})]})})]})}),document.body)]})},Un=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],Wn=t=>{const s=typeof t=="object"&&t!==null?t:{},a=Array.isArray(s.results)?s.results:[];return{total:Number(s.total||0),success_count:Number(s.success_count||0),failed_count:Number(s.failed_count||0),results:a.map(Jn)}},Jn=t=>{const s=typeof t=="object"&&t!==null?t:{};return{order_id:String(s.order_id||"unknown"),success:s.success===!0,message:String(s.message||"")}},Gn=t=>(t==null?void 0:t.results.filter(Kn))||[],Kn=t=>!t.success,Vn=(t,s)=>t!==null&&!s,Qn=t=>{if(!t)return"请选择订单文件";const s=t.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(s)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},ft=(t,s)=>t===s,Hn=(t,s)=>t instanceof Error&&t.message?t.message:s,Zn=({filter:t,onFilterChange:s,accountFilter:a,onAccountFilterChange:l,accounts:n,accountName:c,searchText:u,onSearchChange:h})=>{const m=p=>s(p.currentTarget.dataset.status||"all"),j=p=>l(p.target.value),x=p=>h(p.target.value);return e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:Un.map(p=>e.jsx("button",{"data-status":p.key,onClick:m,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${t===p.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:p.label},p.key))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(yt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:a,onChange:j,className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),n.map(p=>e.jsx("option",{value:p.id,children:c(p.id)},p.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(St,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:u,onChange:x,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Yn=t=>{const s=c=>{var u;t.setImportFile(((u=c.target.files)==null?void 0:u[0])||null)},a=()=>t.closeImportModal(),l=()=>void t.handleImportOrders(),n=()=>void t.handleRetryImport();return t.showImportModal?Oe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:a,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(ke,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:s,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx 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(Ps,{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:g,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:V,children:"取消"}),e.jsxs("button",{onClick:de,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:V,children:[V?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(lt,{className:"w-4 h-4"}),V?"保存中...":"保存"]})]})})]})}),document.body)]})},Un=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],Wn=t=>{const s=typeof t=="object"&&t!==null?t:{},a=Array.isArray(s.results)?s.results:[];return{total:Number(s.total||0),success_count:Number(s.success_count||0),failed_count:Number(s.failed_count||0),results:a.map(Jn)}},Jn=t=>{const s=typeof t=="object"&&t!==null?t:{};return{order_id:String(s.order_id||"unknown"),success:s.success===!0,message:String(s.message||"")}},Gn=t=>(t==null?void 0:t.results.filter(Kn))||[],Kn=t=>!t.success,Vn=(t,s)=>t!==null&&!s,Qn=t=>{if(!t)return"请选择订单文件";const s=t.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(s)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},ft=(t,s)=>t===s,Hn=(t,s)=>t instanceof Error&&t.message?t.message:s,Zn=({filter:t,onFilterChange:s,accountFilter:a,onAccountFilterChange:l,accounts:n,accountName:c,searchText:u,onSearchChange:p})=>{const m=h=>s(h.currentTarget.dataset.status||"all"),f=h=>l(h.target.value),x=h=>p(h.target.value);return e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:Un.map(h=>e.jsx("button",{"data-status":h.key,onClick:m,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${t===h.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:h.label},h.key))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(yt,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:a,onChange:f,className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),n.map(h=>e.jsx("option",{value:h.id,children:c(h.id)},h.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(St,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:u,onChange:x,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Yn=t=>{const s=c=>{var u;t.setImportFile(((u=c.target.files)==null?void 0:u[0])||null)},a=()=>t.closeImportModal(),l=()=>void t.handleImportOrders(),n=()=>void t.handleRetryImport();return t.showImportModal?Oe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:a,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(ke,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:s,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx Line truncated
VIP-002
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["预览:",a.appendPreview.length," 个有效卡密,空行自动忽略。"]})]}),a.appendError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-200 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.appendError}),e.jsx("button",{type:"button",onClick:x,disabled:a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),a.appendResult&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",a.appendResult.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:u,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),a.batchTab==="create"?e.jsxs("button",{onClick:S,disabled:!a.batchFile||a.batchBusy,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(Mt,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:q,disabled:!a.appendTargetId||a.appendPreview.length===0||a.batchBusy||t.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(nt,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},ai=({type:t})=>{switch(t){case"text":return e.jsx(Ia,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(Aa,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(yr,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(Os,{className:"w-5 h-5 text-gray-500"})}},ri=(t,s,a)=>{const l=a.trim().toLocaleLowerCase();return t.filter(n=>(!s||n.type===s)&&(!l||n.name.toLocaleLowerCase().includes(l)))},Qa=t=>t.split(`
`).map(s=>s.trim()).filter(Boolean),li=(t,s,a)=>!!(t&&Qa(s).length>0&&!a),Nt=(t,s,a,l)=>t===s&&a===l,ni=()=>{const[t,s]=r.useState([]),[a,l]=r.useState(!0),n=r.useRef(0),c=r.useRef(null),u=r.useCallback(async()=>{var j;const h=++n.current;(j=c.current)==null||j.abort();const m=new AbortController;c.current=m,l(!0);try{const x=await Ms({signal:m.signal});if(h!==n.current)return;s(x)}catch(x){h===n.current&&!m.signal.aborted&&console.error("加载卡密库存失败:",x)}finally{h===n.current&&l(!1)}},[]);return r.useEffect(()=>(u(),()=>{var m;n.current+=1,(m=c.current)==null||m.abort()}),[u]),{cards:t,setCards:s,loading:a,loadCards:u}},ii=t=>{const s=t.dataCards,a=t.loadCards,[l,n]=r.useState(!1),[c,u]=r.useState("create"),[h,m]=r.useState(null),[j,x]=r.useState(null),[p,_]=r.useState(!1),[S,q]=r.useState(""),[w,O]=r.useState(""),[P,G]=r.useState(null),[H,X]=r.useState(""),f=r.useRef(0),y=r.useRef(null),z=r.useRef(""),I=r.useMemo(()=>Qa(w),[w]),F=r.useCallback(()=>{var k;u("create"),m(null),x(null),q((k=s[0])!=null&&k.id?String(s[0].id):""),O(""),G(null),X(""),n(!0)},[s]),d=r.useCallback(()=>{var k;f.current+=1,(k=y.current)==null||k.abort(),_(!1),n(!1)},[]),B=r.useCallback(async()=>{var C;if(!h||p)return;const k=++f.current;(C=y.current)==null||C.abort();const D=new AbortController;y.current=D,_(!0),x(null);try{const W=await Ll(h,{signal:D.signal});if(!Nt(k,f.current,"",""))return;x(W),W.created>0&&await a()}catch(W){if(!Nt(k,f.current,"",""))return;x({error:(W==null?void 0:W.message)||"上传失败"})}finally{Nt(k,f.current,"","")&&_(!1)}},[p,h,a]),Z=r.useCallback(async()=>{var W;if(!li(S,w,p))return;const k=S,D=++f.current;z.current=k,(W=y.current)==null||W.abort();const C=new AbortController;y.current=C,_(!0),G(null),X("");try{const K=await Rl(k,w,{signal:C.signal});if(!Nt(D,f.current,k,S))return;G({added:K.added}),O(""),await a()}catch(K){if(!Nt(D,f.current,k,S))return;X((K==null?void 0:K.message)||"追加失败")}finally{Nt(D,f.current,k,S)&&_(!1)}},[w,S,p,a]),M=r.useCallback(async()=>{await B()},[B]),b=r.useCallback(async()=>{z.current&&S!==z.current||await Z()},[S,Z]);return{showBatchModal:l,setShowBatchModal:n,batchTab:c,setBatchTab:u,batchFile:h,setBatchFile:m,batchResult:j,batchBusy:p,appendTargetId:S,setAppendTargetId:q,appendContent:w,setAppendContent:O,appendResult:P,appendError:H,appendPreview:I,openBatchModal:F,closeBatchModal:d,handleBatchCreate:B,handleBatchAppend:Z,handleRetryBatchCreate:M,handleRetryBatchAppend:b}},xa=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),oi=()=>{const{cards:t,loadCards:s}=ni(),[a,l]=r.useState(!1),[n,c]=r.useState(!1),[u,h]=r.useState(null),[m,j]=r.useState({}),[x,p]=r.useState(xa),[_,S]=r.useState(""),[q,w]=r.useState(""),O=r.useMemo(()=>t.filter(d=>d.type==="data"),[t]),P=ii({dataCards:O,loadCards:s}),G=d=>{var B,Z,M,b,k;h(d),j({id:d.id,name:d.name||"",type:d.type||"text",api_url:((B=d.api_config)==null?void 0:B.url)||"",api_method:((Z=d.api_config)==null?void 0:Z.method)||"GET",api_timeout:((M=d.api_config)==null?void 0:M.timeout)||10,api_headers:((b=d.api_config)==null?void 0:b.headers)||"",api_params:((k=d.api_config)==null?void 0:k.params)||"",text_content:d.text_content||"",data_content:d.data_content||"",image_url:d.image_url||"",delay_seconds:d.delay_seconds||0,description:d.description||"",enabled:d.enabled}),l(!0)},H=async()=>{var d,B,Z,M,b,k,D,C;if(u){if(!((d=m.name)!=null&&d.trim())){alert("请输入卡密名称");return}if(!m.type){alert("请选择卡密类型");return}try{const W={name:m.name.trim(),type:m.type,description:(B=m.description)==null?void 0:B.trim(),delay_seconds:m.delay_seconds||0,enabled:m.enabled??!0};m.type==="api"?W.api_config={url:((Z=m.api_url)==null?void 0:Z.trim())||"",method:m.api_method,timeout:m.api_timeout||10,headers:((M=m.api_headers)==null?void 0:M.trim())||void 0,params:((b=m.api_params)==null?void 0:b.trim())||void 0}:m.type==="text"?W.text_content=((k=m.text_content)==null?void 0:k.trim())||"":m.type==="data"?W.data_content=((D=m.data_content)==null?void 0:D.trim())||"":m.type==="image"&&(W.image_url=((C=m.image_url)==null?void 0:C.trim())||""),await ta(u.id,W),l(!1),await s()}catch(W){console.error("更新卡密失败:",W),alert("更新失败,请重试")}}},X=async d=>{if(confirm("确认删除该卡密吗?"))try{await Sl(d),await s()}catch(B){console.error("删除卡密失败:",B),alert("删除失败,请重试")}},f=async()=>{if(!x.name.trim()){alert("请输入卡密名称");return}if(!x.content.trim()){alert(x.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const d={name:x.name.trim(),type:x.type,description:x.description.trim(),enabled:x.enabled,delay_seconds:x.delay_seconds};x.type==="text"&&(d.text_content=x.content.trim()),x.type==="data"&&(d.data_content=x.content.trim()),x.type==="image"&&(d.image_url=x.content.trim()),x.type==="api"&&(d.api_config={url:x.content.trim(),method:x.api_me Line truncated
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["预览:",a.appendPreview.length," 个有效卡密,空行自动忽略。"]})]}),a.appendError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-200 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.appendError}),e.jsx("button",{type:"button",onClick:x,disabled:a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),a.appendResult&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",a.appendResult.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:u,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),a.batchTab==="create"?e.jsxs("button",{onClick:S,disabled:!a.batchFile||a.batchBusy,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(Mt,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:q,disabled:!a.appendTargetId||a.appendPreview.length===0||a.batchBusy||t.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(_e,{className:"w-4 h-4 animate-spin"}):e.jsx(nt,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},ai=({type:t})=>{switch(t){case"text":return e.jsx(Aa,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(Ia,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(yr,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(Os,{className:"w-5 h-5 text-gray-500"})}},ri=(t,s,a)=>{const l=a.trim().toLocaleLowerCase();return t.filter(n=>(!s||n.type===s)&&(!l||n.name.toLocaleLowerCase().includes(l)))},Qa=t=>t.split(`
`).map(s=>s.trim()).filter(Boolean),li=(t,s,a)=>!!(t&&Qa(s).length>0&&!a),Nt=(t,s,a,l)=>t===s&&a===l,ni=()=>{const[t,s]=r.useState([]),[a,l]=r.useState(!0),n=r.useRef(0),c=r.useRef(null),u=r.useCallback(async()=>{var f;const p=++n.current;(f=c.current)==null||f.abort();const m=new AbortController;c.current=m,l(!0);try{const x=await Ms({signal:m.signal});if(p!==n.current)return;s(x)}catch(x){p===n.current&&!m.signal.aborted&&console.error("加载卡密库存失败:",x)}finally{p===n.current&&l(!1)}},[]);return r.useEffect(()=>(u(),()=>{var m;n.current+=1,(m=c.current)==null||m.abort()}),[u]),{cards:t,setCards:s,loading:a,loadCards:u}},ii=t=>{const s=t.dataCards,a=t.loadCards,[l,n]=r.useState(!1),[c,u]=r.useState("create"),[p,m]=r.useState(null),[f,x]=r.useState(null),[h,_]=r.useState(!1),[S,q]=r.useState(""),[w,O]=r.useState(""),[P,G]=r.useState(null),[H,X]=r.useState(""),y=r.useRef(0),j=r.useRef(null),z=r.useRef(""),A=r.useMemo(()=>Qa(w),[w]),F=r.useCallback(()=>{var k;u("create"),m(null),x(null),q((k=s[0])!=null&&k.id?String(s[0].id):""),O(""),G(null),X(""),n(!0)},[s]),d=r.useCallback(()=>{var k;y.current+=1,(k=j.current)==null||k.abort(),_(!1),n(!1)},[]),B=r.useCallback(async()=>{var C;if(!p||h)return;const k=++y.current;(C=j.current)==null||C.abort();const D=new AbortController;j.current=D,_(!0),x(null);try{const W=await Ll(p,{signal:D.signal});if(!Nt(k,y.current,"",""))return;x(W),W.created>0&&await a()}catch(W){if(!Nt(k,y.current,"",""))return;x({error:(W==null?void 0:W.message)||"上传失败"})}finally{Nt(k,y.current,"","")&&_(!1)}},[h,p,a]),Z=r.useCallback(async()=>{var W;if(!li(S,w,h))return;const k=S,D=++y.current;z.current=k,(W=j.current)==null||W.abort();const C=new AbortController;j.current=C,_(!0),G(null),X("");try{const K=await Rl(k,w,{signal:C.signal});if(!Nt(D,y.current,k,S))return;G({added:K.added}),O(""),await a()}catch(K){if(!Nt(D,y.current,k,S))return;X((K==null?void 0:K.message)||"追加失败")}finally{Nt(D,y.current,k,S)&&_(!1)}},[w,S,h,a]),M=r.useCallback(async()=>{await B()},[B]),b=r.useCallback(async()=>{z.current&&S!==z.current||await Z()},[S,Z]);return{showBatchModal:l,setShowBatchModal:n,batchTab:c,setBatchTab:u,batchFile:p,setBatchFile:m,batchResult:f,batchBusy:h,appendTargetId:S,setAppendTargetId:q,appendContent:w,setAppendContent:O,appendResult:P,appendError:H,appendPreview:A,openBatchModal:F,closeBatchModal:d,handleBatchCreate:B,handleBatchAppend:Z,handleRetryBatchCreate:M,handleRetryBatchAppend:b}},xa=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),oi=()=>{const{cards:t,loadCards:s}=ni(),[a,l]=r.useState(!1),[n,c]=r.useState(!1),[u,p]=r.useState(null),[m,f]=r.useState({}),[x,h]=r.useState(xa),[_,S]=r.useState(""),[q,w]=r.useState(""),O=r.useMemo(()=>t.filter(d=>d.type==="data"),[t]),P=ii({dataCards:O,loadCards:s}),G=d=>{var B,Z,M,b,k;p(d),f({id:d.id,name:d.name||"",type:d.type||"text",api_url:((B=d.api_config)==null?void 0:B.url)||"",api_method:((Z=d.api_config)==null?void 0:Z.method)||"GET",api_timeout:((M=d.api_config)==null?void 0:M.timeout)||10,api_headers:((b=d.api_config)==null?void 0:b.headers)||"",api_params:((k=d.api_config)==null?void 0:k.params)||"",text_content:d.text_content||"",data_content:d.data_content||"",image_url:d.image_url||"",delay_seconds:d.delay_seconds||0,description:d.description||"",enabled:d.enabled}),l(!0)},H=async()=>{var d,B,Z,M,b,k,D,C;if(u){if(!((d=m.name)!=null&&d.trim())){alert("请输入卡密名称");return}if(!m.type){alert("请选择卡密类型");return}try{const W={name:m.name.trim(),type:m.type,description:(B=m.description)==null?void 0:B.trim(),delay_seconds:m.delay_seconds||0,enabled:m.enabled??!0};m.type==="api"?W.api_config={url:((Z=m.api_url)==null?void 0:Z.trim())||"",method:m.api_method,timeout:m.api_timeout||10,headers:((M=m.api_headers)==null?void 0:M.trim())||void 0,params:((b=m.api_params)==null?void 0:b.trim())||void 0}:m.type==="text"?W.text_content=((k=m.text_content)==null?void 0:k.trim())||"":m.type==="data"?W.data_content=((D=m.data_content)==null?void 0:D.trim())||"":m.type==="image"&&(W.image_url=((C=m.image_url)==null?void 0:C.trim())||""),await ta(u.id,W),l(!1),await s()}catch(W){console.error("更新卡密失败:",W),alert("更新失败,请重试")}}},X=async d=>{if(confirm("确认删除该卡密吗?"))try{await Sl(d),await s()}catch(B){console.error("删除卡密失败:",B),alert("删除失败,请重试")}},y=async()=>{if(!x.name.trim()){alert("请输入卡密名称");return}if(!x.content.trim()){alert(x.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const d={name:x.name.trim(),type:x.type,description:x.description.trim(),enabled:x.enabled,delay_seconds:x.delay_seconds};x.type==="text"&&(d.text_content=x.content.trim()),x.type==="data"&&(d.data_content=x.content.trim()),x.type==="image"&&(d.image_url=x.content.trim()),x.type==="api"&&(d.api_config={url:x.content.trim(),method:x.api_me Line truncated
VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(D=>D.map(C=>`"${String(C).replace(/"/g,'""')}"`).join(",")).join(`
`),M=new Blob(["\uFEFF"+Z],{type:"text/csv;charset=utf-8"}),b=URL.createObjectURL(M),k=document.createElement("a");k.href=b,k.download="卡密组批量导入模板.csv",document.body.appendChild(k),k.click(),k.remove(),URL.revokeObjectURL(b)};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:P.openBatchModal,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(Mt,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:(()=>c(!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(nt,{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(Oa,{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:_,onChange:(d=>S(d.target.value)),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(St,{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:q,onChange:(d=>w(d.target.value)),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",I.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:I.map(d=>{let B="";return d.type==="data"&&d.data_content?B=`库存: ${d.data_content.split(`
`).filter(M=>M.trim()).length} 条`:d.type==="text"&&d.text_content?B=d.text_content:d.type==="api"&&d.api_config?B=d.api_config.url:d.type==="image"&&d.image_url&&(B="图片链接"),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(ai,{type:d.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:d.name,children:d.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:(()=>z(d.id)),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:d.id}),e.jsx(jr,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${d.type==="text"?"bg-blue-50 text-blue-600":d.type==="data"?"bg-purple-50 text-purple-600":d.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:d.type==="text"?"文本":d.type==="data"?"批量":d.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:B,children:B})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:d.description||"-",children:d.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:(()=>y(d)),className:`w-12 h-8 rounded-full relative transition-colors ${d.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${d.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:(()=>G(d)),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(kt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>X(d.id)),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Ze,{className:"h-4 w-4"})})]})})]},d.id)})})]})}),I.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(ka,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),a&&u&&Oe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:(()=>l(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(ke,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:m.name||"",onChange:(d=>j({...m,name:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:m.type||"text",onChange:(d=>j({...m,type:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(u==null?void 0:u.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),m.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:m.api_url||"",onChange:(d=>j({...m,api_url:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",Line truncated
`),M=new Blob(["\uFEFF"+Z],{type:"text/csv;charset=utf-8"}),b=URL.createObjectURL(M),k=document.createElement("a");k.href=b,k.download="卡密组批量导入模板.csv",document.body.appendChild(k),k.click(),k.remove(),URL.revokeObjectURL(b)};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:P.openBatchModal,className:"px-4 py-3 bg-gray-100 hover:bg-gray-200 rounded-2xl font-bold text-gray-700 flex items-center gap-2 transition-colors",children:[e.jsx(Mt,{className:"w-5 h-5"}),"批量导入"]}),e.jsxs("button",{onClick:(()=>c(!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(nt,{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(Oa,{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:_,onChange:(d=>S(d.target.value)),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-9 text-sm shadow-sm",children:[e.jsx("option",{value:"",children:"全部类型"}),e.jsx("option",{value:"data",children:"批量卡密"}),e.jsx("option",{value:"text",children:"文本"}),e.jsx("option",{value:"api",children:"API"}),e.jsx("option",{value:"image",children:"图片"})]})]}),e.jsxs("div",{className:"relative w-full sm:max-w-sm",children:[e.jsx(St,{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:q,onChange:(d=>w(d.target.value)),className:"ios-input w-full rounded-xl border-none bg-white py-2.5 pl-10 pr-4 text-sm shadow-sm"})]})]}),e.jsxs("div",{className:"whitespace-nowrap px-1 text-xs font-bold text-gray-400",children:["显示 ",A.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:A.map(d=>{let B="";return d.type==="data"&&d.data_content?B=`库存: ${d.data_content.split(`
`).filter(M=>M.trim()).length} 条`:d.type==="text"&&d.text_content?B=d.text_content:d.type==="api"&&d.api_config?B=d.api_config.url:d.type==="image"&&d.image_url&&(B="图片链接"),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(ai,{type:d.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:d.name,children:d.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:(()=>z(d.id)),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:d.id}),e.jsx(jr,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${d.type==="text"?"bg-blue-50 text-blue-600":d.type==="data"?"bg-purple-50 text-purple-600":d.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:d.type==="text"?"文本":d.type==="data"?"批量":d.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:B,children:B})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:d.description||"-",children:d.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:(()=>j(d)),className:`w-12 h-8 rounded-full relative transition-colors ${d.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${d.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:(()=>G(d)),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(kt,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>X(d.id)),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(Ze,{className:"h-4 w-4"})})]})})]},d.id)})})]})}),A.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(ka,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:t.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),a&&u&&Oe.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:(()=>l(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(ke,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:m.name||"",onChange:(d=>f({...m,name:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:m.type||"text",onChange:(d=>f({...m,type:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(u==null?void 0:u.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),m.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:m.api_url||"",onChange:(d=>f({...m,api_url:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://api.example.com/get-card"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",Line truncated
卡号1:密码1
卡号2:密码2
或者
兑换码1
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:m.data_content?m.data_content.split(`
`).filter(d=>d.trim()).length:0})," 条"]})]})]}),m.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:m.image_url||"",onChange:(d=>j({...m,image_url:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),m.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:m.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:(d=>{d.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"})})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:m.delay_seconds||0,onChange:(d=>j({...m,delay_seconds:parseInt(d.target.value)||0})),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:m.description||"",onChange:(d=>j({...m,description:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:(()=>j({...m,enabled:!m.enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${m.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${m.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>l(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:H,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),n&&Oe.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:(()=>c(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(ke,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:x.name,onChange:(d=>p({...x,name:d.target.value})),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:(()=>p({...x,type:"data",content:""})),className:`p-3 rounded-xl font-bold transition-all ${x.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(Os,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:(()=>p({...x,type:"text",content:""})),className:`p-3 rounded-xl font-bold transition-all ${x.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Ia,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:(()=>p({...x,type:"image",content:""})),className:`p-3 rounded-xl font-bold transition-all ${x.type==="image"?"bg-brand text-white":"bg-gray-100 textLine truncated
`).filter(d=>d.trim()).length:0})," 条"]})]})]}),m.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:m.image_url||"",onChange:(d=>f({...m,image_url:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"输入图片卡密的 URL 地址"})]}),m.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:m.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:(d=>{d.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"})})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:m.delay_seconds||0,onChange:(d=>f({...m,delay_seconds:parseInt(d.target.value)||0})),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:m.description||"",onChange:(d=>f({...m,description:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:(()=>f({...m,enabled:!m.enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${m.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${m.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>l(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:H,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(lt,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),n&&Oe.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:(()=>c(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(ke,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:x.name,onChange:(d=>h({...x,name:d.target.value})),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:(()=>h({...x,type:"data",content:""})),className:`p-3 rounded-xl font-bold transition-all ${x.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(Os,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:(()=>h({...x,type:"text",content:""})),className:`p-3 rounded-xl font-bold transition-all ${x.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Aa,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:(()=>h({...x,type:"image",content:""})),className:`p-3 rounded-xl font-bold transition-all ${x.type==="image"?"bg-brand text-white":"bg-gray-100 textLine truncated
CODE-789012
...`:"请输入每次发货时发送的固定文字"}),x.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:x.content.split(`
`).filter(d=>d.trim()).length})," 条"]})]}),x.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:x.api_method,onChange:(d=>p({...x,api_method:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:x.api_timeout,onChange:(d=>p({...x,api_timeout:parseInt(d.target.value)||10})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:x.api_headers,onChange:(d=>p({...x,api_headers:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:x.api_params,onChange:(d=>p({...x,api_params:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:x.description,onChange:(d=>p({...x,description:d.target.value})),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:x.delay_seconds,onChange:(d=>p({...x,delay_seconds:parseInt(d.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>c(!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:f,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(nt,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(si,{dataCards:O,downloadCardTemplate:F,...P})]})},ma="ydisks-amap-js-api",ci="c9b68d4ce9a2a97f22a4a439404488ca";let Ot=null;const di=()=>ci,xi=()=>window.AMap?Promise.resolve(window.AMap):Ot||(Ot=new Promise((t,s)=>{const a=document.getElementById(ma),l=a||document.createElement("script"),n=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(u)},c=()=>{window.AMap?(n(),t(window.AMap)):(n(),s(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},u=window.setTimeout(()=>{n(),s(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=c,l.id=ma,l.async=!0,l.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(di())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,l.onerror=()=>{n(),s(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},a||document.head.appendChild(l)}).catch(t=>{throw Ot=null,t}),Ot),ts=t=>Number.isFinite(t)&&t!==0,mi=t=>{var n,c;const s=Number((n=t.location)==null?void 0:n.lng),a=Number((c=t.location)==null?void 0:c.lat),l={area:String(t.adname||"").trim(),city:String(t.cityname||"").trim(),division_id:String(t.adcode||"").trim(),longitude:s,latitude:a,poi_id:String(t.id||"").trim(),poi_name:String(t.name||"").trim(),province:String(t.pname||"").trim()};return!l.division_id||!l.province||!l.city||!l.poi_id||!l.poi_name||!ts(s)||!ts(a)||s<-180||s>180||a<-90||a>90?null:l},ui=async(t,s)=>{if(!ts(t)||!ts(s)||t<-180||t>180||s<-90||s>90)throw new Error("经纬度无效");const a=await xi();return new Promise((l,n)=>{new a.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[t,s],1e3,(u,h)=>{var j;if(u!=="complete"){if(u==="no_data"){l([]);return}n(new Error("高德地图附近地址查询失败,请稍后重试"));return}const m=(((j=h==null?void 0:h.poiList)==null?void 0:j.pois)||[]).map(mi).filter(x=>x!==null);l(m)})})},pi=t=>t.find(s=>s.status==="running"||s.status==="canceling"),Rs=t=>t==="running"||t==="canceling",hi=t=>!!(t! Line truncated
`),Le=new Blob(["\uFEFF"+xe],{type:"text/csv;charset=utf-8"}),st=URL.createObjectURL(Le),Qe=document.createElement("a");Qe.href=st,Qe.download="批量铺货模板.csv",document.body.appendChild(Qe),Qe.click(),Qe.remove(),URL.revokeObjectURL(st)},E=()=>{D(o=>({...o,cookie_id:h||o.cookie_id})),G(!0)},ae=()=>{W(o=>({...o,cookie_id:h||o.cookie_id})),X(!0)},ce=async o=>{if(!(o?h:C.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");y(!0),navigator.geolocation.getCurrentPosition(async xe=>{try{const Le=await ui(xe.coords.longitude,xe.coords.latitude);if(!Le.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");o?(Ue(Le),Me(Le[0])):(I(Le),d(Le[0]))}catch(Le){alert((Le==null?void 0:Le.message)||"获取发货地失败")}finally{y(!1)}},xe=>{y(!1),alert(xe.code===xe.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},fe=o=>l.filter(Q=>Q.cookie_id===o.cookie_id&&Q.item_id===o.item_id).length>0?l.filter(Q=>Q.cookie_id===o.cookie_id&&Q.item_id===o.item_id):l.filter(Q=>Q.cookie_id===o.cookie_id&&!Q.item_id),De=r.useMemo(()=>new Map(c.map(o=>[o.id,o])),[c]),Ne=r.useMemo(()=>j?s.filter(o=>o.cookie_id===j):s,[j,s]),Pe=o=>{const Q=De.get(o),xe=(Q==null?void 0:Q.remark)||(Q==null?void 0:Q.nickname);return xe?`${xe} · ${o.slice(0,6)}`:`账号 ${o.slice(0,8)}`},me=o=>{const Q=De.get(o);return(Q==null?void 0:Q.remark)||(Q==null?void 0:Q.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(vr,{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:j,onChange:(o=>x(o.target.value)),children:[e.jsx("option",{value:"",children:"全部账号"}),c.map(o=>e.jsx("option",{value:o.id,children:Pe(o.id)},o.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(yt,{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:h,onChange:(o=>m(o.target.value)),children:[e.jsx("option",{value:"",children:"请选择账号"}),c.map(o=>e.jsx("option",{value:o.id,children:Pe(o.id)},o.id))]})]})]}),e.jsxs("button",{onClick:Ge,disabled:p||!h,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(We,{className:`w-4 h-4 ${p?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:E,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(nt,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:ae,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(ls,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:(()=>void Be()),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-brand-highlight transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(Wt,{className:"w-4 h-4"}),de&&["running","canceling"].includes(de.status)?"继续批量任务":"批量铺货"]}),de&&!["running","canceling"].includes(de.status)&&e.jsx("button",{onClick:(()=>void He()),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[Ne.map(o=>{const Q=fe(o),xe=Q.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative f Line truncated
`).filter(d=>d.trim()).length})," 条"]})]}),x.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:x.api_method,onChange:(d=>h({...x,api_method:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:x.api_timeout,onChange:(d=>h({...x,api_timeout:parseInt(d.target.value)||10})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:x.api_headers,onChange:(d=>h({...x,api_headers:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:x.api_params,onChange:(d=>h({...x,api_params:d.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:x.description,onChange:(d=>h({...x,description:d.target.value})),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:x.delay_seconds,onChange:(d=>h({...x,delay_seconds:parseInt(d.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>c(!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:y,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(nt,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(si,{dataCards:O,downloadCardTemplate:F,...P})]})},ma="ydisks-amap-js-api",ci="c9b68d4ce9a2a97f22a4a439404488ca";let Ot=null;const di=()=>ci,xi=()=>window.AMap?Promise.resolve(window.AMap):Ot||(Ot=new Promise((t,s)=>{const a=document.getElementById(ma),l=a||document.createElement("script"),n=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(u)},c=()=>{window.AMap?(n(),t(window.AMap)):(n(),s(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},u=window.setTimeout(()=>{n(),s(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=c,l.id=ma,l.async=!0,l.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(di())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,l.onerror=()=>{n(),s(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},a||document.head.appendChild(l)}).catch(t=>{throw Ot=null,t}),Ot),ts=t=>Number.isFinite(t)&&t!==0,mi=t=>{var n,c;const s=Number((n=t.location)==null?void 0:n.lng),a=Number((c=t.location)==null?void 0:c.lat),l={area:String(t.adname||"").trim(),city:String(t.cityname||"").trim(),division_id:String(t.adcode||"").trim(),longitude:s,latitude:a,poi_id:String(t.id||"").trim(),poi_name:String(t.name||"").trim(),province:String(t.pname||"").trim()};return!l.division_id||!l.province||!l.city||!l.poi_id||!l.poi_name||!ts(s)||!ts(a)||s<-180||s>180||a<-90||a>90?null:l},ui=async(t,s)=>{if(!ts(t)||!ts(s)||t<-180||t>180||s<-90||s>90)throw new Error("经纬度无效");const a=await xi();return new Promise((l,n)=>{new a.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[t,s],1e3,(u,p)=>{var f;if(u!=="complete"){if(u==="no_data"){l([]);return}n(new Error("高德地图附近地址查询失败,请稍后重试"));return}const m=(((f=p==null?void 0:p.poiList)==null?void 0:f.pois)||[]).map(mi).filter(x=>x!==null);l(m)})})},pi=t=>t.find(s=>s.status==="running"||s.status==="canceling"),Rs=t=>t==="running"||t==="canceling",hi=t=>!!(t! Line truncated
`),Le=new Blob(["\uFEFF"+xe],{type:"text/csv;charset=utf-8"}),st=URL.createObjectURL(Le),Qe=document.createElement("a");Qe.href=st,Qe.download="批量铺货模板.csv",document.body.appendChild(Qe),Qe.click(),Qe.remove(),URL.revokeObjectURL(st)},E=()=>{D(o=>({...o,cookie_id:p||o.cookie_id})),G(!0)},ae=()=>{W(o=>({...o,cookie_id:p||o.cookie_id})),X(!0)},ce=async o=>{if(!(o?p:C.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");j(!0),navigator.geolocation.getCurrentPosition(async xe=>{try{const Le=await ui(xe.coords.longitude,xe.coords.latitude);if(!Le.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");o?(Ue(Le),Me(Le[0])):(A(Le),d(Le[0]))}catch(Le){alert((Le==null?void 0:Le.message)||"获取发货地失败")}finally{j(!1)}},xe=>{j(!1),alert(xe.code===xe.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},fe=o=>l.filter(Q=>Q.cookie_id===o.cookie_id&&Q.item_id===o.item_id).length>0?l.filter(Q=>Q.cookie_id===o.cookie_id&&Q.item_id===o.item_id):l.filter(Q=>Q.cookie_id===o.cookie_id&&!Q.item_id),De=r.useMemo(()=>new Map(c.map(o=>[o.id,o])),[c]),Ne=r.useMemo(()=>f?s.filter(o=>o.cookie_id===f):s,[f,s]),Pe=o=>{const Q=De.get(o),xe=(Q==null?void 0:Q.remark)||(Q==null?void 0:Q.nickname);return xe?`${xe} · ${o.slice(0,6)}`:`账号 ${o.slice(0,8)}`},me=o=>{const Q=De.get(o);return(Q==null?void 0:Q.remark)||(Q==null?void 0:Q.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:justify-between xl:items-center gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-3xl font-bold text-gray-900",children:"商品管理"}),e.jsx("p",{className:"text-gray-500 mt-2 text-sm",children:"监控并管理所有账号下的闲鱼商品。"})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex min-w-[200px] flex-col gap-1.5",children:[e.jsx("label",{htmlFor:"item-account-filter",className:"px-1 text-[11px] font-extrabold tracking-wide text-gray-500",children:"商品列表筛选"}),e.jsxs("div",{className:"relative",children:[e.jsx(vr,{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:f,onChange:(o=>x(o.target.value)),children:[e.jsx("option",{value:"",children:"全部账号"}),c.map(o=>e.jsx("option",{value:o.id,children:Pe(o.id)},o.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(yt,{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:p,onChange:(o=>m(o.target.value)),children:[e.jsx("option",{value:"",children:"请选择账号"}),c.map(o=>e.jsx("option",{value:o.id,children:Pe(o.id)},o.id))]})]})]}),e.jsxs("button",{onClick:Ge,disabled:h||!p,className:"ios-btn-primary flex items-center gap-2 px-6 py-3 rounded-2xl font-bold shadow-lg shadow-blue-200 disabled:opacity-50",children:[e.jsx(We,{className:`w-4 h-4 ${h?"animate-spin":""}`}),"同步商品"]}),e.jsxs("button",{onClick:E,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(nt,{className:"w-4 h-4"}),"添加商品"]}),e.jsxs("button",{onClick:ae,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(ls,{className:"w-4 h-4"}),"发布商品"]}),e.jsxs("button",{onClick:(()=>void Be()),className:"px-5 py-3 rounded-2xl font-bold bg-brand text-white hover:bg-brand-highlight transition-colors flex items-center gap-2 shadow-lg shadow-blue-100",children:[e.jsx(Wt,{className:"w-4 h-4"}),de&&["running","canceling"].includes(de.status)?"继续批量任务":"批量铺货"]}),de&&!["running","canceling"].includes(de.status)&&e.jsx("button",{onClick:(()=>void He()),className:"px-4 py-3 rounded-2xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"最近批次结果"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5 gap-4",children:[Ne.map(o=>{const Q=fe(o),xe=Q.length>0;return e.jsxs("div",{className:"ios-card p-3 rounded-2xl hover:shadow-lg transition-all group relative f 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-C70ijd-m.js"></script>
<script type="module" crossorigin src="/static/assets/index-B7YpmDTE.js"></script>
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-C_od1ZSF.js">
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-i_74xDZy.js">
<link rel="modulepreload" crossorigin href="/static/assets/vendor-D-Edl3pr.js">