阶段六:修复生命周期与运行状态一致性

This commit is contained in:
Christ committed 2026-08-19 11:34:45 +08:00
1 parent 5f8d999ab0
commit c23a5a18b8
43 files changed
+1541 -171

No files matched your search

+5
View File
@@ -20,6 +20,8 @@ func main() {
withDeps := flag.Bool("with-deps", false, "also install Linux system dependencies")
// depsOnly 用于本次流程后续判断的depsOnly
depsOnly := flag.Bool("deps-only", false, "only install Linux system dependencies; do not download Chromium")
// driverOnly 表示只准备 Playwright driver,供服务初始化的可取消安装子进程使用。
driverOnly := flag.Bool("driver-only", false, "only install the Playwright driver")
flag.Parse()
if *depsOnly && !*withDeps {
*withDeps = true
@@ -55,6 +57,9 @@ func main() {
err := driver.DownloadDriver(); err != nil {
fatal("下载 Playwright driver 失败", err)
}
if *driverOnly {
return
}
// args 用于本次流程后续判断的args
args := []string{"install"}
@@ -4,6 +4,7 @@
本文是唯一的阶段状态、顺序和验收依据。AGENTS.md 只负责要求读取本文;refactoring-progress.md 只
保存最终提交与验收证据;其他架构文档只记录领域约束,不定义阶段状态。
历史验收记录不得写入“唯一当前阶段”“下一阶段入口”或“不得提前执行”等阶段指令,避免与本表形成第二个状态源。
本重构只有六个正式阶段。旧的十阶段编号、阶段 0、纵向切片、当前切片、分轮迭代、局部完成声明和
一个改动一个提交的规则全部失效。阶段是唯一任务、评审和交付单位:一个阶段允许同时修改多个 Go
@@ -213,6 +214,9 @@ git diff --check
受保护的 CAPTCHA 文件和规范未改动。完整原始验收输出、覆盖率、浏览器集成与多数据库环境例外记录在
`refactoring-progress.md`。
阶段六完成后的窄范围缺陷修复仍须保持全部门禁永久启用,不得把阶段状态回退为阶段五或创建新的阶段入口;
修复范围与本次验收证据只追加到 `refactoring-progress.md` 的阶段六记录。
## 执行纪律
1. 开始一个阶段前,只允许读取总计划状态表并审查当前工作树;不得根据旧阶段编号或已落地代码跳阶段。
+65 -14
View File
@@ -132,12 +132,6 @@ $ git diff --check
- 冻结 CAPTCHA:受保护的 slider、token CAPTCHA 实现和测试文件均未出现在最终差异;冻结规范未修改。
- 生成物:`frontend/coverage/` 是未跟踪的测试产物,不纳入提交。
## 下一阶段入口
阶段四已完成,阶段五:DB 与事务治理重新验收为唯一当前阶段。开始阶段五前先运行 architecturecheck,确认
前序 React feature、传输契约、网络旁路和严格 TypeScript 门禁继续 fail-closed;不得提前进入阶段六最终收口,
也不得修改冻结 CAPTCHA。
## 阶段四:React Feature 化和异步状态修复
- 最终提交绑定:`HEAD` 的唯一中文提交 `阶段四:完成 React Feature 化和异步状态修复`。
@@ -182,10 +176,6 @@ $ git diff --check
- 冻结 CAPTCHA:`internal/browser/slider.go`、`token_captcha*.go` 及其测试和规范未修改。
- 生成物:已由 `npm run build --prefix frontend` 重建 `internal/webui/static`,未手工修改嵌入文件。
## 阶段五入口
阶段五现在是唯一当前阶段。下一步只处理 DB 与事务治理重新验收:清除上层裸 `Store.DB`、`sql.DB`、`sql.Tx` 和 row model 泄露,核对 Unit of Work、claim/lease、取消、重试及补偿,并在可用时运行 SQLite、MySQL、PostgreSQL 和 `cmd/dbverify` 证据。不得在阶段五提前执行阶段六兼容退场、复杂度或全量注释收口。
## 阶段五:DB 与事务治理重新验收
- 最终提交绑定:`阶段五:完成数据库与事务治理重新验收`。
@@ -274,12 +264,73 @@ go build ./cmd/server
### 验收边界
- 覆盖率:Go statements 65.9%;前端 V8 statements 79.82%、lines 82.17%。`cover.out` 与 `frontend/coverage/` 均为生成验证产物,未纳入提交。
- 浏览器:已使用 `RUN_BROWSER_INTEGRATION=1` 运行本地 Chromium 集成测试;未调用真实账号或外部平台。
- 多数据库:本次环境未配置 `TEST_MYSQL_URL` 和/或 `TEST_POSTGRES_URL`,因此 `make test-multidb` 与两个 `cmd/dbverify` 未执行;阶段五既有 MySQL/PostgreSQL 实测证据保持有效,当前不伪造外部连接结果。
- 覆盖率:Go statements 65.9%;真实 Chromium 浏览器包 statements 64.0%;前端 V8 statements 79.96%、lines 82.33%。`cover.out`、`cover-browser.out` 与 `frontend/coverage/` 均为生成验证产物,未纳入提交。
- 浏览器:已直接使用 `RUN_BROWSER_INTEGRATION=1 go test ./internal/browser -count=1` 运行本地 Chromium 集成测试并通过;未调用真实账号或外部平台。
- 多数据库:已使用 Docker 临时启动 MySQL 8 与 PostgreSQL 17,实际执行 `make test-multidb` 及两个 `cmd/dbverify`,三方言回归和核心 CRUD 均通过。
- 冻结 CAPTCHA:直接受保护实现、测试和规范均未出现在最终差异中。
- 生成物:`npm run build --prefix frontend` 已执行;当前构建输入未导致 `internal/webui/static` 内容变化,未手工修改嵌入产物。
- 生成物:`npm run build --prefix frontend` 已执行并更新 `internal/webui/static` 哈希资源;生成覆盖率目录未纳入提交。
## 后续维护
六个正式阶段均已完成。之后的功能变更必须保持全部架构门禁永久 fail-closed,不得恢复阶段状态、扩大兼容白名单、修改注释 baseline 或将覆盖率生成物纳入提交。
### 2026-08-19 阶段六生命周期与运行状态一致性维护修复
- 交付范围:订单刷新 HTTP Port 仅接收请求 Context,组合层适配器注入协调器生命周期 Context;账号 Cookie/Token 替换在同一凭证锁内完成,启停与重启按账号串行并在运行时失败时补偿状态;QR 会话轮询和验证由 Manager 根 Context、会话取消函数与 WaitGroup 拥有;浏览器初始化在安装、启动和指纹探测阶段传播取消并释放半成品资源;前端订单刷新超时会使用独立短预算取消并复查终态。
- HTTP 语义:无法停止运行实例返回 `409 Conflict`,启用或 Cookie 重启后运行实例未就绪返回 `503 Service Unavailable`;正常成功路径和既有 API 路径保持兼容。
- 治理修正:删除本文件历史“当前阶段/下一阶段入口”表述,主计划明确只有状态表可定义阶段状态,避免阶段五旧指令与已完成的阶段六状态冲突。
- 冻结边界:未修改 `internal/browser/slider.go`、`token_captcha*.go`、其测试或冻结规范。
### 本次验收
```text
$ go test ./... -count=1
通过。
$ go test -race ./internal/server ./internal/application/account ./internal/application/orders ./internal/account ./internal/xianyu/qrlogin ./internal/browser -count=1
通过。
$ go vet ./...
(无输出,退出码 0)
$ make lint && make comments && go run ./tools/architecturecheck
golangci-lint: 0 issues;Go/前端 commentlint: 通过;architecturecheck: 通过。
$ npm test --prefix frontend -- --run
Test Files 67 passed (67)
Tests 405 passed (405)
$ npm run typecheck --prefix frontend && npm run comments:check --prefix frontend
通过。
$ npm run build --prefix frontend
✓ built in 5.45s;已重建 internal/webui/static。
$ make cover
total: (statements) 65.9%
$ make cover-frontend
Statements: 79.96% (3727/4661)
Lines: 82.33% (3257/3956)
$ RUN_BROWSER_INTEGRATION=1 go test ./internal/browser -count=1
ok \txianyu-go/internal/browser\t34.179s
$ TEST_MYSQL_URL='mysql://***@tcp(127.0.0.1:3306)/xianyu?...' TEST_POSTGRES_URL='postgres://***@127.0.0.1:5432/xianyu?...' make test-multidb
REQUIRE_MULTIDB=1 go test ./internal/db -run '^TestMultiDB_' -v -count=1
PASS
ok \txianyu-go/internal/db\t169.859s
已实际覆盖 SQLite、MySQL、PostgreSQL 的凭证隔离、布尔 UPSERT、可靠性状态、订单协调幂等、
自动化重试、通知、迁移上下行、聊天与账号任务、卡密与订单事件时间。
$ go run ./cmd/dbverify "$TEST_MYSQL_URL"
迁移成功,方言=mysql,数据库版本=33;核心 CRUD、自动化防重与验证数据清理全部通过。
$ go run ./cmd/dbverify "$TEST_POSTGRES_URL"
迁移成功,方言=postgres,数据库版本=33;核心 CRUD、自动化防重与验证数据清理全部通过。
$ git diff --check
(无输出,退出码 0)
```
- 外部环境:2026-08-19 使用 Docker 29.4.0 临时启动 `mysql:8` 与 `postgres:17`,均绑定到本机回环地址并通过就绪检查;真实 Chromium 集成、MySQL/PostgreSQL 多方言回归和两个 `cmd/dbverify` 均已执行且通过。多数据库测试创建并清理独立 `xytest_*` 数据库,验收结束后已删除两个临时容器。未执行真实账号登录或外部平台调用。`cover.out`、`cover-browser.out` 和 `frontend/coverage/` 是生成验证产物,未纳入提交。
@@ -68,7 +68,7 @@ describe('Accounts runtime state', /* 当前回调处理用户交互或异步状
// states 是运行状态到中文标签的完整断言表。
const states = [
['online', '在线'], ['starting', '连接中'], ['connecting', '连接中'], ['reconnecting', '重连中'],
['auth_expired', '登录已失效'], ['verification_required', '需要验证'], ['error', '运行异常'], ['stopped', '运行异常'],
['auth_expired', '登录已失效'], ['verification_required', '需要验证'], ['runtime_conflict', '运行状态冲突'], ['error', '运行异常'], ['stopped', '运行异常'],
] as const;
states.forEach(
// state 是需要验证展示文案的运行状态和预期标签。
@@ -49,6 +49,8 @@ export const accountRuntimePresentation = (account: AccountDetail): AccountRunti
return { label: '登录已失效', badge: 'bg-red-100 text-red-700', dot: 'bg-red-500' };
case 'verification_required':
return { label: '需要验证', badge: 'bg-orange-100 text-orange-700', dot: 'bg-orange-500' };
case 'runtime_conflict':
return { label: '运行状态冲突', badge: 'bg-red-100 text-red-700', dot: 'bg-red-500' };
case 'error':
case 'stopped':
return { label: '运行异常', badge: 'bg-red-100 text-red-700', dot: 'bg-red-500' };
+29
View File
@@ -202,6 +202,35 @@ test('syncOrders aborts while waiting for persisted job status', async () => {
await vi.waitFor(/* 等待取消命令发出。 */ () => expect(fetchMock).toHaveBeenCalledWith('/api/v1/orders/refresh/job-running', expect.objectContaining({ method: 'DELETE', credentials: 'include' })));
} /* 测试回调验证:syncOrders aborts while waiting for persisted job status。 */);
test('syncOrders reaches the front-end budget, cancels, and returns a concurrent success terminal result', async () => {
// fetchMock 模拟轮询仍运行、取消命令返回冲突且复查已拿到成功终态的时间竞争。
const fetchMock = vi.fn()
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-timeout', status: 'running' }))
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-timeout', status: 'running' }))
.mockResolvedValueOnce(new Response(JSON.stringify({ error: { code: 'conflict', message: '任务已结束' } }), { status: 409, headers: { 'content-type': 'application/json' } }))
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-timeout', 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: [] } }));
vi.stubGlobal('fetch', fetchMock);
// result 保存达到本地等待预算后由终态复查返回的成功订单刷新结果。
const result = await syncOrders(undefined, undefined, { pollLimit: 1, pollIntervalMs: 0 });
expect(result.message).toBe('终态成功');
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/orders/refresh/job-timeout', expect.objectContaining({ method: 'DELETE', credentials: 'include' }));
expect(fetchMock).toHaveBeenNthCalledWith(4, '/api/v1/orders/refresh/job-timeout', expect.objectContaining({ method: 'GET', credentials: 'include' }));
} /* 测试回调验证:syncOrders reaches the front-end budget, cancels, and returns a concurrent success terminal result。 */);
test('syncOrders reports a timeout only after cancellation and final terminal read remain non-terminal', async () => {
// fetchMock 模拟后台任务未在取消请求后及时进入成功或失败终态的场景。
const fetchMock = vi.fn()
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-still-running', status: 'running' }))
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-still-running', status: 'running' }))
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-still-running', status: 'cancelled' }))
.mockResolvedValueOnce(jsonResponse({ success: true, job_id: 'job-still-running', status: 'cancelled' }));
vi.stubGlobal('fetch', fetchMock);
await expect(syncOrders(undefined, undefined, { pollLimit: 1, pollIntervalMs: 0 })).rejects.toThrow('订单刷新任务等待超时,已请求取消');
expect(fetchMock).toHaveBeenCalledWith('/api/v1/orders/refresh/job-still-running', expect.objectContaining({ method: 'DELETE', credentials: 'include' }));
} /* 测试回调验证:syncOrders reports a timeout only after cancellation and final terminal read remain non-terminal。 */);
test('cancelOrderRefreshJob sends a user-scoped delete command', async () => {
const fetchMock = vi.fn().mockResolvedValue(jsonResponse({ success: true, job_id: 'job-cancel', status: 'cancelled' })); /* fetchMock 表示fetchMock。 */
vi.stubGlobal('fetch', fetchMock);
+41 -8
View File
@@ -16,6 +16,19 @@ import { del,get,post,postForm,put,type RequestControlOptions } from '../../../s
import { collectionFrom,objectFrom } from '../../../shared/http/contract';
export type * from '../../../shared/api-contract/orders';
/** 订单刷新前端最多轮询约 90 秒,超过该预算必须请求取消后端 worker。 */
const orderRefreshPollLimit = 180;
/** 订单刷新取消和终态复查使用独立五秒网络预算,不能复用已超时或已 Abort 的主信号。 */
const orderRefreshCancelTimeoutMs = 5_000;
/** 订单刷新轮询选项仅控制前端等待行为;不改变后端任务、HTTP 路径或请求体契约。 */
export interface OrderRefreshPollOptions extends RequestControlOptions {
/** pollLimit 是本次前端最多读取任务状态的次数;省略时保持九十秒默认预算。 */
pollLimit?: number;
/** pollIntervalMs 是两次状态读取之间的等待毫秒数;默认五百毫秒。 */
pollIntervalMs?: number;
}
/** 订单筛选器读取非敏感账号摘要。 */
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => get('/api/v1/accounts/details', undefined, options);
@@ -96,7 +109,7 @@ export const deleteOrder = async (orderId: string): Promise<OperationResponse> =
};
// syncOrders 同步订单。
export const syncOrders = async (cookieId?: string, status?: string, options?: RequestControlOptions): Promise<OrderRefreshResponse> => {
export const syncOrders = async (cookieId?: string, status?: string, options?: OrderRefreshPollOptions): Promise<OrderRefreshResponse> => {
// formData 表单数据,用于当前 API 处理流程。
const formData = new FormData();
if (cookieId) formData.append('cookie_id', cookieId);
@@ -104,13 +117,15 @@ export const syncOrders = async (cookieId?: string, status?: string, options?: R
// start 表示后台订单刷新任务创建响应。
const start = await postForm<OrderRefreshJobStartResponse>('/api/v1/orders/refresh', formData, options);
// cancelOnAbort 在调用方取消轮询时通知服务端停止同一后台任务。
// cancelOnAbort 在调用方取消轮询时通知服务端停止同一后台任务;取消命令使用独立信号,主请求已取消也能发出。
const cancelOnAbort = () => {
void cancelOrderRefreshJob(start.job_id).catch(/* 取消请求失败时忽略网络错误,主请求仍按取消语义结束。 */ () => undefined);
void cancelOrderRefreshJob(start.job_id, { timeoutMs: orderRefreshCancelTimeoutMs }).catch(/* 取消请求失败时忽略网络错误,主请求仍按取消语义结束。 */ () => undefined);
};
options?.signal?.addEventListener('abort', cancelOnAbort, { once: true });
// pollLimit 限制前端等待后台任务的轮询次数。
const pollLimit = 180;
const pollLimit = options?.pollLimit ?? orderRefreshPollLimit;
// pollIntervalMs 是本次状态查询之间的等待时长,测试可缩短它验证超时取消而不改变默认产品体验。
const pollIntervalMs = options?.pollIntervalMs ?? 500;
// pollIndex 表示当前订单刷新任务状态轮询次数。
let pollIndex = 0;
try {
@@ -124,7 +139,7 @@ export const syncOrders = async (cookieId?: string, status?: string, options?: R
throw new Error(job.error_message || '订单刷新任务失败');
}
// waitMs 是下一次任务状态轮询前的等待时间。
const waitMs = 500;
const waitMs = pollIntervalMs;
await new Promise<void>(/* 轮询等待器负责等待下一次任务状态查询。 */ (resolve, reject) => {
// abort 负责响应调用方取消轮询。
const abort = () => {
@@ -145,12 +160,30 @@ export const syncOrders = async (cookieId?: string, status?: string, options?: R
} finally {
options?.signal?.removeEventListener('abort', cancelOnAbort);
}
throw new Error('订单刷新任务等待超时');
// finalJob 保存取消命令与终态竞争后的最终任务状态;成功或失败终态优先于“等待超时”展示。
const finalJob = await cancelAndReadOrderRefreshJob(start.job_id);
if (finalJob.status === 'succeeded' && finalJob.result) {
return finalJob.result;
}
if (finalJob.status === 'failed') {
throw new Error(finalJob.error_message || '订单刷新任务失败');
}
throw new Error('订单刷新任务等待超时,已请求取消');
};
/** 取消订单刷新任务后读取一次独立终态,解决取消响应和 worker 完成响应同时到达的竞态。 */
const cancelAndReadOrderRefreshJob = async (jobId: string): Promise<OrderRefreshJobStatusResponse> => {
try {
await cancelOrderRefreshJob(jobId, { timeoutMs: orderRefreshCancelTimeoutMs });
} catch {
// 取消返回冲突或网络错误时仍读取终态:任务可能已经在取消命令到达前结束。
}
return get<OrderRefreshJobStatusResponse>(`/api/v1/orders/refresh/${jobId}`, undefined, { timeoutMs: orderRefreshCancelTimeoutMs });
};
// cancelOrderRefreshJob 请求取消当前用户的订单刷新后台任务。
export const cancelOrderRefreshJob = async (jobId: string): Promise<OrderRefreshJobCancelResponse> => {
return del(`/api/v1/orders/refresh/${jobId}`);
export const cancelOrderRefreshJob = async (jobId: string, options?: RequestControlOptions): Promise<OrderRefreshJobCancelResponse> => {
return del(`/api/v1/orders/refresh/${jobId}`, undefined, options);
};
// syncSingleOrder 同步单个订单。
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { act,renderHook } from '@testing-library/react';
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
import type { Order } from '../../../shared/api-contract/orders';
import type { Order,OrderRefreshResponse } from '../../../shared/api-contract/orders';
import { useOrderActions } from './orderActions';
// orderActionMocks 保存订单动作 Hook 测试使用的 API 替身。
@@ -81,6 +81,30 @@ describe('useOrderActions 订单动作协调器', /* 当前回调验证订单动
expect(hook.result.current.syncingOrderId).toBeNull();
});
test('晚到的旧批量同步结果不会覆盖最新请求的列表刷新和提示', /* 当前回调验证重复点击同步时旧任务响应的代次隔离。 */ async () => {
// resolveFirst 保存首次同步 API 适配器的延迟结果完成函数。
let resolveFirst: ((value: OrderRefreshResponse) => void) | undefined;
// firstCompletion 保存首次同步尚未完成的 API 适配器 Promise。
const firstCompletion = new Promise<OrderRefreshResponse>(/* resolve 保存首次同步的结果完成器。 */ resolve => { resolveFirst = resolve; });
orderActionMocks.syncOrders.mockImplementationOnce(/* firstSync 模拟较早请求尚未返回。 */ () => firstCompletion)
.mockResolvedValueOnce({ message: '最新同步完成' });
// actionContext 保存待验证代次隔离的订单动作 Hook。
const { hook, loadOrders } = createActionHook();
// firstTask 启动旧同步但不等待它完成。
const firstTask = hook.result.current.handleSync();
// secondTask 启动并完成后发起的最新同步。
const secondTask = hook.result.current.handleSync();
await act(/* completeSecond 完成最新同步并等待它刷新列表。 */ async () => { await secondTask; });
expect(loadOrders).toHaveBeenCalledTimes(1);
expect(window.alert).toHaveBeenCalledWith('最新同步完成');
resolveFirst?.({ 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: [] });
await act(/* completeFirst 放行旧任务;它不能再刷新列表或展示提示。 */ async () => { await firstTask; });
expect(loadOrders).toHaveBeenCalledTimes(1);
expect(window.alert).not.toHaveBeenCalledWith('旧同步完成');
});
test('发货结果失败和异常均保留错误结果', /* 当前回调验证订单发货异常分支。 */ async () => {
// actionContext 保存发货动作 Hook 和刷新依赖。
const { hook } = createActionHook();
+8 -1
View File
@@ -1,4 +1,4 @@
import { useCallback,useState,type Dispatch,type SetStateAction } from 'react';
import { useCallback,useRef,useState,type Dispatch,type SetStateAction } from 'react';
import type { Order } from './api';
import { deleteOrder,manualShipOrder,syncOrders,syncSingleOrder,updateOrder } from './api';
@@ -102,15 +102,22 @@ export const useOrderActions = ({ orders, page, accountFilter, filter, setPage,
const [syncingOrderId, setSyncingOrderId] = useState<string | null>(null);
// deletingOrderId 保存当前正在删除的订单号。
const [deletingOrderId, setDeletingOrderId] = useState<string | null>(null);
// syncGeneration 区分连续发起的批量刷新,旧任务完成后不得覆盖最新一次用户操作的列表和提示。
const syncGeneration = useRef(0);
// handleSync 同步当前筛选条件下的订单并刷新列表。
const handleSync = useCallback(/* syncAction 执行当前筛选条件下的订单同步。 */ async () => {
// generation 是本次批量同步的代次;仅仍为最新代次的结果允许更新界面。
const generation = ++syncGeneration.current;
try {
// result 保存订单同步接口返回的结果说明。
const result = await syncOrders(accountFilter || undefined, filter);
if (generation !== syncGeneration.current) return;
await loadOrders();
if (generation !== syncGeneration.current) return;
if (result.message) alert(result.message);
} catch (/* error 表示订单同步请求异常。 */ error: unknown) {
if (generation !== syncGeneration.current) return;
console.error('同步订单失败:', error);
alert(orderErrorMessage(error, '同步失败,请重试'));
}
+1 -1
View File
@@ -86,7 +86,7 @@ export interface AccountDetail {
/** 资料刷新失败时的说明。 */
profile_error?: string;
/** 当前账号运行状态。 */
runtime_state?: 'starting' | 'connecting' | 'online' | 'reconnecting' | 'auth_expired' | 'verification_required' | 'error' | 'stopped' | 'disabled';
runtime_state?: 'starting' | 'connecting' | 'online' | 'reconnecting' | 'auth_expired' | 'verification_required' | 'runtime_conflict' | 'error' | 'stopped' | 'disabled';
/** 当前运行状态的用户可见说明。 */
runtime_message?: string;
/** 当前运行实例是否已连接。 */
@@ -3,6 +3,15 @@ package account
import (
"context"
"errors"
"fmt"
"sync"
)
var (
// ErrRuntimeStopConflict 表示账号实例未能在关闭预算内完全停止,持久化状态保持可重试。
ErrRuntimeStopConflict = errors.New("账号运行实例尚未停止")
// ErrRuntimeStartUnavailable 表示账号已写入启用或新 Cookie,但运行实例未能达到可运行状态。
ErrRuntimeStartUnavailable = errors.New("账号运行实例未能启动")
)
// SettingsUpdateInput 是账号编辑用例的输入;Password 为 nil 时保留数据库中的既有密码。
@@ -93,8 +102,12 @@ type SettingsRepository interface {
type SettingsRuntime interface {
// Restart 在账号启用且 Cookie 变化后重新加载运行实例。
Restart(context.Context, string) error
// Stop 在账号停用后停止运行实例。
Stop(string)
// BeginStopping 建立账号停止 fencing,阻止其他运行时入口在停用转换期间启动实例。
BeginStopping(string) bool
// EndStopping 在状态转换结束后释放账号停止 fencing。
EndStopping(string)
// StopContext 在调用方关闭预算内停止账号实例,并等待其完全退出。
StopContext(context.Context, string) error
}
// SettingsService 编排账号设置、登录信息、状态和暂停用例,不依赖 HTTP 或数据库模型。
@@ -103,6 +116,10 @@ type SettingsService struct {
repository SettingsRepository
// runtime 提供可选的账号运行实例控制能力。
runtime SettingsRuntime
// transitionMu 保护 transitionLocks 映射;每把锁串行化一个账号的启用、停用和重启状态转换。
transitionMu sync.Mutex
// transitionLocks 保存按账号分配的状态转换锁;锁不跨账号共享,也不在持锁时持有凭证锁。
transitionLocks map[string]*sync.Mutex
}
// NewSettingsService 构造账号设置应用服务并校验必需的持久化端口。
@@ -110,10 +127,23 @@ func NewSettingsService(repository SettingsRepository, runtime SettingsRuntime)
if repository == nil {
return nil, errors.New("账号设置 repository 未初始化")
}
return &SettingsService{repository: repository, runtime: runtime}, nil
return &SettingsService{repository: repository, runtime: runtime, transitionLocks: make(map[string]*sync.Mutex)}, nil
}
// UpdateSettings 原子保存账号设置;Cookie 变化后的运行时重启在释放凭证锁后执行。
// transitionLock 返回指定账号唯一的状态转换锁,用于避免启用、停用和 Cookie 重启相互覆盖。
func (s *SettingsService) transitionLock(accountID string) *sync.Mutex {
s.transitionMu.Lock()
defer s.transitionMu.Unlock()
// lock 保存当前账号的转换锁;首次使用时创建,之后在服务生命周期内复用。
lock := s.transitionLocks[accountID]
if lock == nil {
lock = &sync.Mutex{}
s.transitionLocks[accountID] = lock
}
return lock
}
// UpdateSettings 原子保存账号设置;Cookie、metadata 和旧 Token 在同一凭证锁内完成,运行时重启在锁外串行执行。
func (s *SettingsService) UpdateSettings(ctx context.Context, input SettingsUpdateInput) (SettingsResult, error) {
if s == nil || s.repository == nil {
return SettingsResult{}, errors.New("账号设置服务未初始化")
@@ -121,12 +151,12 @@ func (s *SettingsService) UpdateSettings(ctx context.Context, input SettingsUpda
if input.AccountID == "" {
return SettingsResult{}, errors.New("缺少账号 ID")
}
// unlock 负责释放本次账号设置写入的凭证锁。
// unlock 负责释放本次账号设置写入的凭证锁,锁覆盖 Cookie、metadata 和旧 Token 的完整替换。
unlock := s.repository.LockCredentials(input.AccountID)
// pausedUntil、updateErr 保存设置事务返回的暂停截止时间和错误。
pausedUntil, updateErr := s.repository.UpdateSettings(ctx, input)
unlock()
if updateErr != nil {
unlock()
return SettingsResult{}, updateErr
}
// result 保存设置写入及后续运行时处理结果。
@@ -136,16 +166,36 @@ func (s *SettingsService) UpdateSettings(ctx context.Context, input SettingsUpda
tokenErr := s.repository.ClearTokens(ctx, input.AccountID)
result.TokenCleanupError = tokenErr
}
// Cookie、metadata 与旧 Token 都已完成转换后才释放锁;后续运行时 I/O 不得占用该锁。
unlock()
if input.Cookie != nil && s.runtime != nil {
// enabled 表示写入成功后账号的最新启用状态;状态读取失败不覆盖已成功的设置写入。
enabled, statusErr := s.repository.StatusOwned(ctx, input.UserID, input.AccountID)
if statusErr == nil && enabled {
result.RuntimeError = s.runtime.Restart(ctx, input.AccountID)
// lock 串行化 Cookie 重启与同账号启停,避免已更新 Cookie 的实例被并发停用或替换。
lock := s.transitionLock(input.AccountID)
lock.Lock()
// restartErr 保存锁外运行时重启错误;Cookie 主写入仍保留,但数据库必须补偿为停用避免状态失真。
restartErr := s.runtime.Restart(ctx, input.AccountID)
if restartErr != nil {
// compensationErr 保存重启失败后写回停用状态的错误;两个错误共同决定调用方是否需要人工恢复。
compensationErr := s.setStatusLocked(ctx, input.UserID, input.AccountID, false, "runtime_restart_failed")
result.RuntimeError = fmt.Errorf("%w: %v", ErrRuntimeStartUnavailable, errors.Join(restartErr, compensationErr))
}
lock.Unlock()
}
}
return result, nil
}
// setStatusLocked 在短凭证锁内写入账号启用状态;调用方不得在持有该锁时执行运行时或平台 I/O。
func (s *SettingsService) setStatusLocked(ctx context.Context, userID int64, accountID string, enabled bool, reason string) error {
// unlock 仅保护持久化状态更新与相关敏感元数据一致性,不跨越运行时关闭或启动。
unlock := s.repository.LockCredentials(accountID)
defer unlock()
return s.repository.SetStatusOwned(ctx, userID, accountID, enabled, reason)
}
// UpdateLoginInfo 保存账号用户名、密码和浏览器显示设置;既有密码不会被应用层读取。
func (s *SettingsService) UpdateLoginInfo(ctx context.Context, input LoginInfoUpdateInput) error {
if s == nil || s.repository == nil {
@@ -160,7 +210,7 @@ func (s *SettingsService) UpdateLoginInfo(ctx context.Context, input LoginInfoUp
return s.repository.UpdateLoginInfo(ctx, input)
}
// SetStatus 更新账号启用状态并在持久化成功后控制运行实例。
// SetStatus 同步完成账号持久化状态与运行实例转换;失败会保留可重试状态而不是伪造成功。
func (s *SettingsService) SetStatus(ctx context.Context, userID int64, accountID string, enabled bool) (StatusResult, error) {
if s == nil || s.repository == nil {
return StatusResult{}, errors.New("账号设置服务未初始化")
@@ -168,27 +218,43 @@ func (s *SettingsService) SetStatus(ctx context.Context, userID int64, accountID
if accountID == "" {
return StatusResult{}, errors.New("缺少账号 ID")
}
// reason 由应用层统一产生,避免 HTTP 层决定持久化状态原因。
reason := ""
// lock 串行化同一账号的启用、停用和 Cookie 重启,锁顺序始终先转换锁、后短凭证锁。
lock := s.transitionLock(accountID)
lock.Lock()
defer lock.Unlock()
// result 保存持久化状态完成后运行时收束或启动失败的显式结果。
result := StatusResult{}
if !enabled {
reason = "manual"
if s.runtime != nil {
if !s.runtime.BeginStopping(accountID) {
result.RuntimeError = ErrRuntimeStopConflict
return result, nil
}
defer s.runtime.EndStopping(accountID)
// stopErr 保存关闭预算内无法完全停止旧实例的原因;此时禁止写数据库停用状态。
if stopErr := s.runtime.StopContext(ctx, accountID); stopErr != nil {
result.RuntimeError = fmt.Errorf("%w: %v", ErrRuntimeStopConflict, stopErr)
return result, nil
}
}
// statusErr 保存停止完成后写入数据库停用状态的错误。
if statusErr := s.setStatusLocked(ctx, userID, accountID, false, "manual"); statusErr != nil {
return StatusResult{}, statusErr
}
return result, nil
}
// unlock 负责释放账号状态写入期间持有的凭证锁。
unlock := s.repository.LockCredentials(accountID)
// statusErr 保存账号状态持久化错误。
statusErr := s.repository.SetStatusOwned(ctx, userID, accountID, enabled, reason)
unlock()
if statusErr != nil {
// statusErr 保存写入数据库启用状态的错误;写入失败时不得启动运行实例。
if statusErr := s.setStatusLocked(ctx, userID, accountID, true, ""); statusErr != nil {
return StatusResult{}, statusErr
}
// result 保存状态写入后运行时启停的结果。
result := StatusResult{}
if s.runtime != nil {
if enabled {
result.RuntimeError = s.runtime.Restart(ctx, accountID)
} else {
s.runtime.Stop(accountID)
}
if s.runtime == nil {
return result, nil
}
// restartErr 保存启用后实例未能启动的原因;补偿为停用使持久化与运行时状态不再矛盾。
if restartErr := s.runtime.Restart(ctx, accountID); restartErr != nil {
// compensationErr 保存补偿写入失败;错误仍返回给 HTTP 层,避免伪造启用成功。
compensationErr := s.setStatusLocked(ctx, userID, accountID, false, "runtime_start_failed")
result.RuntimeError = fmt.Errorf("%w: %v", ErrRuntimeStartUnavailable, errors.Join(restartErr, compensationErr))
}
return result, nil
}
@@ -3,7 +3,9 @@ package account
import (
"context"
"errors"
"sync"
"testing"
"time"
)
// fakeSettingsRepository 记录账号设置应用服务对持久化端口的调用。
@@ -74,6 +76,66 @@ type fakeSettingsRuntime struct {
stopCalls int
// restartErr 是预置的重启错误。
restartErr error
// stopErr 是预置的运行实例停止错误。
stopErr error
// stopping 表示测试替身是否已建立停止 fencing。
stopping bool
}
// credentialInterleavingRepository 用真实互斥锁模拟 Cookie 替换和平台新 Token 保存的竞争时序。
type credentialInterleavingRepository struct {
// mu 串行化同一账号 Cookie、metadata 与 Token 的敏感持久化转换。
mu sync.Mutex
// token 保存测试观察到的当前连接 Token,不包含真实凭证。
token string
// clearStarted 通知旧 Token 清理已经持有凭证锁。
clearStarted chan struct{}
// allowClear 控制旧 Token 清理何时完成,用于确认并发新 Token 写入会被锁阻塞。
allowClear chan struct{}
}
// LockCredentials 获取测试账号唯一的敏感凭证锁。
func (repository *credentialInterleavingRepository) LockCredentials(string) func() {
repository.mu.Lock()
return repository.mu.Unlock
}
// UpdateSettings 模拟 Cookie 主写入成功,不改变测试中的新 Token。
func (repository *credentialInterleavingRepository) UpdateSettings(context.Context, SettingsUpdateInput) (int64, error) {
return 0, nil
}
// UpdateLoginInfo 满足设置仓储接口;本竞争用例不写入登录资料。
func (repository *credentialInterleavingRepository) UpdateLoginInfo(context.Context, LoginInfoUpdateInput) error {
return nil
}
// SetStatusOwned 满足设置仓储接口;本竞争用例不改变账号状态。
func (repository *credentialInterleavingRepository) SetStatusOwned(context.Context, int64, string, bool, string) error {
return nil
}
// StatusOwned 返回停用,避免本凭证锁测试触发运行时重启。
func (repository *credentialInterleavingRepository) StatusOwned(context.Context, int64, string) (bool, error) {
return false, nil
}
// SetPauseOwned 满足设置仓储接口;本竞争用例不涉及暂停状态。
func (repository *credentialInterleavingRepository) SetPauseOwned(context.Context, int64, string, int) (int64, error) {
return 0, nil
}
// GetPauseOwned 满足设置仓储接口;本竞争用例不读取暂停状态。
func (repository *credentialInterleavingRepository) GetPauseOwned(context.Context, int64, string) (PauseState, error) {
return PauseState{}, nil
}
// ClearTokens 在持有凭证锁时等待测试放行,然后清除 Cookie 变更前的旧 Token。
func (repository *credentialInterleavingRepository) ClearTokens(context.Context, string) error {
close(repository.clearStarted)
<-repository.allowClear
repository.token = ""
return nil
}
// Restart 记录重启并返回预置错误。
@@ -82,8 +144,75 @@ func (f *fakeSettingsRuntime) Restart(context.Context, string) error {
return f.restartErr
}
// Stop 记录运行实例停止。
func (f *fakeSettingsRuntime) Stop(string) { f.stopCalls++ }
// BeginStopping 记录当前测试账号的停止 fencing;重复进入时返回 false。
func (f *fakeSettingsRuntime) BeginStopping(string) bool {
if f.stopping {
return false
}
f.stopping = true
return true
}
// EndStopping 释放当前测试账号的停止 fencing。
func (f *fakeSettingsRuntime) EndStopping(string) { f.stopping = false }
// StopContext 记录带关闭预算的停止调用并返回预置错误。
func (f *fakeSettingsRuntime) StopContext(context.Context, string) error {
f.stopCalls++
return f.stopErr
}
// TestSettingsServiceKeepsCredentialLockUntilOldTokenCleared 验证并发保存的新 Token 不会被旧 Token 清理覆盖。
func TestSettingsServiceKeepsCredentialLockUntilOldTokenCleared(t *testing.T) {
// repository 保存带真实互斥锁的敏感凭证替身。
repository := &credentialInterleavingRepository{token: "old-token", clearStarted: make(chan struct{}), allowClear: make(chan struct{})}
// service 保存待验证 Cookie 更新顺序的账号设置服务。
service, serviceErr := NewSettingsService(repository, nil)
if serviceErr != nil {
t.Fatalf("构造设置服务失败: %v", serviceErr)
}
// cookie 保存本次替换的 Cookie 明文,仅在测试输入范围存在。
cookie := "updated-cookie"
// updateDone 保存 Cookie 更新和旧 Token 清理完成后的结果。
updateDone := make(chan error, 1)
go func() {
// _, updateErr 保存设置写入结果与错误;当前测试只关注凭证锁释放时机。
_, updateErr := service.UpdateSettings(context.Background(), SettingsUpdateInput{UserID: 7, AccountID: "acc-1", Cookie: &cookie})
updateDone <- updateErr
}()
select {
case <-repository.clearStarted:
case <-time.After(time.Second):
t.Fatal("旧 Token 清理未开始")
}
// newTokenWritten 通知并发平台流程何时真正拿到凭证锁并写入新 Token。
newTokenWritten := make(chan struct{})
go func() {
// unlock 是并发平台流程持有的同账号凭证锁释放函数。
unlock := repository.LockCredentials("acc-1")
repository.token = "new-token"
unlock()
close(newTokenWritten)
}()
select {
case <-newTokenWritten:
t.Fatal("旧 Token 清理完成前不应写入新 Token")
case <-time.After(25 * time.Millisecond):
}
close(repository.allowClear)
// updateErr 保存 Cookie 更新协程完成后返回的错误。
if updateErr := <-updateDone; updateErr != nil {
t.Fatalf("Cookie 更新失败: %v", updateErr)
}
select {
case <-newTokenWritten:
case <-time.After(time.Second):
t.Fatal("凭证锁释放后未写入新 Token")
}
if repository.token != "new-token" {
t.Fatalf("旧 Token 清理覆盖了新 Token: %q", repository.token)
}
}
// TestSettingsServiceRestartsAfterCookieWrite 验证 Cookie 写入释放凭证锁后才重启运行实例。
func TestSettingsServiceRestartsAfterCookieWrite(t *testing.T) {
@@ -74,6 +74,74 @@ func TestRefreshJobServiceCreateAndStart(t *testing.T) {
}
}
// TestRefreshJobServiceWorkerOutlivesRequestContext 验证任务创建成功后 HTTP 请求结束不会取消进程生命周期拥有的刷新 worker。
func TestRefreshJobServiceWorkerOutlivesRequestContext(t *testing.T) {
// repository 保存可完成终态写入的测试任务仓储。
repository := completeAppliedRepository()
// owner 允许当前用户操作测试账号。
owner := &refreshJobOwnerTestDouble{owned: true}
// started 通知后台刷新已取得进程生命周期 Context。
started := make(chan context.Context, 1)
// release 控制后台刷新何时正常结束。
release := make(chan struct{})
// refresher 保存会等待 release 的刷新端口,便于在 HTTP Context 取消后检查 worker 是否仍活跃。
refresher := refreshJobServiceBlockingRefresher{started: started, release: release}
// runner、runnerErr 保存应用层 worker 运行器及其构造错误。
runner, runnerErr := NewRefreshJobRunner(repository, refresher, RefreshJobRunnerOptions{})
if runnerErr != nil {
t.Fatalf("构造运行器失败: %v", runnerErr)
}
// service、serviceErr 保存创建和启动任务的应用服务。
service, serviceErr := NewRefreshJobService(repository, owner, runner, RefreshJobServiceOptions{})
if serviceErr != nil {
t.Fatalf("构造刷新任务服务失败: %v", serviceErr)
}
// requestCtx、cancelRequest 模拟在 HTTP 响应返回后立即结束的请求 Context。
requestCtx, cancelRequest := context.WithCancel(context.Background())
defer cancelRequest()
// lifecycleCtx、cancelLifecycle 是独立于请求的进程生命周期 Context。
lifecycleCtx, cancelLifecycle := context.WithCancel(context.Background())
defer cancelLifecycle()
// _, startErr 保存创建并启动后台任务的结果。
_, startErr := service.CreateAndStart(requestCtx, lifecycleCtx, 7, "cookie-1", "")
if startErr != nil {
t.Fatalf("创建并启动刷新任务失败: %v", startErr)
}
// workerCtx 保存后台刷新收到的 Context;必须不是 requestCtx。
workerCtx := <-started
cancelRequest()
if workerCtx == requestCtx || workerCtx.Err() != nil {
t.Fatalf("请求结束后 worker 被误取消: worker=%p request=%p err=%v", workerCtx, requestCtx, workerCtx.Err())
}
close(release)
// closeCtx、cancelClose 限制异步任务正常退出的等待时间。
closeCtx, cancelClose := context.WithTimeout(context.Background(), time.Second)
defer cancelClose()
// closeErr 保存正常完成后运行器关闭与等待的结果。
if closeErr := runner.Close(closeCtx); closeErr != nil {
t.Fatalf("关闭后台刷新 worker 失败: %v", closeErr)
}
}
// refreshJobServiceBlockingRefresher 是请求与后台生命周期分离测试使用的阻塞刷新端口。
type refreshJobServiceBlockingRefresher struct {
// started 返回 worker 实际收到的生命周期 Context。
started chan<- context.Context
// release 控制测试中的刷新业务何时结束。
release <-chan struct{}
}
// Refresh 等待测试放行,并在调用方生命周期取消时提前退出。
func (refresher refreshJobServiceBlockingRefresher) Refresh(ctx context.Context, _ int64, _, _ string) (RefreshResult, error) {
refresher.started <- ctx
select {
case <-refresher.release:
return RefreshResult{Message: "完成"}, nil
case <-ctx.Done():
return RefreshResult{}, ctx.Err()
}
}
// TestRefreshJobServiceCreateRejectsUnownedAccount 验证账号不属于用户时不会创建或抢占任务。
func TestRefreshJobServiceCreateRejectsUnownedAccount(t *testing.T) {
// repository 记录不应发生的创建和抢占调用。
@@ -368,6 +368,71 @@ func TestRefreshJobRunnerRecovery(t *testing.T) {
}
}
// TestRefreshJobRunnerRecoversAfterLifecycleCancellation 验证进程取消导致终态无法写入后,过期租约会在后续恢复扫描中重新接管。
func TestRefreshJobRunnerRecoversAfterLifecycleCancellation(t *testing.T) {
// fixedNow 是首次取消和后续恢复扫描共享的确定性时钟。
fixedNow := time.Date(2026, 8, 19, 9, 0, 0, 0, time.UTC)
// repository 保存终态写入失败及后续恢复队列的测试配置。
repository := completeAppliedRepository()
repository.completeErr = context.Canceled
repository.jobs = []RefreshJob{{ID: "job-recover-after-cancel", UserID: 7, CookieID: "cookie-7"}}
// refresher 等待进程 Context 取消后返回,使失败终态沿用已取消 Context。
refresher := &refreshRunnerTestRefresher{waitForCancel: true}
// runner、runnerErr 保存具有固定租约和令牌的任务运行器。
runner, runnerErr := NewRefreshJobRunner(repository, refresher, RefreshJobRunnerOptions{Now: func() time.Time { return fixedNow }, NewToken: func() string { return "recovered-token" }})
if runnerErr != nil {
t.Fatalf("构造运行器失败: %v", runnerErr)
}
// lifecycleCtx、cancelLifecycle 模拟进程关闭取消。
lifecycleCtx, cancelLifecycle := context.WithCancel(context.Background())
// startErr 保存初始 worker 启动结果。
startErr := runner.StartJob(lifecycleCtx, &RefreshJob{ID: "job-recover-after-cancel", UserID: 7, CookieID: "cookie-7"}, "cancelled-token")
if startErr != nil {
t.Fatalf("启动取消 worker 失败: %v", startErr)
}
cancelLifecycle()
// workerDone 等待取消 worker 清理内存登记;不能调用 Close,否则运行器会拒绝后续恢复 worker。
workerDone := make(chan struct{})
go func() {
runner.Wait()
close(workerDone)
}()
select {
case <-workerDone:
case <-time.After(time.Second):
t.Fatal("取消 worker 未退出")
}
repository.mu.Lock()
// completionCalls 保存进程取消时失败的终态写入记录。
completionCalls := append([]refreshRunnerCompleteCall(nil), repository.completeCalls...)
repository.completeErr = nil
repository.mu.Unlock()
if len(completionCalls) == 0 || completionCalls[0].jobID != "job-recover-after-cancel" {
t.Fatalf("取消后未尝试终态写入: %+v", completionCalls)
}
// recoveryErr 保存新的可用生命周期下恢复扫描的结果。
recoveryErr := runner.RunRecovery(context.Background())
if recoveryErr != nil {
t.Fatalf("恢复扫描失败: %v", recoveryErr)
}
// recoveryCloseCtx、cancelRecoveryClose 等待恢复 worker 完成。
recoveryCloseCtx, cancelRecoveryClose := context.WithTimeout(context.Background(), time.Second)
defer cancelRecoveryClose()
// closeErr 保存恢复 worker 结束后的关闭结果。
if closeErr := runner.Close(recoveryCloseCtx); closeErr != nil {
t.Fatalf("关闭恢复 worker 失败: %v", closeErr)
}
repository.mu.Lock()
// requeues 保存恢复扫描对过期任务的重新入队记录;claims 保存恢复 worker 获得的新租约记录。
requeues := append([]string(nil), repository.requeueCalls...)
// claims 是断言恢复 worker 使用新令牌的租约快照。
claims := append([]refreshRunnerClaimCall(nil), repository.claimCalls...)
repository.mu.Unlock()
if len(requeues) != 1 || requeues[0] != "job-recover-after-cancel" || len(claims) != 1 || claims[0].token != "recovered-token" {
t.Fatalf("取消后的恢复接管不正确: requeues=%v claims=%+v", requeues, claims)
}
}
// TestRefreshJobRunnerRecoveryError 验证恢复仓储错误直接返回,便于生命周期层观测并决定下一轮重试。
func TestRefreshJobRunnerRecoveryError(t *testing.T) {
// scanErr 是恢复扫描仓储返回的错误。
+1 -1
View File
@@ -218,7 +218,7 @@ func TestPasswordDetectorHandlesHTMLAndURLs(t *testing.T) {
}
// failedManager 保存初始化函数失败的浏览器管理器。
failedManager := NewManager(nil)
failedManager.installFn = func() error { return errors.New("测试安装失败") }
failedManager.installFn = func(context.Context) error { return errors.New("测试安装失败") }
if // err 保存初始化失败错误。
err := failedManager.Initialize(); err == nil {
t.Fatal("初始化失败应向调用方返回错误")
+202 -31
View File
@@ -9,6 +9,7 @@ import (
"log/slog"
"net/url"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
@@ -191,8 +192,11 @@ type Manager struct {
browserFingerprint xianyu.BrowserFingerprint
userAgentMetadata map[string]any
once sync.Once
initErr error
// initMu 串行化 Playwright 安装、启动和指纹探测;初始化阶段不与 Close 并发发布半成品资源。
initMu sync.Mutex
// initErr 保存不可恢复的安装或启动错误;调用方取消不会写入该字段,以便后续重试。
initErr error
// installed 表示 Playwright 与运行时指纹均已完整发布。
installed bool
mu sync.Mutex
@@ -206,8 +210,12 @@ type Manager struct {
renewSlots chan struct{}
// 允许测试注入自定义 playwright / 安装函数。
installFn func() error
runFn func() (*playwright.Playwright, error)
// installFn 执行可观察的 runtime 安装阶段;实现必须在开始和返回前尊重 Context。
installFn func(context.Context) error
// runFn 执行可观察的 Playwright 启动阶段;实现必须在开始和返回前尊重 Context。
runFn func(context.Context) (*playwright.Playwright, error)
// fingerprintFn 读取已启动 Chromium 的指纹;测试可注入失败,验证半成品资源不会发布。
fingerprintFn func() error
// 仅用于隔离 token 风控引擎编排测试;生产环境为 nil,调用真实实现。
tokenCaptchaPrimaryFn tokenCaptchaEngineFunc
@@ -237,11 +245,15 @@ func NewManager(logger *slog.Logger) *Manager {
idleTTL: 5 * time.Minute,
renewLocks: make(map[string]*sync.Mutex),
renewSlots: make(chan struct{}, 3),
installFn: func() error {
installFn: func(ctx context.Context) error {
// err 保存安装阶段开始前已取消的调用方 Context 错误。
if err := ctx.Err(); err != nil {
return err
}
if packagedPlaywrightRuntimeReady() {
return nil
}
// opts 用于本次流程后续判断的opts
// opts 保存开发环境安装 driver 和 Chromium 所需的固定运行参数。
opts := &playwright.RunOptions{
Browsers: []string{"chromium"},
Verbose: false,
@@ -249,16 +261,112 @@ func NewManager(logger *slog.Logger) *Manager {
if skipPlaywrightBrowserDownload() {
opts.SkipInstallBrowsers = true
}
return playwright.Install(opts)
// installErr 保存可取消安装流程的错误;浏览器 CLI 必须由 Context 控制,不能包装为不可观察后台 goroutine。
installErr := installPlaywrightRuntime(ctx, opts)
// contextErr 保存安装完成后才观察到的取消错误,禁止发布已无主的安装结果。
if contextErr := ctx.Err(); contextErr != nil {
return contextErr
}
return installErr
},
runFn: func() (*playwright.Playwright, error) {
return playwright.Run()
runFn: func(ctx context.Context) (*playwright.Playwright, error) {
// err 保存启动阶段开始前已取消的调用方 Context 错误。
if err := ctx.Err(); err != nil {
return nil, err
}
// pw、runErr 保存同步启动的 Playwright 进程及启动错误;已取消时调用方负责停止新进程。
pw, runErr := playwright.Run()
// contextErr 保存启动完成后才观察到的取消错误,必须同步停止半成品进程。
if contextErr := ctx.Err(); contextErr != nil {
if pw != nil {
_ = pw.Stop()
}
return nil, contextErr
}
return pw, runErr
},
fingerprintFn: nil,
}
manager.fingerprintFn = manager.detectBrowserFingerprint
manager.lifecycleCond = sync.NewCond(&manager.lifecycleMu)
return manager
}
// installPlaywrightRuntime 下载缺失 driver,并用 Context 控制 Node CLI 安装 Chromium;包内 runtime 已就绪时调用方不会进入此路径。
func installPlaywrightRuntime(ctx context.Context, options *playwright.RunOptions) error {
if ctx == nil {
return errors.New("安装 Playwright runtime 需要 Context")
}
// err 保存安装前调用方已经取消的 Context 错误。
if err := ctx.Err(); err != nil {
return err
}
// installer、args 保存可被 Context 终止的 browser-install 子进程及其参数。
installer, args, installerErr := browserInstallerCommand(options)
if installerErr != nil {
return installerErr
}
// controlledCommand 是由初始化 Context 取消的完整 runtime 安装子进程,覆盖 driver、Node 和 Chromium 下载。
controlledCommand := exec.CommandContext(ctx, installer, args...)
// installErr 保存独立安装器及其子进程树的退出错误;Context 取消时由 os/exec 终止安装器。
installErr := controlledCommand.Run()
// contextErr 保存 CLI 返回后观察到的取消错误,取消语义优先于子进程退出错误。
if contextErr := ctx.Err(); contextErr != nil {
return contextErr
}
return installErr
}
// browserInstallerCommand 查找可取消的 browser-install 命令;优先使用部署提供的可执行文件和同目录打包助手,开发源码树最后通过 go run 调用同一入口。
func browserInstallerCommand(options *playwright.RunOptions) (string, []string, error) {
if options == nil {
return "", nil, errors.New("安装 Playwright runtime 缺少运行参数")
}
// driverOnly 控制是否只准备 driver;跳过浏览器下载时不能让子进程误下载 Chromium。
args := []string{"-driver-dir", options.DriverDirectory}
if options.SkipInstallBrowsers {
args = append(args, "-driver-only")
}
// configured 是部署显式指定的独立安装器路径,必须是可被 Context 直接终止的单一进程入口。
if configured := strings.TrimSpace(os.Getenv("PLAYWRIGHT_BROWSER_INSTALLER")); configured != "" {
return configured, args, nil
}
// executable 保存当前服务可执行文件路径;打包目录约定 browser-install 与服务二进制同目录。
if executable, err := os.Executable(); err == nil {
// candidate 是与服务二进制同目录的打包安装器路径。
candidate := filepath.Join(filepath.Dir(executable), "browser-install")
if runtime.GOOS == "windows" {
candidate += ".exe"
}
// statErr 表示候选安装器不存在或不可访问时的文件检查错误。
if _, statErr := os.Stat(candidate); statErr == nil {
return candidate, args, nil
}
}
// sourceFile 保存当前编译单元的源码路径;开发模式依赖它定位模块内唯一的安装器入口。
_, sourceFile, _, callerOK := runtime.Caller(0)
if callerOK {
// moduleRoot 是从 internal/browser/lifecycle.go 回退两级得到的 Go 模块根目录。
moduleRoot := filepath.Clean(filepath.Join(filepath.Dir(sourceFile), "..", ".."))
// installerSource 是开发源码树中的安装器 main 包,必须与运行中库版本一致。
installerSource := filepath.Join(moduleRoot, "cmd", "browser-install")
// moduleFileErr、installerErr 分别验证模块声明和安装器源码存在,避免把任意工作目录交给 go run。
_, moduleFileErr := os.Stat(filepath.Join(moduleRoot, "go.mod"))
// installerErr 表示源码安装器入口是否存在;缺失时继续尝试其他部署方式并返回可诊断错误。
_, installerErr := os.Stat(filepath.Join(installerSource, "main.go"))
if moduleFileErr == nil && installerErr == nil {
// goCommand 是当前开发工具链的绝对路径;找不到时保留清晰的部署错误,而不是启动无法管理的下载 goroutine。
goCommand, goErr := exec.LookPath("go")
if goErr == nil {
// sourceArgs 强制 Go 工具链在模块根解析依赖,测试或调用方切换工作目录时仍把双横线后的参数交给安装器。
sourceArgs := append([]string{"-C", moduleRoot, "run", installerSource, "--"}, args...)
return goCommand, sourceArgs, nil
}
}
}
return "", nil, errors.New("找不到可取消的 browser-install 安装器,请配置 PLAYWRIGHT_BROWSER_INSTALLER、同目录安装器或在源码开发环境中提供 Go 工具链")
}
// beginOperation 登记一个可能持有 Chromium 实例的调用;关闭开始后拒绝新调用。
// ctx 仅用于在进入状态机前传播调用方取消语义,不会启动无法回收的等待 goroutine。
func (m *Manager) beginOperation(ctx context.Context) error {
@@ -266,6 +374,7 @@ func (m *Manager) beginOperation(ctx context.Context) error {
return errors.New("浏览器操作需要调用方 Context")
}
// err 表示调用方 Context 已取消,管理器不会为已取消调用登记活动任务。
// err 保存进入初始化前已取消的 Context 错误。
if err := ctx.Err(); err != nil {
return err
}
@@ -328,32 +437,94 @@ func (m *Manager) acquireRenewSlot(ctx context.Context) (func(), error) {
}
}
// init 懒加载 playwright(首次调用时下载 driver + chromium)。
// init 为未传递 Context 的既有浏览器调用提供有限预算;冻结验证码调用链继续使用该兼容入口。
func (m *Manager) init() error {
m.once.Do(func() {
if // err 用于本次流程后续判断的err
err := m.installFn(); err != nil {
m.initErr = fmt.Errorf("安装 playwright/chromium 失败(缺系统依赖时需手动执行 playwright install --with-deps): %w", err)
return
// initCtx、initCancel 为兼容调用提供有限初始化预算;新生命周期入口必须使用 initContext。
initCtx, initCancel := context.WithTimeout(context.Background(), legacyLifecycleOperationTimeout)
defer initCancel()
return m.initContext(initCtx)
}
// initContext 串行完成安装、启动和指纹探测;取消或探测失败会释放已经启动的 Playwright,允许后续重试。
func (m *Manager) initContext(ctx context.Context) error {
if ctx == nil {
return errors.New("初始化浏览器需要 Context")
}
// err 保存获得初始化互斥锁后观察到的取消错误。
if err := ctx.Err(); err != nil {
return err
}
m.initMu.Lock()
defer m.initMu.Unlock()
if m.installed {
return nil
}
if m.initErr != nil {
return m.initErr
}
// err 保存获得初始化互斥锁后观察到的取消错误。
if err := ctx.Err(); err != nil {
return err
}
// err 保存可观察安装阶段的错误。
if err := m.installFn(ctx); err != nil {
// contextErr 保存安装返回后观察到的取消错误,取消不应污染可重试初始化状态。
if contextErr := ctx.Err(); contextErr != nil {
return contextErr
}
// pw、err 用于本次流程后续判断的pw、err
pw, err := m.runFn()
if err != nil {
m.initErr = fmt.Errorf("启动 playwright 失败: %w", err)
return
m.initErr = fmt.Errorf("安装 playwright/chromium 失败(缺系统依赖时需手动执行 playwright install --with-deps): %w", err)
return m.initErr
}
// err 保存安装完成后、启动 Playwright 前观察到的取消错误。
if err := ctx.Err(); err != nil {
return err
}
// pw、runErr 保存 Playwright 启动结果;任何后续失败都必须同步停止该进程。
pw, runErr := m.runFn(ctx)
if runErr != nil {
// contextErr 保存启动阶段返回时的取消错误,优先于基础设施启动错误返回。
if contextErr := ctx.Err(); contextErr != nil {
return contextErr
}
m.pw = pw
if // err 用于本次流程后续判断的err
err := m.detectBrowserFingerprint(); err != nil {
m.initErr = fmt.Errorf("读取 Playwright Chromium 原生指纹失败: %w", err)
m.initErr = fmt.Errorf("启动 playwright 失败: %w", runErr)
return m.initErr
}
// err 保存 Playwright 启动后、发布实例前观察到的取消错误。
if err := ctx.Err(); err != nil {
if pw != nil {
_ = pw.Stop()
m.pw = nil
return
}
m.installed = true
m.logger.Info("playwright chromium 就绪")
})
return m.initErr
return err
}
m.pw = pw
// err 保存 Chromium 指纹探测错误;失败时必须释放刚启动的 Playwright。
// fingerprintFn 保存生产探测函数;零值测试 Manager 没有注入时回退到真实实现。
fingerprintFn := m.fingerprintFn
if fingerprintFn == nil {
fingerprintFn = m.detectBrowserFingerprint
}
// err 保存 Chromium 指纹探测失败原因,失败时必须释放尚未发布的 Playwright。
if err := fingerprintFn(); err != nil {
if pw != nil {
_ = pw.Stop()
}
m.pw = nil
// contextErr 保存探测失败同时观察到的取消错误,取消语义优先于探测诊断。
if contextErr := ctx.Err(); contextErr != nil {
return contextErr
}
m.initErr = fmt.Errorf("读取 Playwright Chromium 原生指纹失败: %w", err)
return m.initErr
}
// err 保存指纹探测后、最终发布前观察到的取消错误。
if err := ctx.Err(); err != nil {
_ = pw.Stop()
m.pw = nil
return err
}
m.installed = true
m.logger.Info("playwright chromium 就绪")
return nil
}
// Initialize 为兼容旧调用方在受限 Context 内启动 Playwright。
@@ -371,7 +542,7 @@ func (m *Manager) InitializeContext(ctx context.Context) error {
return err
}
defer m.endOperation()
return m.init()
return m.initContext(ctx)
}
// detectBrowserFingerprint 封装detect浏览器Fingerprint业务协调。
+161
View File
@@ -4,6 +4,7 @@ import (
"context"
"errors"
"os"
"os/exec"
"path/filepath"
"runtime"
"testing"
@@ -91,6 +92,166 @@ func TestManagerCloseContextWithoutOperations(t *testing.T) {
}
}
// TestInitializeContextRejectsCancelledContext 验证初始化在启动安装阶段前就会传播调用方取消。
func TestInitializeContextRejectsCancelledContext(t *testing.T) {
// manager 保存尚未启动 Chromium 的浏览器管理器。
manager := NewManager(nil)
// initializeCtx、cancel 分别是已取消的初始化 Context 及其取消函数。
initializeCtx, cancel := context.WithCancel(context.Background())
cancel()
// initErr 保存已取消初始化返回的错误;不得触发 Playwright 安装或启动。
initErr := manager.InitializeContext(initializeCtx)
if !errors.Is(initErr, context.Canceled) {
t.Fatalf("已取消初始化应返回 Context 错误: %v", initErr)
}
}
// TestInitializeContextCancelsAfterInstall 验证安装阶段结束时收到取消会阻止 Playwright 启动并允许后续关闭。
func TestInitializeContextCancelsAfterInstall(t *testing.T) {
// manager 保存可注入安装回调的浏览器管理器。
manager := NewManager(nil)
// initializeCtx、cancel 分别控制安装阶段完成后的初始化取消。
initializeCtx, cancel := context.WithCancel(context.Background())
// installCalled 记录测试安装回调是否已执行。
installCalled := false
manager.installFn = func(context.Context) error {
installCalled = true
cancel()
return nil
}
manager.runFn = func(context.Context) (*playwright.Playwright, error) {
t.Fatal("安装后取消不应启动 Playwright")
return nil, nil
}
// initErr 保存安装阶段取消传播的结果。
initErr := manager.InitializeContext(initializeCtx)
if !installCalled || !errors.Is(initErr, context.Canceled) {
t.Fatalf("安装阶段取消未传播: called=%v err=%v", installCalled, initErr)
}
// closeErr 验证初始化取消后 CloseContext 仍可幂等完成。
closeErr := manager.CloseContext(context.Background())
if closeErr != nil {
t.Fatalf("初始化取消后关闭失败: %v", closeErr)
}
}
// TestInstallPlaywrightRuntimeCancelsInstaller 验证完整 runtime 安装由 Context 控制的独立进程执行,取消后不会继续后台下载。
func TestInstallPlaywrightRuntimeCancelsInstaller(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Windows 使用不同的脚本启动语义,本机 Unix 受控子进程已覆盖")
}
// installer 保存模拟长期下载的独立安装器;exec 取代 shell 后只保留一个可终止 sleep 进程。
installer := filepath.Join(t.TempDir(), "browser-install")
// writeErr 保存写入模拟安装器脚本时的文件系统错误。
if writeErr := os.WriteFile(installer, []byte("#!/bin/sh\nexec sleep 60\n"), 0o755); writeErr != nil {
t.Fatalf("写入测试安装器失败: %v", writeErr)
}
t.Setenv("PLAYWRIGHT_BROWSER_INSTALLER", installer)
// installCtx、cancel 为安装子进程提供很短的关闭预算。
installCtx, cancel := context.WithTimeout(context.Background(), 30*time.Millisecond)
defer cancel()
// installErr 保存安装器被 Context 终止后的错误;必须是取消而不是等待六十秒。
installErr := installPlaywrightRuntime(installCtx, &playwright.RunOptions{DriverDirectory: t.TempDir()})
if !errors.Is(installErr, context.DeadlineExceeded) {
t.Fatalf("安装器取消错误=%v,want DeadlineExceeded", installErr)
}
}
// TestBrowserInstallerCommandUsesControlledSourceFallback 验证源码开发环境未部署二进制安装器时,仍会选择可被 Context 终止的同一安装入口。
func TestBrowserInstallerCommandUsesControlledSourceFallback(t *testing.T) {
// 无显式安装器时测试二进制同目录不存在 browser-install,解析器必须退回源码入口。
t.Setenv("PLAYWRIGHT_BROWSER_INSTALLER", "")
// driverDir 保存测试专用 Playwright driver 目录,用于验证参数会无损传入独立安装器。
driverDir := t.TempDir()
// command、args、resolveErr 分别保存解析后的 Go 工具链、安装器参数和解析错误。
command, args, resolveErr := browserInstallerCommand(&playwright.RunOptions{DriverDirectory: driverDir})
if resolveErr != nil {
t.Fatalf("源码安装器解析失败: %v", resolveErr)
}
// expectedCommand 是当前测试工具链的绝对 Go 命令路径,源码 fallback 不应依赖调用方 PATH 的后续变化。
expectedCommand, lookErr := exec.LookPath("go")
if lookErr != nil {
t.Fatalf("测试环境找不到 Go 工具链: %v", lookErr)
}
if command != expectedCommand {
t.Fatalf("源码 fallback 命令=%q,want %q", command, expectedCommand)
}
// sourcePath 是从当前测试源码反推的模块安装器目录,必须和生产安装器共用同一 main 包。
_, sourcePath, _, callerOK := runtime.Caller(0)
if !callerOK {
t.Fatal("无法读取测试源码路径")
}
// moduleRoot 是源码 fallback 传给 Go -C 的模块根,避免调用方切换目录后丢失 go.mod。
moduleRoot := filepath.Join(filepath.Dir(sourcePath), "..", "..")
// wantInstaller 是模块根下的唯一安装器源码目录。
wantInstaller := filepath.Join(filepath.Dir(sourcePath), "..", "..", "cmd", "browser-install")
if len(args) != 7 || args[0] != "-C" || args[1] != moduleRoot || args[2] != "run" || args[3] != wantInstaller || args[4] != "--" || args[5] != "-driver-dir" || args[6] != driverDir {
t.Fatalf("源码 fallback 参数=%q,不符合受控安装器契约", args)
}
}
// TestInitializeContextFingerprintFailureReleasesPartialState 验证指纹探测失败不会把尚未完整初始化的 Playwright 发布为可用实例。
func TestInitializeContextFingerprintFailureReleasesPartialState(t *testing.T) {
// manager 使用确定性替身隔离安装和启动,测试只验证发布与关闭语义。
manager := NewManager(nil)
manager.installFn = func(context.Context) error { return nil }
manager.runFn = func(context.Context) (*playwright.Playwright, error) { return nil, nil }
// fingerprintErr 是指纹探测的确定性失败原因。
fingerprintErr := errors.New("fingerprint failed")
manager.fingerprintFn = func() error { return fingerprintErr }
// initErr 保存探测失败的初始化错误,并确认 Manager 未发布半成品实例。
initErr := manager.InitializeContext(context.Background())
if !errors.Is(initErr, fingerprintErr) || manager.pw != nil || manager.installed {
t.Fatalf("指纹失败后发布了半成品: err=%v pw=%p installed=%v", initErr, manager.pw, manager.installed)
}
// closeErr 是半成品资源释放后的关闭结果,验证 CloseContext 仍可幂等收束。
if closeErr := manager.CloseContext(context.Background()); closeErr != nil {
t.Fatalf("指纹失败后关闭失败: %v", closeErr)
}
}
// TestInitializeAndCloseContextShareCancellation 验证初始化与关闭并发时,生命周期取消会让安装退出并让 CloseContext 等待收束。
func TestInitializeAndCloseContextShareCancellation(t *testing.T) {
// manager 保存阻塞安装阶段的浏览器管理器。
manager := NewManager(nil)
// entered 通知安装替身已开始等待生命周期取消。
entered := make(chan struct{})
manager.installFn = func(ctx context.Context) error {
close(entered)
<-ctx.Done()
return ctx.Err()
}
// lifecycleCtx、cancelLifecycle 模拟协调器拥有的进程生命周期。
lifecycleCtx, cancelLifecycle := context.WithCancel(context.Background())
defer cancelLifecycle()
// initDone 保存初始化调用的取消结果。
initDone := make(chan error, 1)
go func() { initDone <- manager.InitializeContext(lifecycleCtx) }()
select {
case <-entered:
case <-time.After(time.Second):
t.Fatal("初始化未进入安装阶段")
}
// closeDone 保存关闭等待结果;关闭应先拒绝新操作并等待正在初始化的调用结束。
closeDone := make(chan error, 1)
go func() { closeDone <- manager.CloseContext(context.Background()) }()
cancelLifecycle()
// initErr 保存生命周期取消后初始化 goroutine 的最终错误。
if initErr := <-initDone; !errors.Is(initErr, context.Canceled) {
t.Fatalf("初始化取消错误=%v", initErr)
}
select {
// closeErr 保存初始化已退出后并发关闭操作的最终结果。
case closeErr := <-closeDone:
if closeErr != nil {
t.Fatalf("并发关闭失败: %v", closeErr)
}
case <-time.After(time.Second):
t.Fatal("并发关闭未等待初始化收束")
}
}
// TestChromiumLaunchArgs 验证启动参数含关键安全/反检测项。
func TestChromiumLaunchArgs(t *testing.T) {
// args 用于本次流程后续判断的args
+49 -5
View File
@@ -44,6 +44,8 @@ const (
// Services 聚合组合根已完成构造的应用服务与后台组件。
// 它只由 composition 创建,随后通过 server.Dependencies 的最小 Port 交给 HTTP transport。
type Services struct {
// lifecycleContext 返回进程协调器拥有的 worker 根 Context;HTTP transport 只能通过组合层适配器使用它。
lifecycleContext func() context.Context
// qrLogin 是二维码平台协议的组合层私有实例,只通过 HTTP 用例 Port 暴露。
qrLogin adapter.QRLoginService
// platformCredentials 负责按需读取平台凭证窄视图并执行归属复核。
@@ -124,6 +126,14 @@ type Services struct {
admin *adminapp.Service
}
// LifecycleContext 返回已启动协调器拥有的进程生命周期 Context,供组合层 transport adapter 注册后台 worker。
func (services *Services) LifecycleContext() context.Context {
if services == nil || services.lifecycleContext == nil {
return nil
}
return services.lifecycleContext()
}
// Dependencies 是进程组合根构造应用服务所需的不可变依赖集合。
// 它不包含 HTTP Server;服务只能使用窄仓储工厂、运行时端口和受控回调。
type Dependencies struct {
@@ -165,6 +175,42 @@ type Dependencies struct {
LifecycleContext func() context.Context
}
// settingsRuntimeTransport 将账号运行时控制投影给设置用例,并确保启用或 Cookie 重启永远使用进程生命周期 Context。
type settingsRuntimeTransport struct {
// manager 是账号运行实例和停止 fencing 的唯一拥有者。
manager *account.Manager
// lifecycleContext 返回协调器已启动后的进程根 Context,不能由 HTTP 请求提供。
lifecycleContext func() context.Context
}
// Restart 使用进程生命周期 Context 重新创建账号实例,避免请求断开后留下半完成转换。
func (transport settingsRuntimeTransport) Restart(_ context.Context, accountID string) error {
// lifecycleCtx 是当前进程拥有的运行实例 Context;nil 表示组合根未正确启动。
lifecycleCtx := context.Context(nil)
if transport.lifecycleContext != nil {
lifecycleCtx = transport.lifecycleContext()
}
if lifecycleCtx == nil {
return errors.New("账号运行时生命周期 Context 未初始化")
}
return transport.manager.Restart(lifecycleCtx, accountID)
}
// BeginStopping 建立账号停止 fencing,阻止其他运行时入口在停用转换中重新启动实例。
func (transport settingsRuntimeTransport) BeginStopping(accountID string) bool {
return transport.manager.BeginStopping(accountID)
}
// EndStopping 释放本次设置转换建立的账号停止 fencing。
func (transport settingsRuntimeTransport) EndStopping(accountID string) {
transport.manager.EndStopping(accountID)
}
// StopContext 在 HTTP 关闭预算内停止账号实例,并将错误回传给设置用例映射为可重试冲突。
func (transport settingsRuntimeTransport) StopContext(ctx context.Context, accountID string) error {
return transport.manager.StopContext(ctx, accountID)
}
// LifecycleComponents 返回由组合根登记的应用 worker 生命周期组件。
// 组件只暴露 Start/Close 端口,启动顺序与进程取消责任由 cmd 的协调器拥有。
func (services *Services) LifecycleComponents() []lifecycleapp.NamedComponent {
@@ -339,11 +385,8 @@ func New(dependencies Dependencies) (*Services, error) {
if longLoginErr != nil {
return nil, fmt.Errorf("构造账号长登录服务失败: %w", longLoginErr)
}
// accountSettings 由独立适配器承载账号设置写入与敏感登录信息更新。
var settingsRuntime accountapp.SettingsRuntime
if dependencies.Manager != nil {
settingsRuntime = dependencies.Manager
}
// settingsRuntime 将运行时启停绑定到协调器 Context,避免把请求 Context 错误当成账号实例生命周期。
settingsRuntime := accountapp.SettingsRuntime(settingsRuntimeTransport{manager: dependencies.Manager, lifecycleContext: dependencies.LifecycleContext})
// accountSettings、accountSettingsErr 保存账号设置应用服务及其装配错误。
accountSettings, accountSettingsErr := accountapp.NewSettingsService(dependencies.AccountDependencies.NewAccountSettingsRepository(), settingsRuntime)
if accountSettingsErr != nil {
@@ -418,6 +461,7 @@ func New(dependencies Dependencies) (*Services, error) {
}
// services 是完成构造后只读注入 Server 的应用服务集合。
services := &Services{
lifecycleContext: dependencies.LifecycleContext,
qrLogin: dependencies.QRLogin,
platformCredentials: platformCredentials,
orders: orderServices,
+11
View File
@@ -133,6 +133,17 @@ func BuildRuntime(options RuntimeOptions, infrastructure RuntimeInfrastructure)
if platformErr != nil {
return Runtime{}, fmt.Errorf("构造平台基础设施依赖失败: %w", platformErr)
}
// qrLifecycle 是二维码平台管理器可选的进程生命周期能力;HTTP Port 仍只暴露二维码用例。
qrLifecycle, qrLifecycleEnabled := platformDependencies.QRLoginService().(interface {
Start(context.Context) error
CloseContext(context.Context) error
})
if qrLifecycleEnabled {
// addErr 是二维码后台会话管理器登记失败原因;其关闭发生在 HTTP 停止之后,由协调器统一等待任务退出。
if addErr := lifecycleCoordinator.Add(lifecycle.NamedComponent{Name: "qr-login-manager", Component: lifecycle.FuncComponent{StartFunc: qrLifecycle.Start, CloseFunc: qrLifecycle.CloseContext}}); addErr != nil {
return Runtime{}, fmt.Errorf("登记二维码生命周期组件失败: %w", addErr)
}
}
// transportApplications、transportErr 分别是通知等共享应用服务集合及其构造错误。
transportApplications, transportErr := adapter.NewTransportApplicationServices(adapter.TransportApplicationServiceOptions{
AutomationDependencies: automationDependencies, MiscDependencies: miscDependencies, AdminSettingsDependencies: adminSettingsDependencies,
@@ -96,6 +96,35 @@ type ordersTransport struct {
services *orderapp.ServiceSet
}
// orderRefreshJobsTransport 将订单刷新后台任务的请求边界与进程生命周期边界分离。
// requestCtx 只用于本次 HTTP 归属校验和任务持久化;lifecycleContext 始终由协调器拥有,确保 worker 不会随请求结束取消。
type orderRefreshJobsTransport struct {
// service 是组合根已经完成构造的订单刷新任务应用服务。
service *orderapp.RefreshJobService
// lifecycleContext 返回协调器启动后拥有的进程生命周期 Context。
lifecycleContext func() context.Context
}
// CreateAndStart 使用请求 Context 完成同步数据库操作,并使用进程 Context 注册后台 worker。
func (transport orderRefreshJobsTransport) CreateAndStart(requestCtx context.Context, userID int64, cookieID, status string) (orderapp.RefreshJobStartResult, error) {
// lifecycleCtx 是当前进程拥有的后台 worker 生命周期;空函数属于构造错误而非 HTTP 请求错误。
lifecycleCtx := context.Context(nil)
if transport.lifecycleContext != nil {
lifecycleCtx = transport.lifecycleContext()
}
return transport.service.CreateAndStart(requestCtx, lifecycleCtx, userID, cookieID, status)
}
// GetJob 读取当前用户拥有的订单刷新任务快照。
func (transport orderRefreshJobsTransport) GetJob(ctx context.Context, userID int64, jobID string) (*orderapp.RefreshJob, error) {
return transport.service.GetJob(ctx, userID, jobID)
}
// CancelForUser 取消当前用户尚未结束的订单刷新任务。
func (transport orderRefreshJobsTransport) CancelForUser(ctx context.Context, userID int64, jobID string) (orderapp.RefreshJobCancelResult, error) {
return transport.service.CancelForUser(ctx, userID, jobID)
}
// RefreshSingle 转发单订单刷新用例。
func (transport ordersTransport) RefreshSingle(ctx context.Context, userID int64, orderID string) (orderapp.SingleRefreshResult, error) {
return transport.services.Refresh.RefreshSingle(ctx, userID, orderID)
@@ -173,7 +202,7 @@ func ServerDependencies(services *composition.Services, base HTTPDependencies, s
return server.Dependencies{
Auth: base.Auth, WebDir: base.WebDir, Addr: base.Addr, Logger: base.Logger, DatabaseHealth: base.DatabaseHealth,
Applications: server.NewApplicationPorts(server.ApplicationPortsInput{
Orders: ordersTransport{services: ports.Orders}, OrderRefreshJobs: ports.OrderRefreshJobs,
Orders: ordersTransport{services: ports.Orders}, OrderRefreshJobs: orderRefreshJobsTransport{service: ports.OrderRefreshJobs, lifecycleContext: services.LifecycleContext},
ItemSinglePublish: ports.ItemSinglePublish, ItemBatchPreview: ports.ItemBatchPreview,
ItemBatchManagement: ports.ItemBatchManagement, ItemCategoryRecommendation: ports.ItemCategoryRecommendation,
ItemBatchPreviewPersistence: ports.ItemBatchPreviewPersistence, ItemBatchLocalPublish: ports.ItemBatchLocalPublish,
+1 -1
View File
@@ -65,7 +65,7 @@ type OrdersPort interface {
// OrderRefreshJobsPort 定义订单刷新任务 HTTP 接口所需的最小能力。
type OrderRefreshJobsPort interface {
CreateAndStart(context.Context, context.Context, int64, string, string) (orderapp.RefreshJobStartResult, error)
CreateAndStart(context.Context, int64, string, string) (orderapp.RefreshJobStartResult, error)
GetJob(context.Context, int64, string) (*orderapp.RefreshJob, error)
CancelForUser(context.Context, int64, string) (orderapp.RefreshJobCancelResult, error)
}
+14 -33
View File
@@ -243,42 +243,15 @@ func (s *Server) updateCookieSettings(w http.ResponseWriter, r *http.Request) {
if settingsResult.RuntimeError != nil && s.Logger != nil {
s.Logger.Error("账号设置保存后重启失败", "cookie_id", cid, "err", settingsResult.RuntimeError)
}
if settingsResult.RuntimeError != nil {
writeErr(w, http.StatusServiceUnavailable, "账号设置已保存,但运行实例重启失败,请重试启用账号")
return
}
writeJSON(w, http.StatusOK, cookieSettingsResponse{
Success: true, PausedUntil: settingsResult.PausedUntil, Paused: settingsResult.PausedUntil > time.Now().UTC().Unix(),
})
}
// listCookieRuntimeStatus 返回本地账号引擎状态,不请求闲鱼 API,可安全用于前端轮询。
func (s *Server) listCookieRuntimeStatus(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。
accountSummary := s.accountSummaryApplication()
cookieIDs, err := accountSummary.ListOwnedIDs(r.Context(), sess.UserID) // cookieIDs 和 err 是账号 ID 列表及查询错误。
if err != nil {
writeErr(w, http.StatusInternalServerError, "获取账号失败")
return
}
// runtime、runtimeErr 保存应用层返回的账号运行状态快照及读取错误。
runtime, runtimeErr := s.accountRuntimeApplication().RuntimeStatuses(r.Context())
if runtimeErr != nil {
writeErr(w, http.StatusInternalServerError, "获取账号运行状态失败")
return
}
result := make(map[string]accountapp.RuntimeStatus, len(cookieIDs)) // result 是返回给前端的状态映射。
for _, cid := range cookieIDs { // cid 是当前账号 ID。
enabled, statusErr := accountSummary.StatusOwned(r.Context(), sess.UserID, cid)
if statusErr != nil || !enabled {
result[cid] = accountapp.RuntimeStatus{State: "disabled", Message: "账号已停用", UpdatedAt: time.Now()}
continue
}
if status, ok := runtime[cid]; ok { // status 和 ok 表示已记录的运行状态及存在性。
result[cid] = status
continue
}
result[cid] = accountapp.RuntimeStatus{State: "error", Message: "账号服务未运行", UpdatedAt: time.Now()}
}
writeJSON(w, http.StatusOK, result)
}
// listCookies 列出当前用户的 cookie_id。
func (s *Server) listCookies(w http.ResponseWriter, r *http.Request) {
sess := auth.SessionFromContext(r.Context()) // sess 是当前认证会话。
@@ -567,8 +540,16 @@ func (s *Server) setCookieStatus(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusInternalServerError, "更新失败")
return
}
if result.RuntimeError != nil && s.Logger != nil {
s.Logger.Error("启停账号运行实例失败", "cookie_id", cid, "err", result.RuntimeError)
if result.RuntimeError != nil {
if s.Logger != nil {
s.Logger.Error("启停账号运行实例失败", "cookie_id", cid, "err", result.RuntimeError)
}
if errors.Is(result.RuntimeError, accountapp.ErrRuntimeStopConflict) {
writeErr(w, http.StatusConflict, "账号运行实例尚未停止,请稍后重试")
return
}
writeErr(w, http.StatusServiceUnavailable, "账号运行实例启动失败,请重试")
return
}
writeJSON(w, http.StatusOK, operationResponse{Success: true})
}
+86
View File
@@ -19,6 +19,92 @@ import (
xrenew "xianyu-go/internal/xianyu/renew"
)
// runtimeStatusPortStub 是运行状态 HTTP 契约测试的最小应用 Port,不持有真实账号实例或凭证。
type runtimeStatusPortStub struct {
// statuses 保存按账号标识返回的非敏感运行时快照。
statuses map[string]accountapp.RuntimeStatus
}
// UpdateCookie 满足运行状态 Port;本测试不触发 Cookie 同步。
func (stub runtimeStatusPortStub) UpdateCookie(context.Context, string, string) error { return nil }
// RuntimeStatuses 返回预置快照,模拟数据库状态与运行实例状态暂时不一致。
func (stub runtimeStatusPortStub) RuntimeStatuses(context.Context) (map[string]accountapp.RuntimeStatus, error) {
return stub.statuses, nil
}
// Restart 满足运行状态 Port;本测试不触发运行实例重启。
func (stub runtimeStatusPortStub) Restart(context.Context, string) error { return nil }
// RecoverExpiredCredential 满足运行状态 Port;本测试不触发平台凭证恢复。
func (stub runtimeStatusPortStub) RecoverExpiredCredential(context.Context, string) bool {
return false
}
// TestRuntimeStatusIsActive 保证已停用账号的存活运行实例不会被状态查询掩盖为普通 disabled。
func TestRuntimeStatusIsActive(t *testing.T) {
// cases 保存运行状态与是否仍需暴露冲突诊断的对应关系。
cases := []struct {
name string
status accountapp.RuntimeStatus
wantAlive bool
}{
{name: "connected", status: accountapp.RuntimeStatus{Connected: true}, wantAlive: true},
{name: "connecting", status: accountapp.RuntimeStatus{State: "connecting"}, wantAlive: true},
{name: "exited", status: accountapp.RuntimeStatus{State: "error", Message: "账号服务已退出"}, wantAlive: false},
{name: "stopped", status: accountapp.RuntimeStatus{State: "stopped"}, wantAlive: false},
}
// testCase 是当前验证的运行状态样本。
for _, testCase := range cases {
t.Run(testCase.name, func(t *testing.T) {
// got 是当前样本是否必须向管理页面暴露运行时冲突的判断结果。
if got := runtimeStatusIsActive(testCase.status); got != testCase.wantAlive {
t.Fatalf("runtimeStatusIsActive(%+v)=%v, want %v", testCase.status, got, testCase.wantAlive)
}
})
}
}
// TestCookieRuntimeStatusPreservesDisabledActiveConflict 验证数据库已停用但实例仍连接时 HTTP 查询返回冲突诊断而非掩盖为 disabled。
func TestCookieRuntimeStatusPreservesDisabledActiveConflict(t *testing.T) {
// srv、store、cleanup 保存已认证 HTTP 夹具、持久化状态和资源清理函数。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// statusErr 保存将测试账号持久化状态切换为停用的错误。
statusErr := store.Cookies.SetStatus(context.Background(), "acc1", false)
if statusErr != nil {
t.Fatalf("停用测试账号失败: %v", statusErr)
}
// runtimePort 模拟旧运行实例尚未退出时返回的连接中快照。
runtimePort := runtimeStatusPortStub{statuses: map[string]accountapp.RuntimeStatus{
"acc1": {State: "connecting", Message: "旧实例仍在关闭", Connected: true, UpdatedAt: time.Now().UTC()},
}}
srv.applications.accountRuntime = runtimePort
// handler 是含认证中间件的 HTTP 路由。
handler := srv.Router()
// sessionCookie 保存管理员认证会话 Cookie。
sessionCookie := loginHelper(t, handler)
// request 是读取版本化运行状态的 HTTP 请求。
request := httptest.NewRequest(http.MethodGet, "/api/v1/accounts/runtime-status", nil)
request.AddCookie(sessionCookie)
// recorder 捕获运行状态响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if recorder.Code != http.StatusOK {
t.Fatalf("运行状态 HTTP status=%d body=%s", recorder.Code, recorder.Body.String())
}
// statuses 保存解码后的按账号运行状态映射。
statuses := map[string]accountapp.RuntimeStatus{}
// decodeErr 保存 HTTP 响应不符合非敏感运行状态 DTO 时的 JSON 解码错误。
if decodeErr := json.Unmarshal(recorder.Body.Bytes(), &statuses); decodeErr != nil {
t.Fatalf("解析运行状态响应失败: %v", decodeErr)
}
// status 是冲突账号返回的运行时快照,必须保留实际连接状态。
if status := statuses["acc1"]; status.State != "runtime_conflict" || !status.Connected {
t.Fatalf("停用但存活的实例被掩盖: %+v", status)
}
}
// cachedAccountNickname 保留测试对账号展示名兼容规则的独立验证,不参与生产 HTTP 路径。
func cachedAccountNickname(d *db.CookieDetail) string {
if strings.TrimSpace(d.Remark) != "" {
+70
View File
@@ -0,0 +1,70 @@
package server
import (
"net/http"
"time"
accountapp "xianyu-go/internal/application/account"
"xianyu-go/internal/auth"
)
// listCookieRuntimeStatus 返回本地账号引擎状态,不请求闲鱼 API;停用但仍存活的实例必须作为冲突诊断返回。
func (s *Server) listCookieRuntimeStatus(w http.ResponseWriter, r *http.Request) {
// sess 是当前认证会话,只用于按用户过滤非敏感账号标识。
sess := auth.SessionFromContext(r.Context())
// accountSummary 提供账号归属、启用状态和非敏感 ID 查询。
accountSummary := s.accountSummaryApplication()
// cookieIDs、listErr 保存当前用户账号标识列表及读取错误。
cookieIDs, listErr := accountSummary.ListOwnedIDs(r.Context(), sess.UserID)
if listErr != nil {
writeErr(w, http.StatusInternalServerError, "获取账号失败")
return
}
// runtime、runtimeErr 保存应用层返回的账号运行状态快照及读取错误。
runtime, runtimeErr := s.accountRuntimeApplication().RuntimeStatuses(r.Context())
if runtimeErr != nil {
writeErr(w, http.StatusInternalServerError, "获取账号运行状态失败")
return
}
// result 是按当前用户账号 ID 返回的非敏感运行状态映射。
result := make(map[string]accountapp.RuntimeStatus, len(cookieIDs))
// cid 是当前需要合并数据库启用状态和运行实例快照的账号标识。
for _, cid := range cookieIDs {
// enabled、statusErr 保存数据库启用状态及归属复核错误。
enabled, statusErr := accountSummary.StatusOwned(r.Context(), sess.UserID, cid)
if statusErr != nil {
result[cid] = accountapp.RuntimeStatus{State: "disabled", Message: "账号已停用", UpdatedAt: time.Now()}
continue
}
// status、ok 保存运行实例快照及其存在标记。
if status, ok := runtime[cid]; ok {
if !enabled && runtimeStatusIsActive(status) {
status.State = "runtime_conflict"
status.Message = "数据库已停用,但运行实例仍存活,请重试停用"
result[cid] = status
continue
}
result[cid] = status
continue
}
if !enabled {
result[cid] = accountapp.RuntimeStatus{State: "disabled", Message: "账号已停用", UpdatedAt: time.Now()}
continue
}
result[cid] = accountapp.RuntimeStatus{State: "error", Message: "账号服务未运行", UpdatedAt: time.Now()}
}
writeJSON(w, http.StatusOK, result)
}
// runtimeStatusIsActive 判断运行时快照是否代表仍需关注的活动实例;已退出的 error/stopped 不伪装成冲突。
func runtimeStatusIsActive(status accountapp.RuntimeStatus) bool {
if status.Connected {
return true
}
switch status.State {
case "starting", "connecting", "online", "reconnecting", "auth_expired", "verification_required":
return true
default:
return false
}
}
@@ -59,7 +59,7 @@ func (s *Server) startOrderRefreshJob(w http.ResponseWriter, r *http.Request) {
// cookieID、filterStatus 保存订单刷新筛选条件。
cookieID, filterStatus := r.FormValue("cookie_id"), r.FormValue("status")
// started、err 保存应用服务创建并启动任务的结果。
started, err := s.orderRefreshJobsApplication().CreateAndStart(r.Context(), r.Context(), sess.UserID, cookieID, filterStatus)
started, err := s.orderRefreshJobsApplication().CreateAndStart(r.Context(), sess.UserID, cookieID, filterStatus)
if errors.Is(err, orderapp.ErrForbidden) {
writeErr(w, http.StatusForbidden, "Cookie不存在或无权访问")
return
@@ -53,6 +53,27 @@ type testOrdersTransport struct {
services *orderapp.ServiceSet
}
// testOrderRefreshJobsTransport 将测试组合根订单刷新服务投影为 HTTP Port,并隔离请求 Context 与 worker 生命周期。
type testOrderRefreshJobsTransport struct {
// service 是测试组合根构造的订单刷新任务应用服务。
service *orderapp.RefreshJobService
}
// CreateAndStart 使用请求 Context 完成创建,并使用测试进程 Context 驱动后台 worker。
func (transport testOrderRefreshJobsTransport) CreateAndStart(requestCtx context.Context, userID int64, cookieID, status string) (orderapp.RefreshJobStartResult, error) {
return transport.service.CreateAndStart(requestCtx, context.Background(), userID, cookieID, status)
}
// GetJob 返回当前用户拥有的订单刷新任务状态。
func (transport testOrderRefreshJobsTransport) GetJob(ctx context.Context, userID int64, jobID string) (*orderapp.RefreshJob, error) {
return transport.service.GetJob(ctx, userID, jobID)
}
// CancelForUser 取消当前用户拥有的订单刷新任务。
func (transport testOrderRefreshJobsTransport) CancelForUser(ctx context.Context, userID int64, jobID string) (orderapp.RefreshJobCancelResult, error) {
return transport.service.CancelForUser(ctx, userID, jobID)
}
// RefreshSingle 转发测试的单订单刷新用例。
func (transport testOrdersTransport) RefreshSingle(ctx context.Context, userID int64, orderID string) (orderapp.SingleRefreshResult, error) {
return transport.services.Refresh.RefreshSingle(ctx, userID, orderID)
+1 -1
View File
@@ -359,7 +359,7 @@ func testServerDependencies(authentication *auth.Service, databaseHealth Databas
// ports 是测试组合根投影的完整 transport Port 集合。
ports := services.TransportPorts()
return Dependencies{Auth: authentication, Addr: ":0", DatabaseHealth: databaseHealth, Applications: NewApplicationPorts(ApplicationPortsInput{
Orders: testOrdersTransport{services: ports.Orders}, OrderRefreshJobs: ports.OrderRefreshJobs, ItemSinglePublish: ports.ItemSinglePublish,
Orders: testOrdersTransport{services: ports.Orders}, OrderRefreshJobs: testOrderRefreshJobsTransport{service: ports.OrderRefreshJobs}, ItemSinglePublish: ports.ItemSinglePublish,
ItemBatchPreview: ports.ItemBatchPreview, ItemBatchManagement: ports.ItemBatchManagement, ItemCategoryRecommendation: ports.ItemCategoryRecommendation,
ItemBatchPreviewPersistence: ports.ItemBatchPreviewPersistence, ItemBatchLocalPublish: ports.ItemBatchLocalPublish,
ItemSync: ports.ItemSync, ItemCatalog: ports.ItemCatalog, ItemCatalogMutation: ports.ItemCatalogMutation,
@@ -1,3 +0,0 @@
import{b as ie,j as e,r as n,c as Oe}from"./react-vendor-C_od1ZSF.js";import{g as X,c as Pe,o as ke,p as ae,a as ce,d as Le}from"./index-CnIcNTyi.js";import{n as ue,X as de,f as ze,L as J,o as Ie,p as Ge,q as We,r as Te,s as $e,U as De,t as te,u as Ve,k as _e,Q as ve,v as Ee,R as Je,w as Ke,x as He,y as Ne,K as Xe,z as Ye,F as Ze,e as Fe,H as es}from"./icons-vendor-DwxdQTKt.js";const ss=(s,t)=>{const r=s.avatar_url||"";if(!r)return"";try{const a=new URL(r,window.location.origin);return a.hostname.endsWith("alicdn.com")&&a.searchParams.set("_v",t),a.toString()}catch{return r}},ts=async s=>{const t=await X("/api/v1/accounts/details",void 0,s),r=Pe(t,["data","accounts","details"]),a=Date.now().toString();return r.map(l=>({id:l.id,cookie_configured:l.has_cookie===!0,enabled:l.enabled,auto_confirm:l.auto_confirm,remark:l.remark,pause_duration:l.pause_duration,paused_until:Number(l.paused_until||0),paused:l.paused===!0,username:l.username||"",login_password_configured:void 0,show_browser:l.show_browser===!0||l.show_browser===1||l.show_browser==="1"||l.show_browser==="true",nickname:l.nickname||l.remark||`账号 ${l.id.substring(0,6)}`,avatar_url:ss(l,a),profile_error:l.profile_error||"",ai_enabled:!1,auto_rate_enabled:l.auto_rate_enabled,rate_content:l.rate_content||"不错的买家,交易愉快",auto_polish_enabled:l.auto_polish_enabled,polish_time:l.polish_time||"03:00",last_rate_scan_at:Number(l.last_rate_scan_at||0),last_polish_date:l.last_polish_date||"",last_polish_at:Number(l.last_polish_at||0)}))},as=async s=>{const t=await X("/api/v1/accounts/runtime-status",void 0,s);return ke(t,["statuses","data","result"])||{}},rs=async s=>ce("/api/v1/qr-login/generate",void 0,{...s,timeoutMs:(s==null?void 0:s.timeoutMs)??13e4}),ns=async(s,t)=>X(`/api/v1/qr-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),ls=async(s,t)=>ce(`/api/v1/qr-login/complete-verification/${s}`,{target_account_id:t||""}),os=async(s,t)=>ae(`/api/v1/accounts/${s}/status`,{enabled:t}),is=async s=>Le(`/api/v1/accounts/${s}`),cs=async(s,t,r)=>ae(`/api/v1/accounts/${s}/pause-duration`,{pause_duration:t},r),ds=async(s,t,r)=>ae(`/api/v1/accounts/${s}/settings`,t,r),us=async(s,t)=>X(`/api/v1/accounts/${s}/long-login`,void 0,t),xs=async(s,t,r)=>ae(`/api/v1/accounts/${s}/long-login`,{enabled:t},r),ms=async(s,t)=>ce("/api/v1/password-login",s,t),bs=async(s,t)=>X(`/api/v1/password-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),hs=async(s,t)=>Le(`/api/v1/password-login/cancel/${s}`,void 0,t),gs=async s=>ce(`/api/v1/accounts/${s}/refresh-profile`,{}),ps=async s=>{const t=await X("/api/v1/settings/ai-reply",void 0,s);return ke(t,["settings","data","result"])||{}},fs=async(s,t)=>X(`/api/v1/settings/ai-reply/${s}`,void 0,t),ys=async(s,t,r)=>{const a={ai_enabled:t.ai_enabled??!1,max_discount_percent:t.max_discount_percent??10,max_discount_amount:t.max_discount_amount??100,max_bargain_rounds:t.max_bargain_rounds??3,custom_prompts:t.custom_prompts??""};return ae(`/api/v1/settings/ai-reply/${s}`,a,r)},js=s=>{if(Array.isArray(s))return s.filter(Boolean);if(typeof s!="string"||!s.trim())return[];try{const t=JSON.parse(s);if(Array.isArray(t))return t.filter(Boolean)}catch{}return s.split(/[,\s;]+/).map(t=>t.trim()).filter(Boolean)},ws=async s=>{const t=await X("/api/v1/notifications/channels",void 0,s);return{success:!0,data:Pe(t,["data","channels","items"]).map(a=>{let l;try{l=typeof a.config=="string"?JSON.parse(a.config):a.config}catch{l={}}const c=a.type==="ding_talk"?"dingtalk":a.type==="lark"?"feishu":a.type;return{id:String(a.id),name:a.name,type:c,config:l,event_types:js(a.event_types),enabled:a.enabled,created_at:a.created_at,updated_at:a.updated_at}})}},_s=async(s,t)=>{const r=await X(`/api/v1/notifications/accounts/${s}/bindings`,void 0,t),a=ke(r,["data","result"])||{};return Array.isArray(a.channel_ids)?a.channel_ids:[]},vs=({account:s,settings:t,saving:r,onChange:a,onClose:l,onSave:c})=>{const i=u=>a({...t,...u}),d=()=>i({ai_enabled:!t.ai_enabled}),b=u=>i({max_discount_percent:parseInt(u.target.value,10)||0}),m=u=>i({max_discount_amount:parseInt(u.target.value,10)||0}),f=u=>i({max_bargain_rounds:parseInt(u.target.value,10)||1}),h=u=>i({custom_prompts:u.target.value});return ie.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-2xl font-extrabold text-gray-900 flex items-center gap-2",children:[e.jsx(ue,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:s.nickname||s.remark||s.id})]}),e.jsx("button",{onClick:l,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0","aria-label":"关闭 AI 设置",children:e.jsx(de,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-betweeLine truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(ze,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:l,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:r,children:"取消"}),e.jsxs("button",{onClick:(()=>void c()),className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:r,children:[r?e.jsx(J,{className:"w-4 h-4 animate-spin"}):e.jsx(Ie,{className:"w-4 h-4"}),r?"保存中...":"保存"]})]})})]})}),document.body)},Ce=async(s,t)=>X(`/api/v1/account-tasks/${s}`,void 0,t),Se=async(s,t,r)=>ae(`/api/v1/account-tasks/${s}`,t,r),Ns=async(s,t,r)=>ce(`/api/v1/account-tasks/${s}/run`,{task_type:t},{timeoutMs:12e4,...r}),Re=s=>({account_id:s.id,auto_rate_enabled:s.auto_rate_enabled===!0,rate_content:s.rate_content||"不错的买家,交易愉快",auto_polish_enabled:s.auto_polish_enabled===!0,polish_time:s.polish_time||"03:00",last_rate_scan_at:s.last_rate_scan_at,last_polish_date:s.last_polish_date,last_polish_at:s.last_polish_at}),Y=(s,t,r)=>s===t&&!r.aborted,je=(s,t)=>s instanceof Error?s.message:t,we=s=>s instanceof Error&&s.message==="请求已取消",Ae=(s,t)=>!s&&t==="",ks=({account:s,onSaved:t})=>{const[r,a]=n.useState(()=>Re(s)),[l,c]=n.useState(!0),[i,d]=n.useState(!1),[b,m]=n.useState(""),[f,h]=n.useState(""),[u,A]=n.useState(null),[k,g]=n.useState(null),p=n.useRef(0),L=n.useRef(null);n.useEffect(()=>{var v;const S=++p.current;(v=L.current)==null||v.abort();const j=new AbortController;return L.current=j,a(Re(s)),A(null),h(""),d(!1),m(""),g(null),c(!0),Ce(s.id,{signal:j.signal}).then(R=>{Y(p.current,S,j.signal)&&a(R)}).catch(R=>{Y(p.current,S,j.signal)&&!we(R)&&h(je(R,"加载任务设置失败"))}).finally(()=>{Y(p.current,S,j.signal)&&c(!1)}),(()=>j.abort())},[s.id]),n.useEffect(()=>(()=>{var S;return(S=L.current)==null?void 0:S.abort()}),[]);const U=n.useCallback(async()=>{var v;if(!Ae(i,b))return;const S=++p.current;(v=L.current)==null||v.abort();const j=new AbortController;L.current=j,d(!0),h(""),g(null);try{const R=await Se(s.id,r,{signal:j.signal});if(!Y(p.current,S,j.signal))return;a(R),t(R)}catch(R){Y(p.current,S,j.signal)&&!we(R)&&(h(je(R,"保存失败")),g(()=>U))}finally{Y(p.current,S,j.signal)&&d(!1)}},[s.id,r,t,b,i]),M=n.useCallback(async S=>{var R;if(!Ae(i,b)||!s.enabled)return;const j=++p.current;(R=L.current)==null||R.abort();const v=new AbortController;L.current=v,m(S),h(""),A(null),g(null);try{await Se(s.id,r,{signal:v.signal});const w=await Ns(s.id,S,{signal:v.signal}),q=await Ce(s.id,{signal:v.signal});if(!Y(p.current,j,v.signal))return;A(w.summary),a(q),t(q)}catch(w){Y(p.current,j,v.signal)&&!we(w)&&(h(je(w,"任务执行失败")),g(()=>(()=>M(S))))}finally{Y(p.current,j,v.signal)&&m("")}},[s.enabled,s.id,r,t,b,i]),T=n.useCallback(async()=>{k&&await k()},[k]);return{form:r,loading:l,saving:i,running:b,summary:u,error:f,retryAvailable:k!==null,setForm:a,save:U,run:M,retry:T}},qe=({checked:s,onChange:t,label:r})=>e.jsx("button",{type:"button","aria-label":r,"aria-pressed":s,onClick:t,className:`relative h-8 w-14 shrink-0 rounded-full transition-colors ${s?"bg-sky-500":"bg-slate-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-sm transition-transform ${s?"translate-x-6":""}`})}),Cs=({account:s,onClose:t,onSaved:r})=>{const{form:a,loading:l,saving:c,running:i,error:d,summary:b,retryAvailable:m,setForm:f,save:h,run:u,retry:A}=ks({account:s,onSaved:r});return e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"640px"},role:"dialog","aria-modal":"true","aria-labelledby":"account-task-title",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{id:"account-task-title",className:"text-2xl font-extrabold text-slate-950",children:"账号自动任务"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:s.nickname||s.remark||s.id})]}),e.jsx("button",{type:"button",onClick:t,className:"rounded-xl p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700","aria-label":"关闭",children:e.jsx(de,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[l& Line truncated
@@ -0,0 +1,3 @@
import{b as ie,j as e,r as n,c as Oe}from"./react-vendor-C_od1ZSF.js";import{g as X,c as Pe,o as ke,p as ae,a as ce,d as Le}from"./index-KV7tSL6x.js";import{n as ue,X as de,f as ze,L as J,o as Ie,p as Ge,q as We,r as Te,s as $e,U as De,t as te,u as Ve,k as _e,Q as ve,v as Ee,R as Je,w as Ke,x as He,y as Ne,K as Xe,z as Ye,F as Ze,e as Fe,H as es}from"./icons-vendor-DwxdQTKt.js";const ss=(s,t)=>{const r=s.avatar_url||"";if(!r)return"";try{const a=new URL(r,window.location.origin);return a.hostname.endsWith("alicdn.com")&&a.searchParams.set("_v",t),a.toString()}catch{return r}},ts=async s=>{const t=await X("/api/v1/accounts/details",void 0,s),r=Pe(t,["data","accounts","details"]),a=Date.now().toString();return r.map(l=>({id:l.id,cookie_configured:l.has_cookie===!0,enabled:l.enabled,auto_confirm:l.auto_confirm,remark:l.remark,pause_duration:l.pause_duration,paused_until:Number(l.paused_until||0),paused:l.paused===!0,username:l.username||"",login_password_configured:void 0,show_browser:l.show_browser===!0||l.show_browser===1||l.show_browser==="1"||l.show_browser==="true",nickname:l.nickname||l.remark||`账号 ${l.id.substring(0,6)}`,avatar_url:ss(l,a),profile_error:l.profile_error||"",ai_enabled:!1,auto_rate_enabled:l.auto_rate_enabled,rate_content:l.rate_content||"不错的买家,交易愉快",auto_polish_enabled:l.auto_polish_enabled,polish_time:l.polish_time||"03:00",last_rate_scan_at:Number(l.last_rate_scan_at||0),last_polish_date:l.last_polish_date||"",last_polish_at:Number(l.last_polish_at||0)}))},as=async s=>{const t=await X("/api/v1/accounts/runtime-status",void 0,s);return ke(t,["statuses","data","result"])||{}},rs=async s=>ce("/api/v1/qr-login/generate",void 0,{...s,timeoutMs:(s==null?void 0:s.timeoutMs)??13e4}),ns=async(s,t)=>X(`/api/v1/qr-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),ls=async(s,t)=>ce(`/api/v1/qr-login/complete-verification/${s}`,{target_account_id:t||""}),os=async(s,t)=>ae(`/api/v1/accounts/${s}/status`,{enabled:t}),is=async s=>Le(`/api/v1/accounts/${s}`),cs=async(s,t,r)=>ae(`/api/v1/accounts/${s}/pause-duration`,{pause_duration:t},r),ds=async(s,t,r)=>ae(`/api/v1/accounts/${s}/settings`,t,r),us=async(s,t)=>X(`/api/v1/accounts/${s}/long-login`,void 0,t),xs=async(s,t,r)=>ae(`/api/v1/accounts/${s}/long-login`,{enabled:t},r),ms=async(s,t)=>ce("/api/v1/password-login",s,t),bs=async(s,t)=>X(`/api/v1/password-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),hs=async(s,t)=>Le(`/api/v1/password-login/cancel/${s}`,void 0,t),gs=async s=>ce(`/api/v1/accounts/${s}/refresh-profile`,{}),ps=async s=>{const t=await X("/api/v1/settings/ai-reply",void 0,s);return ke(t,["settings","data","result"])||{}},fs=async(s,t)=>X(`/api/v1/settings/ai-reply/${s}`,void 0,t),ys=async(s,t,r)=>{const a={ai_enabled:t.ai_enabled??!1,max_discount_percent:t.max_discount_percent??10,max_discount_amount:t.max_discount_amount??100,max_bargain_rounds:t.max_bargain_rounds??3,custom_prompts:t.custom_prompts??""};return ae(`/api/v1/settings/ai-reply/${s}`,a,r)},js=s=>{if(Array.isArray(s))return s.filter(Boolean);if(typeof s!="string"||!s.trim())return[];try{const t=JSON.parse(s);if(Array.isArray(t))return t.filter(Boolean)}catch{}return s.split(/[,\s;]+/).map(t=>t.trim()).filter(Boolean)},ws=async s=>{const t=await X("/api/v1/notifications/channels",void 0,s);return{success:!0,data:Pe(t,["data","channels","items"]).map(a=>{let l;try{l=typeof a.config=="string"?JSON.parse(a.config):a.config}catch{l={}}const c=a.type==="ding_talk"?"dingtalk":a.type==="lark"?"feishu":a.type;return{id:String(a.id),name:a.name,type:c,config:l,event_types:js(a.event_types),enabled:a.enabled,created_at:a.created_at,updated_at:a.updated_at}})}},_s=async(s,t)=>{const r=await X(`/api/v1/notifications/accounts/${s}/bindings`,void 0,t),a=ke(r,["data","result"])||{};return Array.isArray(a.channel_ids)?a.channel_ids:[]},vs=({account:s,settings:t,saving:r,onChange:a,onClose:l,onSave:c})=>{const i=u=>a({...t,...u}),d=()=>i({ai_enabled:!t.ai_enabled}),b=u=>i({max_discount_percent:parseInt(u.target.value,10)||0}),m=u=>i({max_discount_amount:parseInt(u.target.value,10)||0}),f=u=>i({max_bargain_rounds:parseInt(u.target.value,10)||1}),h=u=>i({custom_prompts:u.target.value});return ie.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"600px"},children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-2xl font-extrabold text-gray-900 flex items-center gap-2",children:[e.jsx(ue,{className:"w-6 h-6 text-purple-500"}),"AI助手设置"]}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:s.nickname||s.remark||s.id})]}),e.jsx("button",{onClick:l,className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0","aria-label":"关闭 AI 设置",children:e.jsx(de,{className:"w-5 h-5 text-gray-500"})})]}),e.jsxs("div",{className:"modal-body space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-betweeLine truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(ze,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:l,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:r,children:"取消"}),e.jsxs("button",{onClick:(()=>void c()),className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:r,children:[r?e.jsx(J,{className:"w-4 h-4 animate-spin"}):e.jsx(Ie,{className:"w-4 h-4"}),r?"保存中...":"保存"]})]})})]})}),document.body)},Ce=async(s,t)=>X(`/api/v1/account-tasks/${s}`,void 0,t),Se=async(s,t,r)=>ae(`/api/v1/account-tasks/${s}`,t,r),Ns=async(s,t,r)=>ce(`/api/v1/account-tasks/${s}/run`,{task_type:t},{timeoutMs:12e4,...r}),Re=s=>({account_id:s.id,auto_rate_enabled:s.auto_rate_enabled===!0,rate_content:s.rate_content||"不错的买家,交易愉快",auto_polish_enabled:s.auto_polish_enabled===!0,polish_time:s.polish_time||"03:00",last_rate_scan_at:s.last_rate_scan_at,last_polish_date:s.last_polish_date,last_polish_at:s.last_polish_at}),Y=(s,t,r)=>s===t&&!r.aborted,je=(s,t)=>s instanceof Error?s.message:t,we=s=>s instanceof Error&&s.message==="请求已取消",Ae=(s,t)=>!s&&t==="",ks=({account:s,onSaved:t})=>{const[r,a]=n.useState(()=>Re(s)),[l,c]=n.useState(!0),[i,d]=n.useState(!1),[b,m]=n.useState(""),[f,h]=n.useState(""),[u,A]=n.useState(null),[k,g]=n.useState(null),p=n.useRef(0),L=n.useRef(null);n.useEffect(()=>{var v;const S=++p.current;(v=L.current)==null||v.abort();const j=new AbortController;return L.current=j,a(Re(s)),A(null),h(""),d(!1),m(""),g(null),c(!0),Ce(s.id,{signal:j.signal}).then(R=>{Y(p.current,S,j.signal)&&a(R)}).catch(R=>{Y(p.current,S,j.signal)&&!we(R)&&h(je(R,"加载任务设置失败"))}).finally(()=>{Y(p.current,S,j.signal)&&c(!1)}),(()=>j.abort())},[s.id]),n.useEffect(()=>(()=>{var S;return(S=L.current)==null?void 0:S.abort()}),[]);const U=n.useCallback(async()=>{var v;if(!Ae(i,b))return;const S=++p.current;(v=L.current)==null||v.abort();const j=new AbortController;L.current=j,d(!0),h(""),g(null);try{const R=await Se(s.id,r,{signal:j.signal});if(!Y(p.current,S,j.signal))return;a(R),t(R)}catch(R){Y(p.current,S,j.signal)&&!we(R)&&(h(je(R,"保存失败")),g(()=>U))}finally{Y(p.current,S,j.signal)&&d(!1)}},[s.id,r,t,b,i]),M=n.useCallback(async S=>{var R;if(!Ae(i,b)||!s.enabled)return;const j=++p.current;(R=L.current)==null||R.abort();const v=new AbortController;L.current=v,m(S),h(""),A(null),g(null);try{await Se(s.id,r,{signal:v.signal});const w=await Ns(s.id,S,{signal:v.signal}),q=await Ce(s.id,{signal:v.signal});if(!Y(p.current,j,v.signal))return;A(w.summary),a(q),t(q)}catch(w){Y(p.current,j,v.signal)&&!we(w)&&(h(je(w,"任务执行失败")),g(()=>(()=>M(S))))}finally{Y(p.current,j,v.signal)&&m("")}},[s.enabled,s.id,r,t,b,i]),T=n.useCallback(async()=>{k&&await k()},[k]);return{form:r,loading:l,saving:i,running:b,summary:u,error:f,retryAvailable:k!==null,setForm:a,save:U,run:M,retry:T}},qe=({checked:s,onChange:t,label:r})=>e.jsx("button",{type:"button","aria-label":r,"aria-pressed":s,onClick:t,className:`relative h-8 w-14 shrink-0 rounded-full transition-colors ${s?"bg-sky-500":"bg-slate-300"}`,children:e.jsx("span",{className:`absolute left-1 top-1 h-6 w-6 rounded-full bg-white shadow-sm transition-transform ${s?"translate-x-6":""}`})}),Cs=({account:s,onClose:t,onSaved:r})=>{const{form:a,loading:l,saving:c,running:i,error:d,summary:b,retryAvailable:m,setForm:f,save:h,run:u,retry:A}=ks({account:s,onSaved:r});return e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"640px"},role:"dialog","aria-modal":"true","aria-labelledby":"account-task-title",children:[e.jsxs("div",{className:"modal-header",children:[e.jsxs("div",{children:[e.jsx("h3",{id:"account-task-title",className:"text-2xl font-extrabold text-slate-950",children:"账号自动任务"}),e.jsx("p",{className:"mt-1 text-sm text-slate-500",children:s.nickname||s.remark||s.id})]}),e.jsx("button",{type:"button",onClick:t,className:"rounded-xl p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700","aria-label":"关闭",children:e.jsx(de,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[l& Line truncated
@@ -1,4 +1,4 @@
import{r as i,b as z,j as e}from"./react-vendor-C_od1ZSF.js";import{g as Z,c as ee,p as te,d as ae,a as H,b as se}from"./index-CnIcNTyi.js";import{X as G,W as le,J as O,Y as ne,L as V,N as U,C as W,_ as re,$ as X,a0 as Y,a1 as oe,I as ie,a2 as ce,V as de,y as xe,P as pe,o as me}from"./icons-vendor-DwxdQTKt.js";const he=l=>{let n=l.api_config;if(typeof n=="string"&&n.trim())try{n=JSON.parse(n)}catch{n=void 0}return{...l,api_config:n||void 0}},K=l=>({...l,api_config:l.api_config?JSON.stringify(l.api_config):""}),ue=async l=>{const n=await Z("/api/v1/cards",void 0,l);return ee(n,["cards","data","items"]).map(he)},be=async l=>H("/api/v1/cards",K(l)),J=async(l,n)=>te(`/api/v1/cards/${l}`,K(n)),ge=async l=>ae(`/api/v1/cards/${l}`),ye=async(l,n)=>{const a=new FormData;return a.append("file",l),se("/api/v1/cards/batch",a,n)},fe=async(l,n,a)=>H(`/api/v1/cards/${l}/append-data`,{content:n},a),je=(l,n,a)=>{const u=a.trim().toLocaleLowerCase();return l.filter(m=>(!n||m.type===n)&&(!u||m.name.toLocaleLowerCase().includes(u)))},Q=l=>l.split(`
import{r as i,b as z,j as e}from"./react-vendor-C_od1ZSF.js";import{g as Z,c as ee,p as te,d as ae,a as H,b as se}from"./index-KV7tSL6x.js";import{X as G,W as le,J as O,Y as ne,L as V,N as U,C as W,_ as re,$ as X,a0 as Y,a1 as oe,I as ie,a2 as ce,V as de,y as xe,P as pe,o as me}from"./icons-vendor-DwxdQTKt.js";const he=l=>{let n=l.api_config;if(typeof n=="string"&&n.trim())try{n=JSON.parse(n)}catch{n=void 0}return{...l,api_config:n||void 0}},K=l=>({...l,api_config:l.api_config?JSON.stringify(l.api_config):""}),ue=async l=>{const n=await Z("/api/v1/cards",void 0,l);return ee(n,["cards","data","items"]).map(he)},be=async l=>H("/api/v1/cards",K(l)),J=async(l,n)=>te(`/api/v1/cards/${l}`,K(n)),ge=async l=>ae(`/api/v1/cards/${l}`),ye=async(l,n)=>{const a=new FormData;return a.append("file",l),se("/api/v1/cards/batch",a,n)},fe=async(l,n,a)=>H(`/api/v1/cards/${l}/append-data`,{content:n},a),je=(l,n,a)=>{const u=a.trim().toLocaleLowerCase();return l.filter(m=>(!n||m.type===n)&&(!u||m.name.toLocaleLowerCase().includes(u)))},Q=l=>l.split(`
`).map(n=>n.trim()).filter(Boolean),Ne=(l,n,a)=>!!(l&&Q(n).length>0&&!a),F=(l,n,a,u)=>l===n&&a===u,q=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),D=(l,n)=>l instanceof Error?l.message:n,ve=({cards:l,loadCards:n})=>{const[a,u]=i.useState(!1),[m,_]=i.useState(!1),[f,j]=i.useState(null),[d,A]=i.useState({}),[c,y]=i.useState(q),[N,b]=i.useState(""),[r,x]=i.useState(""),s=i.useMemo(()=>l.filter(o=>o.type==="data"),[l]),h=i.useMemo(()=>je(l,N,r),[l,r,N]),E=i.useCallback(o=>{var t,g,k,S,C;j(o),A({id:o.id,name:o.name||"",type:o.type||"text",api_url:((t=o.api_config)==null?void 0:t.url)||"",api_method:((g=o.api_config)==null?void 0:g.method)||"GET",api_timeout:((k=o.api_config)==null?void 0:k.timeout)||10,api_headers:((S=o.api_config)==null?void 0:S.headers)||"",api_params:((C=o.api_config)==null?void 0:C.params)||"",text_content:o.text_content||"",data_content:o.data_content||"",image_url:o.image_url||"",delay_seconds:o.delay_seconds||0,description:o.description||"",enabled:o.enabled}),u(!0)},[]),M=i.useCallback(async()=>{var o,t,g,k,S,C,p,B;if(f){if(!((o=d.name)!=null&&o.trim())){alert("请输入卡密名称");return}if(!d.type){alert("请选择卡密类型");return}try{const w={name:d.name.trim(),type:d.type,description:(t=d.description)==null?void 0:t.trim(),delay_seconds:d.delay_seconds||0,enabled:d.enabled??!0};d.type==="api"?w.api_config={url:((g=d.api_url)==null?void 0:g.trim())||"",method:d.api_method||"GET",timeout:d.api_timeout||10,headers:((k=d.api_headers)==null?void 0:k.trim())||void 0,params:((S=d.api_params)==null?void 0:S.trim())||void 0}:d.type==="text"?w.text_content=((C=d.text_content)==null?void 0:C.trim())||"":d.type==="data"?w.data_content=((p=d.data_content)==null?void 0:p.trim())||"":d.type==="image"&&(w.image_url=((B=d.image_url)==null?void 0:B.trim())||""),await J(f.id,w),u(!1),await n()}catch(w){console.error("更新卡密失败:",w),alert(D(w,"更新失败,请重试"))}}},[d,n,f]),R=i.useCallback(async o=>{if(confirm("确认删除该卡密吗?"))try{await ge(o),await n()}catch(t){console.error("删除卡密失败:",t),alert(D(t,"删除失败,请重试"))}},[n]),v=i.useCallback(async()=>{if(!c.name.trim()){alert("请输入卡密名称");return}if(!c.content.trim()){alert(c.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const o={name:c.name.trim(),type:c.type,description:c.description.trim(),enabled:c.enabled,delay_seconds:c.delay_seconds};c.type==="text"&&(o.text_content=c.content.trim()),c.type==="data"&&(o.data_content=c.content.trim()),c.type==="image"&&(o.image_url=c.content.trim()),c.type==="api"&&(o.api_config={url:c.content.trim(),method:c.api_method,timeout:c.api_timeout,headers:c.api_headers.trim()||void 0,params:c.api_params.trim()||void 0}),await be(o),_(!1),y(q()),await n()}catch(o){console.error("添加卡密失败:",o),alert(D(o,"添加失败,请重试"))}},[c,n]),T=i.useCallback(async o=>{try{await J(o.id,{...o,enabled:!o.enabled}),await n()}catch(t){console.error("切换状态失败:",t)}},[n]),P=i.useCallback(async o=>{try{await navigator.clipboard.writeText(String(o)),alert(`已复制卡密组ID:${o}`)}catch{prompt("复制卡密组ID",String(o))}},[]),$=i.useCallback(()=>{const g=[["名称","类型","内容","描述","启用","延迟秒","多规格","规格名","规格值"],...[["VIP月卡","data",`VIP-MONTH-001
VIP-MONTH-002
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(p=>p.map(B=>`"${String(B).replace(/"/g,'""')}"`).join(",")).join(`
@@ -1 +1 @@
import{j as e,c as x0,r as i}from"./react-vendor-C_od1ZSF.js";import{L as re}from"./vendor-Es4K8PXl.js";import{e as M0,f as le,h as F0,m as P0,s as ce,i as oe,j as pe,k as me,l as z0}from"./index-CnIcNTyi.js";import{L as X,ak as ge,al as de,M as B0,I as xe,R as ue,ad as U0,k as he,am as _e,t as J0,an as be,ao as fe,ah as Q0,X as je}from"./icons-vendor-DwxdQTKt.js";const Z0=[["尊嘟假嘟","https://img.alicdn.com/imgextra/i2/O1CN01hWzOgD1KcmFEIaGwE_!!6000000001185-2-tps-64-64.png_110x10000.jpg_.webp"],["鸡哔你","https://img.alicdn.com/imgextra/i1/O1CN01P9TVJl1JCqCZcQIdW_!!6000000000993-2-tps-64-64.png_110x10000.jpg_.webp"],["谁懂啊","https://img.alicdn.com/imgextra/i1/O1CN01r9qUnx1g3tcrtSmcs_!!6000000004087-2-tps-64-64.png_110x10000.jpg_.webp"],["吗喽","https://img.alicdn.com/imgextra/i4/O1CN01dTynZh1LnbIYTHI1D_!!6000000001344-2-tps-64-64.png_110x10000.jpg_.webp"],["功德+1","https://img.alicdn.com/imgextra/i1/O1CN01l1G5pS1IVn37pfQJi_!!6000000000899-2-tps-64-64.png_110x10000.jpg_.webp"],["city不city啊","https://img.alicdn.com/imgextra/i2/O1CN01zRjPTR29lWHqabmDA_!!6000000008108-2-tps-64-64.png_110x10000.jpg_.webp"],["激推","https://img.alicdn.com/imgextra/i3/O1CN01ADTJ6u1khypfxbfnQ_!!6000000004716-2-tps-64-64.png_110x10000.jpg_.webp"],["微笑","https://img.alicdn.com/imgextra/i1/O1CN017b61R51wRk2lVV7vx_!!6000000006305-2-tps-980-980.png_110x10000.jpg_.webp"],["龇牙","https://img.alicdn.com/imgextra/i2/O1CN01nmOh4S22Yxz8IdEVf_!!6000000007133-2-tps-980-980.png_110x10000.jpg_.webp"],["流泪","https://img.alicdn.com/imgextra/i2/O1CN01Ec1EaL1zqQETcM2dX_!!6000000006765-2-tps-980-980.png_110x10000.jpg_.webp"],["尴尬","https://img.alicdn.com/imgextra/i2/O1CN01UrWH7a1ZVBrgRYXlc_!!6000000003199-2-tps-980-980.png_110x10000.jpg_.webp"],["撇嘴","https://img.alicdn.com/imgextra/i2/O1CN01Sr7o2b1lUWg5KfOD8_!!6000000004822-2-tps-980-980.png_110x10000.jpg_.webp"],["破涕为笑","https://img.alicdn.com/imgextra/i4/O1CN01pPetah1gkwndfn7Fs_!!6000000004181-2-tps-980-980.png_110x10000.jpg_.webp"],["捂脸哭","https://img.alicdn.com/imgextra/i2/O1CN0170KgpE1dE1TuQgd66_!!6000000003703-2-tps-980-980.png_110x10000.jpg_.webp"],["害羞","https://img.alicdn.com/imgextra/i3/O1CN01ZoB0Lb1ps7XpqP8PQ_!!6000000005415-2-tps-980-980.png_110x10000.jpg_.webp"],["感动","https://img.alicdn.com/imgextra/i2/O1CN01wqD4ly29yndR3Qp3A_!!6000000008137-2-tps-980-980.png_110x10000.jpg_.webp"],["滴泪","https://img.alicdn.com/imgextra/i1/O1CN01MpkJ3L1oUTTqfryOn_!!6000000005228-2-tps-980-980.png_110x10000.jpg_.webp"],["暗中观察","https://img.alicdn.com/imgextra/i1/O1CN010LO9yj272W07GlLls_!!6000000007739-2-tps-980-980.png_110x10000.jpg_.webp"],["偷笑","https://img.alicdn.com/imgextra/i4/O1CN01vJtO031g818IuYO7x_!!6000000004096-2-tps-980-980.png_110x10000.jpg_.webp"],["ok","https://img.alicdn.com/imgextra/i3/O1CN01QRkqDF25tz0WcANje_!!6000000007585-2-tps-980-980.png_110x10000.jpg_.webp"],["送花","https://img.alicdn.com/imgextra/i2/O1CN01PpzBNX1JNpeJBWnvr_!!6000000001017-2-tps-980-980.png_110x10000.jpg_.webp"],["大哭","https://img.alicdn.com/imgextra/i4/O1CN014TiaNb1ViEgNvRrTB_!!6000000002686-2-tps-980-980.png_110x10000.jpg_.webp"],["色","https://img.alicdn.com/imgextra/i2/O1CN01840t1B1JaCLGvHnBK_!!6000000001044-2-tps-980-980.png_110x10000.jpg_.webp"],["惊慌","https://img.alicdn.com/imgextra/i1/O1CN01mnqO7G1LAfUnfAN2U_!!6000000001259-2-tps-980-980.png_110x10000.jpg_.webp"],["惊讶","https://img.alicdn.com/imgextra/i3/O1CN0127IeyS1Kw0p0P4jzI_!!6000000001227-2-tps-980-980.png_110x10000.jpg_.webp"],["得意","https://img.alicdn.com/imgextra/i4/O1CN018QUnFv1WpOUES9POZ_!!6000000002837-2-tps-980-980.png_110x10000.jpg_.webp"],["睡","https://img.alicdn.com/imgextra/i2/O1CN01RprGZl1lqVgnEJLCx_!!6000000004870-2-tps-980-980.png_110x10000.jpg_.webp"],["不好意思","https://img.alicdn.com/imgextra/i3/O1CN01rMJJgn1SUXzuVpUhO_!!6000000002250-2-tps-980-980.png_110x10000.jpg_.webp"],["托腮","https://img.alicdn.com/imgextra/i1/O1CN01w3reBU1d3wlgOBtyZ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["发怒","https://img.alicdn.com/imgextra/i2/O1CN013Wzy8d2A8PxGJZPpT_!!6000000008158-2-tps-980-980.png_110x10000.jpg_.webp"],["难过","https://img.alicdn.com/imgextra/i2/O1CN01zcwaSh1G9gZCFuFal_!!6000000000580-2-tps-980-980.png_110x10000.jpg_.webp"],["调皮","https://img.alicdn.com/imgextra/i3/O1CN01Zd1YHi1TI0lwpBe8c_!!6000000002358-2-tps-980-980.png_110x10000.jpg_.webp"],["愉快","https://img.alicdn.com/imgextra/i2/O1CN0145wDk21SWpyjTvsvA_!!6000000002255-2-tps-980-980.png_110x10000.jpg_.webp"],["白眼","https://img.alicdn.com/imgextra/i4/O1CN01nexGth1hwEAT1SHO2_!!6000000004341-2-tps-980-980.png_110x10000.jpg_.webp"],["拒绝","https://img.alicdn.com/imgextra/i2/O1CN01nqusqS1uHXzoUcpXr_!!6000000006012-2-tps-980-980.png_110x10000.jpg_.webp"],["期待","https://img.alicdn.com/imgextra/i3/O1CN01M44QY11Oh8Q5PdMIx_!!6000000001736-2-tps-980-980.png_110x10000.jpg_.webp"],["困","https://img.alicdn.com/imgextra/i4/O1CN01J4hFFz1Y9pmNdBq76_ Line truncated
import{j as e,c as x0,r as i}from"./react-vendor-C_od1ZSF.js";import{L as re}from"./vendor-Es4K8PXl.js";import{e as M0,f as le,h as F0,m as P0,s as ce,i as oe,j as pe,k as me,l as z0}from"./index-KV7tSL6x.js";import{L as X,ak as ge,al as de,M as B0,I as xe,R as ue,ad as U0,k as he,am as _e,t as J0,an as be,ao as fe,ah as Q0,X as je}from"./icons-vendor-DwxdQTKt.js";const Z0=[["尊嘟假嘟","https://img.alicdn.com/imgextra/i2/O1CN01hWzOgD1KcmFEIaGwE_!!6000000001185-2-tps-64-64.png_110x10000.jpg_.webp"],["鸡哔你","https://img.alicdn.com/imgextra/i1/O1CN01P9TVJl1JCqCZcQIdW_!!6000000000993-2-tps-64-64.png_110x10000.jpg_.webp"],["谁懂啊","https://img.alicdn.com/imgextra/i1/O1CN01r9qUnx1g3tcrtSmcs_!!6000000004087-2-tps-64-64.png_110x10000.jpg_.webp"],["吗喽","https://img.alicdn.com/imgextra/i4/O1CN01dTynZh1LnbIYTHI1D_!!6000000001344-2-tps-64-64.png_110x10000.jpg_.webp"],["功德+1","https://img.alicdn.com/imgextra/i1/O1CN01l1G5pS1IVn37pfQJi_!!6000000000899-2-tps-64-64.png_110x10000.jpg_.webp"],["city不city啊","https://img.alicdn.com/imgextra/i2/O1CN01zRjPTR29lWHqabmDA_!!6000000008108-2-tps-64-64.png_110x10000.jpg_.webp"],["激推","https://img.alicdn.com/imgextra/i3/O1CN01ADTJ6u1khypfxbfnQ_!!6000000004716-2-tps-64-64.png_110x10000.jpg_.webp"],["微笑","https://img.alicdn.com/imgextra/i1/O1CN017b61R51wRk2lVV7vx_!!6000000006305-2-tps-980-980.png_110x10000.jpg_.webp"],["龇牙","https://img.alicdn.com/imgextra/i2/O1CN01nmOh4S22Yxz8IdEVf_!!6000000007133-2-tps-980-980.png_110x10000.jpg_.webp"],["流泪","https://img.alicdn.com/imgextra/i2/O1CN01Ec1EaL1zqQETcM2dX_!!6000000006765-2-tps-980-980.png_110x10000.jpg_.webp"],["尴尬","https://img.alicdn.com/imgextra/i2/O1CN01UrWH7a1ZVBrgRYXlc_!!6000000003199-2-tps-980-980.png_110x10000.jpg_.webp"],["撇嘴","https://img.alicdn.com/imgextra/i2/O1CN01Sr7o2b1lUWg5KfOD8_!!6000000004822-2-tps-980-980.png_110x10000.jpg_.webp"],["破涕为笑","https://img.alicdn.com/imgextra/i4/O1CN01pPetah1gkwndfn7Fs_!!6000000004181-2-tps-980-980.png_110x10000.jpg_.webp"],["捂脸哭","https://img.alicdn.com/imgextra/i2/O1CN0170KgpE1dE1TuQgd66_!!6000000003703-2-tps-980-980.png_110x10000.jpg_.webp"],["害羞","https://img.alicdn.com/imgextra/i3/O1CN01ZoB0Lb1ps7XpqP8PQ_!!6000000005415-2-tps-980-980.png_110x10000.jpg_.webp"],["感动","https://img.alicdn.com/imgextra/i2/O1CN01wqD4ly29yndR3Qp3A_!!6000000008137-2-tps-980-980.png_110x10000.jpg_.webp"],["滴泪","https://img.alicdn.com/imgextra/i1/O1CN01MpkJ3L1oUTTqfryOn_!!6000000005228-2-tps-980-980.png_110x10000.jpg_.webp"],["暗中观察","https://img.alicdn.com/imgextra/i1/O1CN010LO9yj272W07GlLls_!!6000000007739-2-tps-980-980.png_110x10000.jpg_.webp"],["偷笑","https://img.alicdn.com/imgextra/i4/O1CN01vJtO031g818IuYO7x_!!6000000004096-2-tps-980-980.png_110x10000.jpg_.webp"],["ok","https://img.alicdn.com/imgextra/i3/O1CN01QRkqDF25tz0WcANje_!!6000000007585-2-tps-980-980.png_110x10000.jpg_.webp"],["送花","https://img.alicdn.com/imgextra/i2/O1CN01PpzBNX1JNpeJBWnvr_!!6000000001017-2-tps-980-980.png_110x10000.jpg_.webp"],["大哭","https://img.alicdn.com/imgextra/i4/O1CN014TiaNb1ViEgNvRrTB_!!6000000002686-2-tps-980-980.png_110x10000.jpg_.webp"],["色","https://img.alicdn.com/imgextra/i2/O1CN01840t1B1JaCLGvHnBK_!!6000000001044-2-tps-980-980.png_110x10000.jpg_.webp"],["惊慌","https://img.alicdn.com/imgextra/i1/O1CN01mnqO7G1LAfUnfAN2U_!!6000000001259-2-tps-980-980.png_110x10000.jpg_.webp"],["惊讶","https://img.alicdn.com/imgextra/i3/O1CN0127IeyS1Kw0p0P4jzI_!!6000000001227-2-tps-980-980.png_110x10000.jpg_.webp"],["得意","https://img.alicdn.com/imgextra/i4/O1CN018QUnFv1WpOUES9POZ_!!6000000002837-2-tps-980-980.png_110x10000.jpg_.webp"],["睡","https://img.alicdn.com/imgextra/i2/O1CN01RprGZl1lqVgnEJLCx_!!6000000004870-2-tps-980-980.png_110x10000.jpg_.webp"],["不好意思","https://img.alicdn.com/imgextra/i3/O1CN01rMJJgn1SUXzuVpUhO_!!6000000002250-2-tps-980-980.png_110x10000.jpg_.webp"],["托腮","https://img.alicdn.com/imgextra/i1/O1CN01w3reBU1d3wlgOBtyZ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["发怒","https://img.alicdn.com/imgextra/i2/O1CN013Wzy8d2A8PxGJZPpT_!!6000000008158-2-tps-980-980.png_110x10000.jpg_.webp"],["难过","https://img.alicdn.com/imgextra/i2/O1CN01zcwaSh1G9gZCFuFal_!!6000000000580-2-tps-980-980.png_110x10000.jpg_.webp"],["调皮","https://img.alicdn.com/imgextra/i3/O1CN01Zd1YHi1TI0lwpBe8c_!!6000000002358-2-tps-980-980.png_110x10000.jpg_.webp"],["愉快","https://img.alicdn.com/imgextra/i2/O1CN0145wDk21SWpyjTvsvA_!!6000000002255-2-tps-980-980.png_110x10000.jpg_.webp"],["白眼","https://img.alicdn.com/imgextra/i4/O1CN01nexGth1hwEAT1SHO2_!!6000000004341-2-tps-980-980.png_110x10000.jpg_.webp"],["拒绝","https://img.alicdn.com/imgextra/i2/O1CN01nqusqS1uHXzoUcpXr_!!6000000006012-2-tps-980-980.png_110x10000.jpg_.webp"],["期待","https://img.alicdn.com/imgextra/i3/O1CN01M44QY11Oh8Q5PdMIx_!!6000000001736-2-tps-980-980.png_110x10000.jpg_.webp"],["困","https://img.alicdn.com/imgextra/i4/O1CN01J4hFFz1Y9pmNdBq76_ Line truncated
@@ -1 +1 @@
import{j as e,r as c}from"./react-vendor-C_od1ZSF.js";import{f as me}from"./dateTime-DDi7rqpW.js";import{j as de,k as ge,l as te,D as he,c as pe,P as be,m as se,E as fe,T as ye}from"./icons-vendor-DwxdQTKt.js";import{R as E,B as je,X as ae,Y as re,T as F,a as ve,C as U,A as Ne,b as we,c as _e,P as ne,d as le,L as ke}from"./charts-vendor-deWqkrdG.js";import{g as q,c as xe,o as De}from"./index-CnIcNTyi.js";import"./vendor-Es4K8PXl.js";const M=t=>{const a=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),l=String(t.getDate()).padStart(2,"0");return`${a}-${s}-${l}`},H=(t,a)=>{const s=new Date(t);return s.setHours(12,0,0,0),s.setDate(s.getDate()+a),s},X=(t,a)=>({startDate:M(H(t,-(a-1))),endDate:M(t)}),ue=(t,a=new Date,s="",l="")=>{if(t==="custom"&&s&&l){if(s>l)throw new Error("开始日期不能晚于结束日期");return{startDate:s,endDate:l}}return t==="yesterday"?X(H(a,-1),1):X(a,t==="3days"?3:t==="30days"?30:t==="today"?1:7)},Se=t=>{const a=new Date(`${t.startDate}T12:00:00`),s=new Date(`${t.endDate}T12:00:00`),l=Math.round((s.getTime()-a.getTime())/864e5)+1,n=H(a,-1);return X(n,l)},i=(t,a)=>a===void 0?`rgb(var(--color-${t}))`:`rgb(var(--color-${t}) / ${a})`,Ce=({chartData:t,selectedRangeLabel:a,totalAmount:s})=>e.jsxs("div",{className:"ios-card p-8 rounded-xl",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("h3",{className:"text-xl font-bold text-gray-900",children:"营收趋势分析"}),e.jsxs("p",{className:"text-sm text-gray-400 mt-1",children:[a,"的销售额走势"]})]}),e.jsx("div",{className:"dashboard-revenue-chart h-[350px] w-full",children:t.length===0||s===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(de,{className:"w-16 h-16 mb-4 opacity-20"}),e.jsx("p",{className:"text-lg font-medium",children:"暂无营收数据"}),e.jsx("p",{className:"text-sm mt-2",children:"所选时间范围内暂无订单记录"})]}):t.length<=2?e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(je,{data:t,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(ae,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-700"),fontSize:14,fontWeight:600},dy:10}),e.jsx(re,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},tickFormatter:(l=>`¥${l}`)}),e.jsx(F,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{fill:i("brand",.08)},formatter:(l=>[`¥${Number(l).toFixed(2)}`,"营收"])}),e.jsx(ve,{dataKey:"amount",fill:i("brand"),maxBarSize:72,radius:[12,12,0,0],activeBar:!1,stroke:"none",strokeWidth:0,children:t.map((l,n)=>e.jsx(U,{fill:i("brand"),stroke:"none",strokeWidth:0},`cell-${n}`))})]})}):e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(Ne,{data:t,margin:{top:10,right:10,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorAmount",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:i("brand"),stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:i("brand"),stopOpacity:0})]})}),e.jsx(ae,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},dy:15}),e.jsx(re,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500}}),e.jsx(we,{vertical:!1,stroke:i("neutral-100"),strokeDasharray:"3 3"}),e.jsx(F,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{stroke:i("brand"),strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(_e,{type:"monotone",dataKey:"amount",stroke:i("brand"),strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:i("white"),stroke:i("brand"),strokeWidth:2}})]})})})]}),oe=t=>{const a=String(t||"");return a==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(a)?a:"unknown"},$e=async t=>q("/api/v1/analytics/dashboard",void 0,t),Re=async(t,a)=>{const s=await q("/api/v1/items",void 0,a);return xe(s,["items","data","results"]).map(n=>({...n,id:n.id||`${n.cookie_id}-${n.item_id}`,is_multi_spec:n.is_multi_spec===!0||n.is_multi_spec===1,multi_quantity_delivery:n.multi_quantity_delivery===!0||n.multi_quantity_delivery===1}))},ie=async(t=7,a)=>{let s;if(typeof t=="number"){const l=new Date,n=new Date;n.setDate(n.getDate()-t),s={start_date:M(n),end_date:M(l)}}else s=t;return q("/api/v1/analytics/orders",{...s,timezone_offset_minutes:-new Date().getTimezoneOffset()},a)},Le=async(t,a)=>{const s=await q("/api/v1/analytics/orders/valid",{...t,timezone_offset_minutes:-new Date().getTimezoneOffset()},a),l=De(s,["data","result"])||{},o=xe(s,["orders","data","items"]).map(b=>({...b,id:b.order_id,status:oe(b.statusLine truncated
import{j as e,r as c}from"./react-vendor-C_od1ZSF.js";import{f as me}from"./dateTime-DDi7rqpW.js";import{j as de,k as ge,l as te,D as he,c as pe,P as be,m as se,E as fe,T as ye}from"./icons-vendor-DwxdQTKt.js";import{R as E,B as je,X as ae,Y as re,T as F,a as ve,C as U,A as Ne,b as we,c as _e,P as ne,d as le,L as ke}from"./charts-vendor-deWqkrdG.js";import{g as q,c as xe,o as De}from"./index-KV7tSL6x.js";import"./vendor-Es4K8PXl.js";const M=t=>{const a=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),l=String(t.getDate()).padStart(2,"0");return`${a}-${s}-${l}`},H=(t,a)=>{const s=new Date(t);return s.setHours(12,0,0,0),s.setDate(s.getDate()+a),s},X=(t,a)=>({startDate:M(H(t,-(a-1))),endDate:M(t)}),ue=(t,a=new Date,s="",l="")=>{if(t==="custom"&&s&&l){if(s>l)throw new Error("开始日期不能晚于结束日期");return{startDate:s,endDate:l}}return t==="yesterday"?X(H(a,-1),1):X(a,t==="3days"?3:t==="30days"?30:t==="today"?1:7)},Se=t=>{const a=new Date(`${t.startDate}T12:00:00`),s=new Date(`${t.endDate}T12:00:00`),l=Math.round((s.getTime()-a.getTime())/864e5)+1,n=H(a,-1);return X(n,l)},i=(t,a)=>a===void 0?`rgb(var(--color-${t}))`:`rgb(var(--color-${t}) / ${a})`,Ce=({chartData:t,selectedRangeLabel:a,totalAmount:s})=>e.jsxs("div",{className:"ios-card p-8 rounded-xl",children:[e.jsxs("div",{className:"mb-10",children:[e.jsx("h3",{className:"text-xl font-bold text-gray-900",children:"营收趋势分析"}),e.jsxs("p",{className:"text-sm text-gray-400 mt-1",children:[a,"的销售额走势"]})]}),e.jsx("div",{className:"dashboard-revenue-chart h-[350px] w-full",children:t.length===0||s===0?e.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-gray-400",children:[e.jsx(de,{className:"w-16 h-16 mb-4 opacity-20"}),e.jsx("p",{className:"text-lg font-medium",children:"暂无营收数据"}),e.jsx("p",{className:"text-sm mt-2",children:"所选时间范围内暂无订单记录"})]}):t.length<=2?e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(je,{data:t,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(ae,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-700"),fontSize:14,fontWeight:600},dy:10}),e.jsx(re,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},tickFormatter:(l=>`¥${l}`)}),e.jsx(F,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{fill:i("brand",.08)},formatter:(l=>[`¥${Number(l).toFixed(2)}`,"营收"])}),e.jsx(ve,{dataKey:"amount",fill:i("brand"),maxBarSize:72,radius:[12,12,0,0],activeBar:!1,stroke:"none",strokeWidth:0,children:t.map((l,n)=>e.jsx(U,{fill:i("brand"),stroke:"none",strokeWidth:0},`cell-${n}`))})]})}):e.jsx(E,{width:"100%",height:"100%",children:e.jsxs(Ne,{data:t,margin:{top:10,right:10,left:-20,bottom:0},children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"colorAmount",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"5%",stopColor:i("brand"),stopOpacity:.5}),e.jsx("stop",{offset:"95%",stopColor:i("brand"),stopOpacity:0})]})}),e.jsx(ae,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},dy:15}),e.jsx(re,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500}}),e.jsx(we,{vertical:!1,stroke:i("neutral-100"),strokeDasharray:"3 3"}),e.jsx(F,{contentStyle:{backgroundColor:i("white"),borderRadius:"8px",border:`1px solid ${i("neutral-200")}`,boxShadow:"var(--shadow-xl)",padding:"12px 16px"},labelStyle:{color:i("neutral-500"),fontWeight:500},itemStyle:{color:i("brand"),fontWeight:600},cursor:{stroke:i("brand"),strokeWidth:2,strokeDasharray:"4 4"}}),e.jsx(_e,{type:"monotone",dataKey:"amount",stroke:i("brand"),strokeWidth:4,fillOpacity:1,fill:"url(#colorAmount)",activeDot:{r:8,fill:i("white"),stroke:i("brand"),strokeWidth:2}})]})})})]}),oe=t=>{const a=String(t||"");return a==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(a)?a:"unknown"},$e=async t=>q("/api/v1/analytics/dashboard",void 0,t),Re=async(t,a)=>{const s=await q("/api/v1/items",void 0,a);return xe(s,["items","data","results"]).map(n=>({...n,id:n.id||`${n.cookie_id}-${n.item_id}`,is_multi_spec:n.is_multi_spec===!0||n.is_multi_spec===1,multi_quantity_delivery:n.multi_quantity_delivery===!0||n.multi_quantity_delivery===1}))},ie=async(t=7,a)=>{let s;if(typeof t=="number"){const l=new Date,n=new Date;n.setDate(n.getDate()-t),s={start_date:M(n),end_date:M(l)}}else s=t;return q("/api/v1/analytics/orders",{...s,timezone_offset_minutes:-new Date().getTimezoneOffset()},a)},Le=async(t,a)=>{const s=await q("/api/v1/analytics/orders/valid",{...t,timezone_offset_minutes:-new Date().getTimezoneOffset()},a),l=De(s,["data","result"])||{},o=xe(s,["orders","data","items"]).map(b=>({...b,id:b.order_id,status:oe(b.statusLine truncated
@@ -1,2 +1,2 @@
import{j as e,r,b as we}from"./react-vendor-C_od1ZSF.js";import{g as je,c as Qe,a as ce,b as et,d as tt,A as yt,p as ft}from"./index-CnIcNTyi.js";import{a3 as jt,U as De,R as Se,N as Te,a4 as Pe,a5 as _e,V as vt,y as Nt,B as wt,a6 as Ue,a7 as _t,a8 as kt,A as Ct,d as It,X as be,o as St,a9 as ze,I as Oe}from"./icons-vendor-DwxdQTKt.js";const Ke="ydisks-amap-js-api",Pt="c9b68d4ce9a2a97f22a4a439404488ca";let ye=null;const Bt=()=>Pt,qt=()=>window.AMap?Promise.resolve(window.AMap):ye||(ye=new Promise((s,l)=>{const i=document.getElementById(Ke),m=i||document.createElement("script"),u=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(R)},f=()=>{window.AMap?(u(),s(window.AMap)):(u(),l(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},R=window.setTimeout(()=>{u(),l(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=f,m.id=Ke,m.async=!0,m.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(Bt())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,m.onerror=()=>{u(),l(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},i||document.head.appendChild(m)}).catch(s=>{throw ye=null,s}),ye),ke=s=>Number.isFinite(s)&&s!==0,Lt=s=>{var u,f;const l=Number((u=s.location)==null?void 0:u.lng),i=Number((f=s.location)==null?void 0:f.lat),m={area:String(s.adname||"").trim(),city:String(s.cityname||"").trim(),division_id:String(s.adcode||"").trim(),longitude:l,latitude:i,poi_id:String(s.id||"").trim(),poi_name:String(s.name||"").trim(),province:String(s.pname||"").trim()};return!m.division_id||!m.province||!m.city||!m.poi_id||!m.poi_name||!ke(l)||!ke(i)||l<-180||l>180||i<-90||i>90?null:m},At=async(s,l,i={})=>{if(!ke(s)||!ke(l)||s<-180||s>180||l<-90||l>90)throw new Error("经纬度无效");const m=await qt();return new Promise((u,f)=>{var G,E;let R=!1;const k=Math.max(1,i.timeoutMs??1e4),A=M=>{var p;R||(R=!0,globalThis.clearTimeout(Z),(p=i.signal)==null||p.removeEventListener("abort",I),M())},I=()=>A(()=>f(new DOMException("aborted","AbortError"))),Z=globalThis.setTimeout(()=>A(()=>f(new Error("高德地图附近地址查询超时,请稍后重试"))),k);if((G=i.signal)!=null&&G.aborted){I();return}(E=i.signal)==null||E.addEventListener("abort",I,{once:!0}),new m.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[s,l],1e3,(M,p)=>{var d;if(R)return;if(M!=="complete"){if(M==="no_data"){A(()=>u([]));return}A(()=>f(new Error("高德地图附近地址查询失败,请稍后重试")));return}const B=(((d=p==null?void 0:p.poiList)==null?void 0:d.pois)||[]).map(Lt).filter(j=>j!==null);A(()=>u(B))})})},Et=async s=>je("/api/v1/accounts/details",void 0,s),Je=async s=>je("/api/v1/automation-rules",void 0,s),Mt=(s,l,i)=>At(s,l,i),Be=(s,l)=>{if(s instanceof yt)switch(s.code){case"stock_permission_missing":return"发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。";case"conflict":case"item_conflict":return"商品状态已发生变化,请刷新后重试。";case"external_result_unknown":case"manual_review_required":return"平台结果暂时无法确认,请先人工核对闲鱼状态,再决定是否重试。";case"retryable":case"temporarily_unavailable":return"平台暂时不可用,请稍后重试。";default:return s.message||l}if(s instanceof Error)return s.message;const i=typeof s=="object"&&s!==null&&"message"in s?s.message:void 0;return typeof i=="string"?i:l},qe=s=>s===!0||s===1||s==="1",Ze=async(s,l)=>{const i=await je("/api/v1/items",void 0,l);return Qe(i,["items","data","results"]).map(u=>({...u,id:u.id||`${u.cookie_id}-${u.item_id}`,is_multi_spec:qe(u.is_multi_spec),is_multi_qty_ship:qe(u.is_multi_qty_ship??u.multi_quantity_delivery),multi_quantity_delivery:qe(u.multi_quantity_delivery??u.is_multi_qty_ship)}))},Rt=async s=>ce("/api/v1/items/get-all-from-account",{cookie_id:s}),Ft=async(s,l)=>tt(`/api/v1/items/${s}/${l}`),Gt=async(s,l)=>ce(`/api/v1/items/${s}`,l),$t=async s=>{const l=new FormData;l.set("cookie_id",s.cookie_id),l.set("title",s.title),l.set("description",s.description),l.set("price",s.price),l.set("original_price",s.original_price||""),l.set("quantity",String(s.quantity)),l.set("postage_mode",s.postage_mode),l.set("postage",s.postage||""),s.location&&l.set("location",JSON.stringify(s.location));for(const i of s.images)l.append("images",i);return et("/api/v1/items/publish",l)},Dt=async(s,l,i)=>ce("/api/v1/items/publish-categories/recommend",{cookie_id:s,keyword:l},i),Tt=async(s,l)=>{const i=new FormData;return i.set("file",s.file),s.imagesZip&&i.set("images_zip",s.imagesZip),s.defaultCookieId&&i.set("default_cookie_id",s.defaultCookieId),i.set("fallback_category_id",s.fallbackCategory.catId),i.set("fallback_category_name",s.fallbackCategory.catName),i.set("fallback_channel_category_id",s.fallbackCategory.channelCatId||""),i.set("fallback_tb_category_id",s.fallbackCategory.tbCatLine truncated
import{j as e,r,b as we}from"./react-vendor-C_od1ZSF.js";import{g as je,c as Qe,a as ce,b as et,d as tt,A as yt,p as ft}from"./index-KV7tSL6x.js";import{a3 as jt,U as De,R as Se,N as Te,a4 as Pe,a5 as _e,V as vt,y as Nt,B as wt,a6 as Ue,a7 as _t,a8 as kt,A as Ct,d as It,X as be,o as St,a9 as ze,I as Oe}from"./icons-vendor-DwxdQTKt.js";const Ke="ydisks-amap-js-api",Pt="c9b68d4ce9a2a97f22a4a439404488ca";let ye=null;const Bt=()=>Pt,qt=()=>window.AMap?Promise.resolve(window.AMap):ye||(ye=new Promise((s,l)=>{const i=document.getElementById(Ke),m=i||document.createElement("script"),u=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(R)},f=()=>{window.AMap?(u(),s(window.AMap)):(u(),l(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},R=window.setTimeout(()=>{u(),l(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=f,m.id=Ke,m.async=!0,m.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(Bt())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,m.onerror=()=>{u(),l(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},i||document.head.appendChild(m)}).catch(s=>{throw ye=null,s}),ye),ke=s=>Number.isFinite(s)&&s!==0,Lt=s=>{var u,f;const l=Number((u=s.location)==null?void 0:u.lng),i=Number((f=s.location)==null?void 0:f.lat),m={area:String(s.adname||"").trim(),city:String(s.cityname||"").trim(),division_id:String(s.adcode||"").trim(),longitude:l,latitude:i,poi_id:String(s.id||"").trim(),poi_name:String(s.name||"").trim(),province:String(s.pname||"").trim()};return!m.division_id||!m.province||!m.city||!m.poi_id||!m.poi_name||!ke(l)||!ke(i)||l<-180||l>180||i<-90||i>90?null:m},At=async(s,l,i={})=>{if(!ke(s)||!ke(l)||s<-180||s>180||l<-90||l>90)throw new Error("经纬度无效");const m=await qt();return new Promise((u,f)=>{var G,E;let R=!1;const k=Math.max(1,i.timeoutMs??1e4),A=M=>{var p;R||(R=!0,globalThis.clearTimeout(Z),(p=i.signal)==null||p.removeEventListener("abort",I),M())},I=()=>A(()=>f(new DOMException("aborted","AbortError"))),Z=globalThis.setTimeout(()=>A(()=>f(new Error("高德地图附近地址查询超时,请稍后重试"))),k);if((G=i.signal)!=null&&G.aborted){I();return}(E=i.signal)==null||E.addEventListener("abort",I,{once:!0}),new m.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[s,l],1e3,(M,p)=>{var d;if(R)return;if(M!=="complete"){if(M==="no_data"){A(()=>u([]));return}A(()=>f(new Error("高德地图附近地址查询失败,请稍后重试")));return}const B=(((d=p==null?void 0:p.poiList)==null?void 0:d.pois)||[]).map(Lt).filter(j=>j!==null);A(()=>u(B))})})},Et=async s=>je("/api/v1/accounts/details",void 0,s),Je=async s=>je("/api/v1/automation-rules",void 0,s),Mt=(s,l,i)=>At(s,l,i),Be=(s,l)=>{if(s instanceof yt)switch(s.code){case"stock_permission_missing":return"发布失败:该账号没有库存发布权限,无法按库存数量发布商品。请换账号或先在闲鱼确认库存能力。";case"conflict":case"item_conflict":return"商品状态已发生变化,请刷新后重试。";case"external_result_unknown":case"manual_review_required":return"平台结果暂时无法确认,请先人工核对闲鱼状态,再决定是否重试。";case"retryable":case"temporarily_unavailable":return"平台暂时不可用,请稍后重试。";default:return s.message||l}if(s instanceof Error)return s.message;const i=typeof s=="object"&&s!==null&&"message"in s?s.message:void 0;return typeof i=="string"?i:l},qe=s=>s===!0||s===1||s==="1",Ze=async(s,l)=>{const i=await je("/api/v1/items",void 0,l);return Qe(i,["items","data","results"]).map(u=>({...u,id:u.id||`${u.cookie_id}-${u.item_id}`,is_multi_spec:qe(u.is_multi_spec),is_multi_qty_ship:qe(u.is_multi_qty_ship??u.multi_quantity_delivery),multi_quantity_delivery:qe(u.multi_quantity_delivery??u.is_multi_qty_ship)}))},Rt=async s=>ce("/api/v1/items/get-all-from-account",{cookie_id:s}),Ft=async(s,l)=>tt(`/api/v1/items/${s}/${l}`),Gt=async(s,l)=>ce(`/api/v1/items/${s}`,l),$t=async s=>{const l=new FormData;l.set("cookie_id",s.cookie_id),l.set("title",s.title),l.set("description",s.description),l.set("price",s.price),l.set("original_price",s.original_price||""),l.set("quantity",String(s.quantity)),l.set("postage_mode",s.postage_mode),l.set("postage",s.postage||""),s.location&&l.set("location",JSON.stringify(s.location));for(const i of s.images)l.append("images",i);return et("/api/v1/items/publish",l)},Dt=async(s,l,i)=>ce("/api/v1/items/publish-categories/recommend",{cookie_id:s,keyword:l},i),Tt=async(s,l)=>{const i=new FormData;return i.set("file",s.file),s.imagesZip&&i.set("images_zip",s.imagesZip),s.defaultCookieId&&i.set("default_cookie_id",s.defaultCookieId),i.set("fallback_category_id",s.fallbackCategory.catId),i.set("fallback_category_name",s.fallbackCategory.catName),i.set("fallback_channel_category_id",s.fallbackCategory.channelCatId||""),i.set("fallback_tb_category_id",s.fallbackCategory.tbCatLine truncated
`),X=new Blob(["\uFEFF"+L],{type:"text/csv;charset=utf-8"}),F=URL.createObjectURL(X),P=document.createElement("a");P.href=F,P.download="批量铺货模板.csv",document.body.appendChild(P),P.click(),P.remove(),URL.revokeObjectURL(F)},[]),n=r.useCallback(()=>{y(o=>({...o,cookie_id:s||o.cookie_id})),p(!0)},[s]),h=r.useCallback(()=>{v(o=>({...o,cookie_id:s||o.cookie_id})),d(!0)},[s]),q=r.useCallback(async o=>{if(!(o?s:b.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");D();const L=new AbortController;H.current=L;const X=++z.current;S(!0);try{const F=await new Promise((ue,me)=>{const Ce=Q=>ue(Q),re=Q=>me(Q);navigator.geolocation.getCurrentPosition(Ce,re,{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})});if(L.signal.aborted||X!==z.current)return;const P=await Mt(F.coords.longitude,F.coords.latitude,{signal:L.signal});if(L.signal.aborted||X!==z.current)return;if(!P.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");o?(R(P),k(P[0])):(W(P),U(P[0]))}catch(F){if(L.signal.aborted||X!==z.current)return;if(typeof F=="object"&&F!==null&&"code"in F){const P=F;alert(P.code===P.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")}else alert(Be(F,"获取发货地失败"))}finally{X===z.current&&(H.current=null,S(!1))}},[D,b.cookie_id,s,k,R]);return{selectedAccount:s,setSelectedAccount:l,loading:A,publishing:Z,showEditModal:G,setShowEditModal:E,showAddModal:M,setShowAddModal:p,showPublishModal:B,setShowPublishModal:d,locationLoading:j,publishLocations:V,setPublishLocations:W,publishLocation:Y,setPublishLocation:U,selectedItem:$,editForm:C,setEditForm:se,addForm:g,setAddForm:y,publishForm:b,setPublishForm:v,publishImagePreviews:x,handleSync:te,handleEdit:oe,handleSaveEdit:le,handleDelete:de,handleAddItem:xe,handlePublishItem:ve,downloadPublishTemplate:a,openAddModal:n,openPublishModal:h,locateForPublish:q}},Qt=s=>{const l=String(s||"").trim();return l?/^[¥¥]/.test(l)?l:`¥${l}`:"-"},as=({onConfigureDelivery:s})=>{const[l,i]=r.useState([]),[m,u]=r.useState([]),[f,R]=r.useState([]),[k,A]=r.useState(""),[I,Z]=r.useState(""),T=r.useRef(0),G=r.useRef(0),E=r.useCallback(async()=>{const t=++T.current,c=await Ze();t===T.current&&i(c)},[]),M=r.useCallback(async()=>{const t=++G.current,c=await Je();t===G.current&&u(c)},[]),p=Ht({selectedAccount:k,loadItems:E,loadShippingRules:M}),{showBatchModal:B,batchLoading:d,batchPhase:j,batchFile:S,setBatchFile:V,batchImagesZip:W,setBatchImagesZip:Y,batchCategoryKeyword:U,setBatchCategoryKeyword:$,batchCategoryLoading:K,batchFallbackCategory:C,setBatchFallbackCategory:se,batchPreview:g,batchDetail:y,recentBatch:b,setRecentBatch:v,batchLocations:x,batchLocation:ae,batchPublishIntervalSeconds:H,setBatchPublishIntervalSeconds:z,setBatchLocations:D,setBatchLocation:te,openBatchModal:oe,handleRecommendBatchCategory:le,openRecentBatchResult:de,handlePreviewBatch:xe,handleStartBatch:ve,handleCancelBatch:a,abandonBatchPreview:n,closeBatchModal:h,handleRetryBatchFailed:q}=p,o=Xt({selectedAccount:k,setSelectedAccount:A,setItems:i,loadItems:E,loadShippingRules:M,onConfigureDelivery:s,setBatchLocations:D,setBatchLocation:te}),{loading:N,publishing:L,showEditModal:X,setShowEditModal:F,showAddModal:P,setShowAddModal:ue,showPublishModal:me,setShowPublishModal:Ce,locationLoading:re,publishLocations:Q,setPublishLocations:at,publishLocation:lt,setPublishLocation:Le,selectedItem:Ae,editForm:ee,setEditForm:Ne,addForm:O,setAddForm:he,publishForm:w,setPublishForm:J,publishImagePreviews:Ee,handleSync:rt,handleEdit:nt,handleSaveEdit:it,handleDelete:ct,handleAddItem:ot,handlePublishItem:dt,downloadPublishTemplate:xt,openAddModal:ut,openPublishModal:mt,locateForPublish:Me}=o;r.useEffect(()=>{const t=new AbortController,c=++T.current,_=++G.current;let ge=!0;return Promise.all([Et({signal:t.signal}),Ze(void 0,{signal:t.signal}),Je({signal:t.signal}),st(20,{signal:t.signal})]).then(([ne,pt,gt,$e])=>{if(!ge||t.signal.aborted||c!==T.current||_!==G.current)return;R(ne),i(pt),u(gt);const bt=$e.find(Ie=>["running","canceling"].includes(Ie.status))||$e.find(Ie=>Ie.status!=="preview");v(bt||null)}).catch(ne=>{t.signal.aborted||console.error("加载商品配置失败:",ne)}),(()=>{ge=!1,t.abort()})},[]);const ht=t=>m.filter(c=>c.cookie_id===t.cookie_id&&c.item_id===t.item_id).length>0?m.filter(c=>c.cookie_id===t.cookie_id&&c.item_id===t.item_id):m.filter(c=>c.cookie_id===t.cookie_id&&!c.item_id),Re=r.useMemo(()=>new Map(f.map(t=>[t.id,t])),[f]),Fe=r.useMemo(()=>I?l.filter(t=>t.cookie_id===I):l,[I,l]),pe=t=>{const c=Re.get(t),_=(c==null?void 0:c.remark)||(c==null?void 0:c.nickname);return _?`${_} · ${t.slice(0,6)}`:`账号 ${t.slice(0,8)}`},Ge=t=>{const c=Re.get(t);return(c==null?void 0:c.remark)||(c==null?void 0:c.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"fl Line truncated
@@ -1 +1 @@
import{j as e,b as _e,r as d}from"./react-vendor-C_od1ZSF.js";import{ai as ee,ah as se,aj as Ne,u as K,e as W,L as I,w as ve,y as ke,t as Q,X as te,z as ae,F as ne,o as we,R as Se,N as Ce}from"./icons-vendor-DwxdQTKt.js";import{g as re,p as le,a as oe,d as Te}from"./index-CnIcNTyi.js";const H=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],G=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},ie=s=>{const t=Object.prototype.hasOwnProperty.call(s,"use_custom_smtp"),a=H.some(n=>String(s[n]??"").trim()!=="");return{...s,use_custom_smtp:t?G(s.use_custom_smtp,!1):a}},ce=(s,t)=>{const a={...s,use_custom_smtp:!0};for(const n of H)String(a[n]??"").trim()===""&&t[n]!==void 0&&(a[n]=t[n]);return a.smtp_port||(a.smtp_port=587),a.smtp_from_address||(a.smtp_from_address=a.smtp_user||""),a.smtp_use_tls=G(a.smtp_use_tls,!0),a.smtp_use_ssl=G(a.smtp_use_ssl,!1),a},de=s=>{const t=ie(s),a={to_email:String(t.to_email??"").trim(),use_custom_smtp:t.use_custom_smtp===!0};if(a.use_custom_smtp)for(const n of H)a[n]=t[n];return a},B={bark:{label:"Bark",icon:W,fields:[{key:"server_url",label:"Bark 服务器",placeholder:"https://api.day.app",required:!0},{key:"device_key",label:"Device Key",placeholder:"你的 Bark 设备 Key",required:!0},{key:"title",label:"标题(可选)",placeholder:"Ydisks闲鱼助手"},{key:"sound",label:"铃声(可选)",placeholder:"default"},{key:"group",label:"分组(可选)",placeholder:"xianyu"}],guide:{steps:["App Store 搜索并安装 Bark(免费)","打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app/<key>/这是测试推送内容","URL 路径里 <key> 那一段就是 Device Key,复制填入","服务器地址默认 https://api.day.app,自建服务端则填自建域名"],urlFormat:"https://api.day.app/<你的key>/测试内容",note:"不需要 secret,Device Key 本身就是唯一凭证。"}},dingtalk:{label:"钉钉机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://oapi.dingtalk.com/robot/send?access_token=...",required:!0},{key:"secret",label:"加签密钥",placeholder:"SEC...",help:"安全设置勾选「加签」后生成,SEC 开头"}],guide:{steps:["钉钉进入一个群(可建单人群)→ 右上角 群设置","机器人 → 添加机器人 → 选择「自定义机器人」","安全设置勾选「加签」","完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制","Webhook URL 填上面,Secret 填加签密钥"],urlFormat:"https://oapi.dingtalk.com/robot/send?access_token=XXX",note:"加签密钥可选,但强烈建议启用,否则机器人可能被滥用。"}},feishu:{label:"飞书机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://open.feishu.cn/open-apis/bot/v2/hook/...",required:!0},{key:"secret",label:"签名校验密钥",placeholder:"sec-...",help:"安全设置选「签名校验」后生成"}],guide:{steps:["飞书进入目标群 → 右上角 更多 → 设置","群机器人 → 添加机器人 → 自定义机器人","安全设置选择「签名校验」,复制生成的秘钥","完成会给 Webhook 地址,复制","Webhook URL 填上面,秘钥填签名校验密钥"],urlFormat:"https://open.feishu.cn/open-apis/bot/v2/hook/xxx",note:"签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。"}},wechat:{label:"企业微信机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...",required:!0}],guide:{steps:["企业微信进入一个内部群 → 右上角 … → 群设置","找到「群机器人」(新版可能叫「消息推送」)","添加 → 选择自定义机器人","完成给 Webhook 地址(含 ?key=),复制填入"],urlFormat:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX",note:"不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。"}},webhook:{label:"自定义 Webhook",icon:Ne,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://your-server/notify",required:!0}],guide:{steps:["仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON","系统会 POST 这个 URL,Content-Type: application/json","请求体固定为右侧 JSON 格式,按需解析 message 字段"],urlFormat:'{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',note:"若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。"}},telegram:{label:"Telegram",icon:se,fields:[{key:"bot_token",label:"Bot Token",placeholder:"123456:ABC-DEF...",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"-1001234567890 或你的用户 ID",Line truncated
import{j as e,b as _e,r as d}from"./react-vendor-C_od1ZSF.js";import{ai as ee,ah as se,aj as Ne,u as K,e as W,L as I,w as ve,y as ke,t as Q,X as te,z as ae,F as ne,o as we,R as Se,N as Ce}from"./icons-vendor-DwxdQTKt.js";import{g as re,p as le,a as oe,d as Te}from"./index-KV7tSL6x.js";const H=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],G=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},ie=s=>{const t=Object.prototype.hasOwnProperty.call(s,"use_custom_smtp"),a=H.some(n=>String(s[n]??"").trim()!=="");return{...s,use_custom_smtp:t?G(s.use_custom_smtp,!1):a}},ce=(s,t)=>{const a={...s,use_custom_smtp:!0};for(const n of H)String(a[n]??"").trim()===""&&t[n]!==void 0&&(a[n]=t[n]);return a.smtp_port||(a.smtp_port=587),a.smtp_from_address||(a.smtp_from_address=a.smtp_user||""),a.smtp_use_tls=G(a.smtp_use_tls,!0),a.smtp_use_ssl=G(a.smtp_use_ssl,!1),a},de=s=>{const t=ie(s),a={to_email:String(t.to_email??"").trim(),use_custom_smtp:t.use_custom_smtp===!0};if(a.use_custom_smtp)for(const n of H)a[n]=t[n];return a},B={bark:{label:"Bark",icon:W,fields:[{key:"server_url",label:"Bark 服务器",placeholder:"https://api.day.app",required:!0},{key:"device_key",label:"Device Key",placeholder:"你的 Bark 设备 Key",required:!0},{key:"title",label:"标题(可选)",placeholder:"Ydisks闲鱼助手"},{key:"sound",label:"铃声(可选)",placeholder:"default"},{key:"group",label:"分组(可选)",placeholder:"xianyu"}],guide:{steps:["App Store 搜索并安装 Bark(免费)","打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app/<key>/这是测试推送内容","URL 路径里 <key> 那一段就是 Device Key,复制填入","服务器地址默认 https://api.day.app,自建服务端则填自建域名"],urlFormat:"https://api.day.app/<你的key>/测试内容",note:"不需要 secret,Device Key 本身就是唯一凭证。"}},dingtalk:{label:"钉钉机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://oapi.dingtalk.com/robot/send?access_token=...",required:!0},{key:"secret",label:"加签密钥",placeholder:"SEC...",help:"安全设置勾选「加签」后生成,SEC 开头"}],guide:{steps:["钉钉进入一个群(可建单人群)→ 右上角 群设置","机器人 → 添加机器人 → 选择「自定义机器人」","安全设置勾选「加签」","完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制","Webhook URL 填上面,Secret 填加签密钥"],urlFormat:"https://oapi.dingtalk.com/robot/send?access_token=XXX",note:"加签密钥可选,但强烈建议启用,否则机器人可能被滥用。"}},feishu:{label:"飞书机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://open.feishu.cn/open-apis/bot/v2/hook/...",required:!0},{key:"secret",label:"签名校验密钥",placeholder:"sec-...",help:"安全设置选「签名校验」后生成"}],guide:{steps:["飞书进入目标群 → 右上角 更多 → 设置","群机器人 → 添加机器人 → 自定义机器人","安全设置选择「签名校验」,复制生成的秘钥","完成会给 Webhook 地址,复制","Webhook URL 填上面,秘钥填签名校验密钥"],urlFormat:"https://open.feishu.cn/open-apis/bot/v2/hook/xxx",note:"签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。"}},wechat:{label:"企业微信机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...",required:!0}],guide:{steps:["企业微信进入一个内部群 → 右上角 … → 群设置","找到「群机器人」(新版可能叫「消息推送」)","添加 → 选择自定义机器人","完成给 Webhook 地址(含 ?key=),复制填入"],urlFormat:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX",note:"不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。"}},webhook:{label:"自定义 Webhook",icon:Ne,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://your-server/notify",required:!0}],guide:{steps:["仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON","系统会 POST 这个 URL,Content-Type: application/json","请求体固定为右侧 JSON 格式,按需解析 message 字段"],urlFormat:'{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',note:"若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。"}},telegram:{label:"Telegram",icon:se,fields:[{key:"bot_token",label:"Bot Token",placeholder:"123456:ABC-DEF...",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"-1001234567890 或你的用户 ID",Line truncated
@@ -0,0 +1 @@
import{j as e,b as X,r as a}from"./react-vendor-C_od1ZSF.js";import{f as Z}from"./dateTime-DDi7rqpW.js";import{U as re,I as ie,X as H,J as ce,R as K,N as oe,O as ee,m as se,E as de,F as xe,V as me,y as ue,h as he,g as ge,o as pe}from"./icons-vendor-DwxdQTKt.js";import{g as U,o as be,c as ye,b as le,a as Y,p as fe,d as ne}from"./index-KV7tSL6x.js";const ve=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],je=s=>{const t=typeof s=="object"&&s!==null?s:{},i=Array.isArray(t.results)?t.results:[];return{total:Number(t.total||0),success_count:Number(t.success_count||0),failed_count:Number(t.failed_count||0),results:i.map(Ne)}},Ne=s=>{const t=typeof s=="object"&&s!==null?s:{};return{order_id:String(t.order_id||"unknown"),success:t.success===!0,message:String(t.message||"")}},we=s=>(s==null?void 0:s.results.filter(_e))||[],_e=s=>!s.success,ke=(s,t)=>s!==null&&!t,Ce=s=>{if(!s)return"请选择订单文件";const t=s.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(t)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},T=(s,t)=>s===t,Se=(s,t)=>s instanceof Error&&s.message?s.message:t,Ee=({filter:s,onFilterChange:t,accountFilter:i,onAccountFilterChange:u,accounts:b,accountName:m,searchText:h,onSearchChange:N})=>{const g=l=>t(l.currentTarget.dataset.status||"all"),f=l=>u(l.target.value),y=l=>N(l.target.value);return e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:ve.map(l=>e.jsx("button",{"data-status":l.key,onClick:g,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${s===l.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:l.label},l.key))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(re,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:i,onChange:f,className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),b.map(l=>e.jsx("option",{value:l.id,children:m(l.id)},l.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(ie,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:h,onChange:y,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Oe=s=>{const t=m=>{var h;s.setImportFile(((h=m.target.files)==null?void 0:h[0])||null)},i=()=>s.closeImportModal(),u=()=>void s.handleImportOrders(),b=()=>void s.handleRetryImport();return s.showImportModal?X.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:i,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:t,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),s.importFile&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ce,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:s.importFile.name})]})}),s.importError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-100 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.importError}),e.jsx("button",{type:"button",onClick:b,disabled:s.importing||!s.importFile,className:"font-bold whitespace-nowrap",children:"重试"})]}),s.importResult&&s.importResult.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:成功 ",s.importResult.success_count," 条,失败 ",s.iLine truncated
@@ -1 +0,0 @@
import{j as e,b as J,r as a}from"./react-vendor-C_od1ZSF.js";import{f as Y}from"./dateTime-DDi7rqpW.js";import{U as te,I as re,X as W,J as ne,R as H,N as ie,O as Z,m as ee,E as ce,F as oe,V as de,y as xe,h as me,g as ue,o as he}from"./icons-vendor-DwxdQTKt.js";import{g as X,o as ge,c as pe,b as ae,a as K,p as be,d as ye}from"./index-CnIcNTyi.js";const fe=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],je=s=>{const t=typeof s=="object"&&s!==null?s:{},c=Array.isArray(t.results)?t.results:[];return{total:Number(t.total||0),success_count:Number(t.success_count||0),failed_count:Number(t.failed_count||0),results:c.map(ve)}},ve=s=>{const t=typeof s=="object"&&s!==null?s:{};return{order_id:String(t.order_id||"unknown"),success:t.success===!0,message:String(t.message||"")}},Ne=s=>(s==null?void 0:s.results.filter(we))||[],we=s=>!s.success,_e=(s,t)=>s!==null&&!t,ke=s=>{if(!s)return"请选择订单文件";const t=s.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(t)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},T=(s,t)=>s===t,Ce=(s,t)=>s instanceof Error&&s.message?s.message:t,Se=({filter:s,onFilterChange:t,accountFilter:c,onAccountFilterChange:h,accounts:g,accountName:m,searchText:u,onSearchChange:p})=>{const b=r=>t(r.currentTarget.dataset.status||"all"),_=r=>h(r.target.value),y=r=>p(r.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:fe.map(r=>e.jsx("button",{"data-status":r.key,onClick:b,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${s===r.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:r.label},r.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(te,{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:c,onChange:_,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:"全部账号"}),g.map(r=>e.jsx("option",{value:r.id,children:m(r.id)},r.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(re,{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:y,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Ee=s=>{const t=m=>{var u;s.setImportFile(((u=m.target.files)==null?void 0:u[0])||null)},c=()=>s.closeImportModal(),h=()=>void s.handleImportOrders(),g=()=>void s.handleRetryImport();return s.showImportModal?J.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:c,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(W,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:t,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),s.importFile&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ne,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:s.importFile.name})]})}),s.importError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-100 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.importError}),e.jsx("button",{type:"button",onClick:g,disabled:s.importing||!s.importFile,className:"font-bold whitespace-nowrap",children:"重试"})]}),s.importResult&&s.importResult.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:成功 ",s.importResult.success_count," 条,失败 ",s.imLine truncated
@@ -1 +1 @@
import{j as e,r as o,b as Fe}from"./react-vendor-C_od1ZSF.js";import{k as Je,ae as it,af as vt,m as Nt,R as Te,N as Ye,Z as He,u as wt,n as et,I as kt,a1 as Ct,X as ke,V as ze,y as Ce,h as St,g as Rt,a6 as At,ag as $t,o as tt,ah as Mt}from"./icons-vendor-DwxdQTKt.js";import{g as Z,o as Ae,c as Ge,p as Ke,a as fe,d as Ue}from"./index-CnIcNTyi.js";const Ee=(t,a)=>t.allowed_resolutions.includes(a),Pt=(t,a)=>({runs:t.runs.filter(i=>!a||i.cookie_id===a),pending_tasks:t.pending_tasks.filter(i=>!a||i.cookie_id===a)}),Lt=t=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[t]||"自动化异常",It=({runs:t,pendingTasks:a,onResolveRun:i,onResolveDeferredTask:u})=>e.jsxs("section",{className:"rounded-2xl border border-red-200 bg-red-50 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-black text-red-900",children:"需要人工处理的自动化任务"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。"})]})]}),e.jsxs("div",{className:"space-y-3",children:[t.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 订单 ",r.order_id||"-"," · 已记录发送 ",r.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:Lt(r.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[Ee(r,"continue")&&e.jsx("button",{onClick:(()=>i(r.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),Ee(r,"retry")&&e.jsx("button",{onClick:(()=>i(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),Ee(r,"cancel")&&e.jsx("button",{onClick:(()=>i(r.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${r.id}`)),a.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 延迟任务重试已达 ",r.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:(()=>u(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:(()=>u(r.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${r.id}`))]})]}),Dt=async t=>Z("/api/v1/accounts/details",void 0,t),ot=async t=>Z("/api/v1/cards",void 0,t),dt=async(t,a)=>Z("/api/v1/items",void 0,a),ct=t=>t.map(a=>{var i,u;return{id:String(a.id),name:a.name||"",trigger_type:a.trigger_type||"order_paid",item_keyword:a.item_title||a.item_id||"",cookie_id:a.cookie_id||"",item_id:a.item_id||"",item_title:a.item_title||"",card_group_id:Number(((i=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:i.card_id)||0),card_group_name:((u=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:u.card_name)||"",priority:a.priority||100,enabled:a.enabled||!1,config_json:a.config_json||"{}",actions:(a.actions||[]).map(r=>({id:r.id?String(r.id):void 0,action_type:r.action_type,card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),message_template:r.message_template||"",delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}",enabled:r.enabled!==!1,sort_order:Number(r.sort_order||0)})),variants:(a.actions||[]).filter(r=>r.action_type==="send_card").map(r=>{let y={};try{y=JSON.parse(r.config_json||"{}")}catch{}return{id:r.id?String(r.id):void 0,spec_name:y.spec_name||"",spec_value:y.spec_value||"",card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),enabled:r.enabled!==!1,delay_override:y.delay_override===!0,delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}"}})}}),Ft=async()=>{const t=await Z("/api/v1/automation-rules"),a=Ge(t,["data","rules","items"]);return ct(a)},Tt=async({cookieId:t,triggerType:a,enabled:i,search:u,page:r=1,pageSize:y=10}={})=>{const A=await Z("/api/vLine truncated
import{j as e,r as o,b as Fe}from"./react-vendor-C_od1ZSF.js";import{k as Je,ae as it,af as vt,m as Nt,R as Te,N as Ye,Z as He,u as wt,n as et,I as kt,a1 as Ct,X as ke,V as ze,y as Ce,h as St,g as Rt,a6 as At,ag as $t,o as tt,ah as Mt}from"./icons-vendor-DwxdQTKt.js";import{g as Z,o as Ae,c as Ge,p as Ke,a as fe,d as Ue}from"./index-KV7tSL6x.js";const Ee=(t,a)=>t.allowed_resolutions.includes(a),Pt=(t,a)=>({runs:t.runs.filter(i=>!a||i.cookie_id===a),pending_tasks:t.pending_tasks.filter(i=>!a||i.cookie_id===a)}),Lt=t=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[t]||"自动化异常",It=({runs:t,pendingTasks:a,onResolveRun:i,onResolveDeferredTask:u})=>e.jsxs("section",{className:"rounded-2xl border border-red-200 bg-red-50 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-black text-red-900",children:"需要人工处理的自动化任务"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。"})]})]}),e.jsxs("div",{className:"space-y-3",children:[t.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 订单 ",r.order_id||"-"," · 已记录发送 ",r.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:Lt(r.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[Ee(r,"continue")&&e.jsx("button",{onClick:(()=>i(r.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),Ee(r,"retry")&&e.jsx("button",{onClick:(()=>i(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),Ee(r,"cancel")&&e.jsx("button",{onClick:(()=>i(r.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${r.id}`)),a.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 延迟任务重试已达 ",r.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:(()=>u(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:(()=>u(r.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${r.id}`))]})]}),Dt=async t=>Z("/api/v1/accounts/details",void 0,t),ot=async t=>Z("/api/v1/cards",void 0,t),dt=async(t,a)=>Z("/api/v1/items",void 0,a),ct=t=>t.map(a=>{var i,u;return{id:String(a.id),name:a.name||"",trigger_type:a.trigger_type||"order_paid",item_keyword:a.item_title||a.item_id||"",cookie_id:a.cookie_id||"",item_id:a.item_id||"",item_title:a.item_title||"",card_group_id:Number(((i=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:i.card_id)||0),card_group_name:((u=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:u.card_name)||"",priority:a.priority||100,enabled:a.enabled||!1,config_json:a.config_json||"{}",actions:(a.actions||[]).map(r=>({id:r.id?String(r.id):void 0,action_type:r.action_type,card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),message_template:r.message_template||"",delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}",enabled:r.enabled!==!1,sort_order:Number(r.sort_order||0)})),variants:(a.actions||[]).filter(r=>r.action_type==="send_card").map(r=>{let y={};try{y=JSON.parse(r.config_json||"{}")}catch{}return{id:r.id?String(r.id):void 0,spec_name:y.spec_name||"",spec_value:y.spec_value||"",card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),enabled:r.enabled!==!1,delay_override:y.delay_override===!0,delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}"}})}}),Ft=async()=>{const t=await Z("/api/v1/automation-rules"),a=Ge(t,["data","rules","items"]);return ct(a)},Tt=async({cookieId:t,triggerType:a,enabled:i,search:u,page:r=1,pageSize:y=10}={})=>{const A=await Z("/api/vLine truncated
@@ -1 +1 @@
import{r,j as e}from"./react-vendor-C_od1ZSF.js";import{a as xe,g as re,p as le}from"./index-CnIcNTyi.js";import{f as ue,R as se,aa as pe,r as me,z as R,F as O,ab as he,t as ge,S as te,ac as ae,ad as ye,o as fe}from"./icons-vendor-DwxdQTKt.js";const ne="https://dashscope.aliyuncs.com/compatible-mode/v1",be=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],we=new Set(["ai_api_key_configured","smtp_password_configured","qq_reply_secret_key_configured","captcha.remote_secret_key_configured","smtp_server","smtp_port","smtp_user","smtp_password","smtp_from","smtp_from_name","smtp_from_address","registration_enabled","show_default_login_info","login_captcha_enabled","item_sync_enabled","item_sync_interval","item_sync_max_pages","default_reply"]),oe=new Set(["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"]),je=s=>{if("values"in s||"secrets"in s)return s;const a={},o={};for(const[d,h]of Object.entries(s))if(h!=null){if(oe.has(d)){o[d]=h===""?{action:"clear"}:{action:"replace",value:String(h)};continue}a[d]=h}return Object.keys(o).length>0?{values:a,secrets:o}:a},ve=s=>{const a={...s};for(const o of oe){const d=`${o}_configured`;d in a&&(a[d]=a[d]===!0||a[d]==="true")}if("renewal_log_retention_days"in a){const o=Number(a.renewal_log_retention_days);a.renewal_log_retention_days=Number.isFinite(o)?o:10}return a},_e=async(s,a)=>le("/api/v1/session/credentials",s,a),Ne=async s=>{const a=await re("/api/v1/settings/system",void 0,s),o=a.data||a.settings||a;return ve(o)},Se=async(s,a)=>le("/api/v1/settings/system",je(s),a),ke=async(s,a="",o)=>{const d=await xe("/api/v1/settings/ai-models",{base_url:s,api_key:a},o);return Array.isArray(d.models)?d.models:[]},Ce=async s=>re("/api/v1/session",void 0,s),Ee=s=>Object.fromEntries(Object.entries(s).filter(([a,o])=>!we.has(a)&&o!==void 0&&o!==null)),Ae=s=>s.new_username.trim().length<3?"用户名至少需要 3 个字符":s.current_password?s.new_password&&s.new_password.length<8?"新密码至少需要 8 个字符":s.new_password!==s.confirm_password?"两次输入的新密码不一致":"":"请输入当前密码确认身份",f=(s,a,o)=>s===a&&!o.aborted,D=s=>s instanceof Error&&s.message==="请求已取消",K=(s,a)=>s instanceof Error?s.message:a,Ie=(s="")=>({new_username:s,current_password:"",new_password:"",confirm_password:""}),T=(s,a)=>({type:s,text:a}),Me=()=>{const[s,a]=r.useState(null),[o,d]=r.useState(!1),[h,p]=r.useState(""),[S,A]=r.useState(!1),[P,k]=r.useState(""),[C,w]=r.useState([]),[j,I]=r.useState(!1),[M,x]=r.useState(""),[$,v]=r.useState(!1),[z,q]=r.useState(!1),[U,u]=r.useState(!1),[b,F]=r.useState(!1),[G,V]=r.useState(!1),[Y,_]=r.useState(!1),[L,y]=r.useState(null),[t,X]=r.useState(()=>Ie()),[ce,J]=r.useState("idle"),Z=r.useRef(null),ee=r.useRef(null),m=r.useRef(0),W=r.useRef(null);ee.current=s;const E=r.useCallback(()=>{var c;(c=W.current)==null||c.abort();const n=new AbortController;return W.current=n,m.current+=1,{controller:n,sequence:m.current}},[]),B=r.useCallback(async(n,c=!1,l)=>{const i=n||ee.current,g=(i==null?void 0:i.ai_api_url)||(i==null?void 0:i.ai_base_url)||ne;I(!0),x("");try{const N=await ke(g,(i==null?void 0:i.ai_api_key)||"",{signal:l});if(l!=null&&l.aborted)return;w(N),v(c&&N.length>0),!(i!=null&&i.ai_model)&&N.length>0&&a(Q=>Q&&{...Q,ai_model:N[0]})}catch(N){if(l!=null&&l.aborted||D(N))return;w([]),v(!1),x(K(N,"读取模型失败"))}finally{l!=null&&l.aborted||I(!1)}},[]),H=r.useCallback(()=>{const{controller:n,sequence:c}=E();d(!0),J("loading"),p(""),Promise.all([Ne({signal:n.signal}),Ce({signal:n.signal})]).then(([l,i])=>{f(m.current,c,n.signal)&&(a(l),i.username&&X(g=>({...g,new_username:i.username||""})),B(l,!1,n.signal),J("success"))}).catch(l=>{!f(m.current,c,n.signal)||D(l)||(a(null),p(K(l,"加载配置失败")),J("error"))}).finally(()=>{f(m.current,c,n.signal)&&d(!1)})},[E,B]);r.useEffect(()=>(H(),(()=>{var n;return(n=W.current)==null?void 0:n.abort()})),[H]),r.useEffect(()=>{const n=c=>{var l;(l=Z.current)!=null&&l.contains(c.target)||v(!1)};return document.addEventListener("mousedown",n),(()=>document.removeEventListener("mousedown",n))},[]);const ie=r.useCallback(async()=>{if(!s||S)return;const{controller:n,sequence:c}=E();A(!0),k("");try{if(await Se(Ee(s),{signal:n.signal}),!f(m.current,c,n.signal))return;window.alert("系统配置已保存")}catch(l){if(!f(m.current,c,n.signal)||D(l))return;k(K(l,"保存配置失败"))}finally{f(m.current,c,n.signal)&&A(!1)}},[E,S,s]),de=r.useCallback(async n=>{n.preventDefault(),y(null);const c=Ae(t);if(c){y(T("error",c));return}const{controller:l,sequence:i}=E();_(!0);try{const g=await _e({current_password:t.current_password,new_username:t.new_username.trim(),new_password:t.new_password||void 0},{signal:l.signal});if(!f(m.current,i,l.signal))return;if(!g.success){y(T("error",g.message||"登录凭据更新失败"));return}y(T("success",g.message||"登录凭据已更新")),window.setTimeout(()=>windLine truncated
import{r,j as e}from"./react-vendor-C_od1ZSF.js";import{a as xe,g as re,p as le}from"./index-KV7tSL6x.js";import{f as ue,R as se,aa as pe,r as me,z as R,F as O,ab as he,t as ge,S as te,ac as ae,ad as ye,o as fe}from"./icons-vendor-DwxdQTKt.js";const ne="https://dashscope.aliyuncs.com/compatible-mode/v1",be=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],we=new Set(["ai_api_key_configured","smtp_password_configured","qq_reply_secret_key_configured","captcha.remote_secret_key_configured","smtp_server","smtp_port","smtp_user","smtp_password","smtp_from","smtp_from_name","smtp_from_address","registration_enabled","show_default_login_info","login_captcha_enabled","item_sync_enabled","item_sync_interval","item_sync_max_pages","default_reply"]),oe=new Set(["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"]),je=s=>{if("values"in s||"secrets"in s)return s;const a={},o={};for(const[d,h]of Object.entries(s))if(h!=null){if(oe.has(d)){o[d]=h===""?{action:"clear"}:{action:"replace",value:String(h)};continue}a[d]=h}return Object.keys(o).length>0?{values:a,secrets:o}:a},ve=s=>{const a={...s};for(const o of oe){const d=`${o}_configured`;d in a&&(a[d]=a[d]===!0||a[d]==="true")}if("renewal_log_retention_days"in a){const o=Number(a.renewal_log_retention_days);a.renewal_log_retention_days=Number.isFinite(o)?o:10}return a},_e=async(s,a)=>le("/api/v1/session/credentials",s,a),Ne=async s=>{const a=await re("/api/v1/settings/system",void 0,s),o=a.data||a.settings||a;return ve(o)},Se=async(s,a)=>le("/api/v1/settings/system",je(s),a),ke=async(s,a="",o)=>{const d=await xe("/api/v1/settings/ai-models",{base_url:s,api_key:a},o);return Array.isArray(d.models)?d.models:[]},Ce=async s=>re("/api/v1/session",void 0,s),Ee=s=>Object.fromEntries(Object.entries(s).filter(([a,o])=>!we.has(a)&&o!==void 0&&o!==null)),Ae=s=>s.new_username.trim().length<3?"用户名至少需要 3 个字符":s.current_password?s.new_password&&s.new_password.length<8?"新密码至少需要 8 个字符":s.new_password!==s.confirm_password?"两次输入的新密码不一致":"":"请输入当前密码确认身份",f=(s,a,o)=>s===a&&!o.aborted,D=s=>s instanceof Error&&s.message==="请求已取消",K=(s,a)=>s instanceof Error?s.message:a,Ie=(s="")=>({new_username:s,current_password:"",new_password:"",confirm_password:""}),T=(s,a)=>({type:s,text:a}),Me=()=>{const[s,a]=r.useState(null),[o,d]=r.useState(!1),[h,p]=r.useState(""),[S,A]=r.useState(!1),[P,k]=r.useState(""),[C,w]=r.useState([]),[j,I]=r.useState(!1),[M,x]=r.useState(""),[$,v]=r.useState(!1),[z,q]=r.useState(!1),[U,u]=r.useState(!1),[b,F]=r.useState(!1),[G,V]=r.useState(!1),[Y,_]=r.useState(!1),[L,y]=r.useState(null),[t,X]=r.useState(()=>Ie()),[ce,J]=r.useState("idle"),Z=r.useRef(null),ee=r.useRef(null),m=r.useRef(0),W=r.useRef(null);ee.current=s;const E=r.useCallback(()=>{var c;(c=W.current)==null||c.abort();const n=new AbortController;return W.current=n,m.current+=1,{controller:n,sequence:m.current}},[]),B=r.useCallback(async(n,c=!1,l)=>{const i=n||ee.current,g=(i==null?void 0:i.ai_api_url)||(i==null?void 0:i.ai_base_url)||ne;I(!0),x("");try{const N=await ke(g,(i==null?void 0:i.ai_api_key)||"",{signal:l});if(l!=null&&l.aborted)return;w(N),v(c&&N.length>0),!(i!=null&&i.ai_model)&&N.length>0&&a(Q=>Q&&{...Q,ai_model:N[0]})}catch(N){if(l!=null&&l.aborted||D(N))return;w([]),v(!1),x(K(N,"读取模型失败"))}finally{l!=null&&l.aborted||I(!1)}},[]),H=r.useCallback(()=>{const{controller:n,sequence:c}=E();d(!0),J("loading"),p(""),Promise.all([Ne({signal:n.signal}),Ce({signal:n.signal})]).then(([l,i])=>{f(m.current,c,n.signal)&&(a(l),i.username&&X(g=>({...g,new_username:i.username||""})),B(l,!1,n.signal),J("success"))}).catch(l=>{!f(m.current,c,n.signal)||D(l)||(a(null),p(K(l,"加载配置失败")),J("error"))}).finally(()=>{f(m.current,c,n.signal)&&d(!1)})},[E,B]);r.useEffect(()=>(H(),(()=>{var n;return(n=W.current)==null?void 0:n.abort()})),[H]),r.useEffect(()=>{const n=c=>{var l;(l=Z.current)!=null&&l.contains(c.target)||v(!1)};return document.addEventListener("mousedown",n),(()=>document.removeEventListener("mousedown",n))},[]);const ie=r.useCallback(async()=>{if(!s||S)return;const{controller:n,sequence:c}=E();A(!0),k("");try{if(await Se(Ee(s),{signal:n.signal}),!f(m.current,c,n.signal))return;window.alert("系统配置已保存")}catch(l){if(!f(m.current,c,n.signal)||D(l))return;k(K(l,"保存配置失败"))}finally{f(m.current,c,n.signal)&&A(!1)}},[E,S,s]),de=r.useCallback(async n=>{n.preventDefault(),y(null);const c=Ae(t);if(c){y(T("error",c));return}const{controller:l,sequence:i}=E();_(!0);try{const g=await _e({current_password:t.current_password,new_username:t.new_username.trim(),new_password:t.new_password||void 0},{signal:l.signal});if(!f(m.current,i,l.signal))return;if(!g.success){y(T("error",g.message||"登录凭据更新失败"));return}y(T("success",g.message||"登录凭据已更新")),window.setTimeout(()=>windLine truncated
@@ -1,2 +1,2 @@
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-BWEyoN_j.js","assets/react-vendor-C_od1ZSF.js","assets/dateTime-DDi7rqpW.js","assets/icons-vendor-DwxdQTKt.js","assets/charts-vendor-deWqkrdG.js","assets/vendor-Es4K8PXl.js","assets/vendor-DUblxfbA.css","assets/AccountList-Clo3bk6M.js","assets/OrderList-DfvrbOae.js","assets/CardList-K2y0aCW6.js","assets/ItemList-BE7FH0Hk.js","assets/Settings-CdBvAsXQ.js","assets/Rules-JlBshZ7j.js","assets/Notifications-CMZ72DA2.js","assets/Chat-D65uVZd-.js"])))=>i.map(i=>d[i]);
import{c as R,j as t,r as l,d as te}from"./react-vendor-C_od1ZSF.js";import{L as U,a as O,S as se,U as ne,A as re,b as ae,c as oe,M as ie,C as ce,B as le,d as de,Z as ue,e as he,f as me,G as M,g as fe,h as pe,i as xe}from"./icons-vendor-DwxdQTKt.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))o(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&o(a)}).observe(document,{childList:!0,subtree:!0});function s(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function o(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();class ge extends R.Component{constructor(){super(...arguments),this.state={hasError:!1},this.handleReload=()=>{window.location.reload()}}static getDerivedStateFromError(){return{hasError:!0}}render(){const{hasError:n}=this.state,{children:s}=this.props;return n?t.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-6 text-ink",children:t.jsxs("section",{className:"max-w-md text-center",children:[t.jsx("h1",{className:"text-xl font-semibold",children:"页面暂时无法显示"}),t.jsx("button",{className:"ios-btn-primary mt-6 px-4 py-2",type:"button",onClick:this.handleReload,children:"重新加载"})]})}):s}}const be=3e4,ye=10*6e4;let P=!1;class q extends Error{constructor(n,s){super(je(s,n)),this.name="ApiError",this.status=n,this.code=E(s)?s.code:`http_${n}`,this.requestId=E(s)?s.request_id:void 0,this.request_id=this.requestId,this.details=E(s)?s.details:void 0,this.payload=s}}const F=()=>{P||typeof window>"u"||(P=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{P=!1}))},ve=e=>{if(!e)return"";const n=new URLSearchParams;for(const[o,r]of Object.entries(e))r!=null&&n.set(o,String(r));const s=n.toString();return s?`?${s}`:""},A=async(e,n,s={})=>{var d;const o=ve(s.params),r=`${n}${o}`,i=B(s.signal,s.timeoutMs??be);let a;try{a=await fetch(r,{method:e,credentials:"include",signal:i.signal,headers:{...s.body===void 0?{}:{"Content-Type":"application/json"}},body:s.body===void 0?void 0:JSON.stringify(s.body)})}catch(h){throw i.signal.aborted?new Error((d=s.signal)!=null&&d.aborted?"请求已取消":"请求超时,请稍后重试"):h}finally{i.cleanup()}const u=(a.headers.get("content-type")||"").includes("application/json");if(!a.ok){a.status===401&&!s.skipAuthLogout&&F();const h=await V(a,u);throw new q(a.status,h)}return u?await a.json():await a.text()},j=async(e,n,s)=>A("GET",e,{params:n,...s}),L=async(e,n,s)=>A("POST",e,{body:n,...s}),ot=async(e,n,s)=>A("PUT",e,{body:n,...s}),it=async(e,n,s)=>A("DELETE",e,{params:n,...s}),we=async(e,n,s={})=>{var u;const o=B(s.signal,s.timeoutMs??ye);let r;try{r=await fetch(e,{method:"POST",credentials:"include",signal:o.signal,body:n})}catch(d){throw o.signal.aborted?new Error((u=s.signal)!=null&&u.aborted?"请求已取消":"上传超时,请稍后重试"):d}finally{o.cleanup()}const a=(r.headers.get("content-type")||"").includes("application/json"),c=await V(r,a);if(!r.ok)throw r.status===401&&F(),new q(r.status,c);return c},B=(e,n)=>{const s=new AbortController,o=()=>s.abort(e==null?void 0:e.reason);e!=null&&e.aborted?o():e==null||e.addEventListener("abort",o,{once:!0});const r=globalThis.setTimeout(()=>s.abort(new DOMException("timeout","TimeoutError")),Math.max(1,n));return{signal:s.signal,cleanup:()=>{globalThis.clearTimeout(r),e==null||e.removeEventListener("abort",o)}}},V=async(e,n)=>n?e.json().catch(()=>{}):e.text().catch(()=>{}),E=e=>{if(typeof e!="object"||e===null)return!1;const n=e;return typeof n.code=="string"&&typeof n.message=="string"},je=(e,n)=>typeof e=="string"?e:E(e)?e.message:`请求失败: ${n}`,Le=async e=>L("/api/v1/session/login",e,{skipAuthLogout:!0}),Ce=async e=>L("/api/v1/session/initialize",{password:e},{skipAuthLogout:!0}),Ne=async e=>j("/api/v1/session",void 0,e),Ee=async()=>L("/api/v1/session/logout",{}),G=l.createContext(void 0),Se=({children:e})=>{const[n,s]=l.useState(!1),[o,r]=l.useState(!1),[i,a]=l.useState(!0),[c,u]=l.useState(!1),d=()=>{s(!1),r(!1)};l.useEffect(()=>{const x=new AbortController;let p=!0;Ne({signal:x.signal}).then(b=>{if(p){if((b==null?void 0:b.initialized)===!1){u(!0),d();return}u(!1),b!=null&&b.authenticated?(s(!0),r(b.is_admin===!0)):d()}}).catch(b=>{!p||b instanceof DOMException&&b.name==="AbortError"||(u(!1),d())}).finally(()=>{p&&a(!1)});const m=()=>d();return window.addEventListener("auth:logout",m),(()=>{p=!1,x.abort(),window.removeEventListener("auth:logout",m)})},[]);const h=async x=>{const p=await Le(x);return p.success&&(u(!1),s(!0),r(p.is_admin===!0)),p},g=async x=>{const p=await Ce(x);return p.success&&(u(!1),s(!0Line truncated
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-B9IAsTbK.js","assets/react-vendor-C_od1ZSF.js","assets/dateTime-DDi7rqpW.js","assets/icons-vendor-DwxdQTKt.js","assets/charts-vendor-deWqkrdG.js","assets/vendor-Es4K8PXl.js","assets/vendor-DUblxfbA.css","assets/AccountList-cIlnZ13o.js","assets/OrderList-BEavERdn.js","assets/CardList-CcZPotoH.js","assets/ItemList-CyILtubM.js","assets/Settings-eSrR2WFx.js","assets/Rules-DyCI8Yz_.js","assets/Notifications-CusLu0iM.js","assets/Chat-Dnvr2e7q.js"])))=>i.map(i=>d[i]);
import{c as R,j as t,r as l,d as te}from"./react-vendor-C_od1ZSF.js";import{L as U,a as O,S as se,U as ne,A as re,b as ae,c as oe,M as ie,C as ce,B as le,d as de,Z as ue,e as he,f as me,G as M,g as fe,h as pe,i as xe}from"./icons-vendor-DwxdQTKt.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))o(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&o(a)}).observe(document,{childList:!0,subtree:!0});function s(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function o(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();class ge extends R.Component{constructor(){super(...arguments),this.state={hasError:!1},this.handleReload=()=>{window.location.reload()}}static getDerivedStateFromError(){return{hasError:!0}}render(){const{hasError:n}=this.state,{children:s}=this.props;return n?t.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-6 text-ink",children:t.jsxs("section",{className:"max-w-md text-center",children:[t.jsx("h1",{className:"text-xl font-semibold",children:"页面暂时无法显示"}),t.jsx("button",{className:"ios-btn-primary mt-6 px-4 py-2",type:"button",onClick:this.handleReload,children:"重新加载"})]})}):s}}const be=3e4,ye=10*6e4;let P=!1;class q extends Error{constructor(n,s){super(je(s,n)),this.name="ApiError",this.status=n,this.code=E(s)?s.code:`http_${n}`,this.requestId=E(s)?s.request_id:void 0,this.request_id=this.requestId,this.details=E(s)?s.details:void 0,this.payload=s}}const F=()=>{P||typeof window>"u"||(P=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{P=!1}))},ve=e=>{if(!e)return"";const n=new URLSearchParams;for(const[o,r]of Object.entries(e))r!=null&&n.set(o,String(r));const s=n.toString();return s?`?${s}`:""},A=async(e,n,s={})=>{var d;const o=ve(s.params),r=`${n}${o}`,i=B(s.signal,s.timeoutMs??be);let a;try{a=await fetch(r,{method:e,credentials:"include",signal:i.signal,headers:{...s.body===void 0?{}:{"Content-Type":"application/json"}},body:s.body===void 0?void 0:JSON.stringify(s.body)})}catch(h){throw i.signal.aborted?new Error((d=s.signal)!=null&&d.aborted?"请求已取消":"请求超时,请稍后重试"):h}finally{i.cleanup()}const u=(a.headers.get("content-type")||"").includes("application/json");if(!a.ok){a.status===401&&!s.skipAuthLogout&&F();const h=await V(a,u);throw new q(a.status,h)}return u?await a.json():await a.text()},j=async(e,n,s)=>A("GET",e,{params:n,...s}),L=async(e,n,s)=>A("POST",e,{body:n,...s}),ot=async(e,n,s)=>A("PUT",e,{body:n,...s}),it=async(e,n,s)=>A("DELETE",e,{params:n,...s}),we=async(e,n,s={})=>{var u;const o=B(s.signal,s.timeoutMs??ye);let r;try{r=await fetch(e,{method:"POST",credentials:"include",signal:o.signal,body:n})}catch(d){throw o.signal.aborted?new Error((u=s.signal)!=null&&u.aborted?"请求已取消":"上传超时,请稍后重试"):d}finally{o.cleanup()}const a=(r.headers.get("content-type")||"").includes("application/json"),c=await V(r,a);if(!r.ok)throw r.status===401&&F(),new q(r.status,c);return c},B=(e,n)=>{const s=new AbortController,o=()=>s.abort(e==null?void 0:e.reason);e!=null&&e.aborted?o():e==null||e.addEventListener("abort",o,{once:!0});const r=globalThis.setTimeout(()=>s.abort(new DOMException("timeout","TimeoutError")),Math.max(1,n));return{signal:s.signal,cleanup:()=>{globalThis.clearTimeout(r),e==null||e.removeEventListener("abort",o)}}},V=async(e,n)=>n?e.json().catch(()=>{}):e.text().catch(()=>{}),E=e=>{if(typeof e!="object"||e===null)return!1;const n=e;return typeof n.code=="string"&&typeof n.message=="string"},je=(e,n)=>typeof e=="string"?e:E(e)?e.message:`请求失败: ${n}`,Le=async e=>L("/api/v1/session/login",e,{skipAuthLogout:!0}),Ce=async e=>L("/api/v1/session/initialize",{password:e},{skipAuthLogout:!0}),Ne=async e=>j("/api/v1/session",void 0,e),Ee=async()=>L("/api/v1/session/logout",{}),G=l.createContext(void 0),Se=({children:e})=>{const[n,s]=l.useState(!1),[o,r]=l.useState(!1),[i,a]=l.useState(!0),[c,u]=l.useState(!1),d=()=>{s(!1),r(!1)};l.useEffect(()=>{const x=new AbortController;let p=!0;Ne({signal:x.signal}).then(b=>{if(p){if((b==null?void 0:b.initialized)===!1){u(!0),d();return}u(!1),b!=null&&b.authenticated?(s(!0),r(b.is_admin===!0)):d()}}).catch(b=>{!p||b instanceof DOMException&&b.name==="AbortError"||(u(!1),d())}).finally(()=>{p&&a(!1)});const m=()=>d();return window.addEventListener("auth:logout",m),(()=>{p=!1,x.abort(),window.removeEventListener("auth:logout",m)})},[]);const h=async x=>{const p=await Le(x);return p.success&&(u(!1),s(!0),r(p.is_admin===!0)),p},g=async x=>{const p=await Ce(x);return p.success&&(u(!1),s(!0Line truncated
+1 -1
View File
@@ -6,7 +6,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ydisks闲鱼助手 - 自动发货与管家系统</title>
<meta name="description" content="Ydisks闲鱼助手 - 自动回复、自动发货、订单管理、AI智能议价一体化解决方案" />
<script type="module" crossorigin src="/static/assets/index-CnIcNTyi.js"></script>
<script type="module" crossorigin src="/static/assets/index-KV7tSL6x.js"></script>
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-C_od1ZSF.js">
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-DwxdQTKt.js">
<link rel="stylesheet" crossorigin href="/static/assets/index-D5pYdG6n.css">
+183 -24
View File
@@ -59,16 +59,18 @@ var qrHeaders = map[string]string{
// Session 一个扫码登录会话。
type Session struct {
mu sync.RWMutex
SessionID string `json:"session_id"`
Status string `json:"status"` // waiting/scanned/success/expired/cancelled/error/verification_required
QRCodeURL string `json:"qr_code_url"`
qrContent string
cookies map[string]string
cookieSnapshot []cookierefresh.BrowserCookie
unb string
createdTime time.Time
expireTime time.Duration
mu sync.RWMutex
SessionID string `json:"session_id"`
Status string `json:"status"` // waiting/scanned/success/expired/cancelled/error/verification_required
QRCodeURL string `json:"qr_code_url"`
qrContent string
cookies map[string]string
cookieSnapshot []cookierefresh.BrowserCookie
unb string
createdTime time.Time
expireTime time.Duration
// lifecycleCtx 是当前会话全部后台任务共享的可取消根 Context,禁止进入 HTTP 返回值或日志。
lifecycleCtx context.Context
params map[string]string
verificationURL string
verificationScreenshot string // 历史兼容字段;纯 Go 人脸流程直接返回二维码
@@ -112,10 +114,24 @@ func (s *Session) snapshot() sessionSnapshot {
// Manager 扫码登录管理器。
type Manager struct {
mu sync.Mutex
// mu 保护会话表、会话取消函数、根 Context 与 closing;不在持锁时执行网络或等待操作。
mu sync.Mutex
// sessions 保存当前可查询的二维码会话。
sessions map[string]*Session
httpc *http.Client
logger *slog.Logger
// sessionCancels 保存每个会话的根取消函数;删除或关闭会取消其监控和验证子任务。
sessionCancels map[string]context.CancelFunc
// lifecycleCtx 是二维码任务的进程根 Context,由 Start 注入并在 CloseContext 取消。
lifecycleCtx context.Context
// lifecycleCancel 取消当前二维码管理器拥有的根 Context。
lifecycleCancel context.CancelFunc
// closing 表示管理器已拒绝新会话,但仍等待已有任务收束。
closing bool
// tasks 记录所有由 Manager 启动的会话任务;CloseContext 负责等待其结束。
tasks sync.WaitGroup
// closeMu 串行化 CloseContext,避免多个调用重复取消和并发等待。
closeMu sync.Mutex
httpc *http.Client
logger *slog.Logger
}
// NewManager 构造。
@@ -123,15 +139,99 @@ func NewManager(logger *slog.Logger) *Manager {
if logger == nil {
logger = slog.Default()
}
return &Manager{
sessions: make(map[string]*Session),
httpc: &http.Client{Timeout: 60 * time.Second},
logger: logger,
// lifecycleCtx、lifecycleCancel 为未装配进程协调器的测试和兼容调用提供可关闭的默认根 Context。
lifecycleCtx, lifecycleCancel := context.WithCancel(context.Background())
return &Manager{sessions: make(map[string]*Session), sessionCancels: make(map[string]context.CancelFunc), lifecycleCtx: lifecycleCtx, lifecycleCancel: lifecycleCancel, httpc: &http.Client{Timeout: 60 * time.Second}, logger: logger}
}
// Start 注入进程协调器拥有的根 Context;启动后新会话的后台任务都从该 Context 派生。
func (m *Manager) Start(ctx context.Context) error {
if m == nil || ctx == nil {
return errors.New("二维码管理器启动需要生命周期 Context")
}
// err 保存启动前调用方已经取消的生命周期 Context 错误。
if err := ctx.Err(); err != nil {
return err
}
m.mu.Lock()
defer m.mu.Unlock()
if m.closing {
return errors.New("二维码管理器已关闭")
}
// previousCancel 取消构造期默认根 Context;正常运行时尚未创建会话,避免遗留无主根 Context。
previousCancel := m.lifecycleCancel
// lifecycleCtx、lifecycleCancel 将进程根包装为 Manager 自己可取消的子 Context。
lifecycleCtx, lifecycleCancel := context.WithCancel(ctx)
m.lifecycleCtx = lifecycleCtx
m.lifecycleCancel = lifecycleCancel
if previousCancel != nil {
previousCancel()
}
return nil
}
// startSessionTask 在会话根 Context 下登记可等待后台任务;关闭后不再创建新的 goroutine。
func (m *Manager) startSessionTask(sessionID string, timeout time.Duration, task func(context.Context)) bool {
m.mu.Lock()
if m.closing {
m.mu.Unlock()
return false
}
// sessionCtx、exists 保存当前会话根 Context 及其是否仍在会话表中。
sessionCtx, exists := m.sessionContextLocked(sessionID)
if !exists {
m.mu.Unlock()
return false
}
m.tasks.Add(1)
m.mu.Unlock()
go func() {
// taskCtx、cancel 将会话取消和独立有效期合并,任务退出时必须释放定时器。
taskCtx, cancel := context.WithTimeout(sessionCtx, timeout)
defer cancel()
defer m.tasks.Done()
task(taskCtx)
}()
return true
}
// sessionContextLocked 返回会话根 Context;调用方必须已持有 m.mu。
func (m *Manager) sessionContextLocked(sessionID string) (context.Context, bool) {
// sess 保存已登记会话;不存在、未初始化 Context 或已删除的会话都不得再启动后台任务。
sess, exists := m.sessions[sessionID]
if !exists || sess == nil {
return nil, false
}
if sess.lifecycleCtx == nil {
// rootCtx 为历史测试或兼容直接注入的会话补齐可取消根 Context;生产路径会在创建会话时预先登记。
rootCtx := m.lifecycleCtx
if rootCtx == nil {
rootCtx = context.Background()
}
// sessionCtx、sessionCancel 将补齐会话纳入 Manager 的统一取消表。
sessionCtx, sessionCancel := context.WithCancel(rootCtx)
sess.lifecycleCtx = sessionCtx
if m.sessionCancels == nil {
m.sessionCancels = make(map[string]context.CancelFunc)
}
m.sessionCancels[sessionID] = sessionCancel
}
// sessionCancel 表示会话是否仍由 Manager 持有取消权。
if sessionCancel := m.sessionCancels[sessionID]; sessionCancel == nil {
return nil, false
}
return sess.lifecycleCtx, true
}
// GenerateQRCode 生成扫码登录二维码。返回 session_id + qr_code_url(base64 data URL)。
func (m *Manager) GenerateQRCode(ctx context.Context) (sessionID string, qrCodeURL string, err error) {
m.mu.Lock()
// closing 表示 Manager 已经进入关闭阶段,不能在执行任何平台请求前接受新二维码会话。
closing := m.closing
m.mu.Unlock()
if closing {
return "", "", errors.New("二维码管理器已关闭")
}
sessionID, err = randomUUID()
if err != nil {
return "", "", fmt.Errorf("生成扫码会话 ID: %w", err)
@@ -235,17 +335,24 @@ func (m *Manager) GenerateQRCode(ctx context.Context) (sessionID string, qrCodeU
sess.QRCodeURL = qrCodeURL
m.mu.Lock()
if m.closing {
m.mu.Unlock()
return "", "", errors.New("二维码管理器已关闭")
}
// sessionCtx、sessionCancel 将该会话绑定到进程根 Context;DeleteSession 和 CloseContext 都拥有取消权。
sessionCtx, sessionCancel := context.WithCancel(m.lifecycleCtx)
sess.lifecycleCtx = sessionCtx
m.sessions[sessionID] = sess
m.sessionCancels[sessionID] = sessionCancel
m.mu.Unlock()
// 5. 扫码会话独立于生成二维码的 HTTP 请求,但受会话有效期约束。
// #nosec G118 -- 后台任务必须跨越原请求,且由超时上下文保证退出。
go func() {
// monitorCtx、cancel 用于本次流程后续判断的monitorCtx、cancel
monitorCtx, cancel := context.WithTimeout(context.Background(), sess.snapshot().expireTime)
defer cancel()
// 5. 扫码会话独立于生成二维码的 HTTP 请求,但受会话和进程生命周期共同约束。
if !m.startSessionTask(sessionID, sess.snapshot().expireTime, func(monitorCtx context.Context) {
m.monitorQRStatus(monitorCtx, sessionID)
}()
}) {
m.DeleteSession(sessionID)
return "", "", errors.New("二维码会话后台任务未启动")
}
m.logger.Info("二维码生成成功", "session_id", sessionID)
return sessionID, qrCodeURL, nil
@@ -304,8 +411,60 @@ func (m *Manager) GetSessionStatus(sessionID string) map[string]any {
// DeleteSession 主动释放终态/过期扫码会话中的二维码、Cookie 和验证截图。
func (m *Manager) DeleteSession(sessionID string) {
m.mu.Lock()
// sessionCancel 是当前会话全部后台任务的唯一取消入口;先从表中移除再锁外取消,避免新任务重新登记。
sessionCancel := m.sessionCancels[sessionID]
delete(m.sessions, sessionID)
delete(m.sessionCancels, sessionID)
m.mu.Unlock()
if sessionCancel != nil {
sessionCancel()
}
}
// CloseContext 拒绝新会话、取消全部已有任务并等待其退出;超时时可使用新的 Context 重试等待。
func (m *Manager) CloseContext(ctx context.Context) error {
if m == nil {
return nil
}
if ctx == nil {
return errors.New("关闭二维码管理器需要 Context")
}
// err 保存关闭等待开始前调用方已经取消的关闭 Context 错误。
if err := ctx.Err(); err != nil {
return err
}
m.closeMu.Lock()
defer m.closeMu.Unlock()
m.mu.Lock()
m.closing = true
// lifecycleCancel 取消由 Start 或构造期创建的根 Context;sessionCancels 额外确保会话可立即停止。
lifecycleCancel := m.lifecycleCancel
// sessionCancels 保存待锁外触发的每个会话取消函数。
sessionCancels := make([]context.CancelFunc, 0, len(m.sessionCancels))
// _, sessionCancel 分别表示会话标识和对应的根取消函数,后者在锁外取消全部会话任务。
for _, sessionCancel := range m.sessionCancels {
sessionCancels = append(sessionCancels, sessionCancel)
}
m.mu.Unlock()
if lifecycleCancel != nil {
lifecycleCancel()
}
// _, sessionCancel 分别表示待取消列表下标和当前会话根取消函数。
for _, sessionCancel := range sessionCancels {
sessionCancel()
}
// done 仅观察 Manager 自己拥有的 WaitGroup;任务已被取消,waiter 结束后不会留下后台生命周期。
done := make(chan struct{})
go func() {
m.tasks.Wait()
close(done)
}()
select {
case <-done:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
// monitorQRStatus 后台轮询扫码状态。
+157
View File
@@ -23,6 +23,163 @@ type failingReader struct{}
// Read 读取当前值。
func (failingReader) Read([]byte) (int, error) { return 0, errors.New("entropy unavailable") }
// TestManagerCloseContextCancelsSessionTask 验证进程关闭会取消 Manager 拥有的会话后台任务并等待其退出。
func TestManagerCloseContextCancelsSessionTask(t *testing.T) {
// manager 保存待关闭的二维码会话管理器。
manager := NewManager(nil)
// session 保存不依赖平台网络的最小会话,startSessionTask 会为它补齐生命周期 Context。
session := &Session{SessionID: "close-session", Status: "waiting", cookies: map[string]string{}, params: map[string]string{}}
manager.sessions[session.SessionID] = session
// started 通知测试任务已进入等待。
started := make(chan struct{})
// stopped 通知测试任务已收到关闭取消。
stopped := make(chan struct{})
// startedTask 表示后台任务是否被 Manager 成功登记。
startedTask := manager.startSessionTask(session.SessionID, time.Minute, func(ctx context.Context) {
close(started)
<-ctx.Done()
close(stopped)
})
if !startedTask {
t.Fatal("二维码后台任务未启动")
}
select {
case <-started:
case <-time.After(time.Second):
t.Fatal("二维码后台任务未进入等待")
}
// closeErr 保存关闭等待结果;CloseContext 必须在任务退出后才返回。
closeErr := manager.CloseContext(context.Background())
if closeErr != nil {
t.Fatalf("关闭二维码管理器失败: %v", closeErr)
}
select {
case <-stopped:
case <-time.After(time.Second):
t.Fatal("关闭未取消二维码后台任务")
}
}
// TestManagerDeleteSessionCancelsSessionTask 验证删除会话会停止该会话的后台任务而不影响 Manager 的后续关闭。
func TestManagerDeleteSessionCancelsSessionTask(t *testing.T) {
// manager 保存待验证删除行为的二维码会话管理器。
manager := NewManager(nil)
// session 保存被删除的最小会话。
session := &Session{SessionID: "delete-session", Status: "waiting", cookies: map[string]string{}, params: map[string]string{}}
manager.sessions[session.SessionID] = session
// started 协调测试任务进入等待时机。
started := make(chan struct{})
// stopped 协调测试任务收到删除取消后的退出时机。
stopped := make(chan struct{})
if !manager.startSessionTask(session.SessionID, time.Minute, func(ctx context.Context) {
close(started)
<-ctx.Done()
close(stopped)
}) {
t.Fatal("二维码后台任务未启动")
}
select {
case <-started:
case <-time.After(time.Second):
t.Fatal("二维码后台任务未进入等待")
}
manager.DeleteSession(session.SessionID)
select {
case <-stopped:
case <-time.After(time.Second):
t.Fatal("删除会话未取消后台任务")
}
// closeErr 验证删除后的 Manager 仍可幂等关闭并回收 WaitGroup。
closeErr := manager.CloseContext(context.Background())
if closeErr != nil {
t.Fatalf("删除后关闭二维码管理器失败: %v", closeErr)
}
}
// TestManagerCloseRejectsNewQRCode 验证关闭后的 Manager 在访问平台前拒绝创建新二维码会话。
func TestManagerCloseRejectsNewQRCode(t *testing.T) {
// manager 保存已经关闭的二维码会话管理器。
manager := NewManager(nil)
// closeErr 保存关闭后的返回错误。
if closeErr := manager.CloseContext(context.Background()); closeErr != nil {
t.Fatalf("关闭二维码管理器失败: %v", closeErr)
}
// _, _, generateErr 保存关闭后创建二维码返回的结果和错误。
_, _, generateErr := manager.GenerateQRCode(context.Background())
if generateErr == nil || !strings.Contains(generateErr.Error(), "已关闭") {
t.Fatalf("关闭后仍接受新二维码会话: %v", generateErr)
}
}
// TestManagerCloseContextCancelsFaceVerification 验证普通扫码切换到人脸验证后,Manager 关闭仍会取消并等待人脸 HTTP 任务。
func TestManagerCloseContextCancelsFaceVerification(t *testing.T) {
// requestStarted 通知人脸验证的第一跳已经进入测试服务器。
requestStarted := make(chan struct{})
// requestCanceled 通知测试服务器收到请求 Context 取消。
requestCanceled := make(chan struct{})
// manager 是带可阻塞人脸验证 HTTP 传输的二维码管理器。
manager, _, _ := newStubbedManager(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
close(requestStarted)
<-r.Context().Done()
close(requestCanceled)
}))
// session 保存已确认但尚未完成风控的人脸会话。
session := &Session{SessionID: "face-close-session", Status: "waiting", cookies: map[string]string{"tmp": "cookie"}, params: map[string]string{}, createdTime: time.Now(), expireTime: time.Minute}
manager.sessions[session.SessionID] = session
manager.handleConfirmedQRStatus(context.Background(), session, session.SessionID, true, "https://passport.goofish.com/iv/mini/normal_validate.htm")
select {
case <-requestStarted:
case <-time.After(time.Second):
t.Fatal("人脸验证任务未进入第一跳请求")
}
// closeErr 保存 Manager 取消并等待人脸验证任务退出的结果。
if closeErr := manager.CloseContext(context.Background()); closeErr != nil {
t.Fatalf("关闭二维码管理器失败: %v", closeErr)
}
select {
case <-requestCanceled:
case <-time.After(time.Second):
t.Fatal("关闭未取消人脸验证 HTTP 请求")
}
// repeatErr 验证关闭操作幂等。
if repeatErr := manager.CloseContext(context.Background()); repeatErr != nil {
t.Fatalf("重复关闭二维码管理器失败: %v", repeatErr)
}
}
// TestDeleteSessionCancelsFaceVerification 验证删除已进入人脸验证的会话会立即停止其后台 HTTP 任务。
func TestDeleteSessionCancelsFaceVerification(t *testing.T) {
// requestStarted 通知人脸验证已开始网络请求。
requestStarted := make(chan struct{})
// requestCanceled 通知删除会话已经取消网络请求。
requestCanceled := make(chan struct{})
// manager 是带可观察人脸 HTTP 取消信号的二维码管理器。
manager, _, _ := newStubbedManager(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
close(requestStarted)
<-r.Context().Done()
close(requestCanceled)
}))
// session 保存等待人脸验证的会话。
session := &Session{SessionID: "face-delete-session", Status: "waiting", cookies: map[string]string{"tmp": "cookie"}, params: map[string]string{}, createdTime: time.Now(), expireTime: time.Minute}
manager.sessions[session.SessionID] = session
manager.handleConfirmedQRStatus(context.Background(), session, session.SessionID, true, "https://passport.goofish.com/iv/mini/normal_validate.htm")
select {
case <-requestStarted:
case <-time.After(time.Second):
t.Fatal("人脸验证任务未进入第一跳请求")
}
manager.DeleteSession(session.SessionID)
select {
case <-requestCanceled:
case <-time.After(time.Second):
t.Fatal("删除会话未取消人脸验证 HTTP 请求")
}
// closeErr 保存删除人脸会话后等待所有后台任务退出的关闭结果。
if closeErr := manager.CloseContext(context.Background()); closeErr != nil {
t.Fatalf("删除人脸会话后关闭失败: %v", closeErr)
}
}
// TestReadQRBodyRejectsOversizedResponse 封装TestReadQR请求体RejectsOversized响应业务协调。
func TestReadQRBodyRejectsOversizedResponse(t *testing.T) {
if // err 用于本次流程后续判断的err
+3 -6
View File
@@ -34,13 +34,10 @@ func (m *Manager) handleConfirmedQRStatus(ctx context.Context, sess *Session, se
cookieCount := len(sess.cookies)
sess.mu.Unlock()
m.logger.Warn("扫码登录需要风控验证,使用 Go HTTP 保持原登录会话", "session_id", sessionID, "verification_url", logsafe.URL(verURL), "tmp_cookie_count", cookieCount)
// #nosec G118 -- 验证必须跨越轮询请求,且由独立五分钟上下文保证退出。
go func() {
// verifyCtx、cancel 用于本次流程后续判断的verifyCtx、cancel
verifyCtx, cancel := context.WithTimeout(context.Background(), expireTime)
defer cancel()
// 人脸验证任务沿用会话根 Context,由 Manager 统一取消和等待,不能脱离进程生命周期。
_ = m.startSessionTask(sessionID, expireTime, func(verifyCtx context.Context) {
m.runGoVerification(verifyCtx, sessionID, verURL)
}()
})
} else {
sess.mu.Unlock()
}