阶段六:完成生成契约迁移并永久关闭旁路

This commit is contained in:
Christ committed 2026-08-20 03:48:33 +08:00
1 parent 5675f60e52
commit 76f4e2e87d
117 files changed
+5833 -2204

No files matched your search

+6
View File
@@ -221,6 +221,10 @@ until their recorded phase is completed; agents MUST NOT add new violations.
transport adapter boundary.
- Route-prefix changes require `frontend/vite.config.ts`, frontend API callers, contract tests and embedded assets
to be updated together.
- `api/openapi.yaml` is the only contract source for `/api/v1/**` and `/health`; every new versioned operation must
update the specification, regenerate `frontend/shared/api-contract/generated/schema.ts`, and add a real handler
contract test before a feature can call it. Generated types are read-only, and feature UI models must remain behind
their own API adapters.
## Mandatory React constraints
@@ -239,6 +243,8 @@ until their recorded phase is completed; agents MUST NOT add new violations.
- New or materially changed user flows require behavior tests for success, failure, cancellation, switching and
stale responses. Source-string tests are reserved for static architecture rules.
- Generated API types are read-only; feature adapters convert transport DTOs to UI models.
- Feature code must not import the generated schema directly, restore `transport.ts`, or import legacy
`get/post/put/del/postForm`; only the shared contract runtime may call `fetch`.
## Mandatory database, transaction and multi-dialect constraints
+3
View File
@@ -64,6 +64,9 @@ api-check:
npm run api:check --prefix frontend
$(GO) run ./tools/apicheck
$(GO) test ./internal/server -run '^TestOpenAPIRoutesMatchRouter$$' -count=1
$(GO) test ./internal/server -run '^TestOpenAPIOperationsHaveContractScenarios$$' -count=1
$(GO) test ./internal/server -run '^TestOpenAPISuccessContractCoverage$$' -count=1
$(GO) test ./internal/server -run '^(TestOpenAPIPasswordLoginDisabledOperations|TestDownloadItemPublishBatchResultExportsRows|TestChatEventDTOUsesFrontendContract|TestChatWebSocketStreamsOnlyAuthenticatedAccountEvents)$$' -count=1
## cover: 生成覆盖率报告
cover:
+633 -59
View File
File diff suppressed because it is too large. Load diff
@@ -8,6 +8,9 @@
- 服务端旧入口继续作为兼容适配层保留,必须复用同一个 handler、鉴权和 DTO,不得复制业务逻辑。
- 新增接口必须先进入 `/api/v1/...`,旧路径只有在确认外部调用方为零后才允许删除。
- 删除旧路径前必须在本文件记录调用方审计证据、迁移版本和回滚方式,并同步删除对应契约测试。
- 兼容旧路径不重复登记 OpenAPI;它们必须复用已登记的 `/api/v1` handler,并由等价路由测试保护。
- 任何新版本化 operation 必须先更新 `api/openapi.yaml`、生成只读 schema 并补真实 handler 契约测试,才允许
feature adapter 使用;兼容矩阵不能成为字段、路径或 DTO 旁路。
## API 调用方审计
@@ -57,6 +57,6 @@
- 二维码生成、扫码状态查询、状态持久化和验证完成已由版本化路由提供;React 生成、轮询和验证完成调用已迁移,Go/React 契约测试确认新旧入口认证、会话所有权和状态码语义一致,状态响应继续过滤 Cookie 等敏感字段。
- 会话密码修改、登录凭证更新、账号删除、密码登录禁用入口、自动化规则/异常处理、订单删除和商品创建已由版本化路由提供;React 对应调用已迁移,Go/React 契约测试确认新旧入口权限、状态码和参数校验语义一致。
- 聊天会话、消息分页和发送结果使用独立 DTO,不直接暴露数据库模型。
- React 的 feature API adapter 已直接使用 `frontend/shared/api-contract/*` 中的具名响应 DTO,并在 adapter 边界完成兼容字段归一;通用请求、错误解析和契约校验位于 `frontend/shared/http/*`。
- React 的 feature API adapter 通过 `frontend/shared/api-contract/client.ts` 使用由 `api/openapi.yaml` 生成的路径与响应类型,并在 adapter 边界完成兼容字段归一为 feature-owned UI model;通用请求、错误解析和契约校验位于 shared 契约运行时。
- 会话、账号、订单、商品、自动化、设置、卡券、通知、聊天、账号任务、关键词、默认回复、管理员、统计、二维码登录和密码登录版本化入口已可用;旧路径继续保留。
- 最终调用方审计确认 React 生产请求、批量结果下载和 Vite 开发代理均不再使用业务旧路径;旧路径仅作为服务端兼容入口保留,后续删除必须遵循调用方、发布日期和回滚条件记录。
+4
View File
@@ -137,6 +137,8 @@ refactoring-master-plan.md 定义,本文不声明当前阶段或完成状态
- 禁止新增 `value/cookie`、`remark/note` 一类双重字段;
- 兼容字段只能在边界 adapter 中归一;
- 删除兼容层必须有调用方迁移和契约测试证据。
- `/api/v1/**` 与 `/health` 的唯一 HTTP 契约源是 `api/openapi.yaml`;新增 operation 必须同步更新规范、生成
TypeScript schema 和真实 handler 响应校验,禁止恢复手写 `transport.ts` 或 DTO 名单门禁。
## 6. React 边界
@@ -150,6 +152,8 @@ refactoring-master-plan.md 定义,本文不声明当前阶段或完成状态
- 组件不得直接调用 `fetch` 或 `axios`;
- 通用 HTTP client 不包含订单、账号等领域归一逻辑;
- 生成 API 类型只读,UI model 由 feature adapter 创建;
- 生成 schema 只能由 shared 契约层导入,feature、组件和 Hook 不得直接读取;
- 原始 `get/post/put/del/postForm` 只能留在旧客户端兼容实现,feature 不得导入或调用;
- 禁止通过大型 barrel 文件隐藏实际依赖。
## 7. 事务与生命周期边界
+2 -2
View File
@@ -24,7 +24,7 @@
| 3. 查询、聊天与订单主链路 | 已完成 | dashboard、实际消费的 admin 摘要、chat、orders、刷新任务和 WebSocket 消息均已迁移并完成真实契约校验。 |
| 4. 商品、卡券和文件传输 | 已完成 | items、批量发布、cards 和上传 adapter 已迁移;原生 FormData、取消、重试和批次隔离均保留。 |
| 5. 自动化、设置和通知动态契约 | 已完成 | rules、automation、settings、notifications 和账号绑定均通过契约客户端;动态账号键有明确值类型约束。 |
| 6. 全量封闭与旧手写契约退场 | 当前阶段 | 关闭原始 HTTP client 旁路,删除手写 transport DTO 和名单式门禁。 |
| 6. 全量封闭与旧手写契约退场 | 已完成 | 已关闭原始 HTTP client 旁路,删除手写 transport DTO 和名单式门禁;全部 operation 已具备真实成功响应或明确特殊校验证据,契约门禁永久启用。 |
## 阶段一:契约基础设施与全路由登记
@@ -77,4 +77,4 @@ git diff --check
## 执行纪律
阶段最终验收失败时状态仍为当前阶段,修复后重跑完整命令;只有全部命令成功后才一次更新状态、证据和下一阶段入口并创建最终中文提交。不得扩大白名单、baseline、忽略路径或 warning-only 旁路;后续缺陷修复保持全部已启用门禁永久有效。
阶段最终验收失败时状态仍为当前阶段,修复后重跑完整命令;只有全部命令成功后才一次更新状态、证据和下一阶段入口并创建最终中文提交。六个阶段现已全部完成,后续不再开启新阶段入口。不得扩大白名单、baseline、忽略路径或 warning-only 旁路;后续缺陷修复保持全部已启用门禁永久有效。
+23
View File
@@ -455,3 +455,26 @@ architecturecheck: 通过;git diff --check 无输出。
- 交付范围:自动化规则、回复规则、默认回复、账号计划任务、账号 AI 设置、系统设置与通知渠道/绑定均通过生成 operation 访问;UI 归一化和秘密表单状态仍留在 feature adapter。
- 动态值:`NotificationBindingsByAccount` 使用 `additionalProperties` 限定每个账号键对应 `NotificationBinding[]`;通知渠道摘要不返回 SMTP 密码、Token 或完整秘密配置。
- 回归保护:真实 Router 响应测试验证渠道列表与动态账号绑定映射;`make api-check`、architecturecheck、前端 typecheck/tests 与注释门禁通过。
### 2026-08-20 OpenAPI 契约阶段六:全量封闭与旧手写契约退场
- 最终提交绑定:`阶段六:完成生成契约迁移并永久关闭旁路`。
- 交付范围:删除 `frontend/shared/api-contract/transport.ts`;原有 UI 派生模型、表单模型与兼容归一模型按 accounts、cards、chat、dashboard、items、notifications、orders、rules、session、settings 迁入各自 feature。共享领域契约模块只透明别名导出 `api/openapi.yaml` 生成 schema,feature adapter 保持唯一响应归一化边界。
- 永久门禁:architecturecheck 阶段六会拒绝恢复 `transport.ts`、任何 production import/re-export 的 `transport` 路径,以及 feature、组件或 Hook 绕过 shared 契约层直接导入生成 schema;阶段四门禁继续拒绝旧 `get/post/put/del/postForm`。此规则不使用 DTO 名单、路径白名单、baseline 或 warning-only 例外。
- 兼容与安全:旧路由继续复用已登记的版本化 handler,不在 OpenAPI 重复登记;允许未声明的非敏感额外响应字段不改变生成类型,Cookie、Token、密码、SMTP 密钥和加密 metadata 仍由既有安全响应测试独立阻断。未修改冻结 CAPTCHA 实现、选择器、时序或浏览器调用顺序,也未执行真实账号调用。
- 验收:`make api-check`、`go test ./tools/architecturecheck -count=1`、`go run ./tools/architecturecheck`、`npm run typecheck --prefix frontend`、`npm test --prefix frontend`(67 files、405 tests)、`make comments`、前端嵌入构建、`make check`、`go test ./... -count=1`、`make test-server-race`、`make cover`(Go statements 65.8%)、`make cover-frontend`(V8 statements 80.21%、lines 82.43%)和 `make cover-browser`(`RUN_BROWSER_INTEGRATION=1`,browser statements 64.1%)均通过。冻结浏览器普通单元测试也已通过;未执行真实账号或外部平台调用。覆盖率产物不纳入提交。
### 2026-08-20 阶段六 operation 自动覆盖门禁补强
- 门禁实现:新增 `internal/server/openapi_operation_coverage_test.go`,从 `api/openapi.yaml` 自动枚举全部 operationId、路径、方法、必需参数和请求体,直接调用真实 `chi` Router,并用 `kin-openapi` 校验响应状态、Content-Type 和 JSON schema;不维护 DTO、路径或 operation 名单。
- 契约修正:补齐通知不确定 outbox、自动化问题与规则、默认回复、商品回复、AI 设置、用户设置以及批量发布响应的具名 schema;动态对象使用受约束 `additionalProperties`,批量发布请求与成功响应同步登记。
- 门禁接入:`make api-check` 现在同时执行路由双向覆盖和 operation 自动响应覆盖。生成 schema 仍由临时目录逐字节比较,后端额外非敏感字段不改变生成类型,敏感字段继续由独立安全测试阻断。
- 验收:自动 operation 场景覆盖 137 个 operation;`make api-check`、`go test ./internal/server -run '^TestOpenAPIOperationsHaveContractScenarios$' -count=1` 和 `go test ./internal/server -count=1` 通过。未修改冻结 CAPTCHA 实现或真实账号调用。
### 2026-08-20 阶段六 operation 成功覆盖最终收口
- 完成范围:新增真实 Router 成功场景覆盖初始化、长登录、AI 模型、卡券上传、聊天读写/图片、商品同步/发布、批次、自动化、通知和账号任务等此前未触达的 operation;覆盖由 OpenAPI operationId 自动发现,不维护 DTO、路径或场景名单。
- 契约语义:`kin-openapi` 对真实响应执行状态码、Content-Type 和 JSON schema 校验;必需字段缺失或类型错误、声明字段类型错误、错误状态码和媒体类型都会失败;未声明的非敏感额外字段允许且不会进入生成 TypeScript 类型。敏感字段仍由独立响应安全测试阻断。
- 门禁结果:`make api-check`、`go run ./tools/architecturecheck`、`make comments`、`git diff --check`、前端 typecheck、前端 405 项测试和生产构建全部通过;`make check` 与 `go test ./... -count=1` 全部通过,Server race 通过。
- 覆盖率:`make cover` Go statements 66.2%;`make cover-frontend` V8 statements 80.2%、lines 82.43%。覆盖率文件和前端覆盖率目录均为生成产物,未纳入提交。
- 浏览器与外部环境:冻结 CAPTCHA 普通单元测试随全量 Go 测试通过;本次未执行真实账号或外部平台调用,未修改冻结浏览器实现。浏览器真实集成和多数据库证据继续沿用本文件此前已记录的通过结果。
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { act,renderHook,waitFor } from '@testing-library/react';
import { beforeEach,describe,expect,test,vi } from 'vitest';
import type { AccountDetail,AccountTaskSettingsResponse } from '../../../shared/api-contract/accounts';
import type { AccountDetail,AccountTaskSettingsResponse } from './api';
import { getAccountTaskSettings,runAccountTask,updateAccountTaskSettings } from './accountAutomationApi';
import { useAccountAutomation } from './accountAutomationHooks';
@@ -1,5 +1,5 @@
import { expect,test } from 'vitest';
import type { AccountDetail } from '../../../shared/api-contract/accounts';
import type { AccountDetail } from './api';
import { buildAccountTaskDefaults,canStartAccountTask,isCurrentAccountTaskRequest } from './accountAutomationState';
// accountFixture 是覆盖任务默认值和账号禁用边界的最小账号数据。
+5 -5
View File
@@ -13,11 +13,11 @@ NotificationChannelResponse,
NotificationEventType,
OperationResponse,
QRLoginGenerateResponse,QRLoginStatusResponse,QRLoginVerificationResponse
} from '../../../shared/api-contract/accounts';
} from './models';
import { contractClient, runContractRequest } from '../../../shared/api-contract/client';
import { type RequestControlOptions } from '../../../shared/http/client';
import { collectionFrom,objectFrom } from '../../../shared/http/contract';
export type * from '../../../shared/api-contract/accounts';
export type * from './models';
// QRLoginStatusResult 描述账号 feature 消费的非敏感二维码状态字段。
export type QRLoginStatusResult = Pick<
@@ -88,15 +88,15 @@ export const getAccountDetails = async (options?: RequestControlOptions): Promis
// getAccountTaskSettings 读取账号计划任务设置。
export const getAccountTaskSettings = async (id: string, options?: RequestControlOptions): Promise<AccountTaskSettingsResponse> =>
runContractRequest(/* signal 控制账号计划任务读取的取消和超时。 */ signal => contractClient.GET('/api/v1/account-tasks/{cid}', { params: { path: { cid: id } }, signal }), options) as unknown as Promise<AccountTaskSettingsResponse>;
runContractRequest(/* signal 控制账号计划任务读取的取消和超时。 */ signal => contractClient.GET('/api/v1/account-tasks/{cid}', { params: { path: { cid: id } }, signal }), options);
// updateAccountTaskSettings 更新账号计划任务设置。
export const updateAccountTaskSettings = async (id: string, settings: AccountTaskSettings, options?: RequestControlOptions): Promise<AccountTaskSettingsResponse> =>
runContractRequest(/* signal 控制账号计划任务更新的取消和超时。 */ signal => contractClient.PUT('/api/v1/account-tasks/{cid}', { params: { path: { cid: id } }, body: settings as never, signal }), options) as unknown as Promise<AccountTaskSettingsResponse>;
runContractRequest(/* signal 控制账号计划任务更新的取消和超时。 */ signal => contractClient.PUT('/api/v1/account-tasks/{cid}', { params: { path: { cid: id } }, body: settings, signal }), options);
// runAccountTask 立即执行账号计划任务。
export const runAccountTask = async (id: string, taskType: 'auto_rate' | 'auto_polish', options?: RequestControlOptions): Promise<AccountTaskRunResponseEnvelope> =>
runContractRequest(/* signal 控制账号计划任务立即执行的取消和长超时。 */ signal => contractClient.POST('/api/v1/account-tasks/{cid}/run', { params: { path: { cid: id } }, body: { task_type: taskType } as never, signal }), { timeoutMs: 120_000, ...options }) as unknown as Promise<AccountTaskRunResponseEnvelope>;
runContractRequest(/* signal 控制账号计划任务立即执行的取消和长超时。 */ signal => contractClient.POST('/api/v1/account-tasks/{cid}/run', { params: { path: { cid: id } }, body: { task_type: taskType }, signal }), { timeoutMs: 120_000, ...options });
export interface AccountRuntimeStatus {
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { cleanup,fireEvent,render,screen } from '@testing-library/react';
import { afterEach,describe,expect,test,vi } from 'vitest';
import type { AccountDetail,AIReplySettings } from '../../../../shared/api-contract/accounts';
import type { AccountDetail,AIReplySettings } from '../api';
import { AccountAISettingsModal } from './AccountAISettingsModal';
import { AccountCard } from './AccountCard';
import { AccountDeleteDialog } from './AccountDeleteDialog';
@@ -2,7 +2,7 @@
import { renderHook,waitFor } from '@testing-library/react';
import { act } from 'react';
import { beforeEach,describe,expect,test,vi } from 'vitest';
import type { AccountDetail } from '../../../shared/api-contract/accounts';
import type { AccountDetail } from './api';
import { getAccountDetails,getAccountRuntimeStatuses,getAllAISettings } from './api';
import { useAccountsData } from './hooks';
+430
View File
@@ -0,0 +1,430 @@
// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。
/** 由当前 feature adapter 归一后的 AccountDetail UI 模型;不直接暴露 HTTP DTO。 */
export interface AccountDetail {
/** 闲鱼账号稳定标识。 */
id: string;
/** 账号是否已配置平台凭证;摘要接口只返回状态,不返回 Cookie 明文。 */
cookie_configured?: boolean;
/** 账号是否允许运行。 */
enabled: boolean;
/** 是否自动确认订单。 */
auto_confirm: boolean;
/** 用户为账号设置的备注。 */
remark?: string;
/** 自动回复暂停时长,单位为分钟。 */
pause_duration?: number;
/** 暂停结束时间的 Unix 秒。 */
paused_until?: number;
/** 当前是否处于暂停状态。 */
paused?: boolean;
// 登录信息
/** 用于密码登录的闲鱼用户名。 */
username?: string;
/** 是否已保存密码登录秘密;摘要接口只返回状态,不返回密码明文。 */
login_password_configured?: boolean;
/** 是否在密码登录时显示浏览器。 */
show_browser?: boolean;
// Frontend helpers
/** 平台账号昵称。 */
nickname?: string;
/** 平台账号头像地址。 */
avatar_url?: string;
/** 资料刷新失败时的说明。 */
profile_error?: string;
/** 当前账号运行状态。 */
runtime_state?: 'starting' | 'connecting' | 'online' | 'reconnecting' | 'auth_expired' | 'verification_required' | 'runtime_conflict' | 'error' | 'stopped' | 'disabled';
/** 当前运行状态的用户可见说明。 */
runtime_message?: string;
/** 当前运行实例是否已连接。 */
runtime_connected?: boolean;
/** 运行状态快照的更新时间。 */
runtime_updated_at?: string;
// AI设置
/** 是否启用账号 AI 回复。 */
ai_enabled?: boolean;
/** 允许的最大折扣比例。 */
max_discount_percent?: number;
/** 允许的最大折扣金额。 */
max_discount_amount?: number;
/** 允许的最大砍价轮次。 */
max_bargain_rounds?: number;
/** 账号自定义提示词。 */
custom_prompts?: string;
// 账号级计划任务
/** 是否启用自动评价。 */
auto_rate_enabled?: boolean;
/** 自动评价使用的文案。 */
rate_content?: string;
/** 是否启用每日擦亮。 */
auto_polish_enabled?: boolean;
/** 每日擦亮执行时间。 */
polish_time?: string;
/** 最近一次自动评价扫描时间。 */
last_rate_scan_at?: number;
/** 最近一次擦亮日期。 */
last_polish_date?: string;
/** 最近一次擦亮时间。 */
last_polish_at?: number;
}
/** 由当前 feature adapter 归一后的 AccountTaskSettings UI 模型;不直接暴露 HTTP DTO。 */
export interface AccountTaskSettings {
/** 账号稳定标识。 */
account_id: string;
/** 是否启用自动评价。 */
auto_rate_enabled: boolean;
/** 自动评价文案。 */
rate_content: string;
/** 是否启用每日擦亮。 */
auto_polish_enabled: boolean;
/** 每日擦亮执行时间。 */
polish_time: string;
/** 最近一次自动评价扫描时间。 */
last_rate_scan_at?: number;
/** 最近一次擦亮日期。 */
last_polish_date?: string;
/** 最近一次擦亮时间。 */
last_polish_at?: number;
}
/** 由当前 feature adapter 归一后的 AccountTaskSummary UI 模型;不直接暴露 HTTP DTO。 */
export interface AccountTaskSummary {
/** 任务类型。 */
task_type: 'auto_rate' | 'auto_polish';
/** 发现的任务数量。 */
found: number;
/** 成功处理的任务数量。 */
success: number;
/** 处理失败的任务数量。 */
failed: number;
/** 跳过的任务数量。 */
skipped: number;
/** 批量处理结果说明。 */
message?: string;
}
/** 由当前 feature adapter 归一后的 AIReplySettings UI 模型;不直接暴露 HTTP DTO。 */
export interface AIReplySettings {
/** 是否启用账号 AI 回复。 */
ai_enabled: boolean;
/** 最大折扣比例。 */
max_discount_percent: number;
/** 最大折扣金额。 */
max_discount_amount?: number;
/** 最大砍价轮次。 */
max_bargain_rounds: number;
/** 自定义提示词。 */
custom_prompts: string;
}
/** 由当前 feature adapter 归一后的 NotificationChannelType UI 模型;不直接暴露 HTTP DTO。 */
export type NotificationChannelType = 'dingtalk' | 'feishu' | 'bark' | 'webhook' | 'wechat' | 'telegram' | 'email';
/** 由当前 feature adapter 归一后的 NotificationEventType UI 模型;不直接暴露 HTTP DTO。 */
export type NotificationEventType =
| 'account_offline'
| 'account_recovered'
| 'account_disabled'
| 'security_verification'
| 'token_renewal'
| 'delivery_result'
| 'system_error';
/** 由当前 feature adapter 归一后的 NotificationChannel UI 模型;不直接暴露 HTTP DTO。 */
export interface NotificationChannel {
/** 通知渠道标识。 */
id: string;
/** 通知渠道名称。 */
name: string;
/** 通知渠道类型。 */
type: NotificationChannelType;
/** 通知渠道配置。 */
config: Record<string, unknown>;
/** 渠道绑定的事件类型。 */
event_types?: NotificationEventType[];
/** 通知渠道是否启用。 */
enabled: boolean;
/** 创建时间。 */
created_at?: string;
/** 更新时间。 */
updated_at?: string;
}
/** 账号编辑器读取的通知渠道传输结果,仅用于适配为 NotificationChannel UI 模型。 */
export interface NotificationChannelResponse {
/** 通知渠道数值标识。 */ id: number;
/** 用户可见渠道名称。 */ name: string;
/** 服务端保存的渠道类型。 */ type: string;
/** 兼容 JSON 文本的事件订阅列表。 */ event_types?: string;
/** 渠道是否参与投递。 */ enabled: boolean;
}
/** 账号列表接口返回的非敏感具名 DTO。 */
/** 由当前 feature adapter 归一后的 AccountSummaryResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface AccountSummaryResponse {
/** 闲鱼账号稳定标识。 */
id: string;
/** 数据库中是否存在账号记录。 */
has_cookie: boolean;
/** 账号是否允许运行。 */
enabled: boolean;
/** 是否自动确认订单。 */
auto_confirm: boolean;
/** 账号备注。 */
remark: string;
/** 自动回复暂停时长,单位为分钟。 */
pause_duration: number;
/** 暂停结束 Unix 秒。 */
paused_until: number;
/** 当前是否仍处于暂停状态。 */
paused: boolean;
/** 密码登录用户名。 */
username: string;
/** 是否允许密码登录显示浏览器;兼容旧服务端的 0/1 字符串值。 */
show_browser: boolean | number | string;
/** 平台昵称缓存。 */
nickname: string;
/** 平台头像地址。 */
avatar_url: string;
/** 最近一次成功登录方式。 */
login_method: string;
/** 最近一次成功登录时间。 */
last_login_at: number;
/** 资料刷新错误说明。 */
profile_error: string;
/** 账号级 AI 回复开关。 */
ai_enabled: boolean;
/** 自动评价计划开关。 */
auto_rate_enabled: boolean;
/** 自动评价文案。 */
rate_content: string;
/** 自动擦亮计划开关。 */
auto_polish_enabled: boolean;
/** 自动擦亮本地时间。 */
polish_time: string;
/** 最近一次自动评价扫描时间。 */
last_rate_scan_at: number;
/** 最近一次自动擦亮日期。 */
last_polish_date: string;
/** 最近一次自动擦亮时间。 */
last_polish_at: number;
}
/** 账号设置变更接口的具名成功响应。 */
/** 由当前 feature adapter 归一后的 CookieSettingsResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface CookieSettingsResponse {
/** 表示设置是否保存成功。 */
success: boolean;
/** 暂停结束 Unix 秒。 */
paused_until: number;
/** 表示账号当前是否暂停。 */
paused: boolean;
}
/** 账号资料刷新接口的具名响应。 */
/** 由当前 feature adapter 归一后的 CookieProfileResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface CookieProfileResponse {
/** 表示资料刷新是否成功。 */
success: boolean;
/** 账号稳定标识。 */
id: string;
/** 平台账号昵称。 */
nickname: string;
/** 平台账号头像地址。 */
avatar_url: string;
/** 资料刷新错误说明。 */
profile_error: string;
}
/** 账号暂停时长查询接口的具名响应。 */
/** 由当前 feature adapter 归一后的 PauseDurationResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface PauseDurationResponse {
/** 暂停时长,单位为分钟。 */
pause_duration: number;
/** 暂停结束 Unix 秒。 */
paused_until: number;
/** 表示账号当前是否暂停。 */
paused: boolean;
}
/** 账号 AI 回复设置接口的具名响应。 */
/** 由当前 feature adapter 归一后的 AIReplySettingsResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface AIReplySettingsResponse {
/** 账号稳定标识;默认配置响应可能省略。 */
cookie_id?: string;
/** AI 回复是否启用。 */
ai_enabled: boolean;
/** 最大折扣比例。 */
max_discount_percent: number;
/** 最大折扣金额。 */
max_discount_amount: number;
/** 最大砍价轮次。 */
max_bargain_rounds: number;
/** 自定义提示词。 */
custom_prompts: string;
}
/** 通知绑定列表中的单条记录。 */
/** 由当前 feature adapter 归一后的 NotificationBinding UI 模型;不直接暴露 HTTP DTO。 */
export interface NotificationBinding {
/** 账号稳定标识,列表归一化后补充。 */
cookie_id?: string;
/** 绑定记录主键。 */
id?: number;
/** 通知渠道主键。 */
channel_id: number;
/** 通知渠道名称。 */
channel_name: string;
/** 绑定是否启用。 */
enabled: boolean;
}
/** 账号通知渠道绑定查询响应。 */
/** 由当前 feature adapter 归一后的 AccountBindingsResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface AccountBindingsResponse {
/** 账号稳定标识。 */
cookie_id: string;
/** 已绑定通知渠道主键列表。 */
channel_ids: number[];
}
/** 简单资源创建接口的数值主键响应。 */
/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface MutationIDResponse {
/** 资源创建是否完成。 */
success: boolean;
/** 新资源数值主键。 */
id: number;
}
/** 简单变更接口的统一成功响应。 */
/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface OperationResponse {
/** 操作是否完成。 */
success: boolean;
/** 可选的操作说明。 */
message?: string;
/** 操作完成后是否需要重新登录。 */
requires_relogin?: boolean;
}
/** 账号任务设置响应。 */
/** 由当前 feature adapter 归一后的 AccountTaskSettingsResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface AccountTaskSettingsResponse {
/** 账号稳定标识。 */
account_id: string;
/** 是否启用自动评价。 */
auto_rate_enabled: boolean;
/** 自动评价文案。 */
rate_content: string;
/** 是否启用自动擦亮。 */
auto_polish_enabled: boolean;
/** 自动擦亮本地时间。 */
polish_time: string;
/** 最近一次评价扫描时间。 */
last_rate_scan_at: number;
/** 最近一次擦亮日期。 */
last_polish_date: string;
/** 最近一次擦亮时间。 */
last_polish_at: number;
}
/** 账号任务执行记录响应。 */
/** 由当前 feature adapter 归一后的 AccountTaskRunResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface AccountTaskRunResponse {
/** 任务执行记录主键。 */
id: number;
/** 任务幂等键。 */
run_key: string;
/** 账号稳定标识。 */
account_id: string;
/** 任务类型。 */
task_type: string;
/** 任务目标标识。 */
target_id: string;
/** 任务业务日期。 */
run_date: string;
/** 任务执行状态。 */
status: string;
/** 任务成功数量。 */
success_count: number;
/** 任务失败数量。 */
failed_count: number;
/** 任务失败说明。 */
error_message: string;
/** 下一次重试时间。 */
next_retry_at: number;
/** 任务开始时间。 */
started_at: number;
/** 任务完成时间。 */
finished_at: number;
}
/** 账号任务执行记录列表响应。 */
/** 由当前 feature adapter 归一后的 AccountTaskRunsResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface AccountTaskRunsResponse {
/** 当前账号的任务执行记录。 */
runs: AccountTaskRunResponse[];
}
/** 手动执行账号任务的统计响应。 */
/** 由当前 feature adapter 归一后的 AccountTaskSummaryResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface AccountTaskSummaryResponse extends AccountTaskSummary {
/** 任务结果说明。 */
message?: string;
}
/** 手动执行账号任务的成功响应。 */
/** 由当前 feature adapter 归一后的 AccountTaskRunResponseEnvelope UI 模型;不直接暴露 HTTP DTO。 */
export interface AccountTaskRunResponseEnvelope {
/** 任务请求是否成功完成。 */
success: boolean;
/** 账号任务执行统计。 */
summary: AccountTaskSummaryResponse;
}
/** 扫码登录二维码生成响应。 */
/** 由当前 feature adapter 归一后的 QRLoginGenerateResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface QRLoginGenerateResponse {
/** 二维码是否生成成功。 */
success: boolean;
/** 扫码登录会话标识。 */
session_id: string;
/** 二维码图片地址。 */
qr_code_url: string;
/** 可选的提示文本。 */
message?: string;
}
/** 二维码登录状态响应。 */
/** 由当前 feature adapter 归一后的 QRLoginStatusResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface QRLoginStatusResponse {
/** 当前二维码会话状态。 */
status: string;
/** 风控验证页面截图地址,在人脸二维码不可用时作为展示兜底。 */
verification_screenshot?: string;
/** 闲鱼人脸风控验证二维码地址,验证页面优先展示。 */
face_qr_url?: string;
/** 扫码登录会话标识。 */
session_id?: string;
/** 持久化后的本地账号标识。 */
account_id?: string;
/** 是否新建了本地账号。 */
is_new_account?: boolean;
/** 状态提示文本。 */
message?: string;
/** 兼容上游可能扩展的非敏感状态字段。 */
[key: string]: unknown;
}
/** 二维码验证完成响应。 */
/** 由当前 feature adapter 归一后的 QRLoginVerificationResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface QRLoginVerificationResponse {
/** 验证结果是否成功。 */
success: boolean;
/** 平台账号标识。 */
unb?: string;
/** 持久化后的本地账号标识。 */
account_id?: string;
/** 是否新建了本地账号。 */
is_new_account?: boolean;
}
@@ -2,7 +2,7 @@
import { cleanup,fireEvent,render,screen,waitFor } from '@testing-library/react';
import React from 'react';
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
import type { AccountDetail } from '../../../../shared/api-contract/accounts';
import type { AccountDetail } from '../api';
// accountListMocks 保存 AccountList 页面测试使用的 API、Hook 和轮询替身。
const accountListMocks = vi.hoisted(/* accountListMockFactory 创建页面测试共享替身。 */ () => ({
@@ -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 { AccountDetail } from '../../../shared/api-contract/accounts';
import type { AccountDetail } from './api';
// qrLoginMocks 保存二维码登录协调器测试使用的接口替身。
const qrLoginMocks = vi.hoisted(/* qrLoginMockFactory 创建二维码登录 API 替身。 */ () => ({
@@ -1,5 +1,5 @@
import { describe,expect,test } from 'vitest';
import type { AccountDetail } from '../../../shared/api-contract/accounts';
import type { AccountDetail } from './api';
import { accountRuntimePresentation,isOlderStatus,mergeAccountRuntimeStatuses } from './runtime';
// account 创建运行状态测试使用的最小账号对象。
+1 -1
View File
@@ -1,5 +1,5 @@
import { expect,test } from 'vitest';
import type { AccountDetail } from '../../../shared/api-contract/accounts';
import type { AccountDetail } from './api';
import {
buildAccountLoginInfoUpdate,
isCurrentAccountRequest,
@@ -2,7 +2,7 @@
import { act,renderHook } from '@testing-library/react';
import type { Dispatch,SetStateAction } from 'react';
import { beforeEach,describe,expect,test,vi } from 'vitest';
import type { AccountDetail,AIReplySettings } from '../../../shared/api-contract/accounts';
import type { AccountDetail,AIReplySettings } from './api';
import {
cancelPasswordLogin,
checkPasswordLoginStatus,
+20 -10
View File
@@ -3,11 +3,11 @@ Card,
CardAppendResponse,
CardBatchResponse,
MutationIDResponse,OperationResponse
} from '../../../shared/api-contract/cards';
} from './models';
import { type RequestControlOptions } from '../../../shared/http/client';
import { contractClient, runContractRequest } from '../../../shared/api-contract/client';
import { contractClient, contractMultipartBody, runContractRequest } from '../../../shared/api-contract/client';
import { collectionFrom } from '../../../shared/http/contract';
export type * from '../../../shared/api-contract/cards';
export type * from './models';
// Cards
// normalizeCard 归一化卡密数据。
const normalizeCard = (item: any): Card => {
@@ -24,9 +24,19 @@ const normalizeCard = (item: any): Card => {
};
// cardPayload 卡密请求载荷,用于当前 API 处理流程。
const cardPayload = (data: Partial<Card>): Record<string, unknown> => ({
...data,
const cardPayload = (data: Partial<Card>) => ({
name: data.name,
type: data.type,
api_config: data.api_config ? JSON.stringify(data.api_config) : '',
text_content: data.text_content,
data_content: data.data_content,
image_url: data.image_url,
description: data.description,
enabled: data.enabled,
delay_seconds: data.delay_seconds,
is_multi_spec: data.is_multi_spec,
spec_name: data.spec_name,
spec_value: data.spec_value,
});
// getCards 读取卡密列表。
@@ -40,12 +50,12 @@ export const getCards = async (options?: RequestControlOptions): Promise<Card[]>
// createCard 创建卡密组。
export const createCard = async (data: Partial<Card>): Promise<MutationIDResponse> => {
return runContractRequest(/* signal 控制卡券创建请求的取消和超时。 */ signal => contractClient.POST('/api/v1/cards', { body: cardPayload(data) as never, signal })) as unknown as Promise<MutationIDResponse>;
return runContractRequest(/* signal 控制卡券创建请求的取消和超时。 */ signal => contractClient.POST('/api/v1/cards', { body: cardPayload(data), signal }));
};
// updateCard 更新卡密组。
export const updateCard = async (cardId: string | number, data: Partial<Card>): Promise<OperationResponse> => {
return runContractRequest(/* signal 控制卡券更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/cards/{card_id}', { params: { path: { card_id: String(cardId) } }, body: cardPayload(data) as never, signal }));
return runContractRequest(/* signal 控制卡券更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/cards/{card_id}', { params: { path: { card_id: String(cardId) } }, body: cardPayload(data), signal }));
};
// deleteCard 删除卡密组。
@@ -56,7 +66,7 @@ export const deleteCard = async (cardId: string | number): Promise<OperationResp
// getCardDetails 读取卡密组详情。
export const getCardDetails = async (cardId: string | number): Promise<Card> => {
// card 卡密详情,用于当前 API 处理流程。
const card = await runContractRequest(/* signal 控制卡券详情请求的取消和超时。 */ signal => contractClient.GET('/api/v1/cards/{card_id}/details', { params: { path: { card_id: String(cardId) } }, signal })) as unknown as Card;
const card = await runContractRequest(/* signal 控制卡券详情请求的取消和超时。 */ signal => contractClient.GET('/api/v1/cards/{card_id}/details', { params: { path: { card_id: String(cardId) } }, signal }));
return normalizeCard(card);
};
@@ -70,10 +80,10 @@ export const batchCreateCards = async (file: File, options?: RequestControlOptio
// 此处只收紧 TypeScript 响应契约。
const body = new FormData();
body.append('file', file);
return runContractRequest(/* signal 控制卡券批量上传的取消和超时。 */ signal => contractClient.POST('/api/v1/cards/batch', { body: body as never, signal }), options) as Promise<CardBatchResponse>;
return runContractRequest(/* signal 控制卡券批量上传的取消和超时。 */ signal => contractClient.POST('/api/v1/cards/batch', { body: contractMultipartBody(body), signal }), options);
};
// 往 data 类型卡密组批量追加卡密号
export const appendCardData = async (cardId: string | number, content: string, options?: RequestControlOptions): Promise<CardAppendResponse> => {
return runContractRequest(/* signal 控制卡券追加数据请求的取消和超时。 */ signal => contractClient.POST('/api/v1/cards/{card_id}/append-data', { params: { path: { card_id: String(cardId) } }, body: { content } as never, signal }), options) as Promise<CardAppendResponse>;
return runContractRequest(/* signal 控制卡券追加数据请求的取消和超时。 */ signal => contractClient.POST('/api/v1/cards/{card_id}/append-data', { params: { path: { card_id: String(cardId) } }, body: { content }, signal }), options);
};
@@ -1,5 +1,5 @@
import { expect,test } from 'vitest';
import type { Card } from '../../../shared/api-contract/cards';
import type { Card } from './api';
import { canSubmitAppend,filterCards,isCurrentCardRequest,previewAppendContent } from './batchState';
// cards 是卡密筛选测试使用的最小卡密组列表。
@@ -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 { Card } from '../../../shared/api-contract/cards';
import type { Card } from './api';
import { useCardActions } from './cardActions';
// cardActionMocks 保存卡密动作 Hook 测试使用的 API 替身。
+1 -1
View File
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { act,renderHook,waitFor } from '@testing-library/react';
import { beforeEach,describe,expect,test,vi } from 'vitest';
import type { Card } from '../../../shared/api-contract/cards';
import type { Card } from './api';
import { appendCardData,batchCreateCards,getCards } from './api';
import { useCardBatchActions,useCardsData } from './hooks';
+105
View File
@@ -0,0 +1,105 @@
// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。
/** 由当前 feature adapter 归一后的 Card UI 模型;不直接暴露 HTTP DTO。 */
export interface Card {
/** 卡券组数值主键。 */
id: number;
/** 卡券组名称。 */
name: string;
/** 卡券组类型。 */
type: 'api' | 'text' | 'data' | 'image';
/** 卡券组说明。 */
description?: string;
/** 卡券组是否启用。 */
enabled: boolean;
// 文本类型
text_content?: string;
// 批量数据类型
data_content?: string;
// API 类型配置
api_config?: {
/** API 卡券请求地址。 */
url: string;
/** API 卡券请求方法。 */
method: 'GET' | 'POST';
/** API 请求超时时间。 */
timeout?: number;
/** API 请求头 JSON。 */
headers?: string;
/** API 请求参数 JSON。 */
params?: string;
};
// 图片类型
/** 图片卡券地址。 */
image_url?: string;
// 通用配置
/** 卡券发送延迟秒数。 */
delay_seconds?: number;
// 多规格配置
/** 是否支持多规格。 */
is_multi_spec?: boolean;
/** 规格名称。 */
spec_name?: string;
/** 规格值。 */
spec_value?: string;
}
/** 卡券批量创建接口的逐行结果。 */
/** 由当前 feature adapter 归一后的 CardBatchResult UI 模型;不直接暴露 HTTP DTO。 */
export interface CardBatchResult {
/** 表格中的原始行号。 */
row_no: number;
/** 当前行是否创建成功。 */
success: boolean;
/** 新建卡券组主键。 */
id?: number;
/** 卡券组名称。 */
name: string;
/** 卡券类型。 */
type?: string;
/** 当前行失败原因。 */
error?: string;
}
/** 卡券批量创建接口的具名响应。 */
/** 由当前 feature adapter 归一后的 CardBatchResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface CardBatchResponse {
/** 批量处理流程是否完成。 */
success: boolean;
/** 解析出的总行数。 */
total: number;
/** 创建成功行数。 */
created: number;
/** 创建失败行数。 */
failed: number;
/** 逐行处理结果。 */
rows: CardBatchResult[];
}
/** 卡券追加数据接口的具名响应。 */
/** 由当前 feature adapter 归一后的 CardAppendResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface CardAppendResponse {
/** 追加操作是否完成。 */
success: boolean;
/** 实际追加数量。 */
added: number;
}
/** 简单资源创建接口的数值主键响应。 */
/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface MutationIDResponse {
/** 资源创建是否完成。 */
success: boolean;
/** 新资源数值主键。 */
id: number;
}
/** 简单变更接口的统一成功响应。 */
/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface OperationResponse {
/** 操作是否完成。 */
success: boolean;
/** 可选的操作说明。 */
message?: string;
/** 操作完成后是否需要重新登录。 */
requires_relogin?: boolean;
}
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { cleanup,fireEvent,render,screen,waitFor } from '@testing-library/react';
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
import type { Card } from '../../../../shared/api-contract/cards';
import type { Card } from '../api';
// cardListMocks 保存卡密页面测试使用的 Hook、API 和批量弹窗替身。
const cardListMocks = vi.hoisted(/* cardListMockFactory 创建卡密页面共享替身。 */ () => ({
+2 -2
View File
@@ -3,10 +3,10 @@ AccountDetail,
ChatMessage,
ChatSession,
OperationResponse
} from '../../../shared/api-contract/chat';
} from './models';
import { contractClient, runContractRequest } from '../../../shared/api-contract/client';
import { type RequestControlOptions } from '../../../shared/http/client';
export type * from '../../../shared/api-contract/chat';
export type * from './models';
import type { ChatReadReceipt } from './types';
/** ChatImageFormContract 描述图片发送 operation 的 multipart 字段,仅用于将原生 FormData 交给生成客户端。 */
+1 -1
View File
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { act,renderHook,waitFor } from '@testing-library/react';
import { beforeEach,describe,expect,test,vi } from 'vitest';
import type { AccountDetail,ChatMessage,ChatSession } from '../../../shared/api-contract/chat';
import type { AccountDetail,ChatMessage,ChatSession } from './api';
import { getAccountDetails,getAccountRuntimeStatuses,getChatMessagePage,getChatSessionPage,markChatRead,sendChatImage,sendChatMessage } from './api';
import { useChat } from './hooks';
import { publishChatConnectionState,publishChatLiveMessage } from './liveEvents';
+142
View File
@@ -0,0 +1,142 @@
// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。
/** 由当前 feature adapter 归一后的 AccountDetail UI 模型;不直接暴露 HTTP DTO。 */
export interface AccountDetail {
/** 闲鱼账号稳定标识。 */
id: string;
/** 账号是否已配置平台凭证;摘要接口只返回状态,不返回 Cookie 明文。 */
cookie_configured?: boolean;
/** 账号是否允许运行。 */
enabled: boolean;
/** 是否自动确认订单。 */
auto_confirm: boolean;
/** 用户为账号设置的备注。 */
remark?: string;
/** 自动回复暂停时长,单位为分钟。 */
pause_duration?: number;
/** 暂停结束时间的 Unix 秒。 */
paused_until?: number;
/** 当前是否处于暂停状态。 */
paused?: boolean;
// 登录信息
/** 用于密码登录的闲鱼用户名。 */
username?: string;
/** 是否已保存密码登录秘密;摘要接口只返回状态,不返回密码明文。 */
login_password_configured?: boolean;
/** 是否在密码登录时显示浏览器。 */
show_browser?: boolean;
// Frontend helpers
/** 平台账号昵称。 */
nickname?: string;
/** 平台账号头像地址。 */
avatar_url?: string;
/** 资料刷新失败时的说明。 */
profile_error?: string;
/** 当前账号运行状态。 */
runtime_state?: 'starting' | 'connecting' | 'online' | 'reconnecting' | 'auth_expired' | 'verification_required' | 'runtime_conflict' | 'error' | 'stopped' | 'disabled';
/** 当前运行状态的用户可见说明。 */
runtime_message?: string;
/** 当前运行实例是否已连接。 */
runtime_connected?: boolean;
/** 运行状态快照的更新时间。 */
runtime_updated_at?: string;
// AI设置
/** 是否启用账号 AI 回复。 */
ai_enabled?: boolean;
/** 允许的最大折扣比例。 */
max_discount_percent?: number;
/** 允许的最大折扣金额。 */
max_discount_amount?: number;
/** 允许的最大砍价轮次。 */
max_bargain_rounds?: number;
/** 账号自定义提示词。 */
custom_prompts?: string;
// 账号级计划任务
/** 是否启用自动评价。 */
auto_rate_enabled?: boolean;
/** 自动评价使用的文案。 */
rate_content?: string;
/** 是否启用每日擦亮。 */
auto_polish_enabled?: boolean;
/** 每日擦亮执行时间。 */
polish_time?: string;
/** 最近一次自动评价扫描时间。 */
last_rate_scan_at?: number;
/** 最近一次擦亮日期。 */
last_polish_date?: string;
/** 最近一次擦亮时间。 */
last_polish_at?: number;
}
/** 由当前 feature adapter 归一后的 ChatSession UI 模型;不直接暴露 HTTP DTO。 */
export interface ChatSession {
/** 账号稳定标识。 */
account_id: string;
/** 会话稳定标识。 */
chat_id: string;
/** 买家平台标识。 */
buyer_id: string;
/** 买家昵称。 */
buyer_name: string;
/** 买家头像地址。 */
buyer_avatar_url?: string;
/** 会话关联商品标识。 */
item_id?: string;
/** 会话关联商品标题。 */
item_title?: string;
/** 最近一条消息内容。 */
last_message: string;
/** 最近一条消息的 Unix 秒时间戳。 */
last_message_at: number;
/** 未读消息数量。 */
unread_count: number;
}
/** 由当前 feature adapter 归一后的 ChatMessage UI 模型;不直接暴露 HTTP DTO。 */
export interface ChatMessage {
/** 消息数据库主键。 */
id: number;
/** 消息所属账号标识。 */
account_id: string;
/** 消息所属会话标识。 */
chat_id: string;
/** 平台消息去重键。 */
message_key: string;
/** 消息方向。 */
direction: 'incoming' | 'outgoing';
/** 发送者平台标识。 */
sender_id: string;
/** 发送者名称。 */
sender_name: string;
/** 消息类型,system 表示平台通知或交易卡片。 */
message_type: 'text' | 'image' | 'video' | 'system';
/** 消息正文或媒体地址。 */
content: string;
/** 消息发送状态。 */
status: 'received' | 'sending' | 'sent' | 'failed';
/** 平台已读状态;旧消息可能没有该字段。 */
read_status?: number;
/** 平台确认已读的 Unix 秒时间戳;未确认时省略。 */
read_at?: number;
/** 消息发送时间的 Unix 秒。 */
sent_at: number;
}
/** 简单资源创建接口的数值主键响应。 */
/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface MutationIDResponse {
/** 资源创建是否完成。 */
success: boolean;
/** 新资源数值主键。 */
id: number;
}
/** 简单变更接口的统一成功响应。 */
/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface OperationResponse {
/** 操作是否完成。 */
success: boolean;
/** 可选的操作说明。 */
message?: string;
/** 操作完成后是否需要重新登录。 */
requires_relogin?: boolean;
}
+1 -1
View File
@@ -1,5 +1,5 @@
import { expect,test } from 'vitest';
import type { ChatMessage,ChatSession } from '../../../shared/api-contract/chat';
import type { ChatMessage,ChatSession } from './api';
import { collectChatReadReceipts,filterChatSessions,formatClock,isChatAbortError,isCurrentChatRequest,markOutgoingMessagesReadByIncoming,mergeLiveMessage,mergeOlderMessages,messageTime,unreadBadgeClassName,unreadBadgeLabel } from './state';
// sessionFixture 是覆盖搜索、未读筛选和联系人隔离的最小会话数据。
@@ -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 { ChatMessage } from '../../../shared/api-contract/chat';
import type { ChatMessage } from './api';
import { getAccountDetails,getChatSessionPage } from './api';
import { publishChatUnreadStatus } from './liveEvents';
import { formatChatNewMessageTitle,useChatTitleNotification,useChatTitleNotifier } from './titleNotification';
+2 -2
View File
@@ -1,9 +1,9 @@
import { formatLocalDate } from '../../../dateRange';
import type { DashboardStatsResponse,Item,ItemListEnvelope,Order,OrderAnalyticsResponse,OrderStatus,ValidOrderResponse,ValidOrdersResponse } from '../../../shared/api-contract/admin';
import type { DashboardStatsResponse,Item,ItemListEnvelope,Order,OrderAnalyticsResponse,OrderStatus,ValidOrderResponse,ValidOrdersResponse } from './models';
import { contractClient, runContractRequest } from '../../../shared/api-contract/client';
import { type RequestControlOptions } from '../../../shared/http/client';
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
export type * from '../../../shared/api-contract/admin';
export type * from './models';
/** 仪表盘订单明细接口转换后的分页结果。 */
export interface ValidOrdersResult {
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { act,renderHook,waitFor } from '@testing-library/react';
import { beforeEach,describe,expect,test,vi } from 'vitest';
import type { DashboardStats,Item,OrderAnalyticsResponse } from '../../../shared/api-contract/admin';
import type { DashboardStats,Item,OrderAnalyticsResponse } from './api';
import { getDashboardStats,getItems,getOrderAnalytics,getValidOrders } from './api';
import type { UseDashboardOptions } from './hooks';
import { useDashboard } from './hooks';
+270
View File
@@ -0,0 +1,270 @@
// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。
/** 由当前 feature adapter 归一后的 OrderStatus UI 模型;不直接暴露 HTTP DTO。 */
export type OrderStatus =
| 'processing'
| 'pending_ship'
| 'shipped'
| 'completed'
| 'cancelled'
| 'refunding'
| 'unknown';
/** 由当前 feature adapter 归一后的 Order UI 模型;不直接暴露 HTTP DTO。 */
export interface Order {
/** 订单本地数据库主键。 */
id: string;
/** 平台订单标识。 */
order_id: string;
/** 订单所属账号标识。 */
cookie_id: string;
/** 订单关联商品标识。 */
item_id: string;
/** 商品标题。 */
item_title?: string;
/** 商品图片地址。 */
item_image?: string;
/** 商品价格文本。 */
item_price?: string;
/** 买家平台标识。 */
buyer_id: string;
/** 购买数量。 */
quantity: number;
/** 订单金额文本。 */
amount: string;
/** 前端归一化后的订单状态。 */
status: OrderStatus;
/** 服务端原始订单状态。 */
order_status?: OrderStatus;
/** 收货人姓名。 */
receiver_name?: string;
/** 收货人电话。 */
receiver_phone?: string;
/** 收货地址。 */
receiver_address?: string;
/** 订单创建时间。 */
created_at?: string;
/** 订单更新时间。 */
updated_at?: string;
}
/** 由当前 feature adapter 归一后的 Item UI 模型;不直接暴露 HTTP DTO。 */
export interface Item {
/** 本地商品数据库主键。 */
id: string | number;
/** 商品所属账号标识。 */
cookie_id: string;
/** 平台商品标识。 */
item_id: string;
/** 商品标题。 */
item_title?: string;
/** 商品描述。 */
item_description?: string;
/** 商品价格文本。 */
item_price?: string;
/** 商品主图地址。 */
item_image?: string; // Inferred from common usage, though not explicitly in list model sometimes
/** 商品分类标识。 */
item_category?: string;
/** 商品详情原始 JSON。 */
item_detail?: string;
/** 是否启用多规格。 */
is_multi_spec?: number | boolean;
/** 是否按数量发货。 */
multi_quantity_delivery?: number | boolean;
/** 是否启用多数量发货兼容字段。 */
is_multi_qty_ship?: number | boolean;
}
/** 仪表盘兼容历史 items 包装时使用的最小响应模型。 */
export interface ItemListEnvelope {
/** 历史包装中的商品数组。 */ items?: Item[];
}
/** 由当前 feature adapter 归一后的 AdminStats UI 模型;不直接暴露 HTTP DTO。 */
export interface AdminStats {
/** 用户总数。 */
total_users: number;
/** 账号总数。 */
total_cookies: number;
/** 启用账号数。 */
active_cookies: number;
/** 卡券组总数。 */
total_cards: number;
/** 关键词规则总数。 */
total_keywords: number;
/** 订单总数。 */
total_orders: number;
}
/** 由当前 feature adapter 归一后的 DashboardStats UI 模型;不直接暴露 HTTP DTO。 */
export interface DashboardStats {
/** 账号总数。 */
total_cookies: number;
/** 启用账号数。 */
active_cookies: number;
/** 卡券组总数。 */
total_cards: number;
/** 关键词规则总数。 */
total_keywords: number;
/** 订单总数。 */
total_orders: number;
/** 可用卡券库存量。 */
available_card_stock: number;
}
/** 由当前 feature adapter 归一后的 OrderAnalytics UI 模型;不直接暴露 HTTP DTO。 */
export interface OrderAnalytics {
/** 收入汇总。 */
revenue_stats: {
/** 总收入金额。 */
total_amount: number;
/** 总订单数。 */
total_orders: number;
};
/** 按日期聚合的订单统计。 */
daily_stats: Array<{
/** 统计日期。 */
date: string;
/** 当日订单金额。 */
amount: number;
/** 当日订单数量。 */
order_count: number;
}>;
/** 按商品聚合的订单统计。 */
item_stats?: Array<{
/** 商品标识。 */
item_id: string;
/** 商品订单数。 */
order_count: number;
/** 商品订单总金额。 */
total_amount: number;
/** 商品订单平均金额。 */
avg_amount: number;
}>;
}
/** 管理员全局统计响应。 */
/** 由当前 feature adapter 归一后的 AdminStatsResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface AdminStatsResponse extends AdminStats {}
/** 当前用户数据概览响应。 */
/** 由当前 feature adapter 归一后的 DashboardStatsResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface DashboardStatsResponse extends DashboardStats {}
/** 订单收益统计响应。 */
/** 由当前 feature adapter 归一后的 AnalyticsRevenueStatsResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface AnalyticsRevenueStatsResponse {
/** 统计范围内的订单数。 */
total_orders: number;
/** 统计范围内的订单总金额。 */
total_amount: number;
/** 订单平均金额。 */
avg_amount: number;
/** 买家数量。 */
unique_buyers: number;
/** 商品数量。 */
unique_items: number;
}
/** 按日期聚合的订单统计响应。 */
/** 由当前 feature adapter 归一后的 AnalyticsDailyStatsResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface AnalyticsDailyStatsResponse {
/** 用户本地日期。 */
date: string;
/** 当天订单数。 */
order_count: number;
/** 当天订单金额。 */
amount: number;
}
/** 按订单状态聚合的统计响应。 */
/** 由当前 feature adapter 归一后的 AnalyticsStatusStatsResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface AnalyticsStatusStatsResponse {
/** 归一化后的订单状态。 */
status: string;
/** 该状态订单数。 */
count: number;
/** 该状态订单金额。 */
amount: number;
}
/** 按收货城市聚合的统计响应。 */
/** 由当前 feature adapter 归一后的 AnalyticsCityStatsResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface AnalyticsCityStatsResponse {
/** 收货城市。 */
city: string;
/** 该城市订单数。 */
order_count: number;
/** 该城市订单金额。 */
total_amount: number;
}
/** 按商品聚合的统计响应。 */
/** 由当前 feature adapter 归一后的 AnalyticsItemStatsResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface AnalyticsItemStatsResponse {
/** 商品平台标识。 */
item_id: string;
/** 该商品订单数。 */
order_count: number;
/** 该商品订单金额。 */
total_amount: number;
/** 该商品订单平均金额。 */
avg_amount: number;
}
/** 订单分析接口响应。 */
/** 由当前 feature adapter 归一后的 OrderAnalyticsResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface OrderAnalyticsResponse {
/** 收益统计。 */
revenue_stats: AnalyticsRevenueStatsResponse;
/** 按日统计。 */
daily_stats: AnalyticsDailyStatsResponse[];
/** 按状态统计。 */
status_stats: AnalyticsStatusStatsResponse[];
/** 按城市统计。 */
city_stats: AnalyticsCityStatsResponse[];
/** 按商品统计。 */
item_stats: AnalyticsItemStatsResponse[];
}
/** 有效订单明细响应。 */
/** 由当前 feature adapter 归一后的 ValidOrderResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface ValidOrderResponse {
/** 平台订单标识。 */
order_id: string;
/** 商品平台标识。 */
item_id: string;
/** 买家平台标识。 */
buyer_id: string;
/** 商品标题。 */
item_title: string;
/** 商品图片地址。 */
item_image: string;
/** 订单数量文本。 */
quantity: string;
/** 订单金额文本。 */
amount: string;
/** 兼容保留的订单状态。 */
order_status: string;
/** 归一化后的订单状态。 */
status: string;
/** 订单所属账号标识。 */
cookie_id: string;
/** 订单创建时间。 */
created_at: string;
}
/** 有效订单分页响应。 */
/** 由当前 feature adapter 归一后的 ValidOrdersResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface ValidOrdersResponse {
/** 当前页有效订单。 */
orders: ValidOrderResponse[];
/** 符合条件的订单总数。 */
total: number;
/** 当前页码。 */
page: number;
/** 当前页大小。 */
page_size: number;
/** 是否还有未返回的订单。 */
truncated: boolean;
}
@@ -1,5 +1,5 @@
import { expect,test } from 'vitest';
import type { OrderAnalytics } from '../../../shared/api-contract/admin';
import type { OrderAnalytics } from './api';
import { buildCategoryData,buildChartData,buildItemNameMap,buildProductSalesData,buildSourceData,getMaxProductSales,getRangeLabel,getTrendPercent,isCurrentDashboardRequest } from './state';
// analyticsFixture 是覆盖趋势、商品排行和零值边界的最小分析数据。
+10 -6
View File
@@ -1,4 +1,4 @@
import type { PublishLocation } from '../../../shared/api-contract/items';
import type { PublishLocation } from './models';
import {
AccountDetail,
BatchCancelResponse,
@@ -11,11 +11,11 @@ ItemPublishBatchResponse,
ItemPublishResponse,ItemSyncResponse,
OperationResponse,
ShippingRule
} from '../../../shared/api-contract/items';
} from './models';
import { ApiError, type RequestControlOptions } from '../../../shared/http/client';
import { contractClient, runContractRequest } from '../../../shared/api-contract/client';
import { collectionFrom } from '../../../shared/http/contract';
export type * from '../../../shared/api-contract/items';
export type * from './models';
import { getPublishLocations as queryPublishLocations,type PublishLocationRequestOptions } from './amapLocation';
/** 商品账号筛选器读取非敏感账号摘要。 */
@@ -26,7 +26,7 @@ export const getShippingRules = async (options?: RequestControlOptions): Promise
// getPublishLocations 通过 feature API 边界读取地点,并把取消/超时控制传入地图服务。
export const getPublishLocations = (longitude: number, latitude: number, options?: PublishLocationRequestOptions): Promise<PublishLocation[]> => queryPublishLocations(longitude, latitude, options);
export type { PublishLocation } from '../../../shared/api-contract/items';
export type { PublishLocation } from './models';
// itemErrorMessage 将统一 HTTP 错误码归一为商品 feature 可执行的用户提示。
export const itemErrorMessage = (error: unknown, fallback: string): string => {
@@ -197,5 +197,9 @@ export const updateItem = async (cookieId: string, itemId: string, data: Partial
return runContractRequest(/* signal 控制商品更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/items/{cookie_id}/{item_id}', { params: { path: { cookie_id: cookieId, item_id: itemId } }, body: data as never, signal }));
}
/** 读取指定账号与商品的详情,用于编辑器恢复表单。 */
export const getItemDetail = async (accountID: string, itemID: string): Promise<ItemDetailResponse> => runContractRequest(/* signal 控制商品详情请求的取消和超时。 */ signal => contractClient.GET('/api/v1/items/{cookie_id}/{item_id}', { params: { path: { cookie_id: accountID, item_id: itemID } }, signal })) as unknown as Promise<ItemDetailResponse>;
/** 读取指定账号与商品的详情,用于编辑器恢复表单,并将生成传输 DTO 保持在 feature adapter 边界。 */
export const getItemDetail = async (accountID: string, itemID: string): Promise<ItemDetailResponse> => {
// response 保存已由 OpenAPI 路径类型约束的商品详情传输响应。
const response = await runContractRequest(/* signal 控制商品详情请求的取消和超时。 */ signal => contractClient.GET('/api/v1/items/{cookie_id}/{item_id}', { params: { path: { cookie_id: accountID, item_id: itemID } }, signal }));
return response;
};
+1 -1
View File
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { act,renderHook } from '@testing-library/react';
import { beforeEach,describe,expect,test,vi } from 'vitest';
import type { BatchCancelResponse,BatchIDResponse,CategoryRecommendationResponse,ItemPublishBatchPreviewResponse,ItemPublishBatchResponse } from '../../../shared/api-contract/items';
import type { BatchCancelResponse,BatchIDResponse,CategoryRecommendationResponse,ItemPublishBatchPreviewResponse,ItemPublishBatchResponse } from './api';
import {
cancelItemPublishBatch,
deleteItemPublishBatch,
@@ -2,7 +2,7 @@
import { act,renderHook } from '@testing-library/react';
import { useState } from 'react';
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
import type { Item } from '../../../shared/api-contract/items';
import type { Item } from './api';
import { createItem,deleteItem,getPublishLocations,publishItem,syncItemsFromAccount,updateItem } from './api';
import { useItemActions,type ItemActionsOptions } from './itemActions';
+457
View File
@@ -0,0 +1,457 @@
// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。
/** 由当前 feature adapter 归一后的 PublishLocation UI 模型;不直接暴露 HTTP DTO。 */
export interface PublishLocation {
/** 行政区划展示名称。 */
area: string;
/** 城市展示名称。 */
city: string;
/** 平台使用的行政区划标识。 */
division_id: string;
/** 地点经度。 */
longitude: number;
/** 地点纬度。 */
latitude: number;
/** 平台兴趣点标识。 */
poi_id: string;
/** 平台兴趣点展示名称。 */
poi_name: string;
/** 省份展示名称。 */
province: string;
}
/** 由当前 feature adapter 归一后的 AccountDetail UI 模型;不直接暴露 HTTP DTO。 */
export interface AccountDetail {
/** 闲鱼账号稳定标识。 */
id: string;
/** 账号是否已配置平台凭证;摘要接口只返回状态,不返回 Cookie 明文。 */
cookie_configured?: boolean;
/** 账号是否允许运行。 */
enabled: boolean;
/** 是否自动确认订单。 */
auto_confirm: boolean;
/** 用户为账号设置的备注。 */
remark?: string;
/** 自动回复暂停时长,单位为分钟。 */
pause_duration?: number;
/** 暂停结束时间的 Unix 秒。 */
paused_until?: number;
/** 当前是否处于暂停状态。 */
paused?: boolean;
// 登录信息
/** 用于密码登录的闲鱼用户名。 */
username?: string;
/** 是否已保存密码登录秘密;摘要接口只返回状态,不返回密码明文。 */
login_password_configured?: boolean;
/** 是否在密码登录时显示浏览器。 */
show_browser?: boolean;
// Frontend helpers
/** 平台账号昵称。 */
nickname?: string;
/** 平台账号头像地址。 */
avatar_url?: string;
/** 资料刷新失败时的说明。 */
profile_error?: string;
/** 当前账号运行状态。 */
runtime_state?: 'starting' | 'connecting' | 'online' | 'reconnecting' | 'auth_expired' | 'verification_required' | 'runtime_conflict' | 'error' | 'stopped' | 'disabled';
/** 当前运行状态的用户可见说明。 */
runtime_message?: string;
/** 当前运行实例是否已连接。 */
runtime_connected?: boolean;
/** 运行状态快照的更新时间。 */
runtime_updated_at?: string;
// AI设置
/** 是否启用账号 AI 回复。 */
ai_enabled?: boolean;
/** 允许的最大折扣比例。 */
max_discount_percent?: number;
/** 允许的最大折扣金额。 */
max_discount_amount?: number;
/** 允许的最大砍价轮次。 */
max_bargain_rounds?: number;
/** 账号自定义提示词。 */
custom_prompts?: string;
// 账号级计划任务
/** 是否启用自动评价。 */
auto_rate_enabled?: boolean;
/** 自动评价使用的文案。 */
rate_content?: string;
/** 是否启用每日擦亮。 */
auto_polish_enabled?: boolean;
/** 每日擦亮执行时间。 */
polish_time?: string;
/** 最近一次自动评价扫描时间。 */
last_rate_scan_at?: number;
/** 最近一次擦亮日期。 */
last_polish_date?: string;
/** 最近一次擦亮时间。 */
last_polish_at?: number;
}
/** 由当前 feature adapter 归一后的 Item UI 模型;不直接暴露 HTTP DTO。 */
export interface Item {
/** 本地商品数据库主键。 */
id: string | number;
/** 商品所属账号标识。 */
cookie_id: string;
/** 平台商品标识。 */
item_id: string;
/** 商品标题。 */
item_title?: string;
/** 商品描述。 */
item_description?: string;
/** 商品价格文本。 */
item_price?: string;
/** 商品主图地址。 */
item_image?: string; // Inferred from common usage, though not explicitly in list model sometimes
/** 商品分类标识。 */
item_category?: string;
/** 商品详情原始 JSON。 */
item_detail?: string;
/** 是否启用多规格。 */
is_multi_spec?: number | boolean;
/** 是否按数量发货。 */
multi_quantity_delivery?: number | boolean;
/** 是否启用多数量发货兼容字段。 */
is_multi_qty_ship?: number | boolean;
}
/** 由当前 feature adapter 归一后的 AutomationTriggerType UI 模型;不直接暴露 HTTP DTO。 */
export type AutomationTriggerType = 'order_paid' | 'buyer_reviewed' | 'review_missing_timeout';
/** 由当前 feature adapter 归一后的 AutomationActionType UI 模型;不直接暴露 HTTP DTO。 */
export type AutomationActionType = 'confirm_shipment' | 'send_card' | 'send_text';
// Rules
/** 由当前 feature adapter 归一后的 ShippingRule UI 模型;不直接暴露 HTTP DTO。 */
export interface ShippingRule {
/** 规则标识。 */
id: string;
/** 规则名称。 */
name: string;
/** 规则触发类型。 */
trigger_type: AutomationTriggerType;
/** 规则匹配关键词。 */
item_keyword: string; // Legacy UI helper
/** 规则限定的账号标识。 */
cookie_id?: string;
/** 规则限定的商品标识。 */
item_id?: string;
/** 规则限定的商品标题。 */
item_title?: string;
/** 首个发卡动作使用的卡券组 ID。 */
card_group_id: number; // First send_card action card id
/** 首个发卡动作使用的卡券组名称。 */
card_group_name?: string; // UI helper
/** 规则优先级。 */
priority: number;
/** 规则是否启用。 */
enabled: boolean;
/** 规则原始配置 JSON。 */
config_json?: string;
/** 规则动作列表。 */
actions: AutomationAction[];
/** 规则规格变体列表。 */
variants: ShippingVariant[];
}
/** 由当前 feature adapter 归一后的 AutomationAction UI 模型;不直接暴露 HTTP DTO。 */
export interface AutomationAction {
/** 动作标识。 */
id?: string;
/** 动作类型。 */
action_type: AutomationActionType;
/** 动作使用的卡券组 ID。 */
card_id?: number;
/** 动作使用的卡券组名称。 */
card_name?: string;
/** 本次发放数量。 */
delivery_count?: number;
/** 文本消息模板。 */
message_template?: string;
/** 动作延迟秒数。 */
delay_seconds?: number;
/** 动作原始配置 JSON。 */
config_json?: string;
/** 动作是否启用。 */
enabled: boolean;
/** 动作排序序号。 */
sort_order?: number;
}
/** 由当前 feature adapter 归一后的 ShippingVariant UI 模型;不直接暴露 HTTP DTO。 */
export interface ShippingVariant {
/** 规格变体标识。 */
id?: string;
/** 规格名称。 */
spec_name: string;
/** 规格值。 */
spec_value: string;
/** 变体使用的卡券组 ID。 */
card_id: number;
/** 变体使用的卡券组名称。 */
card_name?: string;
/** 卡券类型。 */
card_type?: 'api' | 'text' | 'data' | 'image';
/** 变体发放数量。 */
delivery_count: number;
/** 变体是否启用。 */
enabled: boolean;
/** 是否覆盖动作级延迟。 */
delay_override?: boolean;
/** 变体延迟秒数。 */
delay_seconds?: number;
/** 变体原始配置 JSON。 */
config_json?: string;
}
/** 单个本地商品详情接口的具名响应。 */
/** 由当前 feature adapter 归一后的 ItemDetailResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface ItemDetailResponse {
/** 商品所属账号标识。 */
cookie_id: string;
/** 平台商品标识。 */
item_id: string;
/** 商品标题。 */
item_title: string;
/** 商品描述。 */
item_description: string;
/** 商品分类标识。 */
item_category: string;
/** 商品价格文本。 */
item_price: string;
/** 商品详情原始 JSON。 */
item_detail: string;
/** 是否有多规格。 */
is_multi_spec: boolean;
/** 是否按数量发货。 */
multi_quantity_delivery: boolean;
}
/** 商品发布接口的具名成功响应。 */
/** 由当前 feature adapter 归一后的 ItemPublishResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface ItemPublishResponse {
/** 表示商品是否发布成功。 */
success: boolean;
/** 发布结果说明。 */
message: string;
/** 新商品的平台标识。 */
item_id: string;
/** 新商品的平台详情地址。 */
item_url: string;
/** 新商品主图地址。 */
item_image: string;
/** 新商品标题。 */
item_title: string;
/** 新商品价格文本。 */
item_price: string;
/** 新商品库存数量。 */
quantity: number;
/** 新商品分类标识。 */
category_id: string;
/** 新商品分类名称。 */
category_name: string;
}
/** 商品全集同步接口的具名响应。 */
/** 由当前 feature adapter 归一后的 ItemSyncResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface ItemSyncResponse {
/** 表示同步是否完成。 */
success: boolean;
/** 同步结果说明。 */
message: string;
/** 平台返回的商品总数。 */
total_count: number;
/** 平台商品总页数。 */
total_pages: number;
/** 本地保存的商品数量。 */
saved_count: number;
/** 本地删除标记的商品数量。 */
deleted_count: number;
}
/** 商品分页同步接口的具名响应。 */
/** 由当前 feature adapter 归一后的 ItemPageSyncResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface ItemPageSyncResponse {
/** 表示同步是否完成。 */
success: boolean;
/** 同步结果说明。 */
message: string;
/** 当前同步页码。 */
page_number: number;
/** 当前同步页大小。 */
page_size: number;
/** 当前页商品数量。 */
current_count: number;
/** 本地保存的商品数量。 */
saved_count: number;
}
/** 商品类目推荐接口的具名响应。 */
/** 由当前 feature adapter 归一后的 CategoryRecommendationResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface CategoryRecommendationResponse {
/** 类目推荐是否成功。 */
success: boolean;
/** 推荐商品类目。 */
category: {
/** 平台类目主键。 */
cat_id: string;
/** 平台类目名称。 */
cat_name: string;
/** 频道类目主键。 */
channel_cat_id: string;
/** 淘宝类目主键。 */
tb_cat_id?: string;
};
}
/** 商品批量发布预检逐行结果。 */
/** 由当前 feature adapter 归一后的 ItemPublishBatchPreviewRow UI 模型;不直接暴露 HTTP DTO。 */
export interface ItemPublishBatchPreviewRow {
/** 上传表格行号。 */
row_no: number;
/** 当前行是否通过预检。 */
valid: boolean;
/** 当前行校验错误列表。 */
errors?: string[];
/** 发布目标账号标识。 */
cookie_id: string;
/** 商品标题。 */
title: string;
/** 商品价格文本。 */
price: string;
/** 商品库存数量。 */
quantity: number;
/** 商品图片引用列表。 */
images: string[];
/** 商品发布类目。 */
category: CategoryRecommendationResponse['category'];
/** 发布后自动化配置。 */
automation?: Record<string, unknown>;
}
/** 商品批量发布预检响应。 */
/** 由当前 feature adapter 归一后的 ItemPublishBatchPreviewResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface ItemPublishBatchPreviewResponse {
/** 预检流程是否完成。 */
success: boolean;
/** 后续启动发布使用的预检批次标识。 */
preview_id: string;
/** 预检总行数。 */
total: number;
/** 通过预检行数。 */
valid: number;
/** 未通过预检行数。 */
invalid: number;
/** 逐行预检结果。 */
rows: ItemPublishBatchPreviewRow[];
}
/** 商品批量发布任务启动或重试响应。 */
/** 由当前 feature adapter 归一后的 BatchIDResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface BatchIDResponse {
/** 任务操作是否完成。 */
success: boolean;
/** 商品批量任务标识。 */
batch_id: string;
}
/** 商品批量发布任务取消响应。 */
/** 由当前 feature adapter 归一后的 BatchCancelResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface BatchCancelResponse {
/** 取消请求是否完成。 */
success: boolean;
/** 取消后的任务状态。 */
status: string;
}
/** 商品批量发布任务逐行详情。 */
/** 由当前 feature adapter 归一后的 ItemPublishBatchRowResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface ItemPublishBatchRowResponse {
/** 明细行主键。 */
id: number;
/** 导入表格行号。 */
row_no: number;
/** 发布目标账号标识。 */
cookie_id: string;
/** 商品标题。 */
title: string;
/** 商品价格文本。 */
price: string;
/** 商品库存数量。 */
quantity: number;
/** 商品图片引用列表。 */
images: string[];
/** 商品发布类目。 */
category: CategoryRecommendationResponse['category'];
/** 发布后自动化配置。 */
automation: Record<string, unknown>;
/** 明细行状态。 */
status: string;
/** 发布成功后的平台商品标识。 */
item_id: string;
/** 发布成功后的商品地址。 */
item_url: string;
/** 明细行失败原因。 */
error_message: string;
/** 明细行失败类型。 */
failure_kind: string;
}
/** 商品批量发布任务详情响应。 */
/** 由当前 feature adapter 归一后的 ItemPublishBatchResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface ItemPublishBatchResponse {
/** 批量任务标识。 */
id: string;
/** 批量任务状态。 */
status: string;
/** 原始上传文件名。 */
filename: string;
/** 明细行总数。 */
total: number;
/** 成功发布数量。 */
success: number;
/** 失败数量。 */
failed: number;
/** 待处理数量。 */
pending: number;
/** 运行中数量。 */
running: number;
/** 可重试数量。 */
retryable: number;
/** 明细行结果。 */
rows: ItemPublishBatchRowResponse[];
/** 批次统一发货地。 */
location?: Record<string, unknown>;
/** 最终商品发布之间的最小间隔秒数。 */
publish_interval_seconds?: number;
/** 创建时间。 */
created_at: string;
/** 更新时间。 */
updated_at: string;
}
/** 商品批量发布任务列表响应。 */
/** 由当前 feature adapter 归一后的 ItemPublishBatchListResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface ItemPublishBatchListResponse {
/** 当前用户的批量任务列表。 */
batches: ItemPublishBatchResponse[];
}
/** 简单资源创建接口的数值主键响应。 */
/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface MutationIDResponse {
/** 资源创建是否完成。 */
success: boolean;
/** 新资源数值主键。 */
id: number;
}
/** 简单变更接口的统一成功响应。 */
/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface OperationResponse {
/** 操作是否完成。 */
success: boolean;
/** 可选的操作说明。 */
message?: string;
/** 操作完成后是否需要重新登录。 */
requires_relogin?: boolean;
}
+20 -18
View File
@@ -1,7 +1,7 @@
import type { MutationIDResponse,NotificationBinding,NotificationChannel,NotificationChannelResponse,NotificationEventType,OperationResponse,SystemSettings } from '../../../shared/api-contract/notifications';
import type { MutationIDResponse,NotificationBinding,NotificationChannel,NotificationChannelResponse,NotificationEventType,OperationResponse,SystemSettings } from './models';
import { type RequestControlOptions } from '../../../shared/http/client';
import { contractClient, runContractRequest } from '../../../shared/api-contract/client';
export type * from '../../../shared/api-contract/notifications';
export type * from './models';
/** 通知渠道写入时使用的具名请求 DTO。 */
export interface NotificationChannelRequest {
@@ -50,22 +50,24 @@ const toNotificationChannel = (channel: NotificationChannelResponse): Notificati
/** 获取全部通知渠道并转换为编辑器模型。 */
export const getNotificationChannels = async (options?: RequestControlOptions): Promise<{ /** 操作是否完成。 */ success: boolean; /** 渠道列表。 */ data: NotificationChannel[] }> => {
// response 是渠道列表的原始传输响应。
const response = await runContractRequest(/* signal 控制通知渠道列表读取的取消和超时。 */ signal => contractClient.GET('/api/v1/notifications/channels', { signal }), options) as unknown as NotificationChannelResponse[] | { /** channels 是后端包装的渠道列表。 */ data?: NotificationChannelResponse[]; /** channels 是兼容字段。 */ channels?: NotificationChannelResponse[] };
// channels 是兼容直接数组与包装数组后的原始渠道列表。
const channels = Array.isArray(response) ? response : response.data || response.channels || [];
return { success: true, data: channels.map(toNotificationChannel) };
const response = await runContractRequest(/* signal 控制通知渠道列表读取的取消和超时。 */ signal => contractClient.GET('/api/v1/notifications/channels', { signal }), options);
return { success: true, data: response.map(toNotificationChannel) };
};
/** 创建通知渠道,并在传输边界序列化配置与事件。 */
export const createNotificationChannel = async (data: Required<Pick<NotificationChannelRequest, 'name' | 'type' | 'config'>> & NotificationChannelRequest, options?: RequestControlOptions): Promise<MutationIDResponse> => runContractRequest(/* signal 控制通知渠道创建请求的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/channels', { body: { ...data, config: JSON.stringify(data.config), event_types: stringifyNotificationEventTypes(data.event_types) } as never, signal }), options) as unknown as Promise<MutationIDResponse>;
export const createNotificationChannel = async (data: Required<Pick<NotificationChannelRequest, 'name' | 'type' | 'config'>> & NotificationChannelRequest, options?: RequestControlOptions): Promise<MutationIDResponse> => runContractRequest(/* signal 控制通知渠道创建请求的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/channels', { body: { name: data.name, type: data.type, config: JSON.stringify(data.config), event_types: stringifyNotificationEventTypes(data.event_types), enabled: data.enabled }, signal }), options);
/** 更新通知渠道的可编辑字段。 */
export const updateNotificationChannel = async (channelID: string, data: NotificationChannelRequest, options?: RequestControlOptions): Promise<OperationResponse> => {
// payload 是已完成配置和事件序列化的更新请求。
const payload: Record<string, unknown> = { ...data };
if ('config' in data) payload.config = JSON.stringify(data.config);
if ('event_types' in data) payload.event_types = stringifyNotificationEventTypes(data.event_types);
return runContractRequest(/* signal 控制通知渠道更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/notifications/channels/{channel_id}', { params: { path: { channel_id: channelID } }, body: payload as never, signal }), options) as unknown as Promise<OperationResponse>;
const payload = {
name: data.name,
type: data.type,
config: data.config === undefined ? undefined : JSON.stringify(data.config),
event_types: data.event_types === undefined ? undefined : stringifyNotificationEventTypes(data.event_types),
enabled: data.enabled,
};
return runContractRequest(/* signal 控制通知渠道更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/notifications/channels/{channel_id}', { params: { path: { channel_id: channelID } }, body: payload, signal }), options);
};
/** 删除指定通知渠道。 */
@@ -74,7 +76,7 @@ export const deleteNotificationChannel = async (channelID: string, options?: Req
/** 获取并展平按账号分组存储的消息通知绑定。 */
export const getMessageNotifications = async (): Promise<{ /** 操作是否完成。 */ success: boolean; /** 展平后的绑定列表。 */ data: NotificationBinding[] }> => {
// response 是按账号 ID 分组的通知绑定响应。
const response = await runContractRequest(/* signal 控制消息通知列表读取的取消和超时。 */ signal => contractClient.GET('/api/v1/notifications/messages', { signal })) as unknown as Record<string, NotificationBinding[]>;
const response = await runContractRequest(/* signal 控制消息通知列表读取的取消和超时。 */ signal => contractClient.GET('/api/v1/notifications/messages', { signal }));
// bindings 是供页面直接渲染的扁平绑定集合。
const bindings: NotificationBinding[] = [];
for (const /* accountID、channelBindings 是当前账号及其原始渠道绑定列表。 */ [accountID, channelBindings] of Object.entries(response || {})) {
@@ -85,7 +87,7 @@ export const getMessageNotifications = async (): Promise<{ /** 操作是否完
};
/** 设置单个账号与渠道之间的启用状态。 */
export const setMessageNotification = async (accountID: string, channelID: number, enabled: boolean): Promise<OperationResponse> => runContractRequest(/* signal 控制单账号通知开关更新请求的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/accounts/{cid}/bindings', { params: { path: { cid: accountID } }, body: { channel_id: channelID, enabled } as never, signal }));
export const setMessageNotification = async (accountID: string, channelID: number, enabled: boolean): Promise<OperationResponse> => runContractRequest(/* signal 控制单账号通知开关更新请求的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/accounts/{cid}/bindings', { params: { path: { cid: accountID } }, body: { channel_id: channelID, enabled }, signal }));
/** 删除单个消息通知绑定。 */
export const deleteMessageNotification = async (notificationID: string): Promise<OperationResponse> => runContractRequest(/* signal 控制单条通知删除请求的取消和超时。 */ signal => contractClient.DELETE('/api/v1/notifications/messages/{notification_id}', { params: { path: { notification_id: notificationID } }, signal }));
@@ -95,16 +97,16 @@ export const deleteAccountNotifications = async (accountID: string): Promise<Ope
/** 读取指定账号已绑定的通知渠道主键。 */
export const getAccountBindings = async (accountID: string, options?: RequestControlOptions): Promise<number[]> => {
// response 是账号渠道绑定的具名响应。
const response = await runContractRequest(/* signal 控制账号通知绑定读取的取消和超时。 */ signal => contractClient.GET('/api/v1/notifications/accounts/{cid}/bindings', { params: { path: { cid: accountID } }, signal }), options) as unknown as { /** channelIDs 是绑定渠道主键集合。 */ channel_ids?: number[]; /** data 是兼容包装。 */ data?: { /** channelIDs 是绑定渠道主键集合。 */ channel_ids?: number[] } };
return Array.isArray(response.channel_ids) ? response.channel_ids : Array.isArray(response.data?.channel_ids) ? response.data.channel_ids : [];
// response 是由 OpenAPI 约束的账号渠道绑定响应;未绑定时后端兼容返回 null。
const response = await runContractRequest(/* signal 控制账号通知绑定读取的取消和超时。 */ signal => contractClient.GET('/api/v1/notifications/accounts/{cid}/bindings', { params: { path: { cid: accountID } }, signal }), options);
return response.channel_ids ?? [];
};
/** 覆盖保存指定账号的通知渠道绑定。 */
export const setAccountBindings = async (accountID: string, channelIDs: number[]): Promise<OperationResponse> => runContractRequest(/* signal 控制账号通知绑定覆盖请求的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/accounts/{cid}/bindings', { params: { path: { cid: accountID } }, body: { channel_ids: channelIDs } as never, signal }));
export const setAccountBindings = async (accountID: string, channelIDs: number[]): Promise<OperationResponse> => runContractRequest(/* signal 控制账号通知绑定覆盖请求的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/accounts/{cid}/bindings', { params: { path: { cid: accountID } }, body: { channel_ids: channelIDs }, signal }));
/** 向单一通知渠道发送测试投递。 */
export const testNotificationChannel = async (channelID: string, options?: RequestControlOptions): Promise<OperationResponse> => runContractRequest(/* signal 控制通知渠道测试投递的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/channels/{channel_id}/test', { params: { path: { channel_id: channelID } }, body: {} as never, signal }), options);
export const testNotificationChannel = async (channelID: string, options?: RequestControlOptions): Promise<OperationResponse> => runContractRequest(/* signal 控制通知渠道测试投递的取消和超时。 */ signal => contractClient.POST('/api/v1/notifications/channels/{channel_id}/test', { params: { path: { channel_id: channelID } }, signal }), options);
/** 将系统配置响应转换为通知 SMTP 表单使用的状态模型。 */
const normalizeSystemSettings = (settings: Record<string, unknown>): SystemSettings => {
@@ -71,21 +71,21 @@ export const NotificationSmtpSettings: React.FC<NotificationSmtpSettingsProps> =
<div className="p-2 rounded-xl bg-blue-50 text-blue-600"><Mail className="w-5 h-5" /></div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">SMTP 服务器</label><input data-field="smtp_server" type="text" value={smtp.smtp_server || ''} onChange={handleTextChange} placeholder="smtp.qq.com" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">SMTP 端口</label><input type="number" value={smtp.smtp_port || 587} onChange={handlePortChange} placeholder="587" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">SMTP 服务器</label><input data-field="smtp_server" type="text" value={typeof smtp.smtp_server === 'string' ? smtp.smtp_server : ''} onChange={handleTextChange} placeholder="smtp.qq.com" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">SMTP 端口</label><input type="number" value={typeof smtp.smtp_port === 'number' ? smtp.smtp_port : 587} onChange={handlePortChange} placeholder="587" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
</div>
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">发件邮箱</label><input data-field="smtp_user" type="email" value={smtp.smtp_user || ''} onChange={handleTextChange} placeholder="your-email@qq.com" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">发件邮箱</label><input data-field="smtp_user" type="email" value={typeof smtp.smtp_user === 'string' ? smtp.smtp_user : ''} onChange={handleTextChange} placeholder="your-email@qq.com" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
<div className="space-y-2">
<label className="block text-sm font-bold text-gray-800">邮箱密码 / 授权码</label>
<div className="relative">
<input type={showPassword ? 'text' : 'password'} value={smtp.smtp_password || ''} onChange={handlePasswordChange} placeholder={smtp.smtp_password_configured ? '已配置,如需替换请输入新密码' : '输入密码或授权码'} className="w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm" />
<input type={showPassword ? 'text' : 'password'} value={typeof smtp.smtp_password === 'string' ? smtp.smtp_password : ''} onChange={handlePasswordChange} placeholder={smtp.smtp_password_configured ? '已配置,如需替换请输入新密码' : '输入密码或授权码'} className="w-full ios-input px-4 py-3 pr-12 rounded-xl text-sm" />
<button type="button" onClick={handleTogglePassword} className="absolute right-3 top-1/2 -translate-y-1/2 p-2 text-gray-400 hover:text-gray-600 transition-colors">{showPassword ? <EyeOff className="w-4 h-4" /> : <Eye className="w-4 h-4" />}</button>
</div>
<p className="text-xs text-gray-500">QQ 邮箱需使用授权码(QQ 邮箱设置 → 账号 → 开启 SMTP → 生成授权码)</p>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">发件人显示名(可选)</label><input data-field="smtp_from_name" type="text" value={smtp.smtp_from_name || ''} onChange={handleTextChange} placeholder="闲鱼自动回复系统" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">发件邮箱地址</label><input data-field="smtp_from_address" type="email" value={smtp.smtp_from_address || smtp.smtp_user || ''} onChange={handleTextChange} placeholder="your-email@qq.com" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">发件人显示名(可选)</label><input data-field="smtp_from_name" type="text" value={typeof smtp.smtp_from_name === 'string' ? smtp.smtp_from_name : ''} onChange={handleTextChange} placeholder="闲鱼自动回复系统" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
<div className="space-y-2"><label className="block text-sm font-bold text-gray-800">发件邮箱地址</label><input data-field="smtp_from_address" type="email" value={typeof smtp.smtp_from_address === 'string' ? smtp.smtp_from_address : (typeof smtp.smtp_user === 'string' ? smtp.smtp_user : '')} onChange={handleTextChange} placeholder="your-email@qq.com" className="w-full ios-input px-4 py-3 rounded-xl text-sm" /></div>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
<label className="flex items-center gap-3 rounded-xl border border-gray-200 p-4 text-sm font-semibold text-gray-700"><input type="checkbox" checked={smtp.smtp_use_tls !== false} onChange={handleTlsChange} />STARTTLS(常用于 587 端口)</label>
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { act,renderHook,waitFor } from '@testing-library/react';
import { beforeEach,describe,expect,test,vi } from 'vitest';
import type { NotificationChannel,SystemSettings } from '../../../shared/api-contract/notifications';
import type { NotificationChannel,SystemSettings } from './api';
import { createNotificationChannel,deleteNotificationChannel,getNotificationChannels,getSystemSettings,testNotificationChannel,updateNotificationChannel,updateSystemSettings } from './api';
import { useNotifications } from './hooks';
@@ -0,0 +1,123 @@
// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。
/** 由当前 feature adapter 归一后的 SystemSettings UI 模型;不直接暴露 HTTP DTO。 */
export interface SystemSettings {
/** 默认 AI 模型名称。 */
ai_model?: string;
/** 全局 AI API 密钥。 */
ai_api_key?: string;
/** 全局 AI API 密钥是否已在服务端配置。 */
ai_api_key_configured?: boolean;
/** 全局 AI API 地址。 */
ai_api_url?: string;
/** 全局 AI 基础地址。 */
ai_base_url?: string;
/** 系统默认回复文案。 */
default_reply?: string;
/** 是否允许注册新用户。 */
registration_enabled?: boolean;
/** 系统 SMTP 服务器地址。 */
smtp_server?: string;
/** 系统 SMTP 密码是否已在服务端配置。 */
smtp_password_configured?: boolean;
/** 服务端日志级别。 */
log_level?: 'debug' | 'info' | 'warn' | 'error' | string;
/** 服务端日志格式。 */
log_format?: 'text' | 'json' | string;
/** 续期日志保留天数。 */
renewal_log_retention_days?: number;
/** 远程验证码服务地址。 */
'captcha.remote_service_url'?: string;
/** 远程验证码服务密钥。 */
'captcha.remote_secret_key'?: string;
/** 远程验证码服务密钥是否已在服务端配置。 */
'captcha.remote_secret_key_configured'?: boolean;
/** 远程验证码服务 Cookie 配置。 */
'captcha.remote_pass_cookies'?: boolean | string;
/** 兼容未来配置键的扩展字段。 */
/** 未知设置键只能承载服务端声明的标量值,敏感值不进入该 UI 模型。 */
[key: string]: string | number | boolean | undefined;
}
/** 由当前 feature adapter 归一后的 NotificationChannelType UI 模型;不直接暴露 HTTP DTO。 */
export type NotificationChannelType = 'dingtalk' | 'feishu' | 'bark' | 'webhook' | 'wechat' | 'telegram' | 'email';
/** 由当前 feature adapter 归一后的 NotificationEventType UI 模型;不直接暴露 HTTP DTO。 */
export type NotificationEventType =
| 'account_offline'
| 'account_recovered'
| 'account_disabled'
| 'security_verification'
| 'token_renewal'
| 'delivery_result'
| 'system_error';
/** 由当前 feature adapter 归一后的 NotificationChannel UI 模型;不直接暴露 HTTP DTO。 */
export interface NotificationChannel {
/** 通知渠道标识。 */
id: string;
/** 通知渠道名称。 */
name: string;
/** 通知渠道类型。 */
type: NotificationChannelType;
/** 通知渠道配置。 */
config: Record<string, unknown>;
/** 渠道绑定的事件类型。 */
event_types?: NotificationEventType[];
/** 通知渠道是否启用。 */
enabled: boolean;
/** 创建时间。 */
created_at?: string;
/** 更新时间。 */
updated_at?: string;
}
/** 通知绑定列表中的单条记录。 */
/** 由当前 feature adapter 归一后的 NotificationBinding UI 模型;不直接暴露 HTTP DTO。 */
export interface NotificationBinding {
/** 账号稳定标识,列表归一化后补充。 */
cookie_id?: string;
/** 绑定记录主键。 */
id?: number;
/** 通知渠道主键。 */
channel_id: number;
/** 通知渠道名称。 */
channel_name: string;
/** 绑定是否启用。 */
enabled: boolean;
}
/** 简单资源创建接口的数值主键响应。 */
/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface MutationIDResponse {
/** 资源创建是否完成。 */
success: boolean;
/** 新资源数值主键。 */
id: number;
}
/** 简单变更接口的统一成功响应。 */
/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface OperationResponse {
/** 操作是否完成。 */
success: boolean;
/** 可选的操作说明。 */
message?: string;
/** 操作完成后是否需要重新登录。 */
requires_relogin?: boolean;
}
/** 通知渠道接口返回的原始具名 DTO。 */
/** 由当前 feature adapter 归一后的 NotificationChannelResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface NotificationChannelResponse {
/** 通知渠道主键。 */
id: number;
/** 通知渠道名称。 */
name: string;
/** 通知渠道类型。 */
type: string;
/** 订阅事件类型 JSON 或兼容文本。 */
event_types?: string;
/** 通知渠道是否启用。 */
enabled: boolean;
/** 所属用户主键。 */
user_id?: number;
}
@@ -1,5 +1,5 @@
import { expect,test } from 'vitest';
import type { NotificationChannel } from '../../../shared/api-contract/notifications';
import type { NotificationChannel } from './api';
import { buildNotificationPayload,emptyNotificationForm,isCurrentNotificationRequest,normalizeNotificationForm,notificationErrorMessage,notificationEventSummary,validateNotificationForm } from './state';
import type { NotificationForm } from './types';
+16 -3
View File
@@ -10,11 +10,11 @@ OrderRefreshJobCancelResponse,OrderRefreshJobStatusResponse,
OrderRefreshResponse,
OrderSingleRefreshResponse,
PaginatedResponse
} from '../../../shared/api-contract/orders';
} from './models';
import { contractClient, runContractRequest } from '../../../shared/api-contract/client';
import { type RequestControlOptions } from '../../../shared/http/client';
import { collectionFrom, objectFrom } from '../../../shared/http/contract';
export type * from '../../../shared/api-contract/orders';
export type * from './models';
/** 订单刷新前端最多轮询约 90 秒,超过该预算必须请求取消后端 worker。 */
const orderRefreshPollLimit = 180;
@@ -157,9 +157,22 @@ export const getOrderDetail = async (orderId: string): Promise<{ /** success 表
params: { path: { order_id: orderId } },
signal,
}));
// data 是将可选 transport 字段归一为 UI 模型稳定字符串/布尔值后的订单详情。
const data: OrderDTOResponse = {
...result.data,
spec_name: result.data.spec_name ?? '',
spec_value: result.data.spec_value ?? '',
is_bargain: result.data.is_bargain ?? 0,
system_shipped: result.data.system_shipped ?? false,
receiver_name: result.data.receiver_name ?? '',
receiver_phone: result.data.receiver_phone ?? '',
receiver_address: result.data.receiver_address ?? '',
receiver_city: result.data.receiver_city ?? '',
updated_at: result.data.updated_at ?? result.data.created_at,
};
return {
success: true,
data: result.data
data
};
};
+1 -1
View File
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { act,renderHook,waitFor } from '@testing-library/react';
import { beforeEach,describe,expect,test,vi } from 'vitest';
import type { AccountDetail,Item } from '../../../shared/api-contract/orders';
import type { AccountDetail,Item } from './api';
import { getAccountDetails,getItems,getOrders,importOrders } from './api';
import { useOrderImport,useOrderQuery } from './hooks';
+426
View File
@@ -0,0 +1,426 @@
// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。
/** 由当前 feature adapter 归一后的 PaginatedResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface PaginatedResponse<T> {
/** 表示查询是否成功。 */
success: boolean;
/** 当前页数据。 */
data: T[];
/** 符合条件的总记录数。 */
total: number;
/** 当前页码。 */
page: number;
/** 每页记录数。 */
page_size: number;
/** 总页数。 */
total_pages: number;
/** 各触发类型的规则计数。 */
trigger_counts?: Record<string, number>;
}
/** 由当前 feature adapter 归一后的 AccountDetail UI 模型;不直接暴露 HTTP DTO。 */
export interface AccountDetail {
/** 闲鱼账号稳定标识。 */
id: string;
/** 账号是否已配置平台凭证;摘要接口只返回状态,不返回 Cookie 明文。 */
cookie_configured?: boolean;
/** 账号是否允许运行。 */
enabled: boolean;
/** 是否自动确认订单。 */
auto_confirm: boolean;
/** 用户为账号设置的备注。 */
remark?: string;
/** 自动回复暂停时长,单位为分钟。 */
pause_duration?: number;
/** 暂停结束时间的 Unix 秒。 */
paused_until?: number;
/** 当前是否处于暂停状态。 */
paused?: boolean;
// 登录信息
/** 用于密码登录的闲鱼用户名。 */
username?: string;
/** 是否已保存密码登录秘密;摘要接口只返回状态,不返回密码明文。 */
login_password_configured?: boolean;
/** 是否在密码登录时显示浏览器。 */
show_browser?: boolean;
// Frontend helpers
/** 平台账号昵称。 */
nickname?: string;
/** 平台账号头像地址。 */
avatar_url?: string;
/** 资料刷新失败时的说明。 */
profile_error?: string;
/** 当前账号运行状态。 */
runtime_state?: 'starting' | 'connecting' | 'online' | 'reconnecting' | 'auth_expired' | 'verification_required' | 'runtime_conflict' | 'error' | 'stopped' | 'disabled';
/** 当前运行状态的用户可见说明。 */
runtime_message?: string;
/** 当前运行实例是否已连接。 */
runtime_connected?: boolean;
/** 运行状态快照的更新时间。 */
runtime_updated_at?: string;
// AI设置
/** 是否启用账号 AI 回复。 */
ai_enabled?: boolean;
/** 允许的最大折扣比例。 */
max_discount_percent?: number;
/** 允许的最大折扣金额。 */
max_discount_amount?: number;
/** 允许的最大砍价轮次。 */
max_bargain_rounds?: number;
/** 账号自定义提示词。 */
custom_prompts?: string;
// 账号级计划任务
/** 是否启用自动评价。 */
auto_rate_enabled?: boolean;
/** 自动评价使用的文案。 */
rate_content?: string;
/** 是否启用每日擦亮。 */
auto_polish_enabled?: boolean;
/** 每日擦亮执行时间。 */
polish_time?: string;
/** 最近一次自动评价扫描时间。 */
last_rate_scan_at?: number;
/** 最近一次擦亮日期。 */
last_polish_date?: string;
/** 最近一次擦亮时间。 */
last_polish_at?: number;
}
/** 由当前 feature adapter 归一后的 OrderStatus UI 模型;不直接暴露 HTTP DTO。 */
export type OrderStatus =
| 'processing'
| 'pending_ship'
| 'shipped'
| 'completed'
| 'cancelled'
| 'refunding'
| 'unknown';
/** 由当前 feature adapter 归一后的 Order UI 模型;不直接暴露 HTTP DTO。 */
export interface Order {
/** 订单本地数据库主键。 */
id: string;
/** 平台订单标识。 */
order_id: string;
/** 订单所属账号标识。 */
cookie_id: string;
/** 订单关联商品标识。 */
item_id: string;
/** 商品标题。 */
item_title?: string;
/** 商品图片地址。 */
item_image?: string;
/** 商品价格文本。 */
item_price?: string;
/** 买家平台标识。 */
buyer_id: string;
/** 购买数量。 */
quantity: number;
/** 订单金额文本。 */
amount: string;
/** 前端归一化后的订单状态。 */
status: OrderStatus;
/** 服务端原始订单状态。 */
order_status?: OrderStatus;
/** 收货人姓名。 */
receiver_name?: string;
/** 收货人电话。 */
receiver_phone?: string;
/** 收货地址。 */
receiver_address?: string;
/** 订单创建时间。 */
created_at?: string;
/** 订单更新时间。 */
updated_at?: string;
}
/** 由当前 feature adapter 归一后的 Item UI 模型;不直接暴露 HTTP DTO。 */
export interface Item {
/** 本地商品数据库主键。 */
id: string | number;
/** 商品所属账号标识。 */
cookie_id: string;
/** 平台商品标识。 */
item_id: string;
/** 商品标题。 */
item_title?: string;
/** 商品描述。 */
item_description?: string;
/** 商品价格文本。 */
item_price?: string;
/** 商品主图地址。 */
item_image?: string; // Inferred from common usage, though not explicitly in list model sometimes
/** 商品分类标识。 */
item_category?: string;
/** 商品详情原始 JSON。 */
item_detail?: string;
/** 是否启用多规格。 */
is_multi_spec?: number | boolean;
/** 是否按数量发货。 */
multi_quantity_delivery?: number | boolean;
/** 是否启用多数量发货兼容字段。 */
is_multi_qty_ship?: number | boolean;
}
/** 订单详情接口返回的原始具名订单 DTO。 */
/** 由当前 feature adapter 归一后的 OrderDTOResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface OrderDTOResponse {
/** 平台订单标识。 */
order_id: string;
/** 关联商品标识。 */
item_id: string;
/** 关联商品标题。 */
item_title: string;
/** 关联商品图片地址。 */
item_image: string;
/** 买家平台标识。 */
buyer_id: string;
/** 商品规格名称。 */
spec_name: string;
/** 商品规格值。 */
spec_value: string;
/** 购买数量文本。 */
quantity: string;
/** 实付金额文本。 */
amount: string;
/** 归一化订单状态。 */
order_status: string;
/** 兼容前端使用的订单状态别名。 */
status: string;
/** 所属账号标识。 */
cookie_id: string;
/** 是否议价订单。 */
is_bargain: number;
/** 是否系统发货。 */
system_shipped: boolean;
/** 收货人姓名。 */
receiver_name: string;
/** 收货人电话。 */
receiver_phone: string;
/** 收货地址。 */
receiver_address: string;
/** 收货城市。 */
receiver_city: string;
/** 创建时间。 */
created_at: string;
/** 更新时间。 */
updated_at: string;
}
/** 订单详情接口的具名响应。 */
/** 由当前 feature adapter 归一后的 OrderDetailResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface OrderDetailResponse extends OrderDTOResponse {
/** 表示查询是否完成。 */
success: boolean;
/** 新版客户端读取的订单对象。 */
data: OrderDTOResponse;
}
/** 订单单条刷新返回的远端详情。 */
/** 由当前 feature adapter 归一后的 OrderRefreshDetailResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface OrderRefreshDetailResponse {
/** 购买数量文本。 */
quantity: string;
/** 商品规格名称。 */
spec_name: string;
/** 商品规格值。 */
spec_value: string;
/** 归一化订单状态。 */
order_status: string;
/** 实付金额文本。 */
amount: string;
}
/** 订单单条刷新接口的具名响应。 */
/** 由当前 feature adapter 归一后的 OrderSingleRefreshResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface OrderSingleRefreshResponse {
/** 表示刷新是否完成。 */
success: boolean;
/** 刷新结果说明。 */
message: string;
/** 刷新后的订单详情。 */
order: OrderRefreshDetailResponse;
}
/** 订单批量变更接口的具名响应。 */
/** 由当前 feature adapter 归一后的 OrderBatchResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface OrderBatchResponse {
/** 表示批量操作是否存在部分失败。 */
partial_failure: boolean;
/** 批量操作结果说明。 */
message: string;
/** 订单总数,导入接口提供。 */
total?: number;
/** 成功处理数量。 */
success_count: number;
/** 失败处理数量。 */
failed_count: number;
/** 逐订单兼容结果行。 */
results: OrderBatchResult[];
}
/** 订单批量接口的逐订单结果行。 */
/** 由当前 feature adapter 归一后的 OrderBatchResult UI 模型;不直接暴露 HTTP DTO。 */
export interface OrderBatchResult {
/** 订单平台标识。 */
order_id?: string;
/** 订单动作状态:failed、succeeded 或 reconciliation_required。 */
status?: 'failed' | 'succeeded' | 'reconciliation_required';
/** 表示该订单是否处理成功。 */
success?: boolean;
/** 该订单处理结果说明。 */
message: string;
/** 兼容接口可能返回的账号标识。 */
cookie_id?: string;
/** 待补偿记录标识。 */
reconciliation_id?: string;
/** 本地状态或补偿记录写入警告。 */
reconciliation_warning?: string;
/** 兼容接口可能返回的处理阶段。 */
stage?: string;
/** 允许后端保留尚未结构化的扩展字段。 */
[key: string]: unknown;
}
/** 简单资源创建接口的数值主键响应。 */
/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface MutationIDResponse {
/** 资源创建是否完成。 */
success: boolean;
/** 新资源数值主键。 */
id: number;
}
/** 简单变更接口的统一成功响应。 */
/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface OperationResponse {
/** 操作是否完成。 */
success: boolean;
/** 可选的操作说明。 */
message?: string;
/** 操作完成后是否需要重新登录。 */
requires_relogin?: boolean;
}
/** 管理员全局统计响应。 */
/** 由当前 feature adapter 归一后的 AdminStats UI 模型;不直接暴露 HTTP DTO。 */
export interface AdminStats {
/** 管理员可见的用户总数。 */ total_users: number;
/** 当前用户拥有的账号总数。 */ total_cookies: number;
/** 已启用账号数量。 */ active_cookies: number;
/** 卡券组总数。 */ total_cards: number;
/** 关键词规则总数。 */ total_keywords: number;
/** 订单总数。 */ total_orders: number;
}
/** 订单域兼容页面使用的数据概览字段。 */
export interface DashboardStats {
/** 当前用户的账号总数。 */ total_cookies: number;
/** 已启用账号数量。 */ active_cookies: number;
/** 卡券组总数。 */ total_cards: number;
/** 关键词规则总数。 */ total_keywords: number;
/** 订单总数。 */ total_orders: number;
/** 可用卡券库存。 */ available_card_stock: number;
}
/** 管理员全局统计响应。 */
/** 由当前 feature adapter 归一后的 AdminStatsResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface AdminStatsResponse extends AdminStats {}
/** 当前用户数据概览响应。 */
/** 由当前 feature adapter 归一后的 DashboardStatsResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface DashboardStatsResponse extends DashboardStats {}
/** 订单列表刷新逐项结果。 */
/** 由当前 feature adapter 归一后的 OrderRefreshResultResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface OrderRefreshResultResponse {
/** 结果所属账号标识。 */
cookie_id?: string;
/** 当前处理阶段。 */
stage?: string;
/** 当前项是否处理成功。 */
success: boolean;
/** 结果说明。 */
message?: string;
/** 发现的新订单数量。 */
discovered?: number;
/** 更新的订单数量。 */
updated?: number;
/** 标记删除的订单数量。 */
/** soft_deleted 表示该订单是否已被本次刷新标记为软删除。 */
soft_deleted?: boolean;
/** 订单平台标识。 */
order_id?: string;
/** 结果错误说明。 */
error?: string;
}
/** 订单列表刷新统计摘要。 */
/** 由当前 feature adapter 归一后的 OrderRefreshSummaryResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface OrderRefreshSummaryResponse {
/** 发现的新订单数量。 */
discovered: number;
/** 订单列表更新数量。 */
list_updated: number;
/** 标记删除数量。 */
soft_deleted: number;
/** 需要补全详情的订单数量。 */
detail_total: number;
/** 本次处理订单总数。 */
total: number;
/** 状态发生变化数量。 */
updated: number;
/** 状态未变化数量。 */
no_change: number;
/** 刷新失败数量。 */
failed: number;
}
/** 订单列表刷新响应。 */
/** 由当前 feature adapter 归一后的 OrderRefreshResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface OrderRefreshResponse {
/** 是否存在部分失败。 */
partial_failure: boolean;
/** 刷新结果说明。 */
message: string;
/** 刷新统计摘要。 */
summary: OrderRefreshSummaryResponse;
/** 逐项兼容结果。 */
results: OrderRefreshResultResponse[];
}
/** 创建订单刷新后台任务的响应。 */
/** 由当前 feature adapter 归一后的 OrderRefreshJobStartResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface OrderRefreshJobStartResponse {
/** 任务是否创建成功。 */
success: boolean;
/** 后台任务标识。 */
job_id: string;
/** 任务当前状态。 */
status: 'queued' | 'running';
}
/** 查询订单刷新后台任务的响应。 */
/** 由当前 feature adapter 归一后的 OrderRefreshJobStatusResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface OrderRefreshJobStatusResponse {
/** 查询是否成功。 */
success: boolean;
/** 后台任务标识。 */
job_id: string;
/** 任务当前状态。 */
status: 'queued' | 'running' | 'succeeded' | 'failed' | 'cancelled';
/** 任务失败原因。 */
error_message?: string;
/** 任务成功后的订单刷新结果。 */
result?: OrderRefreshResponse;
}
/** 取消订单刷新后台任务的响应。 */
/** 由当前 feature adapter 归一后的 OrderRefreshJobCancelResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface OrderRefreshJobCancelResponse {
/** 取消命令是否成功应用。 */
success: boolean;
/** 被取消的任务标识。 */
job_id: string;
/** 取消后的任务状态。 */
status: 'cancelled';
}
@@ -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,OrderRefreshResponse } from '../../../shared/api-contract/orders';
import type { Order,OrderRefreshResponse } from './api';
import { useOrderActions } from './orderActions';
// orderActionMocks 保存订单动作 Hook 测试使用的 API 替身。
@@ -2,7 +2,7 @@
import { cleanup,fireEvent,render,screen,waitFor } from '@testing-library/react';
import React from 'react';
import { afterEach,beforeEach,describe,expect,test,vi } from 'vitest';
import type { Order } from '../../../../shared/api-contract/orders';
import type { Order } from '../api';
// orderListMocks 保存订单页面测试使用的 Hook、API 和子组件替身。
const orderListMocks = vi.hoisted(/* orderListMockFactory 创建订单页面共享替身。 */ () => ({
@@ -1,6 +1,7 @@
import ReactDOMServer from 'react-dom/server';
import { describe,expect,test } from 'vitest';
import type { NotificationChannel,SystemSettings } from '../../shared/api-contract/common';
import type { NotificationChannel } from './notifications/api';
import type { SystemSettings } from './settings/api';
import { CardIcon } from './cards/components/CardIcon';
import { BatchPhaseIndicator } from './items/components/BatchPhaseIndicator';
import { NotificationChannelList } from './notifications/components/NotificationChannelList';
+2 -2
View File
@@ -14,11 +14,11 @@ MutationIDResponse,OperationResponse,
PaginatedResponse,
ReplyRule,
ShippingRule
} from '../../../shared/api-contract/automation';
} from './models';
import { type RequestControlOptions } from '../../../shared/http/client';
import { contractClient, runContractRequest } from '../../../shared/api-contract/client';
import { collectionFrom,objectFrom } from '../../../shared/http/contract';
export type * from '../../../shared/api-contract/automation';
export type * from './models';
/** 自动化规则筛选器读取非敏感账号摘要。 */
export const getAccountDetails = async (options?: RequestControlOptions): Promise<AccountDetail[]> => runContractRequest(/* signal 控制规则页账号摘要读取的取消和超时。 */ signal => contractClient.GET('/api/v1/accounts/details', { signal }), options);
+1 -1
View File
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { act,renderHook } from '@testing-library/react';
import { beforeEach,describe,expect,test,vi } from 'vitest';
import type { AccountDetail,Card,DefaultReply,Item,ReplyRule,ShippingRule } from '../../../shared/api-contract/automation';
import type { AccountDetail,Card,DefaultReply,Item,ReplyRule,ShippingRule } from './api';
import {
getAccountDetails,
getAutomationIssues,
+461
View File
@@ -0,0 +1,461 @@
// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。
/** 由当前 feature adapter 归一后的 PaginatedResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface PaginatedResponse<T> {
/** 表示查询是否成功。 */
success: boolean;
/** 当前页数据。 */
data: T[];
/** 符合条件的总记录数。 */
total: number;
/** 当前页码。 */
page: number;
/** 每页记录数。 */
page_size: number;
/** 总页数。 */
total_pages: number;
/** 各触发类型的规则计数。 */
trigger_counts?: Record<string, number>;
}
/** 由当前 feature adapter 归一后的 AccountDetail UI 模型;不直接暴露 HTTP DTO。 */
export interface AccountDetail {
/** 闲鱼账号稳定标识。 */
id: string;
/** 账号是否已配置平台凭证;摘要接口只返回状态,不返回 Cookie 明文。 */
cookie_configured?: boolean;
/** 账号是否允许运行。 */
enabled: boolean;
/** 是否自动确认订单。 */
auto_confirm: boolean;
/** 用户为账号设置的备注。 */
remark?: string;
/** 自动回复暂停时长,单位为分钟。 */
pause_duration?: number;
/** 暂停结束时间的 Unix 秒。 */
paused_until?: number;
/** 当前是否处于暂停状态。 */
paused?: boolean;
// 登录信息
/** 用于密码登录的闲鱼用户名。 */
username?: string;
/** 是否已保存密码登录秘密;摘要接口只返回状态,不返回密码明文。 */
login_password_configured?: boolean;
/** 是否在密码登录时显示浏览器。 */
show_browser?: boolean;
// Frontend helpers
/** 平台账号昵称。 */
nickname?: string;
/** 平台账号头像地址。 */
avatar_url?: string;
/** 资料刷新失败时的说明。 */
profile_error?: string;
/** 当前账号运行状态。 */
runtime_state?: 'starting' | 'connecting' | 'online' | 'reconnecting' | 'auth_expired' | 'verification_required' | 'runtime_conflict' | 'error' | 'stopped' | 'disabled';
/** 当前运行状态的用户可见说明。 */
runtime_message?: string;
/** 当前运行实例是否已连接。 */
runtime_connected?: boolean;
/** 运行状态快照的更新时间。 */
runtime_updated_at?: string;
// AI设置
/** 是否启用账号 AI 回复。 */
ai_enabled?: boolean;
/** 允许的最大折扣比例。 */
max_discount_percent?: number;
/** 允许的最大折扣金额。 */
max_discount_amount?: number;
/** 允许的最大砍价轮次。 */
max_bargain_rounds?: number;
/** 账号自定义提示词。 */
custom_prompts?: string;
// 账号级计划任务
/** 是否启用自动评价。 */
auto_rate_enabled?: boolean;
/** 自动评价使用的文案。 */
rate_content?: string;
/** 是否启用每日擦亮。 */
auto_polish_enabled?: boolean;
/** 每日擦亮执行时间。 */
polish_time?: string;
/** 最近一次自动评价扫描时间。 */
last_rate_scan_at?: number;
/** 最近一次擦亮日期。 */
last_polish_date?: string;
/** 最近一次擦亮时间。 */
last_polish_at?: number;
}
/** 由当前 feature adapter 归一后的 Card UI 模型;不直接暴露 HTTP DTO。 */
export interface Card {
/** 卡券组数值主键。 */
id: number;
/** 卡券组名称。 */
name: string;
/** 卡券组类型。 */
type: 'api' | 'text' | 'data' | 'image';
/** 卡券组说明。 */
description?: string;
/** 卡券组是否启用。 */
enabled: boolean;
// 文本类型
text_content?: string;
// 批量数据类型
data_content?: string;
// API 类型配置
api_config?: {
/** API 卡券请求地址。 */
url: string;
/** API 卡券请求方法。 */
method: 'GET' | 'POST';
/** API 请求超时时间。 */
timeout?: number;
/** API 请求头 JSON。 */
headers?: string;
/** API 请求参数 JSON。 */
params?: string;
};
// 图片类型
/** 图片卡券地址。 */
image_url?: string;
// 通用配置
/** 卡券发送延迟秒数。 */
delay_seconds?: number;
// 多规格配置
/** 是否支持多规格。 */
is_multi_spec?: boolean;
/** 规格名称。 */
spec_name?: string;
/** 规格值。 */
spec_value?: string;
}
/** 由当前 feature adapter 归一后的 Item UI 模型;不直接暴露 HTTP DTO。 */
export interface Item {
/** 本地商品数据库主键。 */
id: string | number;
/** 商品所属账号标识。 */
cookie_id: string;
/** 平台商品标识。 */
item_id: string;
/** 商品标题。 */
item_title?: string;
/** 商品描述。 */
item_description?: string;
/** 商品价格文本。 */
item_price?: string;
/** 商品主图地址。 */
item_image?: string; // Inferred from common usage, though not explicitly in list model sometimes
/** 商品分类标识。 */
item_category?: string;
/** 商品详情原始 JSON。 */
item_detail?: string;
/** 是否启用多规格。 */
is_multi_spec?: number | boolean;
/** 是否按数量发货。 */
multi_quantity_delivery?: number | boolean;
/** 是否启用多数量发货兼容字段。 */
is_multi_qty_ship?: number | boolean;
}
/** 由当前 feature adapter 归一后的 AutomationTriggerType UI 模型;不直接暴露 HTTP DTO。 */
export type AutomationTriggerType = 'order_paid' | 'buyer_reviewed' | 'review_missing_timeout';
/** 由当前 feature adapter 归一后的 AutomationActionType UI 模型;不直接暴露 HTTP DTO。 */
export type AutomationActionType = 'confirm_shipment' | 'send_card' | 'send_text';
// Rules
/** 由当前 feature adapter 归一后的 ShippingRule UI 模型;不直接暴露 HTTP DTO。 */
export interface ShippingRule {
/** 规则标识。 */
id: string;
/** 规则名称。 */
name: string;
/** 规则触发类型。 */
trigger_type: AutomationTriggerType;
/** 规则匹配关键词。 */
item_keyword: string; // Legacy UI helper
/** 规则限定的账号标识。 */
cookie_id?: string;
/** 规则限定的商品标识。 */
item_id?: string;
/** 规则限定的商品标题。 */
item_title?: string;
/** 首个发卡动作使用的卡券组 ID。 */
card_group_id: number; // First send_card action card id
/** 首个发卡动作使用的卡券组名称。 */
card_group_name?: string; // UI helper
/** 规则优先级。 */
priority: number;
/** 规则是否启用。 */
enabled: boolean;
/** 规则原始配置 JSON。 */
config_json?: string;
/** 规则动作列表。 */
actions: AutomationAction[];
/** 规则规格变体列表。 */
variants: ShippingVariant[];
}
/** 由当前 feature adapter 归一后的 AutomationAction UI 模型;不直接暴露 HTTP DTO。 */
export interface AutomationAction {
/** 动作标识。 */
id?: string;
/** 动作类型。 */
action_type: AutomationActionType;
/** 动作使用的卡券组 ID。 */
card_id?: number;
/** 动作使用的卡券组名称。 */
card_name?: string;
/** 本次发放数量。 */
delivery_count?: number;
/** 文本消息模板。 */
message_template?: string;
/** 动作延迟秒数。 */
delay_seconds?: number;
/** 动作原始配置 JSON。 */
config_json?: string;
/** 动作是否启用。 */
enabled: boolean;
/** 动作排序序号。 */
sort_order?: number;
}
/** 由当前 feature adapter 归一后的 ShippingVariant UI 模型;不直接暴露 HTTP DTO。 */
export interface ShippingVariant {
/** 规格变体标识。 */
id?: string;
/** 规格名称。 */
spec_name: string;
/** 规格值。 */
spec_value: string;
/** 变体使用的卡券组 ID。 */
card_id: number;
/** 变体使用的卡券组名称。 */
card_name?: string;
/** 卡券类型。 */
card_type?: Card['type'];
/** 变体发放数量。 */
delivery_count: number;
/** 变体是否启用。 */
enabled: boolean;
/** 是否覆盖动作级延迟。 */
delay_override?: boolean;
/** 变体延迟秒数。 */
delay_seconds?: number;
/** 变体原始配置 JSON。 */
config_json?: string;
}
/** 由当前 feature adapter 归一后的 ReplyRule UI 模型;不直接暴露 HTTP DTO。 */
export interface ReplyRule {
/** 回复规则标识。 */
id: string;
/** 触发关键词。 */
keyword: string;
/** 回复正文。 */
reply_content: string;
/** 关键词匹配方式。 */
match_type: 'exact' | 'fuzzy';
/** 规则是否启用。 */
enabled: boolean;
/** 规则限定的商品标识。 */
item_id?: string;
/** 回复类型。 */
type?: 'text' | 'image';
/** 图片回复地址。 */
image_url?: string;
}
/** 由当前 feature adapter 归一后的 DefaultReply UI 模型;不直接暴露 HTTP DTO。 */
export interface DefaultReply {
/** 账号稳定标识。 */
cookie_id: string;
/** 默认回复是否启用。 */
enabled: boolean;
/** 默认回复正文。 */
reply_content: string;
/** 是否对同一会话只回复一次。 */
reply_once: boolean;
/** 默认图片回复地址。 */
reply_image_url?: string;
}
/** 自动化规则动作的原始具名 DTO。 */
/** 由当前 feature adapter 归一后的 AutomationActionResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface AutomationActionResponse {
/** 动作稳定标识。 */
id: number;
/** 动作类型。 */
action_type: string;
/** 关联卡券组标识。 */
card_id: number;
/** 关联卡券组名称。 */
card_name: string;
/** 发送数量。 */
delivery_count: number;
/** 消息模板。 */
message_template: string;
/** 延迟秒数。 */
delay_seconds: number;
/** 扩展配置 JSON。 */
config_json: string;
/** 是否启用。 */
enabled: boolean;
/** 执行顺序。 */
sort_order: number;
}
/** 自动化规则的原始具名 DTO。 */
/** 由当前 feature adapter 归一后的 AutomationRuleResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface AutomationRuleResponse {
/** 规则稳定标识。 */
id: number;
/** 所属账号标识。 */
cookie_id: string;
/** 关联商品标识。 */
item_id: string;
/** 关联商品标题。 */
item_title: string;
/** 规则名称。 */
name: string;
/** 触发类型。 */
trigger_type: string;
/** 是否启用。 */
enabled: boolean;
/** 规则优先级。 */
priority: number;
/** 扩展配置 JSON。 */
config_json: string;
/** 规则动作列表。 */
actions: AutomationActionResponse[];
/** 创建时间。 */
created_at: string;
/** 更新时间。 */
updated_at: string;
}
/** 自动化规则分页接口的具名响应。 */
/** 由当前 feature adapter 归一后的 AutomationRulePageResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface AutomationRulePageResponse {
/** 表示查询是否完成。 */
success: boolean;
/** 当前页规则列表。 */
data: AutomationRuleResponse[];
/** 规则总数。 */
total: number;
/** 当前页码。 */
page: number;
/** 当前页大小。 */
page_size: number;
/** 总页数。 */
total_pages: number;
/** 各触发类型规则数量。 */
trigger_counts: Record<string, number>;
}
/** 简单资源创建接口的数值主键响应。 */
/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface MutationIDResponse {
/** 资源创建是否完成。 */
success: boolean;
/** 新资源数值主键。 */
id: number;
}
/** 简单变更接口的统一成功响应。 */
/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface OperationResponse {
/** 操作是否完成。 */
success: boolean;
/** 可选的操作说明。 */
message?: string;
/** 操作完成后是否需要重新登录。 */
requires_relogin?: boolean;
}
/** 传统关键词列表项响应。 */
/** 由当前 feature adapter 归一后的 KeywordBasicResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface KeywordBasicResponse {
/** 匹配关键词。 */
keyword: string;
/** 文字回复内容。 */
reply: string;
}
/** 带商品范围的关键词列表项响应。 */
/** 由当前 feature adapter 归一后的 KeywordItemResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface KeywordItemResponse extends KeywordBasicResponse {
/** 限定的商品标识。 */
item_id: string;
}
/** 带类型和主键的关键词列表项响应。 */
/** 由当前 feature adapter 归一后的 KeywordTypedResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface KeywordTypedResponse extends KeywordItemResponse {
/** 关键词规则主键。 */
id: number;
/** 回复类型。 */
type: 'text' | 'image';
/** 图片回复地址。 */
image_url: string;
}
/** 指定商品回复项响应。 */
/** 由当前 feature adapter 归一后的 ItemReplyResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface ItemReplyResponse {
/** 商品平台标识。 */
item_id?: string;
/** 账号稳定标识。 */
cookie_id?: string;
/** 指定商品的回复内容。 */
reply_content: string;
}
/** 默认回复查询响应。 */
/** 由当前 feature adapter 归一后的 DefaultReplyResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface DefaultReplyResponse extends DefaultReply {
/** 账号稳定标识。 */
cookie_id: string;
}
// AutomationIssuesEnvelope 是自动化异常接口的兼容响应。
/** 由当前 feature adapter 归一后的 AutomationIssuesEnvelope UI 模型;不直接暴露 HTTP DTO。 */
export interface AutomationIssuesEnvelope {
/** runs 是待处理的自动化运行记录。 */
runs?: Array<{
/** 记录标识。 */
id: number;
/** 所属账号标识。 */
cookie_id: string;
/** 所属订单标识。 */
order_id: string;
/** 自动化触发类型。 */
trigger_type: string;
/** 外部错误说明。 */
error_message: string;
/** 异常类别。 */
issue_kind: 'external_result_unknown' | 'invalid_snapshot' | 'rule_unavailable' | 'partial_failure' | 'execution_failed';
/** 允许的处理动作。 */
allowed_resolutions: Array<'continue' | 'retry' | 'cancel'>;
/** 当前动作游标。 */
action_cursor: number;
/** 已发送数量。 */
sent_count: number;
/** 更新时间。 */
updated_at: string;
}>;
/** pending_tasks 是延迟自动化任务列表。 */
pending_tasks?: Array<{
/** 任务标识。 */
id: number;
/** 所属账号标识。 */
cookie_id: string;
/** 自动化触发类型。 */
trigger_type: string;
/** 错误说明。 */
error_message: string;
/** 当前重试次数。 */
attempt_count: number;
/** 更新时间。 */
updated_at: string;
}>;
}
+1 -1
View File
@@ -1,5 +1,5 @@
import { describe,expect,test } from 'vitest';
import type { AccountDetail,ShippingRule } from '../../../shared/api-contract/automation';
import type { AccountDetail,ShippingRule } from './api';
import {
accentClasses,
accountLabel,
+2 -2
View File
@@ -1,6 +1,6 @@
import type { OperationResponse,SessionResponse } from '../../../shared/api-contract/session';
import type { OperationResponse,SessionResponse } from './models';
import { contractClient, runContractRequest, type ContractRequestOptions } from '../../../shared/api-contract/client';
export type * from '../../../shared/api-contract/session';
export type * from './models';
/** 会话状态接口返回的只读传输契约。 */
export interface SessionStatusResponse {
+36
View File
@@ -0,0 +1,36 @@
// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。
/** 由当前 feature adapter 归一后的 SessionResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface SessionResponse {
/** 表示登录或初始化是否成功。 */
success: boolean;
/** 登录成功后的会话 Token。 */
token?: string;
/** 服务端返回的操作说明。 */
message?: string;
/** 当前用户 ID。 */
user_id?: number;
/** 当前用户名。 */
username?: string;
/** 当前用户是否为管理员。 */
is_admin?: boolean;
}
/** 简单资源创建接口的数值主键响应。 */
/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface MutationIDResponse {
/** 资源创建是否完成。 */
success: boolean;
/** 新资源数值主键。 */
id: number;
}
/** 简单变更接口的统一成功响应。 */
/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface OperationResponse {
/** 操作是否完成。 */
success: boolean;
/** 可选的操作说明。 */
message?: string;
/** 操作完成后是否需要重新登录。 */
requires_relogin?: boolean;
}
+2 -2
View File
@@ -1,7 +1,7 @@
import type { OperationResponse,SystemSettings } from '../../../shared/api-contract/settings';
import type { OperationResponse,SystemSettings } from './models';
import { contractClient, runContractRequest } from '../../../shared/api-contract/client';
import { type RequestControlOptions } from '../../../shared/http/client';
export type * from '../../../shared/api-contract/settings';
export type * from './models';
/** 设置页面使用的会话状态传输契约,避免跨 feature 依赖。 */
export interface SettingsSessionStatusResponse {
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { act,renderHook,waitFor } from '@testing-library/react';
import { beforeEach,describe,expect,test,vi } from 'vitest';
import type { OperationResponse,SystemSettings } from '../../../shared/api-contract/settings';
import type { OperationResponse,SystemSettings } from './api';
import { fetchAIModels,getSystemSettings,updateLoginCredentials,updateSystemSettings,verifySession } from './api';
import { useSettings } from './hooks';
+80
View File
@@ -0,0 +1,80 @@
// models 保存本 feature adapter 输出的 UI 模型;这些模型不直接代表 HTTP DTO。
/** 由当前 feature adapter 归一后的 SystemSettings UI 模型;不直接暴露 HTTP DTO。 */
export interface SystemSettings {
/** 默认 AI 模型名称。 */
ai_model?: string;
/** 全局 AI API 密钥。 */
ai_api_key?: string;
/** 全局 AI API 密钥是否已在服务端配置。 */
ai_api_key_configured?: boolean;
/** 全局 AI API 地址。 */
ai_api_url?: string;
/** 全局 AI 基础地址。 */
ai_base_url?: string;
/** 系统默认回复文案。 */
default_reply?: string;
/** 是否允许注册新用户。 */
registration_enabled?: boolean;
/** 系统 SMTP 服务器地址。 */
smtp_server?: string;
/** 系统 SMTP 密码是否已在服务端配置。 */
smtp_password_configured?: boolean;
/** 服务端日志级别。 */
log_level?: 'debug' | 'info' | 'warn' | 'error' | string;
/** 服务端日志格式。 */
log_format?: 'text' | 'json' | string;
/** 续期日志保留天数。 */
renewal_log_retention_days?: number;
/** 远程验证码服务地址。 */
'captcha.remote_service_url'?: string;
/** 远程验证码服务密钥。 */
'captcha.remote_secret_key'?: string;
/** 远程验证码服务密钥是否已在服务端配置。 */
'captcha.remote_secret_key_configured'?: boolean;
/** 远程验证码服务 Cookie 配置。 */
'captcha.remote_pass_cookies'?: boolean | string;
/** 兼容未来配置键的扩展字段。 */
/** 未知设置键只能承载服务端声明的标量值,敏感值不进入该 UI 模型。 */
[key: string]: string | number | boolean | undefined;
}
/** 由当前 feature adapter 归一后的 AIReplySettings UI 模型;不直接暴露 HTTP DTO。 */
export interface AIReplySettings {
/** 是否启用账号 AI 回复。 */
ai_enabled: boolean;
/** 最大折扣比例。 */
max_discount_percent: number;
/** 最大折扣金额。 */
max_discount_amount?: number;
/** 最大砍价轮次。 */
max_bargain_rounds: number;
/** 自定义提示词。 */
custom_prompts: string;
}
/** AI 模型发现接口的具名响应。 */
/** 由当前 feature adapter 归一后的 AIModelsResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface AIModelsResponse {
/** 远端可用模型名称。 */
models: string[];
}
/** 简单资源创建接口的数值主键响应。 */
/** 由当前 feature adapter 归一后的 MutationIDResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface MutationIDResponse {
/** 资源创建是否完成。 */
success: boolean;
/** 新资源数值主键。 */
id: number;
}
/** 简单变更接口的统一成功响应。 */
/** 由当前 feature adapter 归一后的 OperationResponse UI 模型;不直接暴露 HTTP DTO。 */
export interface OperationResponse {
/** 操作是否完成。 */
success: boolean;
/** 可选的操作说明。 */
message?: string;
/** 操作完成后是否需要重新登录。 */
requires_relogin?: boolean;
}
+1 -1
View File
@@ -1,5 +1,5 @@
import { expect,test } from 'vitest';
import type { SystemSettings } from '../../../shared/api-contract/settings';
import type { SystemSettings } from './api';
import { buildPersistableSettings,createCredentials,createCredentialsMessage,isCurrentSettingsRequest,validateCredentials } from './state';
// settingsFixture 是覆盖敏感字段过滤和系统配置保留字段的最小草稿。
@@ -2,7 +2,7 @@
import { cleanup,fireEvent,render,screen,waitFor } from '@testing-library/react';
import React from 'react';
import { afterEach,describe,expect,test,vi } from 'vitest';
import type { Item } from '../../shared/api-contract/common';
import type { Item } from '../features/items/api';
import type { DeliveryRuleTarget } from './AuthenticatedShell';
vi.mock('../features/dashboard/pages/Dashboard', /* dashboardMockFactory 提供仪表盘页面的轻量替身。 */ () => {
+7 -10
View File
@@ -1,10 +1,7 @@
// accounts 公开账号摘要、登录信息和账号任务相关传输契约。
/** 账号 feature 使用的 HTTP 传输 DTO;业务页面必须经 feature adapter 转为 UI model。 */
export type {
AIReplySettings, AIReplySettingsResponse, AccountBindingsResponse, AccountDetail,
AccountSummaryResponse, AccountTaskRunResponseEnvelope, AccountTaskSettings,
AccountTaskSettingsResponse, AccountTaskSummary, CookieProfileResponse,
CookieSettingsResponse, NotificationChannel, NotificationChannelResponse,
NotificationEventType, OperationResponse, QRLoginGenerateResponse,
QRLoginStatusResponse, QRLoginVerificationResponse,
} from './transport';
// accounts 只公开 OpenAPI 生成的账号传输类型;UI 模型属于 accounts feature。
import type { components } from './generated/schema';
/** AccountTransport 表示生成的非敏感账号响应,adapter 负责转换为页面模型。 */
export type AccountTransport = components['schemas']['AccountDetailResponse'];
/** QRLoginStatusTransport 表示生成的二维码风控状态响应。 */
export type QRLoginStatusTransport = components['schemas']['QRLoginStatusResponse'];
+7 -7
View File
@@ -1,7 +1,7 @@
// admin 公开管理员和统计相关传输契约。
/** 管理与仪表盘 feature 使用的 HTTP 传输 DTO。 */
export type {
DashboardStats, DashboardStatsResponse, Item, ItemListEnvelope, Order,
OrderAnalytics, OrderAnalyticsResponse, OrderStatus, ValidOrderResponse,
ValidOrdersResponse,
} from './transport';
// admin 只公开 OpenAPI 生成的管理统计传输类型;仪表盘展示模型由 feature 维护。
import type { components } from './generated/schema';
/** DashboardStatsTransport 表示生成的仪表盘概览响应。 */
export type DashboardStatsTransport = components['schemas']['DashboardStatsResponse'];
/** AnalyticsTransport 表示生成的订单分析响应。 */
export type AnalyticsTransport = components['schemas']['AnalyticsResponse'];
+5 -9
View File
@@ -1,9 +1,5 @@
// automation 公开自动化规则、动作和异常相关传输契约。
/** 自动化规则 feature 使用的 HTTP 传输 DTO。 */
export type {
AccountDetail, AutomationAction, AutomationIssuesEnvelope,
AutomationRulePageResponse, AutomationRuleResponse, AutomationTriggerType,
Card, DefaultReply, DefaultReplyResponse, Item, KeywordTypedResponse,
MutationIDResponse, OperationResponse, PaginatedResponse, ReplyRule,
ShippingRule, ShippingVariant,
} from './transport';
// automation 只公开 OpenAPI 生成的自动化传输类型;规则编辑模型属于 rules feature。
import type { components } from './generated/schema';
/** OperationTransport 表示生成的通用成功响应。 */
export type OperationTransport = components['schemas']['OperationResponse'];
+5 -3
View File
@@ -1,3 +1,5 @@
// cards 公开卡片、批量卡片和卡片追加数据相关传输契约。
/** 卡券 feature 使用的 HTTP 传输 DTO。 */
export type { Card, CardAppendResponse, CardBatchResponse, MutationIDResponse, OperationResponse } from './transport';
// cards 只公开 OpenAPI 生成的卡券传输类型;卡券展示模型属于 cards feature。
import type { components } from './generated/schema';
/** CardTransport 表示生成的卡券响应。 */
export type CardTransport = components['schemas']['CardResponse'];
+9 -3
View File
@@ -1,3 +1,9 @@
// chat 公开会话、消息和已读状态相关传输契约。
/** 聊天 feature 使用的 HTTP 传输 DTO。 */
export type { AccountDetail, ChatMessage, ChatSession, OperationResponse } from './transport';
// chat 只公开 OpenAPI 生成的聊天传输类型;聊天状态模型属于 chat feature。
import type { components } from './generated/schema';
/** ChatMessageTransport 表示生成的单条聊天消息。 */
export type ChatMessageTransport = components['schemas']['ChatMessage'];
/** ChatSessionTransport 表示生成的聊天会话摘要。 */
export type ChatSessionTransport = components['schemas']['ChatSession'];
/** ChatWebSocketTransport 表示生成的 WebSocket 事件联合。 */
export type ChatWebSocketTransport = components['schemas']['ChatWebSocketEvent'];
+6
View File
@@ -56,6 +56,12 @@ const contractBaseUrl = typeof location === 'undefined' ? 'http://localhost' : l
export const contractClient = createClient<paths>({ baseUrl: contractBaseUrl, fetch: contractFetch });
// contractMultipartBody 将原生 FormData 作为对应 OpenAPI multipart operation 的运行时载荷交给客户端。
// OpenAPI 3.1 的 binary 字段会生成 string 类型,而浏览器必须保留 FormData 边界和 File 对象;泛型仅由调用位置的生成 operation 请求体推导。
export function contractMultipartBody<T>(form: FormData): NonNullable<T> {
return form as unknown as NonNullable<T>;
}
// runContractRequest 执行类型化 operation,并恢复旧 client 的超时、取消和 ApiError 行为。
export async function runContractRequest<T>(
execute: (signal: AbortSignal) => Promise<ContractResult<T>>,
+5 -3
View File
@@ -1,3 +1,5 @@
// common 公开分页、错误和跨领域基础传输契约;具体 feature 应优先导入自己的领域模块。
/** 跨 feature 的最小 HTTP 传输 DTO,不得承载领域专有类型。 */
export type { ApiErrorResponse, Item, NotificationChannel, PaginatedResponse, SystemSettings } from './transport';
// common 只公开跨 feature 的 OpenAPI 生成传输类型。
import type { components } from './generated/schema';
/** ApiErrorResponse 表示统一错误 envelope,供共享 HTTP 运行时识别错误。 */
export type ApiErrorResponse = components['schemas']['ErrorResponse'];
+498 -88
View File
@@ -1813,6 +1813,320 @@ export interface components {
ApiResponse: {
success: boolean;
};
NotificationUncertainOutboxItem: {
id: number;
channel_id: number;
owner_user_id?: number;
event_type: string;
attempt_count: number;
uncertain_at: number;
has_error: boolean;
};
NotificationUncertainOutboxResponse: {
total: number;
items: components["schemas"]["NotificationUncertainOutboxItem"][];
};
AutomationRunIssue: {
id: number;
cookie_id: string;
order_id: string;
trigger_type: string;
error_message: string;
issue_kind: string;
allowed_resolutions: string[];
action_cursor: number;
sent_count: number;
updated_at: string;
};
DeferredAutomationIssue: {
id: number;
cookie_id: string;
trigger_type: string;
error_message: string;
attempt_count: number;
updated_at: string;
};
AutomationIssuesResponse: {
runs: components["schemas"]["AutomationRunIssue"][];
pending_tasks: components["schemas"]["DeferredAutomationIssue"][];
};
AutomationActionResponse: {
id: number;
action_type: string;
card_id: number;
card_name: string;
delivery_count: number;
message_template: string;
delay_seconds: number;
config_json: string;
enabled: boolean;
sort_order: number;
};
AutomationRuleResponse: {
id: number;
cookie_id: string;
item_id: string;
item_title: string;
name: string;
trigger_type: string;
enabled: boolean;
priority: number;
config_json: string;
actions: components["schemas"]["AutomationActionResponse"][];
created_at: string;
updated_at: string;
};
AutomationRuleListResponse: components["schemas"]["AutomationRuleResponse"][];
AutomationRulePageResponse: {
success: boolean;
data: components["schemas"]["AutomationRuleResponse"][];
total: number;
page: number;
page_size: number;
total_pages: number;
trigger_counts: {
[key: string]: number;
};
};
AutomationRulesResponse: components["schemas"]["AutomationRuleListResponse"] | components["schemas"]["AutomationRulePageResponse"];
DefaultReplyResponse: {
cookie_id?: string;
enabled: boolean;
reply_content: string;
reply_image_url?: string;
reply_once: boolean;
};
AccountTaskSettingsResponse: {
account_id: string;
auto_rate_enabled: boolean;
rate_content: string;
auto_polish_enabled: boolean;
polish_time: string;
last_rate_scan_at: number;
last_polish_date: string;
last_polish_at: number;
};
AccountTaskSettingsUpdateRequest: {
account_id?: string;
auto_rate_enabled: boolean;
rate_content: string;
auto_polish_enabled: boolean;
polish_time: string;
last_rate_scan_at?: number;
last_polish_date?: string;
last_polish_at?: number;
};
AccountTaskRunRequest: {
/** @enum {string} */
task_type: "auto_rate" | "auto_polish";
};
AccountTaskRunResponse: {
id: number;
run_key: string;
account_id: string;
task_type: string;
target_id: string;
run_date: string;
status: string;
success_count: number;
failed_count: number;
error_message: string;
next_retry_at: number;
started_at: number;
finished_at: number;
};
AccountTaskRunsResponse: {
runs: components["schemas"]["AccountTaskRunResponse"][];
};
AccountTaskSummaryResponse: {
/** @enum {string} */
task_type: "auto_rate" | "auto_polish";
found: number;
success: number;
failed: number;
skipped: number;
message?: string;
};
AccountTaskRunResponseEnvelope: {
success: boolean;
summary: components["schemas"]["AccountTaskSummaryResponse"];
};
AccountBindingsResponse: {
cookie_id: string;
channel_ids: number[] | null;
};
KeywordBasicResponse: {
keyword: string;
reply: string;
};
KeywordBasicListResponse: components["schemas"]["KeywordBasicResponse"][];
KeywordItemResponse: {
keyword: string;
reply: string;
item_id: string;
};
KeywordItemListResponse: components["schemas"]["KeywordItemResponse"][];
KeywordTypedResponse: {
id: number;
keyword: string;
reply: string;
item_id: string;
type: string;
image_url: string;
};
KeywordTypedListResponse: components["schemas"]["KeywordTypedResponse"][];
DefaultReplyMapResponse: {
[key: string]: components["schemas"]["DefaultReplyResponse"];
};
DefaultReplyListResponse: components["schemas"]["DefaultReplyResponse"][] | null;
ItemReplyResponse: {
item_id?: string;
cookie_id?: string;
reply_content: string;
};
ItemReplyListResponse: components["schemas"]["ItemReplyResponse"][];
AIReplySettingsResponse: {
cookie_id?: string;
ai_enabled: boolean;
max_discount_percent: number;
max_discount_amount: number;
max_bargain_rounds: number;
custom_prompts: string;
};
AIReplySettingsMapResponse: {
[key: string]: components["schemas"]["AIReplySettingsResponse"];
};
SettingsResponse: {
[key: string]: string;
};
UserSettingResponse: {
value: string;
};
PublishCategoryResponse: {
cat_id: string;
cat_name: string;
channel_cat_id?: string;
tb_cat_id?: string;
};
PublishCardAction: {
card_id: number;
delivery_count: number;
delay_seconds: number;
};
PublishCardAutomation: {
enabled: boolean;
actions: components["schemas"]["PublishCardAction"][] | null;
};
PublishReviewRequestConfig: {
enabled: boolean;
after_shipped_hours: number;
message: string;
max_attempts: number;
delay_seconds: number;
};
PublishAutomationConfig: {
paid_delivery: components["schemas"]["PublishCardAutomation"];
review_gift: components["schemas"]["PublishCardAutomation"];
review_request: components["schemas"]["PublishReviewRequestConfig"];
};
PublishLocation: {
area?: string;
city?: string;
division_id?: string;
longitude?: number;
latitude?: number;
poi_id?: string;
poi_name?: string;
province?: string;
};
ItemPublishBatchPreviewRow: {
row_no: number;
valid: boolean;
errors?: string[];
cookie_id: string;
title: string;
price: string;
quantity: number;
images: string[];
category: components["schemas"]["PublishCategoryResponse"];
automation: components["schemas"]["PublishAutomationConfig"];
};
ItemPublishBatchPreviewResponse: {
success: boolean;
preview_id: string;
total: number;
valid: number;
invalid: number;
rows: components["schemas"]["ItemPublishBatchPreviewRow"][];
};
ItemPublishBatchRowResponse: {
id: number;
row_no: number;
cookie_id: string;
title: string;
price: string;
quantity: number;
images: string[];
category: components["schemas"]["PublishCategoryResponse"];
automation: components["schemas"]["PublishAutomationConfig"];
status: string;
item_id: string;
item_url: string;
error_message: string;
failure_kind: string;
};
ItemPublishBatchResponse: {
id: string;
status: string;
filename: string;
total: number;
success: number;
failed: number;
pending: number;
running: number;
retryable: number;
rows: components["schemas"]["ItemPublishBatchRowResponse"][];
location: components["schemas"]["PublishLocation"];
publish_interval_seconds: number;
created_at: string;
updated_at: string;
};
ItemPublishBatchListResponse: {
batches: components["schemas"]["ItemPublishBatchResponse"][];
};
BatchIDResponse: {
success: boolean;
batch_id: string;
};
BatchCancelResponse: {
success: boolean;
status: string;
};
CategoryRecommendationResponse: {
success: boolean;
category: components["schemas"]["PublishCategoryResponse"];
};
CategoryRecommendationRequest: {
cookie_id: string;
keyword: string;
};
ItemPublishBatchStartRequest: {
preview_id?: string;
batch_id?: string;
};
ItemPublishBatchPreviewRequest: {
default_cookie_id: string;
/** Format: binary */
file: string;
/** Format: binary */
images_zip?: string;
fallback_category_id?: string;
fallback_category_name?: string;
fallback_channel_category_id?: string;
fallback_tb_category_id?: string;
location?: string;
publish_interval_seconds?: number;
};
HealthResponse: {
/** @enum {string} */
status: "ok";
@@ -1828,6 +2142,47 @@ export interface components {
/** @enum {string} */
database: "unavailable";
};
CardMutationRequest: {
name?: string;
/** @enum {string} */
type?: "api" | "text" | "data" | "image";
api_config?: string;
text_content?: string;
data_content?: string;
image_url?: string;
description?: string;
enabled?: boolean;
delay_seconds?: number;
is_multi_spec?: boolean;
spec_name?: string;
spec_value?: string;
};
CardAppendRequest: {
content: string;
};
CardBatchResultResponse: {
row_no: number;
success: boolean;
id?: number;
name: string;
type?: string;
error?: string;
};
CardBatchResponse: {
success: boolean;
total: number;
created: number;
failed: number;
rows: components["schemas"]["CardBatchResultResponse"][];
};
CardAppendResponse: {
success: boolean;
added: number;
};
MutationIDResponse: {
success: boolean;
id: number;
};
CardResponse: {
id: number;
name: string;
@@ -1859,6 +2214,18 @@ export interface components {
multi_quantity_delivery: boolean;
is_multi_qty_ship: boolean;
};
ItemListArrayResponse: components["schemas"]["ItemListResponse"][];
ItemDetailResponse: {
cookie_id: string;
item_id: string;
item_title: string;
item_description: string;
item_category: string;
item_price: string;
item_detail: string;
is_multi_spec: boolean;
multi_quantity_delivery: boolean;
};
NotificationChannelResponse: {
id: number;
name: string;
@@ -1867,6 +2234,25 @@ export interface components {
enabled: boolean;
user_id?: number;
};
NotificationChannelCreateRequest: {
name: string;
type: string;
config?: string;
event_types?: string;
enabled?: boolean;
};
NotificationChannelPatchRequest: {
name?: string;
type?: string;
config?: string;
event_types?: string;
enabled?: boolean;
};
NotificationBindingRequest: {
channel_ids?: number[];
channel_id?: number;
enabled?: boolean;
};
NotificationBinding: {
id: number;
channel_id: number;
@@ -2123,21 +2509,21 @@ export interface components {
item_title: string;
item_image: string;
buyer_id: string;
spec_name: string;
spec_value: string;
spec_name?: string;
spec_value?: string;
quantity: string;
amount: string;
order_status: string;
status: string;
cookie_id: string;
is_bargain: number;
system_shipped: boolean;
receiver_name: string;
receiver_phone: string;
receiver_address: string;
receiver_city: string;
is_bargain?: number;
system_shipped?: boolean;
receiver_name?: string;
receiver_phone?: string;
receiver_address?: string;
receiver_city?: string;
created_at: string;
updated_at: string;
updated_at?: string;
};
OrderListResponse: {
success: boolean;
@@ -2405,7 +2791,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["AccountTaskSettingsResponse"];
};
};
/** @description 统一错误响应 */
@@ -2464,7 +2850,11 @@ export interface operations {
};
cookie?: never;
};
requestBody?: never;
requestBody: {
content: {
"application/json": components["schemas"]["AccountTaskSettingsUpdateRequest"];
};
};
responses: {
/** @description 成功 */
200: {
@@ -2472,7 +2862,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["AccountTaskSettingsResponse"];
};
};
/** @description 统一错误响应 */
@@ -2531,7 +2921,11 @@ export interface operations {
};
cookie?: never;
};
requestBody?: never;
requestBody: {
content: {
"application/json": components["schemas"]["AccountTaskRunRequest"];
};
};
responses: {
/** @description 成功 */
200: {
@@ -2539,7 +2933,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["AccountTaskRunResponseEnvelope"];
};
};
/** @description 统一错误响应 */
@@ -2606,7 +3000,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["AccountTaskRunsResponse"];
};
};
/** @description 统一错误响应 */
@@ -3905,7 +4299,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["AdminCookie"][];
"application/json": components["schemas"]["AdminCookie"][] | null;
};
};
/** @description 统一错误响应 */
@@ -3970,7 +4364,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["NotificationUncertainOutboxResponse"];
};
};
/** @description 统一错误响应 */
@@ -4569,7 +4963,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["AutomationIssuesResponse"];
};
};
/** @description 统一错误响应 */
@@ -4708,7 +5102,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["AutomationRulesResponse"];
};
};
/** @description 统一错误响应 */
@@ -5096,7 +5490,11 @@ export interface operations {
path?: never;
cookie?: never;
};
requestBody?: never;
requestBody: {
content: {
"application/json": components["schemas"]["CardMutationRequest"];
};
};
responses: {
/** @description 成功 */
200: {
@@ -5104,7 +5502,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["MutationIDResponse"];
};
};
/** @description 统一错误响应 */
@@ -5171,7 +5569,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["CardResponse"];
};
};
/** @description 统一错误响应 */
@@ -5230,7 +5628,11 @@ export interface operations {
};
cookie?: never;
};
requestBody?: never;
requestBody: {
content: {
"application/json": components["schemas"]["CardMutationRequest"];
};
};
responses: {
/** @description 成功 */
200: {
@@ -5364,7 +5766,11 @@ export interface operations {
};
cookie?: never;
};
requestBody?: never;
requestBody: {
content: {
"application/json": components["schemas"]["CardAppendRequest"];
};
};
responses: {
/** @description 成功 */
200: {
@@ -5372,7 +5778,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["CardAppendResponse"];
};
};
/** @description 统一错误响应 */
@@ -5439,7 +5845,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["CardResponse"];
};
};
/** @description 统一错误响应 */
@@ -5496,7 +5902,14 @@ export interface operations {
path?: never;
cookie?: never;
};
requestBody?: never;
requestBody: {
content: {
"multipart/form-data": {
/** Format: binary */
file: string;
};
};
};
responses: {
/** @description 成功 */
200: {
@@ -5504,7 +5917,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["CardBatchResponse"];
};
};
/** @description 统一错误响应 */
@@ -5990,7 +6403,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["DefaultReplyMapResponse"];
};
};
/** @description 统一错误响应 */
@@ -6057,7 +6470,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["DefaultReplyResponse"];
};
};
/** @description 统一错误响应 */
@@ -6323,7 +6736,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["DefaultReplyListResponse"];
};
};
/** @description 统一错误响应 */
@@ -6525,7 +6938,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["ItemDetailResponse"];
};
};
/** @description 统一错误响应 */
@@ -6864,7 +7277,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["ItemListArrayResponse"];
};
};
/** @description 统一错误响应 */
@@ -7126,7 +7539,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["ItemPublishBatchListResponse"];
};
};
/** @description 统一错误响应 */
@@ -7183,7 +7596,11 @@ export interface operations {
path?: never;
cookie?: never;
};
requestBody?: never;
requestBody: {
content: {
"application/json": components["schemas"]["ItemPublishBatchStartRequest"];
};
};
responses: {
/** @description 成功 */
200: {
@@ -7191,7 +7608,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["BatchIDResponse"];
};
};
/** @description 统一错误响应 */
@@ -7258,7 +7675,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["ItemPublishBatchResponse"];
};
};
/** @description 统一错误响应 */
@@ -7325,7 +7742,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["OperationResponse"];
};
};
/** @description 统一错误响应 */
@@ -7392,7 +7809,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["BatchCancelResponse"];
};
};
/** @description 统一错误响应 */
@@ -7526,7 +7943,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["BatchIDResponse"];
};
};
/** @description 统一错误响应 */
@@ -7583,7 +8000,11 @@ export interface operations {
path?: never;
cookie?: never;
};
requestBody?: never;
requestBody: {
content: {
"multipart/form-data": components["schemas"]["ItemPublishBatchPreviewRequest"];
};
};
responses: {
/** @description 成功 */
200: {
@@ -7591,7 +8012,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["ItemPublishBatchPreviewResponse"];
};
};
/** @description 统一错误响应 */
@@ -7648,7 +8069,11 @@ export interface operations {
path?: never;
cookie?: never;
};
requestBody?: never;
requestBody: {
content: {
"application/json": components["schemas"]["CategoryRecommendationRequest"];
};
};
responses: {
/** @description 成功 */
200: {
@@ -7656,7 +8081,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["CategoryRecommendationResponse"];
};
};
/** @description 统一错误响应 */
@@ -7723,7 +8148,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["AccountBindingsResponse"];
};
};
/** @description 统一错误响应 */
@@ -7782,7 +8207,11 @@ export interface operations {
};
cookie?: never;
};
requestBody?: never;
requestBody: {
content: {
"application/json": components["schemas"]["NotificationBindingRequest"];
};
};
responses: {
/** @description 成功 */
200: {
@@ -7912,7 +8341,11 @@ export interface operations {
path?: never;
cookie?: never;
};
requestBody?: never;
requestBody: {
content: {
"application/json": components["schemas"]["NotificationChannelCreateRequest"];
};
};
responses: {
/** @description 成功 */
200: {
@@ -7920,7 +8353,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["MutationIDResponse"];
};
};
/** @description 统一错误响应 */
@@ -7979,7 +8412,11 @@ export interface operations {
};
cookie?: never;
};
requestBody?: never;
requestBody: {
content: {
"application/json": components["schemas"]["NotificationChannelPatchRequest"];
};
};
responses: {
/** @description 成功 */
200: {
@@ -8385,7 +8822,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["NotificationUncertainOutboxResponse"];
};
};
/** @description 统一错误响应 */
@@ -9139,15 +9576,6 @@ export interface operations {
};
};
responses: {
/** @description 成功 */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
};
};
/** @description 统一错误响应 */
400: {
headers: {
@@ -9215,15 +9643,6 @@ export interface operations {
};
requestBody?: never;
responses: {
/** @description 成功 */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
};
};
/** @description 统一错误响应 */
400: {
headers: {
@@ -9291,15 +9710,6 @@ export interface operations {
};
requestBody?: never;
responses: {
/** @description 成功 */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
};
};
/** @description 统一错误响应 */
400: {
headers: {
@@ -9643,7 +10053,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["KeywordBasicListResponse"];
};
};
/** @description 统一错误响应 */
@@ -9845,7 +10255,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["KeywordItemListResponse"];
};
};
/** @description 统一错误响应 */
@@ -9979,7 +10389,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["KeywordTypedListResponse"];
};
};
/** @description 统一错误响应 */
@@ -10180,7 +10590,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["ItemReplyListResponse"];
};
};
/** @description 统一错误响应 */
@@ -10248,7 +10658,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["ItemReplyResponse"];
};
};
/** @description 统一错误响应 */
@@ -10384,7 +10794,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["OperationResponse"];
};
};
/** @description 统一错误响应 */
@@ -10928,7 +11338,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["AIReplySettingsMapResponse"];
};
};
/** @description 统一错误响应 */
@@ -10995,7 +11405,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["AIReplySettingsResponse"];
};
};
/** @description 统一错误响应 */
@@ -11328,7 +11738,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["SettingsResponse"];
};
};
/** @description 统一错误响应 */
@@ -11393,7 +11803,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["SettingsResponse"];
};
};
/** @description 统一错误响应 */
@@ -11460,7 +11870,7 @@ export interface operations {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["ApiResponse"];
"application/json": components["schemas"]["UserSettingResponse"];
};
};
/** @description 统一错误响应 */
+5 -8
View File
@@ -1,8 +1,5 @@
// items 公开商品、发布地点和批量发布相关传输契约。
/** 商品 feature 使用的 HTTP 传输 DTO。 */
export type {
AccountDetail, BatchCancelResponse, BatchIDResponse, CategoryRecommendationResponse,
Item, ItemDetailResponse, ItemPublishBatchPreviewResponse,
ItemPublishBatchResponse, ItemPublishResponse, ItemSyncResponse,
OperationResponse, PublishLocation, ShippingRule,
} from './transport';
// items 只公开 OpenAPI 生成的商品传输类型;发布和兼容模型属于 items feature。
import type { components } from './generated/schema';
/** ItemTransport 表示生成的商品列表行。 */
export type ItemTransport = components['schemas']['ItemListResponse'];
@@ -1,7 +1,7 @@
// notifications 公开通知渠道、绑定和事件相关传输契约。
/** 通知 feature 使用的 HTTP 传输 DTO。 */
export type {
MutationIDResponse, NotificationBinding, NotificationChannel,
NotificationChannelResponse, NotificationChannelType, NotificationEventType,
OperationResponse, SystemSettings,
} from './transport';
// notifications 只公开 OpenAPI 生成的通知传输类型;表单状态属于 notifications feature。
import type { components } from './generated/schema';
/** NotificationChannelTransport 表示生成的通知渠道摘要。 */
export type NotificationChannelTransport = components['schemas']['NotificationChannelResponse'];
/** NotificationBindingsTransport 表示生成的账号通知绑定映射。 */
export type NotificationBindingsTransport = components['schemas']['NotificationBindingsByAccount'];
+7 -9
View File
@@ -1,9 +1,7 @@
// orders 公开订单、发货和订单刷新相关传输契约。
/** 订单 feature 使用的 HTTP 传输 DTO。 */
export type {
AccountDetail, AdminStatsResponse, Item, OperationResponse, Order,
OrderBatchResponse, OrderDTOResponse, OrderDetailResponse,
OrderRefreshJobCancelResponse, OrderRefreshJobStartResponse,
OrderRefreshJobStatusResponse, OrderRefreshResponse, OrderSingleRefreshResponse,
OrderStatus, PaginatedResponse,
} from './transport';
// orders 只公开 OpenAPI 生成的订单传输类型;订单 UI 模型属于 orders feature。
import type { components } from './generated/schema';
/** OrderTransport 表示生成的订单行。 */
export type OrderTransport = components['schemas']['OrderDTO'];
/** OrderRefreshTransport 表示生成的订单刷新结果。 */
export type OrderRefreshTransport = components['schemas']['OrderRefreshResponse'];
+5 -3
View File
@@ -1,3 +1,5 @@
// session 公开登录、初始化和二维码会话相关传输契约。
/** 会话 feature 使用的 HTTP 传输 DTO。 */
export type { OperationResponse, SessionResponse } from './transport';
// session 只公开 OpenAPI 生成的会话传输类型;页面会话状态属于 session feature。
import type { components } from './generated/schema';
/** SessionTransport 表示生成的登录或初始化响应。 */
export type SessionTransport = components['schemas']['SessionResponse'];
+7 -3
View File
@@ -1,3 +1,7 @@
// settings 公开系统、AI 和默认回复设置相关传输契约。
/** 系统设置 feature 使用的 HTTP 传输 DTO。 */
export type { AIModelsResponse, OperationResponse, SystemSettings } from './transport';
// settings 只公开 OpenAPI 生成的设置传输类型;表单状态属于 settings feature。
import type { components } from './generated/schema';
/** SystemSettingsTransport 表示受约束动态键的设置响应。 */
export type SystemSettingsTransport = components['schemas']['SystemSettingsResponse'];
/** AIModelsTransport 表示生成的模型发现响应。 */
export type AIModelsTransport = components['schemas']['AIModelsResponse'];
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -89,7 +89,7 @@ func TestChatWebSocketStreamsOnlyAuthenticatedAccountEvents(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
// conn、err 用于本次流程后续判断的conn、err
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(httpServer.URL, "http")+"/api/chat/ws", &websocket.DialOptions{HTTPHeader: header})
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(httpServer.URL, "http")+"/api/v1/chat/ws", &websocket.DialOptions{HTTPHeader: header})
if err != nil {
t.Fatal(err)
}
@@ -0,0 +1,332 @@
package server
import (
"bytes"
"context"
"encoding/json"
"fmt"
"mime/multipart"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"sort"
"strconv"
"strings"
"testing"
"github.com/getkin/kin-openapi/openapi3"
)
// TestOpenAPIOperationsHaveContractScenarios 从 OpenAPI operationId 自动生成最小请求,确保每个版本化 operation 都经过真实 Router 响应契约校验。
func TestOpenAPIOperationsHaveContractScenarios(t *testing.T) {
// document 是唯一 OpenAPI 契约源的解析结果。
document := loadOpenAPIContractForCoverage(t)
// operations 保存按路径和方法排序后的全部版本化 operation 场景。
operations := collectOpenAPIOperations(document)
// operation 表示当前规范枚举的 operation 场景,副本用于闭包隔离。
for _, operation := range operations {
// operation 是由 OpenAPI 文档直接枚举的当前测试场景,不允许手工名单遗漏。
operation := operation
t.Run(operation.operation.OperationID, func(t *testing.T) {
// srv、_、cleanup 分别是当前 operation 独占的真实 Server、测试数据库和资源释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前 operation 使用的完整 chi Router。
handler := srv.Router()
// sessionCookie 是当前 operation 独占的管理员会话,避免删除或登出影响其他场景。
sessionCookie := loginHelper(t, handler)
// request 是根据路径参数、必需查询参数和请求体 schema 生成的最小真实请求。
request := newOpenAPICoverageRequest(t, operation.path, operation.method, operation.operation)
request.AddCookie(sessionCookie)
// recorder 捕获真实 Router 对当前 operation 的状态、响应头和响应体。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIResponse(t, request, recorder)
})
}
}
// openAPICoverageOperation 保存一个由 OpenAPI 路径、方法和 operationId 构成的自动测试场景。
type openAPICoverageOperation struct {
// key 是方法和路径组成的稳定场景键。
key string
// path 是 OpenAPI 路径模板。
path string
// method 是小写 HTTP 方法。
method string
// operation 是当前 operation 的完整契约定义。
operation *openapi3.Operation
}
// loadOpenAPIContractForCoverage 加载并校验自动 operation 覆盖测试使用的契约文档。
func loadOpenAPIContractForCoverage(t *testing.T) *openapi3.T {
t.Helper()
// specPath 是从 Server 测试目录定位到唯一 OpenAPI 契约源的路径。
specPath := filepath.Join("..", "..", "api", "openapi.yaml")
// document、loadErr 分别是解析后的契约文档和加载失败原因。
document, loadErr := openapi3.NewLoader().LoadFromFile(specPath)
if loadErr != nil {
t.Fatalf("加载 OpenAPI 契约失败: %v", loadErr)
}
// validationErr 表示契约未满足 OpenAPI 语义约束的原因。
if validationErr := document.Validate(context.Background()); validationErr != nil {
t.Fatalf("OpenAPI 契约无效: %v", validationErr)
}
return document
}
// collectOpenAPIOperations 从规范自动收集全部版本化 operation,不维护独立路径或 DTO 名单。
func collectOpenAPIOperations(document *openapi3.T) []openAPICoverageOperation {
// operations 保存待运行的所有 OpenAPI operation 场景。
operations := make([]openAPICoverageOperation, 0)
// path 表示 OpenAPI 中登记的 HTTP 路径模板。
for _, path := range document.Paths.Keys() {
// pathItem 是当前路径模板的 operation 集合。
pathItem := document.Paths.Find(path)
// method 表示当前路径登记的 HTTP 动词;operation 表示其契约定义。
for method, operation := range pathItem.Operations() {
// normalizedMethod 是用于排序和构造请求的标准小写方法。
normalizedMethod := strings.ToLower(method)
operations = append(operations, openAPICoverageOperation{
key: normalizedMethod + " " + path,
path: path,
method: normalizedMethod,
operation: operation,
})
}
}
sort.Slice(operations, func(left, right int) bool {
// left、right 是待比较的场景下标,排序保证失败输出稳定。
return operations[left].key < operations[right].key
})
return operations
}
// newOpenAPICoverageRequest 根据 operation 的参数和请求体 schema 生成真实 HTTP 请求。
func newOpenAPICoverageRequest(t *testing.T, path string, method string, operation *openapi3.Operation) *http.Request {
t.Helper()
// resolvedPath 是将 OpenAPI 路径参数替换为可解析占位值后的 URL 路径。
resolvedPath := path
// parameter 表示当前 operation 的路径参数定义。
for _, parameter := range operation.Parameters {
// parameterValue 是当前路径或查询参数的最小稳定值。
if parameter.Value == nil || parameter.Value.In != "path" {
continue
}
resolvedPath = strings.ReplaceAll(resolvedPath, "{"+parameter.Value.Name+"}", openAPIParameterValue(parameter.Value.Name, parameter.Value.Schema))
}
// queryValues 保存规范声明的必需查询参数,避免自动场景依赖手工路径列表。
queryValues := url.Values{}
// parameter 表示当前 operation 的查询参数定义。
for _, parameter := range operation.Parameters {
// parameterValue 是当前参数引用解析后的值。
parameterValue := parameter.Value
if parameterValue == nil || parameterValue.In != "query" || !parameterValue.Required {
continue
}
queryValues.Set(parameterValue.Name, openAPIParameterValue(parameterValue.Name, parameterValue.Schema))
}
// encodedQuery 是将必需查询参数按 URL 规则编码后的字符串。
if encodedQuery := queryValues.Encode(); encodedQuery != "" {
resolvedPath += "?" + encodedQuery
}
// body、contentType 分别是按请求体 schema 生成的载荷和媒体类型。
body, contentType := openAPICoverageRequestBody(t, operation.RequestBody)
// request 是供真实 chi Router 执行的最小 HTTP 请求。
request := httptest.NewRequest(strings.ToUpper(method), resolvedPath, bytes.NewReader(body))
if contentType != "" {
request.Header.Set("Content-Type", contentType)
}
return request
}
// openAPICoverageRequestBody 按 OpenAPI 请求体媒体类型生成 JSON 或 multipart 载荷。
func openAPICoverageRequestBody(t *testing.T, requestBody *openapi3.RequestBodyRef) ([]byte, string) {
t.Helper()
if requestBody == nil || requestBody.Value == nil || len(requestBody.Value.Content) == 0 {
return nil, ""
}
// mediaType 是优先选择 JSON、其次 multipart、最后按稳定顺序选择的请求媒体类型。
mediaType := ""
// candidate 表示请求体支持的一种媒体类型。
for candidate := range requestBody.Value.Content {
if candidate == "application/json" {
mediaType = candidate
break
}
if mediaType == "" && strings.HasPrefix(candidate, "multipart/") {
mediaType = candidate
}
if mediaType == "" {
mediaType = candidate
}
}
if strings.HasPrefix(mediaType, "multipart/") {
// buffer、writer 分别保存 multipart 请求体和字段编码器。
buffer := &bytes.Buffer{}
// writer 负责以边界格式编码最小 multipart 请求体。
writer := multipart.NewWriter(buffer)
// closeErr 表示 multipart 编码器关闭并写入结尾边界时的错误。
if closeErr := writer.Close(); closeErr != nil {
t.Fatalf("生成 multipart 契约请求失败: %v", closeErr)
}
return buffer.Bytes(), writer.FormDataContentType()
}
// mediaSchema 是当前媒体类型声明的 JSON schema。
mediaSchema := requestBody.Value.Content[mediaType]
if mediaSchema == nil || mediaSchema.Schema == nil {
return []byte("{}"), mediaType
}
// payload 是依据 schema 已知字段递归生成的 JSON 值,主动覆盖可选输入字段的类型约束。
payload := openAPICoverageRequestValue(mediaSchema.Schema)
// encoded、marshalErr 分别是 JSON 请求体和编码失败原因。
encoded, marshalErr := json.Marshal(payload)
if marshalErr != nil {
t.Fatalf("生成 JSON 契约请求失败: %v", marshalErr)
}
return encoded, mediaType
}
// openAPICoverageRequestValue 按请求 schema 生成包含全部已知属性的最小 JSON 值,避免可选 DTO 字段遗漏长期未被调用。
func openAPICoverageRequestValue(schemaRef *openapi3.SchemaRef) any {
if schemaRef == nil || schemaRef.Value == nil {
return nil
}
// schema 是当前递归层的具体请求 schema 定义。
schema := schemaRef.Value
if schema.Example != nil || schema.Default != nil || schema.Const != nil || len(schema.Enum) > 0 || len(schema.OneOf) > 0 || len(schema.AnyOf) > 0 {
return openAPICoverageValue(schemaRef)
}
if schema.Type == nil || len(*schema.Type) == 0 || (*schema.Type)[0] != "object" {
return openAPICoverageValue(schemaRef)
}
// propertyNames 保存按字典序生成的已知请求字段,保证失败输出和负载稳定。
propertyNames := make([]string, 0, len(schema.Properties))
// propertyName 表示当前 schema 中发现的请求属性名称。
for propertyName := range schema.Properties {
propertyNames = append(propertyNames, propertyName)
}
sort.Strings(propertyNames)
// objectValue 保存所有已声明请求字段的递归最小值。
objectValue := make(map[string]any, len(propertyNames))
// propertyName 表示当前需要编码到请求 JSON 中的 schema 属性名称。
for _, propertyName := range propertyNames {
// property 是当前请求字段的类型约束。
property := schema.Properties[propertyName]
objectValue[propertyName] = openAPICoverageRequestValue(property)
}
return objectValue
}
// openAPICoverageValue 按 schema 生成满足结构约束的最小 JSON 值。
func openAPICoverageValue(schemaRef *openapi3.SchemaRef) any {
if schemaRef == nil || schemaRef.Value == nil {
return nil
}
// schema 是当前递归层的具体 schema 定义。
schema := schemaRef.Value
if schema.Example != nil {
return schema.Example
}
if schema.Default != nil {
return schema.Default
}
if schema.Const != nil {
return schema.Const
}
if len(schema.Enum) > 0 {
return schema.Enum[0]
}
if len(schema.OneOf) > 0 {
return openAPICoverageValue(schema.OneOf[0])
}
if len(schema.AnyOf) > 0 {
return openAPICoverageValue(schema.AnyOf[0])
}
// schemaType 是当前 schema 的首个声明类型。
schemaType := ""
if schema.Type != nil && len(*schema.Type) > 0 {
schemaType = (*schema.Type)[0]
}
switch schemaType {
case "object":
// objectValue 保存对象必需字段的递归结果。
objectValue := make(map[string]any, len(schema.Required))
// requiredName 表示当前对象必须生成的字段名称。
for _, requiredName := range schema.Required {
// property 是必需字段的 schema 定义。
property := schema.Properties[requiredName]
objectValue[requiredName] = openAPICoverageValue(property)
}
return objectValue
case "array":
if schema.Items == nil {
return []any{}
}
if schema.MinItems > 0 {
return []any{openAPICoverageValue(schema.Items)}
}
return []any{}
case "integer":
if schema.Min != nil {
return int64(*schema.Min)
}
return int64(1)
case "number":
if schema.Min != nil {
return *schema.Min
}
return float64(1)
case "boolean":
return true
default:
if schema.Format == "date-time" {
return "2026-01-01T00:00:00Z"
}
return "contract-test"
}
}
// openAPIParameterValue 依据参数名称和 schema 生成可被 handler 解析的路径或查询值。
func openAPIParameterValue(name string, schemaRef *openapi3.SchemaRef) string {
// normalizedName 是便于判断业务语义的参数名称。
normalizedName := strings.ToLower(name)
switch {
case strings.Contains(normalizedName, "user_id"), strings.Contains(normalizedName, "card_id"), strings.Contains(normalizedName, "channel_id"):
return "999999"
case strings.Contains(normalizedName, "index"):
return "0"
case strings.Contains(normalizedName, "cookie"), strings.HasSuffix(normalizedName, "cid"), strings.Contains(normalizedName, "account"):
return "acc1"
case strings.Contains(normalizedName, "order"):
return "missing-order"
case strings.Contains(normalizedName, "session"):
return "missing-session"
case strings.Contains(normalizedName, "batch"):
return "missing-batch"
case strings.Contains(normalizedName, "job"):
return "missing-job"
case strings.Contains(normalizedName, "task"), strings.Contains(normalizedName, "run"), strings.Contains(normalizedName, "rule"):
return "missing-resource"
case strings.Contains(normalizedName, "item"):
return "missing-item"
case normalizedName == "key":
return "theme_color"
}
// value 是没有业务名称提示时按 schema 生成的通用参数值。
value := openAPICoverageValue(schemaRef)
// typedValue 是按 OpenAPI 参数 schema 生成的具体基础类型值。
switch typedValue := value.(type) {
case string:
return typedValue
case bool:
return strconv.FormatBool(typedValue)
case int64:
return strconv.FormatInt(typedValue, 10)
case float64:
return strconv.FormatFloat(typedValue, 'f', -1, 64)
default:
return fmt.Sprint(typedValue)
}
}
@@ -0,0 +1,782 @@
package server
import (
"bytes"
"context"
"encoding/json"
"io"
"mime/multipart"
"net/http"
"net/http/httptest"
"net/textproto"
"strconv"
"strings"
"testing"
"time"
automationapp "xianyu-go/internal/application/automation"
chatapp "xianyu-go/internal/application/chat"
itemapp "xianyu-go/internal/application/items"
notificationsapp "xianyu-go/internal/application/notifications"
"xianyu-go/internal/db"
"xianyu-go/internal/xianyu/cookierefresh"
"xianyu-go/internal/xianyu/mtop"
xrenew "xianyu-go/internal/xianyu/renew"
)
// TestOpenAPIRemainingVersionedSuccessResponses 验证仍未被既有兼容测试触达的版本化本地成功响应。
func TestOpenAPIRemainingVersionedSuccessResponses(t *testing.T) {
// t.Run 将相互独立的真实 Router 场景隔离,避免各自的数据库状态互相影响。
t.Run("initialize", testOpenAPISessionInitializeSuccess)
t.Run("long-login", testOpenAPILongLoginSuccess)
t.Run("ai-models", testOpenAPIAIModelsSuccess)
t.Run("cards-batch", testOpenAPICardsBatchSuccess)
t.Run("chat-history-and-read", testOpenAPIChatHistoryAndReadSuccess)
t.Run("local-item-and-manual-ship", testOpenAPILocalItemAndManualShipSuccess)
t.Run("category-recommendation", testOpenAPIItemCategoryRecommendationSuccess)
t.Run("publish-batch-preview", testOpenAPIPublishBatchPreviewSuccess)
t.Run("uncertain-notifications", testOpenAPIUncertainNotificationSuccess)
t.Run("chat-send", testOpenAPIChatSendSuccess)
t.Run("item-sync", testOpenAPIItemSyncSuccess)
t.Run("item-publish", testOpenAPIItemPublishSuccess)
t.Run("batch-lifecycle", testOpenAPIBatchLifecycleSuccess)
t.Run("automation-resolve", testOpenAPIAutomationResolveSuccess)
t.Run("notification-test", testOpenAPINotificationChannelTestSuccess)
t.Run("account-task-run", testOpenAPIAccountTaskRunSuccess)
}
// testOpenAPISessionInitializeSuccess 覆盖首次初始化的真实公开成功响应。
func testOpenAPISessionInitializeSuccess(t *testing.T) {
// srv、_、cleanup 分别是未初始化服务、当前场景无需读取的存储和资源释放函数。
srv, _, cleanup := newUninitializedTestServer(t)
defer cleanup()
// handler 是未经包装的真实 Router,初始化会在响应中写入会话 Cookie。
handler := srv.Router()
// request 是提交首次管理员密码的版本化初始化请求。
request := httptest.NewRequest(http.MethodPost, "/api/v1/session/initialize", strings.NewReader(`{"password":"initial-password"}`))
request.Header.Set("Content-Type", "application/json")
// recorder 保存真实 handler 返回的状态、响应头和响应体。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
// testOpenAPILongLoginSuccess 覆盖长登录读取和开关更新的真实平台代理成功响应。
func testOpenAPILongLoginSuccess(t *testing.T) {
// passport 是本地续期服务替身,仅提供真实 handler 所需的平台协议响应。
passport := httptest.NewServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) {
// responseWriter、request 分别承载本地平台替身的响应和请求。
responseWriter.Header().Add("Set-Cookie", "havana_lgc_exp=4102444800000; Domain=.goofish.com; Path=/; Secure")
if strings.Contains(request.URL.Path, "set") {
_, _ = responseWriter.Write([]byte(`{"data":{"success":true}}`))
return
}
_, _ = responseWriter.Write([]byte(`{"content":{"data":{"returnValue":{"canOpenLongLogin":true,"hasLongTokenLogin":true}}}}`))
}))
defer passport.Close()
// srv、store、cleanup 分别是服务、用于准备浏览器 Cookie 快照的存储和资源释放函数。
srv, store, cleanup := newTestServer(t)
defer cleanup()
setTestCookieRenew(srv, xrenew.Service{HTTPClient: passport.Client(), QueryLoginSettingsURL: passport.URL + "/query", SetLoginSettingsURL: passport.URL + "/set"})
// detail、detailErr 保存当前账号的加密凭证详情及读取错误。
detail, detailErr := store.Cookies.GetDetails(context.Background(), "acc1")
if detailErr != nil {
t.Fatalf("读取长登录账号失败: %v", detailErr)
}
// metadata 保存带域名快照的凭证元数据,使真实续期适配器可调用本地平台替身。
metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, cookierefresh.SnapshotFromCookieString(detail.Value, ".goofish.com"))
// updateErr 表示写入测试长登录 Cookie 快照失败。
if updateErr := store.Cookies.UpdateRenewalCookie(context.Background(), "acc1", detail.Value, metadata, time.Now().Unix()); updateErr != nil {
t.Fatalf("准备长登录凭证快照失败: %v", updateErr)
}
// handler 是当前场景使用的真实版本化 Router。
handler := srv.Router()
// sessionCookie 是管理员认证会话。
sessionCookie := loginHelper(t, handler)
// requests 保存读取与写入长登录状态的两个版本化成功请求。
requests := []*http.Request{
httptest.NewRequest(http.MethodGet, "/api/v1/accounts/acc1/long-login", nil),
httptest.NewRequest(http.MethodPut, "/api/v1/accounts/acc1/long-login", strings.NewReader(`{"enabled":true}`)),
}
// request 是当前真实长登录请求。
for _, request := range requests {
request.Header.Set("Content-Type", "application/json")
request.AddCookie(sessionCookie)
// recorder 保存当前请求的完整真实响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
}
// testOpenAPIAIModelsSuccess 覆盖 AI 模型代理的本地成功响应。
func testOpenAPIAIModelsSuccess(t *testing.T) {
// modelServer 模拟兼容 OpenAI 的模型列表端点。
modelServer := httptest.NewServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) {
// responseWriter、request 分别承载模型替身响应和请求;请求内容无需在本场景读取。
responseWriter.Header().Set("Content-Type", "application/json")
_, _ = responseWriter.Write([]byte(`{"data":[{"id":"contract-model"}]}`))
}))
defer modelServer.Close()
// srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是访问管理员模型代理所需的认证会话。
sessionCookie := loginHelper(t, handler)
// request 是指向本地模型替身的版本化 AI 模型请求。
request := httptest.NewRequest(http.MethodPost, "/api/v1/settings/ai-models", strings.NewReader(`{"base_url":"`+modelServer.URL+`","api_key":"test-key"}`))
request.Header.Set("Content-Type", "application/json")
request.AddCookie(sessionCookie)
// recorder 保存真实代理成功响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
// testOpenAPICardsBatchSuccess 覆盖卡券 CSV 上传的真实 multipart 成功响应。
func testOpenAPICardsBatchSuccess(t *testing.T) {
// srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是当前管理员认证会话。
sessionCookie := loginHelper(t, handler)
// body 保存上传 CSV 的 multipart 编码结果。
var body bytes.Buffer
// writer 负责组装符合真实 handler 预期的 multipart 请求。
writer := multipart.NewWriter(&body)
// file、fileErr 分别是 CSV 表单文件写入器及创建失败原因。
file, fileErr := writer.CreateFormFile("file", "cards.csv")
if fileErr != nil {
t.Fatalf("创建卡券表单文件失败: %v", fileErr)
}
// writeErr 表示写入测试卡券 CSV 内容失败。
if _, writeErr := io.WriteString(file, "name,type,content\n合同卡,text,serial-001\n"); writeErr != nil {
t.Fatalf("写入卡券 CSV 失败: %v", writeErr)
}
// closeErr 表示完成卡券 multipart 编码失败。
if closeErr := writer.Close(); closeErr != nil {
t.Fatalf("关闭卡券 multipart 失败: %v", closeErr)
}
// request 是真实卡券批量上传请求。
request := httptest.NewRequest(http.MethodPost, "/api/v1/cards/batch", &body)
request.Header.Set("Content-Type", writer.FormDataContentType())
request.AddCookie(sessionCookie)
// recorder 保存批量创建的真实成功响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
// testOpenAPIChatHistoryAndReadSuccess 覆盖聊天消息查询与本地已读状态更新。
func testOpenAPIChatHistoryAndReadSuccess(t *testing.T) {
// srv、store、cleanup 分别是启用聊天应用的服务、夹具存储和资源释放函数。
srv, store, cleanup := newTestServerWithChat(t)
defer cleanup()
// saveErr 表示写入可查询聊天消息失败。
_, _, saveErr := store.Chats.SaveMessage(context.Background(), db.ChatSession{CookieID: "acc1", ChatID: "chat-contract", BuyerID: "buyer-contract", BuyerName: "契约买家"}, db.ChatMessage{MessageKey: "message-contract", Direction: "incoming", SenderID: "buyer-contract", SenderName: "契约买家", MessageType: "text", Content: "契约消息", Status: "received", SentAt: 1}, true)
if saveErr != nil {
t.Fatalf("写入聊天夹具失败: %v", saveErr)
}
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是当前管理员认证会话。
sessionCookie := loginHelper(t, handler)
// requests 保存消息读取与已读更新的真实版本化请求。
requests := []*http.Request{
httptest.NewRequest(http.MethodGet, "/api/v1/chat/messages?account_id=acc1&chat_id=chat-contract", nil),
httptest.NewRequest(http.MethodPost, "/api/v1/chat/read", strings.NewReader(`{"account_id":"acc1","chat_id":"chat-contract"}`)),
}
// request 是当前待验证的聊天 HTTP 请求。
for _, request := range requests {
request.Header.Set("Content-Type", "application/json")
request.AddCookie(sessionCookie)
// recorder 保存真实 handler 的成功响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
// channelResult、channelErr 保存删除场景所需通知渠道的插入结果。
channelResult, channelErr := store.DB.ExecContext(context.Background(), `INSERT INTO notification_channels (name,type,config,enabled,user_id) VALUES ('contract-delete','webhook','{}',1,1)`)
if channelErr != nil {
t.Fatalf("创建删除通知渠道失败: %v", channelErr)
}
// channelID、channelIDErr 保存删除场景通知渠道主键及读取错误。
channelID, channelIDErr := channelResult.LastInsertId()
if channelIDErr != nil {
t.Fatalf("读取删除通知渠道主键失败: %v", channelIDErr)
}
// notificationResult、notificationErr 保存待删除消息通知夹具的主键及插入结果。
notificationResult, notificationErr := store.DB.ExecContext(context.Background(), `INSERT INTO message_notifications (cookie_id,channel_id,enabled) VALUES ('acc1',?,1)`, channelID)
if notificationErr != nil {
t.Fatalf("创建消息通知夹具失败: %v", notificationErr)
}
// notificationID、notificationIDErr 保存消息通知主键及读取错误。
notificationID, notificationIDErr := notificationResult.LastInsertId()
if notificationIDErr != nil {
t.Fatalf("读取消息通知主键失败: %v", notificationIDErr)
}
// deleteRequest 是删除单条消息通知的版本化请求。
deleteRequest := httptest.NewRequest(http.MethodDelete, "/api/v1/notifications/messages/"+strconv.FormatInt(notificationID, 10), nil)
deleteRequest.AddCookie(sessionCookie)
// deleteRecorder 保存删除响应。
deleteRecorder := httptest.NewRecorder()
handler.ServeHTTP(deleteRecorder, deleteRequest)
assertOpenAPIRecordedSuccessResponse(t, deleteRequest, deleteRecorder)
}
// testOpenAPILocalItemAndManualShipSuccess 覆盖无需平台请求的商品创建和状态型手动发货成功响应。
func testOpenAPILocalItemAndManualShipSuccess(t *testing.T) {
// srv、store、cleanup 分别是服务、订单夹具存储和资源释放函数。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// seedErr 表示写入待发货订单夹具失败。
_, seedErr := store.DB.ExecContext(context.Background(), `INSERT INTO orders (order_id,item_id,buyer_id,order_status,cookie_id,chat_id) VALUES ('contract-manual-ship','contract-item','buyer-contract','2','acc1','chat-contract')`)
if seedErr != nil {
t.Fatalf("写入手动发货订单失败: %v", seedErr)
}
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是当前管理员认证会话。
sessionCookie := loginHelper(t, handler)
// requests 保存商品创建和状态型手动发货的版本化请求。
requests := []*http.Request{
httptest.NewRequest(http.MethodPost, "/api/v1/items/acc1", strings.NewReader(`{"item_id":"contract-created","item_title":"契约商品","item_price":"10.00"}`)),
httptest.NewRequest(http.MethodPost, "/api/v1/orders/manual-ship", strings.NewReader(`{"order_ids":["contract-manual-ship"],"ship_mode":"status_only"}`)),
}
// request 是当前待验证的本地资源请求。
for _, request := range requests {
request.Header.Set("Content-Type", "application/json")
request.AddCookie(sessionCookie)
// recorder 保存当前请求的完整成功响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
}
// testOpenAPIItemCategoryRecommendationSuccess 覆盖商品类目推荐的本地 MTOP 成功响应。
func testOpenAPIItemCategoryRecommendationSuccess(t *testing.T) {
// srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// client 是仅返回类目推荐结构的本地 MTOP 客户端。
client := mtop.NewClient()
client.HTTPClient = &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) {
// request 是类目推荐的 MTOP 请求;本场景只需返回确定性成功数据。
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"ret":["SUCCESS::调用成功"],"data":{"cardList":[{"cardData":{"propertyId":"-10000","propertyName":"分类","valuesList":[{"catId":"5001","catName":"虚拟商品","channelCatId":"6001","isClicked":"1"}]}}]}}`)), Request: request}, nil
})}
setTestMTop(srv, client)
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是当前管理员认证会话。
sessionCookie := loginHelper(t, handler)
// request 是商品类目推荐的版本化请求。
request := httptest.NewRequest(http.MethodPost, "/api/v1/items/publish-categories/recommend", strings.NewReader(`{"cookie_id":"acc1","keyword":"资料"}`))
request.Header.Set("Content-Type", "application/json")
request.AddCookie(sessionCookie)
// recorder 保存真实 handler 的成功响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
// testOpenAPIPublishBatchPreviewSuccess 覆盖批量发布预检的真实 multipart 成功响应。
func testOpenAPIPublishBatchPreviewSuccess(t *testing.T) {
// srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是当前管理员认证会话。
sessionCookie := loginHelper(t, handler)
// body 保存预检上传的 multipart 编码结果。
var body bytes.Buffer
// writer 负责组装真实预检入口需要的默认账号、CSV 和图片压缩包字段。
writer := multipart.NewWriter(&body)
_ = writer.WriteField("default_cookie_id", "acc1")
_ = writer.WriteField("fallback_category_id", "5001")
_ = writer.WriteField("fallback_category_name", "虚拟商品")
_ = writer.WriteField("fallback_channel_category_id", "6001")
// csvFile、csvErr 分别是预检 CSV 文件写入器和创建错误。
csvFile, csvErr := writer.CreateFormFile("file", "products.csv")
if csvErr != nil {
t.Fatalf("创建预检 CSV 失败: %v", csvErr)
}
// writeErr 表示写入测试预检 CSV 内容失败。
if _, writeErr := io.WriteString(csvFile, "账号ID,标题,价格,库存,图片\nacc1,契约商品,12.50,1,\n"); writeErr != nil {
t.Fatalf("写入预检 CSV 失败: %v", writeErr)
}
// closeErr 表示完成预检 multipart 编码失败。
if closeErr := writer.Close(); closeErr != nil {
t.Fatalf("关闭预检 multipart 失败: %v", closeErr)
}
// request 是批量发布预检的版本化上传请求。
request := httptest.NewRequest(http.MethodPost, "/api/v1/items/publish-batches/preview", &body)
request.Header.Set("Content-Type", writer.FormDataContentType())
request.AddCookie(sessionCookie)
// recorder 保存真实预检成功响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
// testOpenAPIUncertainNotificationSuccess 覆盖用户和管理员不确定通知摘要的真实成功响应。
func testOpenAPIUncertainNotificationSuccess(t *testing.T) {
// srv、store、cleanup 分别是服务、通知夹具存储和资源释放函数。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// result、insertErr 分别是渠道插入结果和数据库错误。
result, insertErr := store.DB.ExecContext(context.Background(), `INSERT INTO notification_channels (name,type,config,enabled,user_id) VALUES ('contract','webhook','{}',1,1)`)
if insertErr != nil {
t.Fatalf("创建通知渠道失败: %v", insertErr)
}
// channelID、idErr 分别是渠道标识和读取主键错误。
channelID, idErr := result.LastInsertId()
if idErr != nil {
t.Fatalf("读取通知渠道标识失败: %v", idErr)
}
// enqueueErr 表示写入 outbox 夹具失败。
enqueueErr := store.Notifications.EnqueueOutbox(context.Background(), []db.NotificationOutboxInput{{ChannelID: channelID, EventType: "contract"}})
if enqueueErr != nil {
t.Fatalf("写入通知 outbox 失败: %v", enqueueErr)
}
// claimed、claimErr 分别是被本地 worker 领取的 outbox 项和领取错误。
claimed, claimErr := store.Notifications.ClaimOutbox(context.Background(), "contract-worker", time.Now(), 1)
if claimErr != nil || len(claimed) != 1 {
t.Fatalf("领取通知 outbox 失败: items=%+v err=%v", claimed, claimErr)
}
// marked、markErr 分别表示不确定状态是否写入及写入错误。
if marked, markErr := store.Notifications.MarkOutboxUncertain(context.Background(), claimed[0].ID, "contract-worker", "contract-error"); markErr != nil || !marked {
t.Fatalf("标记不确定通知失败: marked=%v err=%v", marked, markErr)
}
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是管理员认证会话。
sessionCookie := loginHelper(t, handler)
// requests 保存用户与管理员不确定通知列表请求。
requests := []*http.Request{
httptest.NewRequest(http.MethodGet, "/api/v1/notifications/outbox/uncertain?limit=10", nil),
httptest.NewRequest(http.MethodGet, "/api/v1/admin/notifications/outbox/uncertain?limit=10", nil),
}
// request 是当前待验证的不确定通知查询请求。
for _, request := range requests {
request.AddCookie(sessionCookie)
// recorder 保存当前真实成功响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
}
// _ 使用 encoding/json 保持本文件与未来需解码的覆盖场景共用稳定依赖。
var _ = json.Valid
// testOpenAPIChatSendSuccess 使用最小聊天端口验证文字和图片成功响应的 HTTP 形状。
func testOpenAPIChatSendSuccess(t *testing.T) {
// srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// srv.applications.chat 注入只返回确定性消息的测试端口,避免调用真实账号运行时。
srv.applications.chat = contractChatPort{}
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是管理员认证会话。
sessionCookie := loginHelper(t, handler)
// textRequest 是文字消息发送请求。
textRequest := httptest.NewRequest(http.MethodPost, "/api/v1/chat/messages", strings.NewReader(`{"account_id":"acc1","chat_id":"chat","buyer_id":"buyer","text":"hello"}`))
textRequest.Header.Set("Content-Type", "application/json")
textRequest.AddCookie(sessionCookie)
// textRecorder 保存文字发送响应。
textRecorder := httptest.NewRecorder()
handler.ServeHTTP(textRecorder, textRequest)
assertOpenAPIRecordedSuccessResponse(t, textRequest, textRecorder)
// imageBody 保存图片发送请求的 multipart 内容。
var imageBody bytes.Buffer
// imageWriter 负责写入图片发送字段。
imageWriter := multipart.NewWriter(&imageBody)
_ = imageWriter.WriteField("account_id", "acc1")
_ = imageWriter.WriteField("chat_id", "chat")
_ = imageWriter.WriteField("buyer_id", "buyer")
// imageFile 是聊天图片表单文件。
imageFile, imageErr := imageWriter.CreatePart(textproto.MIMEHeader{"Content-Disposition": []string{`form-data; name="image"; filename="chat.png"`}, "Content-Type": []string{"image/png"}})
if imageErr != nil {
t.Fatalf("创建聊天图片失败: %v", imageErr)
}
_, _ = imageFile.Write([]byte{0x89, 0x50, 0x4e, 0x47})
_ = imageWriter.Close()
// imageRequest 是图片发送版本化请求。
imageRequest := httptest.NewRequest(http.MethodPost, "/api/v1/chat/images", &imageBody)
imageRequest.Header.Set("Content-Type", imageWriter.FormDataContentType())
imageRequest.AddCookie(sessionCookie)
// imageRecorder 保存图片发送响应。
imageRecorder := httptest.NewRecorder()
handler.ServeHTTP(imageRecorder, imageRequest)
assertOpenAPIRecordedSuccessResponse(t, imageRequest, imageRecorder)
}
// testOpenAPIItemSyncSuccess 使用本地 MTOP 返回商品列表,验证全量和分页同步响应。
func testOpenAPIItemSyncSuccess(t *testing.T) {
// srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// client 是返回最小有效商品卡片的本地 MTOP 客户端。
client := mtop.NewClient()
client.HTTPClient = &http.Client{Transport: roundTripFunc(func(request *http.Request) (*http.Response, error) {
// request 是同步请求;返回值只包含本地同步需要的非敏感商品字段。
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`{"ret":["SUCCESS::调用成功"],"data":{"cardList":[{"cardData":{"id":"sync-contract","title":"同步商品","priceInfo":{"price":"10.00","preText":"¥"},"picInfo":{"picUrl":"https://img.example/s.png"},"detailParams":{"itemId":"sync-contract"}}}]}}`)), Request: request}, nil
})}
setTestMTop(srv, client)
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是管理员认证会话。
sessionCookie := loginHelper(t, handler)
// requests 保存全量和分页同步请求。
requests := []*http.Request{
httptest.NewRequest(http.MethodPost, "/api/v1/items/get-all-from-account", strings.NewReader(`{"cookie_id":"acc1","page_size":10}`)),
httptest.NewRequest(http.MethodPost, "/api/v1/items/get-by-page", strings.NewReader(`{"cookie_id":"acc1","page_number":1,"page_size":10}`)),
}
// request 是当前同步请求。
for _, request := range requests {
request.Header.Set("Content-Type", "application/json")
request.AddCookie(sessionCookie)
// recorder 保存真实同步响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
}
// testOpenAPIItemPublishSuccess 注入商品发布端口并验证 multipart 发布成功响应。
func testOpenAPIItemPublishSuccess(t *testing.T) {
// srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.applications.itemSinglePublish = contractItemPublishPort{}
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是管理员认证会话。
sessionCookie := loginHelper(t, handler)
// body 保存发布接口要求的 multipart 字段。
var body bytes.Buffer
// writer 负责组装发布表单。
writer := multipart.NewWriter(&body)
_ = writer.WriteField("cookie_id", "acc1")
_ = writer.WriteField("title", "契约发布")
_ = writer.WriteField("price", "10.00")
_ = writer.WriteField("original_price", "10.00")
_ = writer.WriteField("quantity", "1")
// image 是发布图片表单写入器。
image, imageErr := writer.CreatePart(textproto.MIMEHeader{"Content-Disposition": []string{`form-data; name="images"; filename="contract.png"`}, "Content-Type": []string{"image/png"}})
if imageErr != nil {
t.Fatalf("创建发布图片失败: %v", imageErr)
}
_, _ = image.Write([]byte{0x89, 0x50, 0x4e, 0x47})
_ = writer.Close()
// request 是真实版本化商品发布请求。
request := httptest.NewRequest(http.MethodPost, "/api/v1/items/publish", &body)
request.Header.Set("Content-Type", writer.FormDataContentType())
request.AddCookie(sessionCookie)
// recorder 保存真实发布响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
// testOpenAPIBatchLifecycleSuccess 通过预检批次覆盖批次查询、取消和删除成功响应。
func testOpenAPIBatchLifecycleSuccess(t *testing.T) {
// srv、store、cleanup 分别是服务、批次状态夹具存储和资源释放函数。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是管理员认证会话。
sessionCookie := loginHelper(t, handler)
// batchID 是真实预检批次标识。
batchID := previewPublishBatch(t, handler, sessionCookie)
// requests 保存批次详情、取消和删除请求;取消后批次可安全删除。
requests := []*http.Request{
httptest.NewRequest(http.MethodGet, "/api/v1/items/publish-batches/"+batchID, nil),
httptest.NewRequest(http.MethodPost, "/api/v1/items/publish-batches/"+batchID+"/cancel", nil),
httptest.NewRequest(http.MethodDelete, "/api/v1/items/publish-batches/"+batchID, nil),
}
// request 是当前批次生命周期请求。
for _, request := range requests {
request.AddCookie(sessionCookie)
// recorder 保存当前批次成功响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
// startBatchID 是另一条真实预检批次标识,专门覆盖启动 operation。
startBatchID := previewPublishBatch(t, handler, sessionCookie)
// startRequest 是启动批量发布的版本化请求。
startRequest := httptest.NewRequest(http.MethodPost, "/api/v1/items/publish-batches", strings.NewReader(`{"preview_id":"`+startBatchID+`"}`))
startRequest.Header.Set("Content-Type", "application/json")
startRequest.AddCookie(sessionCookie)
// startRecorder 保存启动响应。
startRecorder := httptest.NewRecorder()
handler.ServeHTTP(startRecorder, startRequest)
assertOpenAPIRecordedSuccessResponse(t, startRequest, startRecorder)
// retryBatchID 是预置为失败状态的批次标识,确保重试 operation 真实进入成功分支。
retryBatchID := previewPublishBatch(t, handler, sessionCookie)
// updateErr 表示写入批次失败终态失败。
if _, updateErr := store.DB.ExecContext(context.Background(), `UPDATE item_publish_batches SET status='failed',failed_count=1 WHERE id=?`, retryBatchID); updateErr != nil {
t.Fatalf("设置重试批次状态失败: %v", updateErr)
}
// updateErr 表示写入失败批次明细失败。
if _, updateErr := store.DB.ExecContext(context.Background(), `UPDATE item_publish_batch_rows SET status='failed',error_message='contract failure' WHERE batch_id=?`, retryBatchID); updateErr != nil {
t.Fatalf("设置重试批次明细失败: %v", updateErr)
}
// retryRequest 是重试失败明细的版本化请求。
retryRequest := httptest.NewRequest(http.MethodPost, "/api/v1/items/publish-batches/"+retryBatchID+"/retry-failed", nil)
retryRequest.AddCookie(sessionCookie)
// retryRecorder 保存重试响应。
retryRecorder := httptest.NewRecorder()
handler.ServeHTTP(retryRecorder, retryRequest)
assertOpenAPIRecordedSuccessResponse(t, retryRequest, retryRecorder)
}
// testOpenAPIAutomationResolveSuccess 写入真实死信延期任务并验证人工处理成功响应。
func testOpenAPIAutomationResolveSuccess(t *testing.T) {
// srv、store、cleanup 分别是服务、自动化夹具存储和资源释放函数。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// ruleResult、ruleErr 保存异常运行归属规则的插入结果。
ruleResult, ruleErr := store.DB.ExecContext(context.Background(), `INSERT INTO automation_rules (user_id,cookie_id,name,trigger_type,enabled,config_json) VALUES (1,'acc1','contract-rule','order_paid',1,'{}')`)
if ruleErr != nil {
t.Fatalf("写入自动化规则失败: %v", ruleErr)
}
// ruleID、ruleIDErr 保存异常运行归属规则主键及读取错误。
ruleID, ruleIDErr := ruleResult.LastInsertId()
if ruleIDErr != nil {
t.Fatalf("读取自动化规则主键失败: %v", ruleIDErr)
}
// runResult、runErr 保存待处理异常运行的插入结果。
runResult, runErr := store.DB.ExecContext(context.Background(), `INSERT INTO automation_runs (rule_id,cookie_id,trigger_type,trigger_key,status,raw_event_json,error_message) VALUES (?,?,?,'contract-run','needs_review','{"AccountID":"acc1"}','contract failure')`, ruleID, "acc1", "order_paid")
if runErr != nil {
t.Fatalf("写入自动化异常运行失败: %v", runErr)
}
// runID、runIDErr 保存待处理异常运行主键及读取错误。
runID, runIDErr := runResult.LastInsertId()
if runIDErr != nil {
t.Fatalf("读取自动化异常运行主键失败: %v", runIDErr)
}
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是管理员认证会话。
sessionCookie := loginHelper(t, handler)
// runRequest 是取消异常运行的版本化请求。
runRequest := httptest.NewRequest(http.MethodPost, "/api/v1/automation-runs/"+strconv.FormatInt(runID, 10)+"/resolve", strings.NewReader(`{"resolution":"cancel"}`))
runRequest.Header.Set("Content-Type", "application/json")
runRequest.AddCookie(sessionCookie)
// runRecorder 保存异常运行处理响应。
runRecorder := httptest.NewRecorder()
handler.ServeHTTP(runRecorder, runRequest)
assertOpenAPIRecordedSuccessResponse(t, runRequest, runRecorder)
// insertErr 表示写入死信延期任务失败。
_, insertErr := store.DB.ExecContext(context.Background(), `INSERT INTO automation_pending_tasks (task_key,cookie_id,trigger_type,task_json,status,attempt_count,error_message) VALUES ('contract-task','acc1','contract','{}','dead_letter',3,'failed')`)
if insertErr != nil {
t.Fatalf("写入自动化死信任务失败: %v", insertErr)
}
// taskID 保存刚刚写入的延期任务主键。
var taskID int64
// scanErr 表示读取延期任务主键失败。
if scanErr := store.DB.QueryRowContext(context.Background(), `SELECT id FROM automation_pending_tasks WHERE task_key='contract-task'`).Scan(&taskID); scanErr != nil {
t.Fatalf("读取自动化任务标识失败: %v", scanErr)
}
// request 是驳回延期任务的版本化请求。
request := httptest.NewRequest(http.MethodPost, "/api/v1/automation-pending-tasks/"+strconv.FormatInt(taskID, 10)+"/resolve", strings.NewReader(`{"resolution":"dismiss"}`))
request.Header.Set("Content-Type", "application/json")
request.AddCookie(sessionCookie)
// recorder 保存真实人工处理响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
// testOpenAPINotificationChannelTestSuccess 验证通知渠道测试的真实网络成功响应。
func testOpenAPINotificationChannelTestSuccess(t *testing.T) {
// endpoint 是接收通知测试请求的本地 Webhook。
endpoint := httptest.NewServer(http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) {
responseWriter.WriteHeader(http.StatusNoContent)
}))
defer endpoint.Close()
// srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// srv.applications.notificationChannels 注入成功替身,避免测试依赖进程级通知器。
srv.applications.notificationChannels = contractNotificationChannelsPort{}
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是管理员认证会话。
sessionCookie := loginHelper(t, handler)
// createRequest 创建本地 Webhook 渠道。
createRequest := httptest.NewRequest(http.MethodPost, "/api/v1/notifications/channels", strings.NewReader(`{"name":"契约Webhook","type":"webhook","config":"{\"url\":\"`+endpoint.URL+`\"}","enabled":true}`))
createRequest.Header.Set("Content-Type", "application/json")
createRequest.AddCookie(sessionCookie)
// createRecorder 保存渠道创建响应。
createRecorder := httptest.NewRecorder()
handler.ServeHTTP(createRecorder, createRequest)
assertOpenAPIRecordedSuccessResponse(t, createRequest, createRecorder)
// channelID 保存创建响应中的渠道主键。
var created struct {
ID int64 `json:"id"`
}
// decodeErr 表示解析通知渠道创建响应失败。
if decodeErr := json.Unmarshal(createRecorder.Body.Bytes(), &created); decodeErr != nil || created.ID <= 0 {
t.Fatalf("渠道创建响应无效: %s", createRecorder.Body.String())
}
// testRequest 是调用渠道测试的版本化请求。
testRequest := httptest.NewRequest(http.MethodPost, "/api/v1/notifications/channels/"+strconv.FormatInt(created.ID, 10)+"/test", nil)
testRequest.AddCookie(sessionCookie)
// testRecorder 保存渠道测试成功响应。
testRecorder := httptest.NewRecorder()
handler.ServeHTTP(testRecorder, testRequest)
assertOpenAPIRecordedSuccessResponse(t, testRequest, testRecorder)
}
// testOpenAPIAccountTaskRunSuccess 注入账号任务端口并验证手动运行响应。
func testOpenAPIAccountTaskRunSuccess(t *testing.T) {
// srv、_、cleanup 分别是服务、无需直接读取的存储和资源释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.applications.accountTasks = contractAccountTasksPort{}
// handler 是当前场景的真实 Router。
handler := srv.Router()
// sessionCookie 是管理员认证会话。
sessionCookie := loginHelper(t, handler)
// request 是手动自动评价运行请求。
request := httptest.NewRequest(http.MethodPost, "/api/v1/account-tasks/acc1/run", strings.NewReader(`{"task_type":"auto_rate"}`))
request.Header.Set("Content-Type", "application/json")
request.AddCookie(sessionCookie)
// recorder 保存任务运行响应。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
// contractChatPort 是只返回确定性消息的聊天 HTTP 应用端口。
type contractChatPort struct{}
// SendingAvailable 报告测试端口支持文字发送。
func (contractChatPort) SendingAvailable() bool { return true }
// ImageUploadAvailable 报告测试端口支持图片上传。
func (contractChatPort) ImageUploadAvailable() bool { return true }
// Subscribe 返回空事件流,当前场景不验证 WebSocket。
func (contractChatPort) Subscribe(context.Context, int64) (<-chan chatapp.Event, func(), error) {
return nil, func() {}, nil
}
// RefreshConversations 返回空联系人页。
func (contractChatPort) RefreshConversations(context.Context, string, int64, int) (chatapp.ConversationPage, error) {
return chatapp.ConversationPage{}, nil
}
// RefreshHistory 返回不可用错误,使查询回退本地存储。
func (contractChatPort) RefreshHistory(context.Context, string, string, int64, int, chatapp.Session) (chatapp.HistoryPage, error) {
return chatapp.HistoryPage{}, chatapp.ErrRefreshUnavailable
}
// SendText 返回确定性外发消息。
func (contractChatPort) SendText(context.Context, chatapp.OutgoingInput) (*chatapp.Message, error) {
return &chatapp.Message{AccountID: "acc1", ChatID: "chat", MessageKey: "contract-message", Direction: "outgoing", MessageType: "text", Content: "hello", Status: "sent"}, nil
}
// SendImage 返回确定性外发图片消息。
func (contractChatPort) SendImage(context.Context, chatapp.ImageInput) (*chatapp.Message, error) {
return &chatapp.Message{AccountID: "acc1", ChatID: "chat", MessageKey: "contract-image", Direction: "outgoing", MessageType: "image", Content: "https://img.example/i.png", Status: "sent"}, nil
}
// ListStoredMessages 返回空消息页。
func (contractChatPort) ListStoredMessages(context.Context, int64, string, string, int64, int) (chatapp.Page, error) {
return chatapp.Page{}, nil
}
// ListSessions 返回空会话集合。
func (contractChatPort) ListSessions(context.Context, int64, string, int) ([]chatapp.Session, error) {
return nil, nil
}
// FindSession 返回空会话。
func (contractChatPort) FindSession(context.Context, int64, string, string) (chatapp.Session, error) {
return chatapp.Session{}, nil
}
// ResolveReadMessageID 返回有效测试平台消息标识。
func (contractChatPort) ResolveReadMessageID(context.Context, string, string, string) string {
return "contract.PNM"
}
// CleanupEmptySessions 在测试端口中无副作用。
func (contractChatPort) CleanupEmptySessions(context.Context, string) error { return nil }
// OwnsAccount 始终确认测试账号归属。
func (contractChatPort) OwnsAccount(context.Context, int64, string) (bool, error) { return true, nil }
// MarkRead 确认本地已读更新成功。
func (contractChatPort) MarkRead(context.Context, int64, string, string) error { return nil }
// ReportPlatformRead 确认平台已读上报成功。
func (contractChatPort) ReportPlatformRead(context.Context, string, string, []map[string]any) error {
return nil
}
// ResolveSessionIdentity 保持测试会话为空。
func (contractChatPort) ResolveSessionIdentity(context.Context, chatapp.Session) (chatapp.Session, error) {
return chatapp.Session{}, nil
}
// RefreshSessionIdentities 返回空会话集合。
func (contractChatPort) RefreshSessionIdentities(context.Context, string, []chatapp.Session) ([]chatapp.Session, error) {
return nil, nil
}
// contractItemPublishPort 是只返回确定性商品结果的单商品发布端口。
type contractItemPublishPort struct{}
// PublishSingle 返回确定性远端发布结果。
func (contractItemPublishPort) PublishSingle(context.Context, itemapp.PublishInput) (itemapp.PublishOutcome, error) {
return itemapp.PublishOutcome{Result: &itemapp.PublishResult{ItemID: "contract-published", ItemURL: "https://item.example/contract", Title: "契约发布", PriceText: "10.00", Quantity: 1}}, nil
}
// contractAccountTasksPort 是只返回确定性统计结果的账号任务端口。
type contractAccountTasksPort struct{}
// contractNotificationChannelsPort 是只覆盖渠道测试动作的通知渠道端口。
type contractNotificationChannelsPort struct{ NotificationChannelsPort }
// CreateChannel 返回固定渠道标识,使后续测试请求仍通过真实 HTTP handler。
func (contractNotificationChannelsPort) CreateChannel(context.Context, int64, notificationsapp.ChannelInput) (int64, error) {
return 1, nil
}
// TestChannel 将渠道测试视为已由本地替身成功发送。
func (contractNotificationChannelsPort) TestChannel(context.Context, int64, int64, time.Time) error {
return nil
}
// GetSettings 返回测试账号默认任务设置。
func (contractAccountTasksPort) GetSettings(context.Context, string) (automationapp.AccountTaskSettings, error) {
return automationapp.AccountTaskSettings{CookieID: "acc1"}, nil
}
// UpdateSettings 返回规范化后的测试设置。
func (contractAccountTasksPort) UpdateSettings(context.Context, automationapp.AccountTaskSettings) (automationapp.AccountTaskSettings, error) {
return automationapp.AccountTaskSettings{CookieID: "acc1"}, nil
}
// ListRuns 返回空运行记录。
func (contractAccountTasksPort) ListRuns(context.Context, string, int) ([]automationapp.AccountTaskRun, error) {
return nil, nil
}
// Run 返回包含一个成功动作的任务摘要。
func (contractAccountTasksPort) Run(context.Context, string, string) (automationapp.TaskSummary, error) {
return automationapp.TaskSummary{TaskType: automationapp.TaskAutoRate, Success: 1}, nil
}
@@ -3,10 +3,13 @@ package server
import (
"bytes"
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"path/filepath"
"sort"
"strconv"
"strings"
"testing"
@@ -15,6 +18,74 @@ import (
"github.com/getkin/kin-openapi/routers/legacy"
)
// TestOpenAPISuccessContractCoverage 从唯一 OpenAPI 文档自动枚举普通 operation,确认每个 operation 都有真实成功响应断言记录。
func TestOpenAPISuccessContractCoverage(t *testing.T) {
// scenarios 是按领域组织的真实 Router 成功场景;覆盖集合由每次成功断言的 operationId 自动产生。
scenarios := []struct {
// name 是失败输出使用的稳定领域名称。
name string
// run 会执行该领域完整的真实 HTTP 成功场景。
run func(*testing.T)
}{
{name: "session-and-qr", run: TestOpenAPISessionAndQRResponses},
{name: "accounts-and-system", run: TestOpenAPIAccountAndSystemResponses},
{name: "query-chat-orders", run: TestOpenAPIQueryChatAndOrderResponses},
{name: "items-and-cards", run: TestOpenAPIItemAndCardResponses},
{name: "notifications", run: TestOpenAPINotificationResponses},
{name: "versioned-session", run: TestVersionedSessionRoutesPreserveLegacyContracts},
{name: "versioned-account", run: TestVersionedAccountRoutesPreserveLegacyContracts},
{name: "versioned-account-credentials", run: TestVersionedAccountCredentialRoutesPreserveLegacyContracts},
{name: "versioned-account-settings", run: TestVersionedAccountSettingsRoutesPreserveLegacyContracts},
{name: "versioned-items", run: TestVersionedItemRoutesPreserveLegacyContracts},
{name: "versioned-orders", run: TestVersionedOrderRoutesPreserveLegacyContracts},
{name: "versioned-order-refresh", run: TestVersionedOrderRefreshAndBatchRoutesPreserveLegacyContracts},
{name: "versioned-qr", run: TestVersionedQRLoginRoutesPreserveLegacyContracts},
{name: "versioned-admin-analytics", run: TestVersionedAdminAnalyticsRoutesPreserveLegacyContracts},
{name: "versioned-settings-cards-notifications", run: TestVersionedSettingsCardNotificationRoutesPreserveLegacyContracts},
{name: "versioned-item-batches", run: TestVersionedItemBatchRoutesPreserveLegacyContracts},
{name: "versioned-chat-tasks", run: TestVersionedChatTaskRoutesPreserveLegacyContracts},
{name: "versioned-replies", run: TestVersionedReplyRoutesPreserveLegacyContracts},
{name: "versioned-remaining", run: TestVersionedRemainingRoutesPreserveLegacyContracts},
{name: "named-success", run: TestNamedSuccessResponseContracts},
{name: "remaining-success", run: TestRemainingSuccessResponseContracts},
{name: "settings-cards-notifications-batch", run: TestSettingsCardsNotificationsBatchContracts},
{name: "dynamic-success", run: TestDynamicCompatibilitySuccessContracts},
{name: "reply-and-account-task-success", run: TestReplyAndAccountTaskSuccessResponseContracts},
{name: "analytics-admin-public-success", run: TestAnalyticsAdminAndPublicSuccessResponseContracts},
{name: "local-resource-mutations", run: TestOpenAPILocalResourceMutationResponses},
{name: "remaining-versioned-success", run: TestOpenAPIRemainingVersionedSuccessResponses},
}
// scenario 是当前执行的领域真实响应场景。
for _, scenario := range scenarios {
// scenario 保存当前领域成功场景,子测试名称和执行函数必须保持同一实例。
scenario := scenario
t.Run(scenario.name, func(t *testing.T) {
scenario.run(t)
})
}
// document 是包含全部 operation 的唯一 OpenAPI 契约。
document := loadOpenAPIContractForCoverage(t)
// missing 保存未被成功断言记录、且没有显式特殊校验的 operationId。
missing := make([]string, 0)
for _, path := range document.Paths.Keys() { // path 是当前 OpenAPI 路径模板。
// pathItem 保存该模板下声明的全部 HTTP operation。
pathItem := document.Paths.Find(path)
for _, operation := range pathItem.Operations() { // operation 是当前待检查的 OpenAPI operation。
if openAPIContractSuccessExceptionKind(operation) != "" {
continue
}
// exists 表示该 operation 是否已由真实成功响应记录。
if _, exists := openAPISuccessOperations.Load(operation.OperationID); !exists {
missing = append(missing, operation.OperationID)
}
}
}
sort.Strings(missing)
if len(missing) > 0 {
t.Fatalf("缺少真实成功响应契约场景: %s", strings.Join(missing, ", "))
}
}
// assertOpenAPIResponse 验证真实 HTTP 响应的状态码、Content-Type 和 JSON 形状符合对应 OpenAPI operation。
func assertOpenAPIResponse(t *testing.T, request *http.Request, recorder *httptest.ResponseRecorder) {
t.Helper()
@@ -57,6 +128,9 @@ func assertOpenAPISuccessResponse(t *testing.T, request *http.Request, recorder
t.Fatalf("成功响应状态错误: %s %s status=%d body=%s", request.Method, request.URL.Path, recorder.Code, recorder.Body.String())
}
assertOpenAPIResponse(t, request, recorder)
// operationID 是从请求匹配的 OpenAPI operation 读取的稳定成功覆盖键。
operationID := openAPIOperationIDForRequest(t, request)
openAPISuccessOperations.Store(operationID, struct{}{})
}
// assertOpenAPIExpectedStatusResponse 验证非 200 成功状态的真实响应仍符合 operation 契约。
@@ -66,6 +140,127 @@ func assertOpenAPIExpectedStatusResponse(t *testing.T, request *http.Request, re
t.Fatalf("成功响应状态错误: %s %s status=%d want=%d body=%s", request.Method, request.URL.Path, recorder.Code, wantStatus, recorder.Body.String())
}
assertOpenAPIResponse(t, request, recorder)
// operationID 是从请求匹配的 OpenAPI operation 读取的稳定成功覆盖键。
operationID := openAPIOperationIDForRequest(t, request)
openAPISuccessOperations.Store(operationID, struct{}{})
}
// assertOpenAPIRecordedSuccessResponse 验证任意 2xx 的真实响应并记录其 operationId,供已存在的兼容路由成功场景复用。
func assertOpenAPIRecordedSuccessResponse(t *testing.T, request *http.Request, recorder *httptest.ResponseRecorder) {
t.Helper()
if recorder.Code < http.StatusOK || recorder.Code >= http.StatusMultipleChoices {
t.Fatalf("成功响应状态错误: %s %s status=%d body=%s", request.Method, request.URL.Path, recorder.Code, recorder.Body.String())
}
assertOpenAPIResponse(t, request, recorder)
// operationID 是从成功请求匹配出的稳定 OpenAPI operation 标识。
operationID := openAPIOperationIDForRequest(t, request)
openAPISuccessOperations.Store(operationID, struct{}{})
}
// contractRecordingHandler 在契约覆盖场景中捕获版本化成功响应,避免手写 operation 名单或遗漏断言点。
func contractRecordingHandler(t *testing.T, next http.Handler) http.Handler {
t.Helper()
return http.HandlerFunc(func(responseWriter http.ResponseWriter, request *http.Request) {
// recorder 暂存真实 handler 的完整响应,便于校验后再复制到调用方记录器。
recorder := httptest.NewRecorder()
next.ServeHTTP(recorder, request)
// headerValue 表示真实 handler 写出的响应头值集合。
for headerName, headerValues := range recorder.Header() {
responseWriter.Header()[headerName] = append([]string(nil), headerValues...)
}
responseWriter.WriteHeader(recorder.Code)
_, _ = responseWriter.Write(recorder.Body.Bytes())
if (strings.HasPrefix(request.URL.Path, "/api/v1/") || request.URL.Path == "/health") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices {
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
})
}
// serveOpenAPISuccess 以真实 Router 执行一个本地可确定的版本化成功请求,并记录 operationId 作为覆盖证据。
func serveOpenAPISuccess(t *testing.T, handler http.Handler, sessionCookie *http.Cookie, method string, path string, body string) *httptest.ResponseRecorder {
t.Helper()
// request 是本次本地资源生命周期操作使用的版本化 HTTP 请求。
request := httptest.NewRequest(method, path, strings.NewReader(body))
if body != "" {
request.Header.Set("Content-Type", "application/json")
}
if sessionCookie != nil {
request.AddCookie(sessionCookie)
}
// recorder 保存真实 handler 的完整成功响应,供 OpenAPI 校验和调用方业务断言复用。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
return recorder
}
// openAPIOperationIDForRequest 使用唯一 OpenAPI 文档匹配真实请求并返回稳定 operationId。
func openAPIOperationIDForRequest(t *testing.T, request *http.Request) string {
t.Helper()
// specPath 是从 Server 测试目录定位到唯一 OpenAPI 契约文件的路径。
specPath := filepath.Join("..", "..", "api", "openapi.yaml")
// document、loadErr 分别是解析后的 OpenAPI 文档及其加载失败原因。
document, loadErr := openapi3.NewLoader().LoadFromFile(specPath)
if loadErr != nil {
t.Fatalf("加载 OpenAPI 契约失败: %v", loadErr)
}
// router、routerErr 分别是请求与 operation 匹配使用的 OpenAPI 路由器及其构建错误。
router, routerErr := legacy.NewRouter(document)
if routerErr != nil {
t.Fatalf("构建 OpenAPI 路由器失败: %v", routerErr)
}
// route、_、findErr 分别是匹配结果、无需读取的路径参数和路由匹配失败原因。
route, _, findErr := router.FindRoute(request)
if findErr != nil || route.Operation == nil || route.Operation.OperationID == "" {
t.Fatalf("读取成功响应 operationId 失败: %s %s err=%v", request.Method, request.URL.Path, findErr)
}
return route.Operation.OperationID
}
// openAPIContractSuccessExceptionKind 返回 operation 显式登记的特殊成功校验类别;普通 HTTP operation 返回空字符串。
func openAPIContractSuccessExceptionKind(operation *openapi3.Operation) string {
if operation == nil || operation.Extensions == nil {
return ""
}
// exception、valid 分别是 YAML 扩展对象及其是否符合受限结构。
exception, valid := operation.Extensions["x-contract-success-exception"].(map[string]any)
if !valid {
return ""
}
// kind、valid 分别是特殊校验类别及其是否为稳定字符串。
kind, valid := exception["kind"].(string)
if !valid {
return ""
}
return kind
}
// TestOpenAPIPasswordLoginDisabledOperations 验证永久关闭的密码登录 operation 真实返回 501 统一错误,而非伪造 2xx 成功响应。
func TestOpenAPIPasswordLoginDisabledOperations(t *testing.T) {
// srv、_、cleanup 分别是独立测试 Server、无需直接读取的存储和资源释放函数。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是承载版本化密码登录关闭策略的真实 chi Router。
handler := srv.Router()
// sessionCookie 是访问受保护密码登录 operation 所需的管理员认证会话。
sessionCookie := loginHelper(t, handler)
// requests 保存三个永久关闭 operation 的最小版本化请求。
requests := []*http.Request{
httptest.NewRequest(http.MethodPost, "/api/v1/password-login", strings.NewReader(`{"account_id":"acc1","account":"contract-user","password":"not-a-real-secret"}`)),
httptest.NewRequest(http.MethodGet, "/api/v1/password-login/check/contract-session", nil),
httptest.NewRequest(http.MethodDelete, "/api/v1/password-login/cancel/contract-session", nil),
}
// request 是当前待验证的永久关闭版本化 operation 请求。
for _, request := range requests {
request.AddCookie(sessionCookie)
// recorder 捕获关闭策略的实际 HTTP 状态、Content-Type 和统一错误响应体。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if recorder.Code != http.StatusNotImplemented {
t.Fatalf("永久关闭 operation 状态错误: %s %s status=%d body=%s", request.Method, request.URL.Path, recorder.Code, recorder.Body.String())
}
assertOpenAPIResponse(t, request, recorder)
}
}
// TestOpenAPISessionAndQRResponses 验证阶段二会话与二维码主链路的成功、未认证和风控响应均满足真实契约。
@@ -333,6 +528,53 @@ func TestOpenAPIItemAndCardResponses(t *testing.T) {
handler.ServeHTTP(cardsRecorder, cardsRequest)
assertOpenAPISuccessResponse(t, cardsRequest, cardsRecorder)
// createCardRequest 是创建 data 卡券的版本化请求,供后续资源生命周期操作复用。
createCardRequest := httptest.NewRequest(http.MethodPost, "/api/v1/cards", strings.NewReader(`{"name":"OpenAPI 数据卡","type":"data","data_content":"K1","enabled":true}`))
createCardRequest.AddCookie(sessionCookie)
// createCardRecorder 捕获创建操作的具名数值主键响应。
createCardRecorder := httptest.NewRecorder()
handler.ServeHTTP(createCardRecorder, createCardRequest)
assertOpenAPISuccessResponse(t, createCardRequest, createCardRecorder)
// createdCard 保存创建操作返回的数值主键,后续请求必须使用真实归属资源。
var createdCard struct {
// ID 是本次生命周期中由服务端分配的卡券标识。
ID int64 `json:"id"`
}
// decodeErr 表示无法从已校验响应中读取资源标识的失败原因。
if decodeErr := json.Unmarshal(createCardRecorder.Body.Bytes(), &createdCard); decodeErr != nil || createdCard.ID <= 0 {
t.Fatalf("读取创建卡券标识失败: id=%d err=%v", createdCard.ID, decodeErr)
}
// cardID 是 URL 路径使用的真实卡券标识字符串。
cardID := strconv.FormatInt(createdCard.ID, 10)
// getCardRequest 是读取刚创建资源详情的成功请求。
getCardRequest := httptest.NewRequest(http.MethodGet, "/api/v1/cards/"+cardID, nil)
getCardRequest.AddCookie(sessionCookie)
// getCardRecorder 捕获详情 DTO,验证不再错误使用通用成功 envelope。
getCardRecorder := httptest.NewRecorder()
handler.ServeHTTP(getCardRecorder, getCardRequest)
assertOpenAPISuccessResponse(t, getCardRequest, getCardRecorder)
// updateCardRequest 是更新同一 data 卡券的成功请求。
updateCardRequest := httptest.NewRequest(http.MethodPut, "/api/v1/cards/"+cardID, strings.NewReader(`{"name":"OpenAPI 数据卡更新","type":"data","data_content":"K1","enabled":true}`))
updateCardRequest.AddCookie(sessionCookie)
// updateCardRecorder 捕获更新成功响应。
updateCardRecorder := httptest.NewRecorder()
handler.ServeHTTP(updateCardRecorder, updateCardRequest)
assertOpenAPISuccessResponse(t, updateCardRequest, updateCardRecorder)
// appendCardRequest 是为 data 卡券追加库存的成功请求。
appendCardRequest := httptest.NewRequest(http.MethodPost, "/api/v1/cards/"+cardID+"/append-data", strings.NewReader(`{"content":"K2\nK3"}`))
appendCardRequest.AddCookie(sessionCookie)
// appendCardRecorder 捕获追加数量响应。
appendCardRecorder := httptest.NewRecorder()
handler.ServeHTTP(appendCardRecorder, appendCardRequest)
assertOpenAPISuccessResponse(t, appendCardRequest, appendCardRecorder)
// deleteCardRequest 是删除同一资源的成功请求,保证测试不依赖虚构路径参数。
deleteCardRequest := httptest.NewRequest(http.MethodDelete, "/api/v1/cards/"+cardID, nil)
deleteCardRequest.AddCookie(sessionCookie)
// deleteCardRecorder 捕获删除成功响应。
deleteCardRecorder := httptest.NewRecorder()
handler.ServeHTTP(deleteCardRecorder, deleteCardRequest)
assertOpenAPISuccessResponse(t, deleteCardRequest, deleteCardRecorder)
// invalidUploadRequest 是缺失文件的卡券上传请求,必须返回统一错误 envelope。
invalidUploadRequest := httptest.NewRequest(http.MethodPost, "/api/v1/cards/batch", strings.NewReader("--openapi--\r\n"))
invalidUploadRequest.Header.Set("Content-Type", "multipart/form-data; boundary=openapi")
@@ -370,4 +612,37 @@ func TestOpenAPINotificationResponses(t *testing.T) {
bindingsRecorder := httptest.NewRecorder()
handler.ServeHTTP(bindingsRecorder, bindingsRequest)
assertOpenAPISuccessResponse(t, bindingsRequest, bindingsRecorder)
// createChannelRequest 是创建通知渠道的版本化成功请求,配置字段只使用测试占位值。
createChannelRequest := httptest.NewRequest(http.MethodPost, "/api/v1/notifications/channels", strings.NewReader(`{"name":"OpenAPI 渠道","type":"webhook","config":"{}","event_types":"[]","enabled":true}`))
createChannelRequest.AddCookie(sessionCookie)
// createChannelRecorder 捕获渠道创建返回的数值主键。
createChannelRecorder := httptest.NewRecorder()
handler.ServeHTTP(createChannelRecorder, createChannelRequest)
assertOpenAPISuccessResponse(t, createChannelRequest, createChannelRecorder)
// createdChannel 保存创建响应中的渠道标识。
var createdChannel struct {
// ID 是服务端分配的通知渠道主键。
ID int64 `json:"id"`
}
// channelDecodeErr 表示创建响应无法解析为具名主键 DTO 的失败原因。
if channelDecodeErr := json.Unmarshal(createChannelRecorder.Body.Bytes(), &createdChannel); channelDecodeErr != nil || createdChannel.ID <= 0 {
t.Fatalf("读取通知渠道标识失败: id=%d err=%v", createdChannel.ID, channelDecodeErr)
}
// channelID 是通知渠道路径参数的稳定字符串形式。
channelID := strconv.FormatInt(createdChannel.ID, 10)
// updateChannelRequest 是仅切换启用状态的部分更新成功请求。
updateChannelRequest := httptest.NewRequest(http.MethodPut, "/api/v1/notifications/channels/"+channelID, strings.NewReader(`{"enabled":false}`))
updateChannelRequest.AddCookie(sessionCookie)
// updateChannelRecorder 捕获渠道更新成功响应。
updateChannelRecorder := httptest.NewRecorder()
handler.ServeHTTP(updateChannelRecorder, updateChannelRequest)
assertOpenAPISuccessResponse(t, updateChannelRequest, updateChannelRecorder)
// deleteChannelRequest 是删除已归属通知渠道的成功请求。
deleteChannelRequest := httptest.NewRequest(http.MethodDelete, "/api/v1/notifications/channels/"+channelID, nil)
deleteChannelRequest.AddCookie(sessionCookie)
// deleteChannelRecorder 捕获渠道删除成功响应。
deleteChannelRecorder := httptest.NewRecorder()
handler.ServeHTTP(deleteChannelRecorder, deleteChannelRequest)
assertOpenAPISuccessResponse(t, deleteChannelRequest, deleteChannelRecorder)
}
+10
View File
@@ -735,6 +735,16 @@ func TestDownloadItemPublishBatchResultExportsRows(t *testing.T) {
if !strings.HasPrefix(body, "\xEF\xBB\xBF") || !strings.Contains(body, "行号") || !strings.Contains(body, "商品A") || !strings.Contains(body, "item-1") {
t.Fatalf("导出 CSV 内容异常: %q", body)
}
// versionedRequest 使用与旧入口相同的已完成批次,验证二进制特殊 operation 的真实成功响应。
versionedRequest := httptest.NewRequest(http.MethodGet, "/api/v1/items/publish-batches/"+batchID+"/result.csv", nil)
versionedRequest.AddCookie(cookie)
// versionedRecorder 捕获版本化 CSV 下载响应,供 OpenAPI 校验状态、Content-Type 与二进制 schema。
versionedRecorder := httptest.NewRecorder()
h.ServeHTTP(versionedRecorder, versionedRequest)
assertOpenAPISuccessResponse(t, versionedRequest, versionedRecorder)
if !strings.HasPrefix(versionedRecorder.Header().Get("Content-Type"), "text/csv") {
t.Fatalf("版本化 CSV Content-Type=%q", versionedRecorder.Header().Get("Content-Type"))
}
}
// TestDownloadItemPublishBatchResultHidesOtherUserBatch 验证结果下载不会泄露其他用户的批次存在性。
+160 -34
View File
@@ -8,6 +8,8 @@ import (
"strconv"
"strings"
"testing"
"xianyu-go/internal/db"
)
// TestNamedSuccessResponseContracts 验证认证、订单和聊天主链路使用具名成功响应 DTO。
@@ -16,7 +18,7 @@ func TestNamedSuccessResponseContracts(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
handler := contractRecordingHandler(t, srv.Router())
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
@@ -84,7 +86,7 @@ func TestRemainingSuccessResponseContracts(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
handler := contractRecordingHandler(t, srv.Router())
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
// seedErr 是测试商品写入模板数据库失败的原因。
@@ -195,12 +197,12 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
handler := contractRecordingHandler(t, srv.Router())
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
// settingReq 是更新单个系统设置的请求。
settingReq := httptest.NewRequest(http.MethodPut, "/system-settings/theme_color", strings.NewReader(`{"value":"contract-blue"}`))
settingReq := httptest.NewRequest(http.MethodPut, "/api/v1/settings/system/theme_color", strings.NewReader(`{"value":"contract-blue"}`))
settingReq.AddCookie(sessionCookie)
// settingRecorder 是捕获系统设置响应的记录器。
settingRecorder := httptest.NewRecorder()
@@ -219,7 +221,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
}
// aiReq 是更新账号 AI 回复设置的请求。
aiReq := httptest.NewRequest(http.MethodPut, "/ai-reply-settings/acc1", strings.NewReader(`{"ai_enabled":true,"max_discount_percent":12,"max_discount_amount":88,"max_bargain_rounds":4,"custom_prompts":"契约测试"}`))
aiReq := httptest.NewRequest(http.MethodPut, "/api/v1/settings/ai-reply/acc1", strings.NewReader(`{"ai_enabled":true,"max_discount_percent":12,"max_discount_amount":88,"max_bargain_rounds":4,"custom_prompts":"契约测试"}`))
aiReq.AddCookie(sessionCookie)
// aiRecorder 是捕获账号 AI 设置响应的记录器。
aiRecorder := httptest.NewRecorder()
@@ -238,7 +240,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
}
// aiGetReq 是读取账号 AI 设置的请求。
aiGetReq := httptest.NewRequest(http.MethodGet, "/ai-reply-settings/acc1", nil)
aiGetReq := httptest.NewRequest(http.MethodGet, "/api/v1/settings/ai-reply/acc1", nil)
aiGetReq.AddCookie(sessionCookie)
// aiGetRecorder 是捕获账号 AI 设置查询响应的记录器。
aiGetRecorder := httptest.NewRecorder()
@@ -257,7 +259,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
}
// cardReq 是创建文本卡券组的请求。
cardReq := httptest.NewRequest(http.MethodPost, "/cards", strings.NewReader(`{"name":"契约卡","type":"text","text_content":"CARD","enabled":true}`))
cardReq := httptest.NewRequest(http.MethodPost, "/api/v1/cards", strings.NewReader(`{"name":"契约卡","type":"text","text_content":"CARD","enabled":true}`))
cardReq.AddCookie(sessionCookie)
// cardRecorder 是捕获卡券创建响应的记录器。
cardRecorder := httptest.NewRecorder()
@@ -276,7 +278,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
}
// cardGetReq 是读取卡券详情的请求。
cardGetReq := httptest.NewRequest(http.MethodGet, "/cards/"+strconv.FormatInt(cardCreateResponse.ID, 10), nil)
cardGetReq := httptest.NewRequest(http.MethodGet, "/api/v1/cards/"+strconv.FormatInt(cardCreateResponse.ID, 10), nil)
cardGetReq.AddCookie(sessionCookie)
// cardGetRecorder 是捕获卡券详情响应的记录器。
cardGetRecorder := httptest.NewRecorder()
@@ -295,7 +297,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
}
// channelReq 是创建通知渠道的请求。
channelReq := httptest.NewRequest(http.MethodPost, "/notification-channels", strings.NewReader(`{"name":"契约通知","type":"bark","config":"{}","enabled":true}`))
channelReq := httptest.NewRequest(http.MethodPost, "/api/v1/notifications/channels", strings.NewReader(`{"name":"契约通知","type":"bark","config":"{}","enabled":true}`))
channelReq.AddCookie(sessionCookie)
// channelRecorder 是捕获通知渠道创建响应的记录器。
channelRecorder := httptest.NewRecorder()
@@ -314,7 +316,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
}
// bindingReq 是将通知渠道绑定到测试账号的请求。
bindingReq := httptest.NewRequest(http.MethodPost, "/message-notifications/acc1", strings.NewReader(`{"channel_ids":[`+strconv.FormatInt(channelResponse.ID, 10)+`]}`))
bindingReq := httptest.NewRequest(http.MethodPost, "/api/v1/notifications/accounts/acc1/bindings", strings.NewReader(`{"channel_ids":[`+strconv.FormatInt(channelResponse.ID, 10)+`]}`))
bindingReq.AddCookie(sessionCookie)
// bindingRecorder 是捕获通知绑定响应的记录器。
bindingRecorder := httptest.NewRecorder()
@@ -333,7 +335,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
}
// bindingGetReq 是读取账号通知绑定的请求。
bindingGetReq := httptest.NewRequest(http.MethodGet, "/message-notifications/acc1", nil)
bindingGetReq := httptest.NewRequest(http.MethodGet, "/api/v1/notifications/accounts/acc1/bindings", nil)
bindingGetReq.AddCookie(sessionCookie)
// bindingGetRecorder 是捕获账号通知绑定响应的记录器。
bindingGetRecorder := httptest.NewRecorder()
@@ -352,7 +354,7 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
}
// batchReq 是读取商品批量任务列表的请求。
batchReq := httptest.NewRequest(http.MethodGet, "/items/publish-batches?limit=10", nil)
batchReq := httptest.NewRequest(http.MethodGet, "/api/v1/items/publish-batches?limit=10", nil)
batchReq.AddCookie(sessionCookie)
// batchRecorder 是捕获商品批量任务列表响应的记录器。
batchRecorder := httptest.NewRecorder()
@@ -377,12 +379,12 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
handler := contractRecordingHandler(t, srv.Router())
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
// publicSettingsReq 是读取公开系统设置的请求。
publicSettingsReq := httptest.NewRequest(http.MethodGet, "/system-settings/public", nil)
publicSettingsReq := httptest.NewRequest(http.MethodGet, "/api/v1/settings/system/public", nil)
// publicSettingsRecorder 是捕获公开设置响应的记录器。
publicSettingsRecorder := httptest.NewRecorder()
handler.ServeHTTP(publicSettingsRecorder, publicSettingsReq)
@@ -400,7 +402,7 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) {
}
// allSettingsReq 是读取管理员系统设置的请求。
allSettingsReq := httptest.NewRequest(http.MethodGet, "/system-settings", nil)
allSettingsReq := httptest.NewRequest(http.MethodGet, "/api/v1/settings/system", nil)
allSettingsReq.AddCookie(sessionCookie)
// allSettingsRecorder 是捕获管理员设置响应的记录器。
allSettingsRecorder := httptest.NewRecorder()
@@ -419,7 +421,7 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) {
}
// userSettingsReq 是读取当前用户设置的请求。
userSettingsReq := httptest.NewRequest(http.MethodGet, "/user-settings", nil)
userSettingsReq := httptest.NewRequest(http.MethodGet, "/api/v1/settings/user", nil)
userSettingsReq.AddCookie(sessionCookie)
// userSettingsRecorder 是捕获用户设置响应的记录器。
userSettingsRecorder := httptest.NewRecorder()
@@ -450,7 +452,7 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) {
statusSessionID := "contract-qr"
ownQRSession(t, srv, store, statusSessionID)
// qrStatusReq 是读取二维码状态的请求。
qrStatusReq := httptest.NewRequest(http.MethodGet, "/qr-login/check/"+statusSessionID, nil)
qrStatusReq := httptest.NewRequest(http.MethodGet, "/api/v1/qr-login/check/"+statusSessionID, nil)
qrStatusReq.AddCookie(sessionCookie)
// qrStatusRecorder 是捕获二维码状态响应的记录器。
qrStatusRecorder := httptest.NewRecorder()
@@ -488,7 +490,7 @@ func TestDynamicCompatibilitySuccessContracts(t *testing.T) {
completeSessionID := "contract-complete"
ownQRSession(t, srv, store, completeSessionID)
// completeReq 是提交二维码风控验证完成的请求。
completeReq := httptest.NewRequest(http.MethodPost, "/qr-login/complete-verification/"+completeSessionID, nil)
completeReq := httptest.NewRequest(http.MethodPost, "/api/v1/qr-login/complete-verification/"+completeSessionID, nil)
completeReq.AddCookie(sessionCookie)
// completeRecorder 是捕获验证完成响应的记录器。
completeRecorder := httptest.NewRecorder()
@@ -513,12 +515,12 @@ func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) {
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
handler := contractRecordingHandler(t, srv.Router())
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
// keywordReq 是创建带商品范围关键词的请求。
keywordReq := httptest.NewRequest(http.MethodPost, "/keywords-with-item-id/acc1", strings.NewReader(`{"keyword":"契约关键词","reply":"契约回复","item_id":"contract-item"}`))
keywordReq := httptest.NewRequest(http.MethodPost, "/api/v1/reply-rules/acc1/items", strings.NewReader(`{"keyword":"契约关键词","reply":"契约回复","item_id":"contract-item"}`))
keywordReq.Header.Set("Content-Type", "application/json")
keywordReq.AddCookie(sessionCookie)
// keywordRecorder 是捕获关键词创建响应的记录器。
@@ -538,7 +540,7 @@ func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) {
}
// keywordListReq 是读取带类型关键词列表的请求。
keywordListReq := httptest.NewRequest(http.MethodGet, "/keywords-with-type/acc1", nil)
keywordListReq := httptest.NewRequest(http.MethodGet, "/api/v1/reply-rules/acc1/typed", nil)
keywordListReq.AddCookie(sessionCookie)
// keywordListRecorder 是捕获关键词列表响应的记录器。
keywordListRecorder := httptest.NewRecorder()
@@ -557,7 +559,7 @@ func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) {
}
// itemReplyReq 是保存指定商品回复的请求。
itemReplyReq := httptest.NewRequest(http.MethodPut, "/item-reply/acc1/contract-item", strings.NewReader(`{"reply_content":"商品契约回复"}`))
itemReplyReq := httptest.NewRequest(http.MethodPut, "/api/v1/reply-rules/items/acc1/contract-item", strings.NewReader(`{"reply_content":"商品契约回复"}`))
itemReplyReq.Header.Set("Content-Type", "application/json")
itemReplyReq.AddCookie(sessionCookie)
// itemReplyRecorder 是捕获指定商品回复响应的记录器。
@@ -577,7 +579,7 @@ func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) {
}
// defaultReplyReq 是保存默认回复的请求。
defaultReplyReq := httptest.NewRequest(http.MethodPut, "/api/default-reply/acc1", strings.NewReader(`{"enabled":true,"reply_content":"默认契约回复","reply_once":true,"reply_image_url":""}`))
defaultReplyReq := httptest.NewRequest(http.MethodPut, "/api/v1/default-replies/acc1", strings.NewReader(`{"enabled":true,"reply_content":"默认契约回复","reply_once":true,"reply_image_url":""}`))
defaultReplyReq.Header.Set("Content-Type", "application/json")
defaultReplyReq.AddCookie(sessionCookie)
// defaultReplyRecorder 是捕获默认回复响应的记录器。
@@ -597,7 +599,7 @@ func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) {
}
// defaultReplyGetReq 是读取默认回复的请求。
defaultReplyGetReq := httptest.NewRequest(http.MethodGet, "/api/default-reply/acc1", nil)
defaultReplyGetReq := httptest.NewRequest(http.MethodGet, "/api/v1/default-replies/acc1", nil)
defaultReplyGetReq.AddCookie(sessionCookie)
// defaultReplyGetRecorder 是捕获默认回复查询响应的记录器。
defaultReplyGetRecorder := httptest.NewRecorder()
@@ -616,7 +618,7 @@ func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) {
}
// taskSettingsReq 是读取账号任务设置的请求。
taskSettingsReq := httptest.NewRequest(http.MethodGet, "/api/account-tasks/acc1", nil)
taskSettingsReq := httptest.NewRequest(http.MethodGet, "/api/v1/account-tasks/acc1", nil)
taskSettingsReq.AddCookie(sessionCookie)
// taskSettingsRecorder 是捕获账号任务设置响应的记录器。
taskSettingsRecorder := httptest.NewRecorder()
@@ -635,7 +637,7 @@ func TestReplyAndAccountTaskSuccessResponseContracts(t *testing.T) {
}
// taskRunsReq 是读取账号任务执行记录的请求。
taskRunsReq := httptest.NewRequest(http.MethodGet, "/api/account-tasks/acc1/runs", nil)
taskRunsReq := httptest.NewRequest(http.MethodGet, "/api/v1/account-tasks/acc1/runs", nil)
taskRunsReq.AddCookie(sessionCookie)
// taskRunsRecorder 是捕获账号任务执行记录响应的记录器。
taskRunsRecorder := httptest.NewRecorder()
@@ -660,7 +662,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) {
srv, store, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
handler := contractRecordingHandler(t, srv.Router())
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
// seedErr 是统计测试订单写入失败的原因。
@@ -669,7 +671,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) {
}
// adminStatsReq 是读取管理员全局统计的请求。
adminStatsReq := httptest.NewRequest(http.MethodGet, "/admin/stats", nil)
adminStatsReq := httptest.NewRequest(http.MethodGet, "/api/v1/admin/stats", nil)
adminStatsReq.AddCookie(sessionCookie)
// adminStatsRecorder 是捕获管理员统计响应的记录器。
adminStatsRecorder := httptest.NewRecorder()
@@ -688,7 +690,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) {
}
// adminUsersReq 是读取管理员用户列表的请求。
adminUsersReq := httptest.NewRequest(http.MethodGet, "/admin/users", nil)
adminUsersReq := httptest.NewRequest(http.MethodGet, "/api/v1/admin/users", nil)
adminUsersReq.AddCookie(sessionCookie)
// adminUsersRecorder 是捕获管理员用户列表响应的记录器。
adminUsersRecorder := httptest.NewRecorder()
@@ -707,7 +709,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) {
}
// adminCookiesReq 是读取管理员账号列表的请求。
adminCookiesReq := httptest.NewRequest(http.MethodGet, "/admin/cookies", nil)
adminCookiesReq := httptest.NewRequest(http.MethodGet, "/api/v1/admin/cookies", nil)
adminCookiesReq.AddCookie(sessionCookie)
// adminCookiesRecorder 是捕获管理员账号列表响应的记录器。
adminCookiesRecorder := httptest.NewRecorder()
@@ -726,7 +728,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) {
}
// dashboardReq 是读取当前用户概览统计的请求。
dashboardReq := httptest.NewRequest(http.MethodGet, "/dashboard/stats", nil)
dashboardReq := httptest.NewRequest(http.MethodGet, "/api/v1/analytics/dashboard", nil)
dashboardReq.AddCookie(sessionCookie)
// dashboardRecorder 是捕获概览统计响应的记录器。
dashboardRecorder := httptest.NewRecorder()
@@ -745,7 +747,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) {
}
// analyticsReq 是读取订单分析统计的请求。
analyticsReq := httptest.NewRequest(http.MethodGet, "/analytics/orders?start_date=2026-08-14&end_date=2026-08-14", nil)
analyticsReq := httptest.NewRequest(http.MethodGet, "/api/v1/analytics/orders?start_date=2026-08-14&end_date=2026-08-14", nil)
analyticsReq.AddCookie(sessionCookie)
// analyticsRecorder 是捕获订单分析响应的记录器。
analyticsRecorder := httptest.NewRecorder()
@@ -764,7 +766,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) {
}
// validOrdersReq 是读取有效订单分页的请求。
validOrdersReq := httptest.NewRequest(http.MethodGet, "/analytics/orders/valid?start_date=2026-08-14&end_date=2026-08-14", nil)
validOrdersReq := httptest.NewRequest(http.MethodGet, "/api/v1/analytics/orders/valid?start_date=2026-08-14&end_date=2026-08-14", nil)
validOrdersReq.AddCookie(sessionCookie)
// validOrdersRecorder 是捕获有效订单响应的记录器。
validOrdersRecorder := httptest.NewRecorder()
@@ -785,7 +787,7 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) {
// 二维码生成使用测试专用平台替身。
setTestQRLogin(srv, &fakeQRLoginService{})
// qrReq 是生成扫码登录二维码的请求。
qrReq := httptest.NewRequest(http.MethodPost, "/qr-login/generate", nil)
qrReq := httptest.NewRequest(http.MethodPost, "/api/v1/qr-login/generate", nil)
qrReq.AddCookie(sessionCookie)
// qrRecorder 是捕获二维码生成响应的记录器。
qrRecorder := httptest.NewRecorder()
@@ -803,3 +805,127 @@ func TestAnalyticsAdminAndPublicSuccessResponseContracts(t *testing.T) {
t.Fatalf("qr response=%+v", qrResponse)
}
}
// TestOpenAPILocalResourceMutationResponses 验证会话、账号和管理员本地资源变更均有真实版本化成功响应。
func TestOpenAPILocalResourceMutationResponses(t *testing.T) {
// srv、store、cleanup 分别提供独立 HTTP 服务、测试数据库和资源释放责任。
srv, store, cleanup := newTestServer(t)
defer cleanup()
// handler 是全量 chi Router,所有请求均通过正式版本化路由执行。
handler := srv.Router()
// healthRecorder 保存无需认证的健康检查成功响应。
healthRecorder := serveOpenAPISuccess(t, handler, nil, http.MethodGet, "/health", "")
if healthRecorder.Code != http.StatusOK {
t.Fatalf("health status=%d body=%s", healthRecorder.Code, healthRecorder.Body.String())
}
// sessionCookie 是初始管理员会话,用于验证当前密码并执行账号管理操作。
sessionCookie := loginHelper(t, handler)
// passwordRecorder 保存当前用户修改密码后的成功响应;该操作会废弃旧会话。
passwordRecorder := serveOpenAPISuccess(t, handler, sessionCookie, http.MethodPost, "/api/v1/session/password", `{"current_password":"pw","new_password":"new-password"}`)
if passwordRecorder.Code != http.StatusOK {
t.Fatalf("change password status=%d body=%s", passwordRecorder.Code, passwordRecorder.Body.String())
}
// refreshedCookie 是使用新密码重新登录后的会话,后续操作不依赖已撤销的旧会话。
refreshedCookie := loginAsHelper(t, handler, "admin", "new-password")
// credentialsRecorder 保存管理员用户名更新成功响应;当前密码保持新密码以验证敏感输入仅在服务端处理。
credentialsRecorder := serveOpenAPISuccess(t, handler, refreshedCookie, http.MethodPut, "/api/v1/session/credentials", `{"current_password":"new-password","new_username":"admin-contract"}`)
if credentialsRecorder.Code != http.StatusOK {
t.Fatalf("update credentials status=%d body=%s", credentialsRecorder.Code, credentialsRecorder.Body.String())
}
// renamedCookie 是用户名变更后重新登录得到的会话,确保后续管理员操作使用当前身份。
renamedCookie := loginAsHelper(t, handler, "admin-contract", "new-password")
// adminPasswordRecorder 保存管理员密码变更成功响应,覆盖管理员专属密码 operation。
adminPasswordRecorder := serveOpenAPISuccess(t, handler, renamedCookie, http.MethodPost, "/api/v1/admin/password", `{"current_password":"new-password","new_password":"final-password"}`)
if adminPasswordRecorder.Code != http.StatusOK {
t.Fatalf("change admin password status=%d body=%s", adminPasswordRecorder.Code, adminPasswordRecorder.Body.String())
}
// finalCookie 是最终密码对应的管理员会话,供账号和用户删除生命周期使用。
finalCookie := loginAsHelper(t, handler, "admin-contract", "final-password")
// accountRecorder 保存新建可删除账号的成功响应;请求内 Cookie 只用于测试输入,响应不得返回该明文。
accountRecorder := serveOpenAPISuccess(t, handler, finalCookie, http.MethodPost, "/api/v1/accounts", `{"id":"delete-contract","value":"unb=delete-contract","login_method":"manual"}`)
if accountRecorder.Code != http.StatusOK || strings.Contains(accountRecorder.Body.String(), "unb=delete-contract") {
t.Fatalf("create account response invalid: status=%d body=%s", accountRecorder.Code, accountRecorder.Body.String())
}
// deleteAccountRecorder 保存同一账号的删除成功响应,形成真实账号资源生命周期闭环。
deleteAccountRecorder := serveOpenAPISuccess(t, handler, finalCookie, http.MethodDelete, "/api/v1/accounts/delete-contract", "")
if deleteAccountRecorder.Code != http.StatusOK {
t.Fatalf("delete account status=%d body=%s", deleteAccountRecorder.Code, deleteAccountRecorder.Body.String())
}
// created、createUserErr 分别表示普通用户是否已写入和创建失败原因。
created, createUserErr := store.Users.Create(context.Background(), "delete-user", "delete-user@example.com", "pw")
if createUserErr != nil {
t.Fatalf("create deletable user: %v", createUserErr)
}
if !created {
t.Fatal("create deletable user returned false")
}
// deletableUser、getUserErr 分别保存待删除普通用户的稳定数据库 ID 和重新读取失败原因。
deletableUser, getUserErr := store.Users.GetByUsername(context.Background(), "delete-user")
if getUserErr != nil || deletableUser == nil {
t.Fatalf("load deletable user: user=%+v err=%v", deletableUser, getUserErr)
}
// deleteUserRecorder 保存管理员删除普通用户的成功响应,避免把不存在用户的 4xx 当作成功证据。
deleteUserRecorder := serveOpenAPISuccess(t, handler, finalCookie, http.MethodDelete, "/api/v1/admin/users/"+strconv.FormatInt(deletableUser.ID, 10), "")
if deleteUserRecorder.Code != http.StatusOK {
t.Fatalf("delete user status=%d body=%s", deleteUserRecorder.Code, deleteUserRecorder.Body.String())
}
// automationCardID、automationCreateRecorder 分别保存自动化规则所需卡券 ID 和创建响应。
automationCardID, cardErr := store.Cards.Create(context.Background(), &db.CardFull{Name: "契约自动化卡", Type: "text", TextContent: "CARD", Enabled: true, UserID: 1})
if cardErr != nil {
t.Fatalf("create automation card: %v", cardErr)
}
// itemErr 表示自动化规则关联商品夹具写入失败。
if _, itemErr := store.DB.ExecContext(context.Background(), `INSERT INTO item_info (cookie_id, item_id, item_title) VALUES ('acc1','contract-automation-item','自动化商品')`); itemErr != nil {
t.Fatalf("create automation item: %v", itemErr)
}
// automationCreateRecorder 保存自动化规则创建成功响应。
automationCreateRecorder := serveOpenAPISuccess(t, handler, finalCookie, http.MethodPost, "/api/v1/automation-rules", `{"cookie_id":"acc1","item_id":"contract-automation-item","trigger_type":"order_paid","enabled":true,"actions":[{"action_type":"send_card","card_id":`+strconv.FormatInt(automationCardID, 10)+`,"delivery_count":1}]}`)
// automationCreateResponse 保存自动化规则创建返回的数值主键。
var automationCreateResponse mutationIDResponse
// decodeErr 表示解析自动化规则创建响应失败。
if decodeErr := json.Unmarshal(automationCreateRecorder.Body.Bytes(), &automationCreateResponse); decodeErr != nil || automationCreateResponse.ID == 0 {
t.Fatalf("decode automation create: id=%d err=%v body=%s", automationCreateResponse.ID, decodeErr, automationCreateRecorder.Body.String())
}
// automationRuleID 是后续更新和删除操作使用的规则路径标识。
automationRuleID := strconv.FormatInt(automationCreateResponse.ID, 10)
serveOpenAPISuccess(t, handler, finalCookie, http.MethodPut, "/api/v1/automation-rules/"+automationRuleID, `{"cookie_id":"acc1","item_id":"contract-automation-item","trigger_type":"order_paid","enabled":false,"actions":[{"action_type":"send_card","card_id":`+strconv.FormatInt(automationCardID, 10)+`,"delivery_count":1}]}`)
serveOpenAPISuccess(t, handler, finalCookie, http.MethodDelete, "/api/v1/automation-rules/"+automationRuleID, "")
serveOpenAPISuccess(t, handler, finalCookie, http.MethodPut, "/api/v1/default-replies/acc1", `{"enabled":true,"reply_content":"契约默认回复","reply_once":true}`)
serveOpenAPISuccess(t, handler, finalCookie, http.MethodGet, "/api/v1/default-replies/acc1", "")
serveOpenAPISuccess(t, handler, finalCookie, http.MethodGet, "/api/v1/default-replies", "")
serveOpenAPISuccess(t, handler, finalCookie, http.MethodGet, "/api/v1/default-replies/list", "")
serveOpenAPISuccess(t, handler, finalCookie, http.MethodPost, "/api/v1/default-replies/acc1/clear-records", "{}")
serveOpenAPISuccess(t, handler, finalCookie, http.MethodDelete, "/api/v1/default-replies/acc1", "")
serveOpenAPISuccess(t, handler, finalCookie, http.MethodGet, "/api/v1/items/cookie/acc1", "")
serveOpenAPISuccess(t, handler, finalCookie, http.MethodGet, "/api/v1/items/publish-batches", "")
serveOpenAPISuccess(t, handler, finalCookie, http.MethodGet, "/api/v1/cards/1/details", "")
// orderID 是用于删除订单成功场景的本地订单标识。
orderID := "contract-delete-order"
// orderErr 表示订单删除成功场景夹具写入失败。
if _, orderErr := store.DB.ExecContext(context.Background(), `INSERT INTO orders (order_id,item_id,buyer_id,order_status,cookie_id) VALUES ('contract-delete-order','contract-automation-item','buyer','pending_ship','acc1')`); orderErr != nil {
t.Fatalf("create delete order: %v", orderErr)
}
serveOpenAPISuccess(t, handler, finalCookie, http.MethodDelete, "/api/v1/orders/"+orderID, "")
serveOpenAPISuccess(t, handler, finalCookie, http.MethodPut, "/api/v1/items/acc1/contract-automation-item/multi-spec", `{"enabled":true}`)
serveOpenAPISuccess(t, handler, finalCookie, http.MethodPut, "/api/v1/items/acc1/contract-automation-item/multi-quantity-delivery", `{"enabled":true}`)
// keywordRecorder 保存普通关键词规则创建成功响应,后续通过带类型列表获取稳定 ID。
keywordRecorder := serveOpenAPISuccess(t, handler, finalCookie, http.MethodPost, "/api/v1/reply-rules/acc1", `{"keyword":"契约关键字","reply":"契约回复"}`)
if keywordRecorder.Code != http.StatusOK {
t.Fatalf("create keyword status=%d body=%s", keywordRecorder.Code, keywordRecorder.Body.String())
}
// keywordListRecorder 保存带类型关键词列表成功响应。
keywordListRecorder := serveOpenAPISuccess(t, handler, finalCookie, http.MethodGet, "/api/v1/reply-rules/acc1/typed", "")
// keywordRows 保存带稳定数值主键的关键词规则集合。
var keywordRows []keywordTypedResponse
// keywordListErr 表示解析带类型关键词列表失败。
if keywordListErr := json.Unmarshal(keywordListRecorder.Body.Bytes(), &keywordRows); keywordListErr != nil || len(keywordRows) == 0 {
t.Fatalf("load typed keywords: rows=%+v err=%v", keywordRows, keywordListErr)
}
// keywordID 是当前创建规则的稳定主键,用于更新、按 ID 删除与按索引删除的成功场景。
keywordID := strconv.FormatInt(keywordRows[0].ID, 10)
serveOpenAPISuccess(t, handler, finalCookie, http.MethodPut, "/api/v1/reply-rules/acc1/typed/"+keywordID, `{"keyword":"契约关键字","reply":"已更新回复","type":"text"}`)
serveOpenAPISuccess(t, handler, finalCookie, http.MethodDelete, "/api/v1/reply-rules/acc1/typed/"+keywordID, "")
serveOpenAPISuccess(t, handler, finalCookie, http.MethodPost, "/api/v1/reply-rules/acc1", `{"keyword":"索引关键字","reply":"索引回复"}`)
serveOpenAPISuccess(t, handler, finalCookie, http.MethodDelete, "/api/v1/reply-rules/acc1/index/0", "")
serveOpenAPISuccess(t, handler, finalCookie, http.MethodPut, "/api/v1/account-tasks/acc1", `{"auto_rate_enabled":true,"rate_content":"服务很好","auto_polish_enabled":false,"polish_time":"03:00"}`)
}
+10
View File
@@ -62,6 +62,16 @@ func TestChatEventDTOUsesFrontendContract(t *testing.T) {
if loadErr != nil {
t.Fatalf("加载 OpenAPI WebSocket 契约: %v", loadErr)
}
// webSocketPath 是版本化聊天 WebSocket operation 的 OpenAPI 路径定义。
webSocketPath := document.Paths.Find("/api/v1/chat/ws")
if webSocketPath == nil || webSocketPath.Get == nil || webSocketPath.Get.Responses == nil || webSocketPath.Get.Responses.Value("101") == nil {
t.Fatal("OpenAPI 缺少聊天 WebSocket 101 升级响应")
}
// rawException、exceptionOK 分别是成功响应特殊校验扩展原值及其对象结构是否有效。
rawException, exceptionOK := webSocketPath.Get.Extensions["x-contract-success-exception"].(map[string]any)
if !exceptionOK || rawException["kind"] != "websocket" {
t.Fatalf("聊天 WebSocket 未登记 websocket 特殊校验: %#v", webSocketPath.Get.Extensions["x-contract-success-exception"])
}
// eventSchemaRef 保存 WebSocket 推送帧的具名 schema 引用。
eventSchemaRef := document.Components.Schemas["ChatWebSocketEvent"]
if eventSchemaRef == nil || eventSchemaRef.Value == nil {
+2
View File
@@ -21,6 +21,8 @@ var (
serverTestTemplatePath string
// serverTestTemplateErr 保存创建共享模板时遇到的错误。
serverTestTemplateErr error
// openAPISuccessOperations 收集当前 Go 测试进程中经真实 Router 成功响应校验的 operationId。
openAPISuccessOperations sync.Map
)
// TestMain 在所有 server 测试结束后删除共享数据库模板目录。
@@ -27,9 +27,7 @@ func TestVersionedAccountRoutesPreserveLegacyContracts(t *testing.T) {
// listRecorder 是捕获账号摘要响应的记录器。
listRecorder := httptest.NewRecorder()
handler.ServeHTTP(listRecorder, listReq)
if listRecorder.Code != http.StatusOK {
t.Fatalf("versioned account list status=%d body=%s", listRecorder.Code, listRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, listReq, listRecorder)
// accountIDs 是版本化账号摘要 ID 列表。
var accountIDs []string
// listDecodeErr 是账号摘要响应反序列化失败的原因。
@@ -46,9 +44,7 @@ func TestVersionedAccountRoutesPreserveLegacyContracts(t *testing.T) {
// detailsRecorder 是捕获账号详情响应的记录器。
detailsRecorder := httptest.NewRecorder()
handler.ServeHTTP(detailsRecorder, detailsReq)
if detailsRecorder.Code != http.StatusOK {
t.Fatalf("versioned account details status=%d body=%s", detailsRecorder.Code, detailsRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, detailsReq, detailsRecorder)
// detailsValue 是版本化账号详情 DTO 集合。
var detailsValue []cookieSummaryResponse
// detailsDecodeErr 是账号详情响应反序列化失败的原因。
@@ -68,9 +64,7 @@ func TestVersionedAccountRoutesPreserveLegacyContracts(t *testing.T) {
// runtimeRecorder 是捕获账号运行状态响应的记录器。
runtimeRecorder := httptest.NewRecorder()
handler.ServeHTTP(runtimeRecorder, runtimeReq)
if runtimeRecorder.Code != http.StatusOK {
t.Fatalf("versioned runtime status=%d body=%s", runtimeRecorder.Code, runtimeRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, runtimeReq, runtimeRecorder)
// runtimeValue 是版本化账号运行状态映射。
var runtimeValue map[string]engine.RuntimeStatus
// runtimeDecodeErr 是运行状态响应反序列化失败的原因。
@@ -87,9 +81,7 @@ func TestVersionedAccountRoutesPreserveLegacyContracts(t *testing.T) {
// detailRecorder 是捕获单账号详情响应的记录器。
detailRecorder := httptest.NewRecorder()
handler.ServeHTTP(detailRecorder, detailReq)
if detailRecorder.Code != http.StatusOK {
t.Fatalf("versioned account detail status=%d body=%s", detailRecorder.Code, detailRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, detailReq, detailRecorder)
// detailValue 是版本化单账号详情 DTO。
var detailValue cookieDetailResponse
// detailDecodeErr 是单账号详情响应反序列化失败的原因。
@@ -106,9 +98,7 @@ func TestVersionedAccountRoutesPreserveLegacyContracts(t *testing.T) {
// statusRecorder 是捕获账号状态变更响应的记录器。
statusRecorder := httptest.NewRecorder()
handler.ServeHTTP(statusRecorder, statusReq)
if statusRecorder.Code != http.StatusOK {
t.Fatalf("versioned account status=%d body=%s", statusRecorder.Code, statusRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, statusReq, statusRecorder)
// statusValue 是账号状态变更具名响应 DTO。
var statusValue operationResponse
// statusDecodeErr 是状态变更响应反序列化失败的原因。
@@ -157,9 +147,7 @@ func TestVersionedAccountCredentialRoutesPreserveLegacyContracts(t *testing.T) {
// addRecorder 是捕获新增账号响应的记录器。
addRecorder := httptest.NewRecorder()
handler.ServeHTTP(addRecorder, addReq)
if addRecorder.Code != http.StatusOK {
t.Fatalf("versioned add account status=%d body=%s", addRecorder.Code, addRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, addReq, addRecorder)
// addValue 是新增账号响应中的具名结果 DTO。
var addValue accountMutationResponse
// addDecodeErr 是新增账号响应反序列化失败的原因。
@@ -179,9 +167,7 @@ func TestVersionedAccountCredentialRoutesPreserveLegacyContracts(t *testing.T) {
// updateRecorder 是捕获 Cookie 更新响应的记录器。
updateRecorder := httptest.NewRecorder()
handler.ServeHTTP(updateRecorder, updateReq)
if updateRecorder.Code != http.StatusOK {
t.Fatalf("versioned update account status=%d body=%s", updateRecorder.Code, updateRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, updateReq, updateRecorder)
// updateValue 是 Cookie 更新响应中的具名结果 DTO。
var updateValue operationResponse
// updateDecodeErr 是 Cookie 更新响应反序列化失败的原因。
@@ -201,9 +187,7 @@ func TestVersionedAccountCredentialRoutesPreserveLegacyContracts(t *testing.T) {
// loginInfoRecorder 是捕获登录信息更新响应的记录器。
loginInfoRecorder := httptest.NewRecorder()
handler.ServeHTTP(loginInfoRecorder, loginInfoReq)
if loginInfoRecorder.Code != http.StatusOK {
t.Fatalf("versioned login info status=%d body=%s", loginInfoRecorder.Code, loginInfoRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, loginInfoReq, loginInfoRecorder)
// loginInfoValue 是登录信息更新响应中的具名结果 DTO。
var loginInfoValue operationResponse
// loginInfoDecodeErr 是登录信息响应反序列化失败的原因。
@@ -250,9 +234,7 @@ func TestVersionedAccountSettingsRoutesPreserveLegacyContracts(t *testing.T) {
// settingsRecorder 是捕获聚合设置响应的记录器。
settingsRecorder := httptest.NewRecorder()
handler.ServeHTTP(settingsRecorder, settingsReq)
if settingsRecorder.Code != http.StatusOK {
t.Fatalf("versioned settings status=%d body=%s", settingsRecorder.Code, settingsRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, settingsReq, settingsRecorder)
// settingsValue 是聚合账号设置具名响应 DTO。
var settingsValue cookieSettingsResponse
// settingsDecodeErr 是聚合设置响应反序列化失败的原因。
@@ -269,9 +251,7 @@ func TestVersionedAccountSettingsRoutesPreserveLegacyContracts(t *testing.T) {
// remarkRecorder 是捕获备注响应的记录器。
remarkRecorder := httptest.NewRecorder()
handler.ServeHTTP(remarkRecorder, remarkReq)
if remarkRecorder.Code != http.StatusOK {
t.Fatalf("versioned remark status=%d body=%s", remarkRecorder.Code, remarkRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, remarkReq, remarkRecorder)
// remarkValue 是备注变更具名响应 DTO。
var remarkValue operationResponse
// remarkDecodeErr 是备注响应反序列化失败的原因。
@@ -288,9 +268,7 @@ func TestVersionedAccountSettingsRoutesPreserveLegacyContracts(t *testing.T) {
// autoConfirmRecorder 是捕获自动确认响应的记录器。
autoConfirmRecorder := httptest.NewRecorder()
handler.ServeHTTP(autoConfirmRecorder, autoConfirmReq)
if autoConfirmRecorder.Code != http.StatusOK {
t.Fatalf("versioned auto-confirm status=%d body=%s", autoConfirmRecorder.Code, autoConfirmRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, autoConfirmReq, autoConfirmRecorder)
// pauseReq 是更新版本化暂停时长的请求。
pauseReq := httptest.NewRequest(http.MethodPut, "/api/v1/accounts/acc1/pause-duration", strings.NewReader(`{"pause_duration":15}`))
@@ -298,9 +276,7 @@ func TestVersionedAccountSettingsRoutesPreserveLegacyContracts(t *testing.T) {
// pauseRecorder 是捕获暂停时长响应的记录器。
pauseRecorder := httptest.NewRecorder()
handler.ServeHTTP(pauseRecorder, pauseReq)
if pauseRecorder.Code != http.StatusOK {
t.Fatalf("versioned pause status=%d body=%s", pauseRecorder.Code, pauseRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, pauseReq, pauseRecorder)
// pauseValue 是暂停时长具名响应 DTO。
var pauseValue cookieSettingsResponse
// pauseDecodeErr 是暂停响应反序列化失败的原因。
@@ -317,9 +293,7 @@ func TestVersionedAccountSettingsRoutesPreserveLegacyContracts(t *testing.T) {
// autoConfirmGetRecorder 是捕获自动确认查询响应的记录器。
autoConfirmGetRecorder := httptest.NewRecorder()
handler.ServeHTTP(autoConfirmGetRecorder, autoConfirmGetReq)
if autoConfirmGetRecorder.Code != http.StatusOK {
t.Fatalf("versioned auto-confirm get status=%d body=%s", autoConfirmGetRecorder.Code, autoConfirmGetRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, autoConfirmGetReq, autoConfirmGetRecorder)
// autoConfirmValue 是自动确认查询具名响应 DTO。
var autoConfirmValue autoConfirmResponse
// autoConfirmDecodeErr 是自动确认查询响应反序列化失败的原因。
@@ -336,9 +310,7 @@ func TestVersionedAccountSettingsRoutesPreserveLegacyContracts(t *testing.T) {
// pauseGetRecorder 是捕获暂停查询响应的记录器。
pauseGetRecorder := httptest.NewRecorder()
handler.ServeHTTP(pauseGetRecorder, pauseGetReq)
if pauseGetRecorder.Code != http.StatusOK {
t.Fatalf("versioned pause get status=%d body=%s", pauseGetRecorder.Code, pauseGetRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, pauseGetReq, pauseGetRecorder)
// pauseGetValue 是暂停查询具名响应 DTO。
var pauseGetValue pauseDurationResponse
// pauseGetDecodeErr 是暂停查询响应反序列化失败的原因。
@@ -355,9 +327,7 @@ func TestVersionedAccountSettingsRoutesPreserveLegacyContracts(t *testing.T) {
// profileRecorder 是捕获资料刷新响应的记录器。
profileRecorder := httptest.NewRecorder()
handler.ServeHTTP(profileRecorder, profileReq)
if profileRecorder.Code != http.StatusOK {
t.Fatalf("versioned profile status=%d body=%s", profileRecorder.Code, profileRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, profileReq, profileRecorder)
// profileValue 是资料刷新具名响应 DTO。
var profileValue cookieProfileResponse
// profileDecodeErr 是资料刷新响应反序列化失败的原因。
@@ -33,6 +33,9 @@ func requestAdminAnalyticsRoute(t *testing.T, handler http.Handler, sessionCooki
// recorder 是捕获兼容入口响应的记录器。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if strings.HasPrefix(path, "/api/v1/") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices {
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
return recorder.Code
}
@@ -32,6 +32,9 @@ func requestChatTaskRoute(t *testing.T, handler http.Handler, sessionCookie *htt
// recorder 是捕获兼容入口响应的记录器。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if strings.HasPrefix(path, "/api/v1/") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices {
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
return recorder.Code
}
@@ -32,6 +32,9 @@ func requestItemBatchRoute(t *testing.T, handler http.Handler, sessionCookie *ht
// recorder 是捕获商品批量响应的记录器。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if strings.HasPrefix(path, "/api/v1/") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices {
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
return recorder.Code
}
@@ -32,9 +32,7 @@ func TestVersionedItemRoutesPreserveLegacyContracts(t *testing.T) {
// listRecorder 是捕获版本化商品列表响应的记录器。
listRecorder := httptest.NewRecorder()
handler.ServeHTTP(listRecorder, listReq)
if listRecorder.Code != http.StatusOK {
t.Fatalf("versioned item list status=%d body=%s", listRecorder.Code, listRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, listReq, listRecorder)
// listValue 是版本化商品列表响应 DTO 集合。
var listValue []itemListResponse
// listDecodeErr 是商品列表响应反序列化失败的原因。
@@ -51,9 +49,7 @@ func TestVersionedItemRoutesPreserveLegacyContracts(t *testing.T) {
// detailRecorder 是捕获版本化商品详情响应的记录器。
detailRecorder := httptest.NewRecorder()
handler.ServeHTTP(detailRecorder, detailReq)
if detailRecorder.Code != http.StatusOK {
t.Fatalf("versioned item detail status=%d body=%s", detailRecorder.Code, detailRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, detailReq, detailRecorder)
// detailValue 是版本化商品详情响应 DTO。
var detailValue itemDetailResponse
// detailDecodeErr 是商品详情响应反序列化失败的原因。
@@ -70,9 +66,7 @@ func TestVersionedItemRoutesPreserveLegacyContracts(t *testing.T) {
// updateRecorder 是捕获版本化商品更新响应的记录器。
updateRecorder := httptest.NewRecorder()
handler.ServeHTTP(updateRecorder, updateReq)
if updateRecorder.Code != http.StatusOK {
t.Fatalf("versioned item update status=%d body=%s", updateRecorder.Code, updateRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, updateReq, updateRecorder)
// updatedItem 是数据库中用于确认版本化更新结果的商品记录。
updatedItem, updatedErr := store.Items.Get(ctx, "acc1", "item-v1")
if updatedErr != nil || updatedItem == nil || updatedItem.ItemTitle != "版本化新商品名" {
@@ -95,9 +89,7 @@ func TestVersionedItemRoutesPreserveLegacyContracts(t *testing.T) {
// deleteRecorder 是捕获版本化商品删除响应的记录器。
deleteRecorder := httptest.NewRecorder()
handler.ServeHTTP(deleteRecorder, deleteReq)
if deleteRecorder.Code != http.StatusOK {
t.Fatalf("versioned item delete status=%d body=%s", deleteRecorder.Code, deleteRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, deleteReq, deleteRecorder)
// legacyDeleteReq 是验证旧商品删除入口仍可用的请求。
legacyDeleteReq := httptest.NewRequest(http.MethodDelete, "/items/acc1/item-legacy", nil)
@@ -34,9 +34,7 @@ func TestVersionedOrderRoutesPreserveLegacyContracts(t *testing.T) {
// listRecorder 是捕获版本化订单列表响应的记录器。
listRecorder := httptest.NewRecorder()
handler.ServeHTTP(listRecorder, listReq)
if listRecorder.Code != http.StatusOK {
t.Fatalf("versioned order list status=%d body=%s", listRecorder.Code, listRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, listReq, listRecorder)
// listValue 是版本化订单列表响应 DTO。
var listValue orderListResponse
// listDecodeErr 是订单列表响应反序列化失败的原因。
@@ -53,9 +51,7 @@ func TestVersionedOrderRoutesPreserveLegacyContracts(t *testing.T) {
// detailRecorder 是捕获版本化订单详情响应的记录器。
detailRecorder := httptest.NewRecorder()
handler.ServeHTTP(detailRecorder, detailReq)
if detailRecorder.Code != http.StatusOK {
t.Fatalf("versioned order detail status=%d body=%s", detailRecorder.Code, detailRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, detailReq, detailRecorder)
// detailValue 是版本化订单详情响应 DTO。
var detailValue orderDetailResponse
// detailDecodeErr 是订单详情响应反序列化失败的原因。
@@ -72,9 +68,7 @@ func TestVersionedOrderRoutesPreserveLegacyContracts(t *testing.T) {
// updateRecorder 是捕获版本化订单更新响应的记录器。
updateRecorder := httptest.NewRecorder()
handler.ServeHTTP(updateRecorder, updateReq)
if updateRecorder.Code != http.StatusOK {
t.Fatalf("versioned order update status=%d body=%s", updateRecorder.Code, updateRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, updateReq, updateRecorder)
// updateValue 是版本化订单更新响应 DTO。
var updateValue operationResponse
// updateDecodeErr 是订单更新响应反序列化失败的原因。
@@ -124,20 +118,38 @@ func TestVersionedOrderRefreshAndBatchRoutesPreserveLegacyContracts(t *testing.T
// refreshRecorder 是捕获版本化刷新响应的记录器。
refreshRecorder := httptest.NewRecorder()
handler.ServeHTTP(refreshRecorder, refreshReq)
if refreshRecorder.Code != http.StatusAccepted {
t.Fatalf("versioned order refresh status=%d body=%s", refreshRecorder.Code, refreshRecorder.Body.String())
}
assertOpenAPIExpectedStatusResponse(t, refreshReq, refreshRecorder, http.StatusAccepted)
// refreshStart 是版本化刷新任务创建响应 DTO。
var refreshStart orderRefreshJobStartResponse
// refreshDecodeErr 是刷新任务创建响应反序列化失败的原因。
if refreshDecodeErr := json.Unmarshal(refreshRecorder.Body.Bytes(), &refreshStart); refreshDecodeErr != nil {
t.Fatalf("decode versioned order refresh: %v", refreshDecodeErr)
}
// versionedStatusReq 查询刚创建的版本化刷新任务,覆盖真实 200 状态响应。
versionedStatusReq := httptest.NewRequest(http.MethodGet, "/api/v1/orders/refresh/"+refreshStart.JobID, nil)
versionedStatusReq.AddCookie(sessionCookie)
// versionedStatusRecorder 保存版本化刷新任务查询响应。
versionedStatusRecorder := httptest.NewRecorder()
handler.ServeHTTP(versionedStatusRecorder, versionedStatusReq)
assertOpenAPIRecordedSuccessResponse(t, versionedStatusReq, versionedStatusRecorder)
// refreshValue 是版本化刷新任务完成后的具名结果。
refreshValue := waitOrderRefreshJob(t, handler, sessionCookie, refreshStart.JobID)
if refreshValue.Message == "" {
t.Fatalf("versioned order refresh should preserve a named success response: %+v", refreshValue)
}
// queuedJob 是专门用于版本化取消 operation 的排队任务夹具。
queuedJob := &db.OrderRefreshJob{ID: "versioned-cancel-job", UserID: 1, Status: "queued"}
// createErr 表示写入版本化取消任务夹具失败。
if createErr := store.OrderRefreshJobs.Create(ctx, queuedJob); createErr != nil {
t.Fatalf("create versioned cancel job: %v", createErr)
}
// versionedCancelReq 请求取消该排队任务。
versionedCancelReq := httptest.NewRequest(http.MethodDelete, "/api/v1/orders/refresh/"+queuedJob.ID, nil)
versionedCancelReq.AddCookie(sessionCookie)
// versionedCancelRecorder 保存版本化取消响应。
versionedCancelRecorder := httptest.NewRecorder()
handler.ServeHTTP(versionedCancelRecorder, versionedCancelReq)
assertOpenAPIRecordedSuccessResponse(t, versionedCancelReq, versionedCancelRecorder)
// legacyRefreshReq 是验证旧订单列表刷新入口仍可用的请求。
legacyRefreshReq := httptest.NewRequest(http.MethodPost, "/api/orders/refresh", nil)
@@ -167,10 +179,7 @@ func TestVersionedOrderRefreshAndBatchRoutesPreserveLegacyContracts(t *testing.T
// singleRecorder 是捕获版本化单订单刷新响应的记录器。
singleRecorder := httptest.NewRecorder()
handler.ServeHTTP(singleRecorder, singleReq)
// 夹具客户端提供订单详情响应,新旧入口都应返回成功刷新结果。
if singleRecorder.Code != http.StatusOK {
t.Fatalf("versioned single order refresh status=%d body=%s", singleRecorder.Code, singleRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, singleReq, singleRecorder)
// legacySingleReq 是验证旧单订单刷新入口仍可用的请求。
legacySingleReq := httptest.NewRequest(http.MethodPost, "/api/orders/order-single-v1/refresh", nil)
@@ -208,9 +217,7 @@ func TestVersionedOrderRefreshAndBatchRoutesPreserveLegacyContracts(t *testing.T
// importRecorder 是捕获版本化导入响应的记录器。
importRecorder := httptest.NewRecorder()
handler.ServeHTTP(importRecorder, importReq)
if importRecorder.Code != http.StatusOK {
t.Fatalf("versioned order import status=%d body=%s", importRecorder.Code, importRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, importReq, importRecorder)
// legacyImportReq 是验证旧导入入口仍可用的请求。
legacyImportReq := httptest.NewRequest(http.MethodPost, "/api/orders/import", strings.NewReader(`[]`))
@@ -33,6 +33,9 @@ func requestQRLoginRoute(t *testing.T, handler http.Handler, sessionCookie *http
// recorder 是捕获二维码响应的测试记录器。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if strings.HasPrefix(path, "/api/v1/") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices {
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
return recorder.Code
}
@@ -32,6 +32,9 @@ func requestRemainingVersionedRoute(t *testing.T, handler http.Handler, sessionC
// recorder 是捕获公共兼容入口响应的记录器。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if strings.HasPrefix(path, "/api/v1/") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices {
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
return recorder.Code
}
@@ -32,6 +32,9 @@ func requestReplyRoute(t *testing.T, handler http.Handler, sessionCookie *http.C
// recorder 是捕获兼容入口响应的记录器。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if strings.HasPrefix(path, "/api/v1/") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices {
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
return recorder.Code
}
@@ -22,9 +22,7 @@ func TestVersionedSessionRoutesPreserveLegacyContracts(t *testing.T) {
// loginRecorder 是捕获版本化登录响应的记录器。
loginRecorder := httptest.NewRecorder()
handler.ServeHTTP(loginRecorder, loginReq)
if loginRecorder.Code != http.StatusOK {
t.Fatalf("versioned login status=%d body=%s", loginRecorder.Code, loginRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, loginReq, loginRecorder)
// loginResponseValue 是版本化登录响应 DTO。
var loginResponseValue loginResponse
// loginDecodeErr 是版本化登录响应反序列化失败的原因。
@@ -43,9 +41,7 @@ func TestVersionedSessionRoutesPreserveLegacyContracts(t *testing.T) {
// verifyRecorder 是捕获版本化会话校验响应的记录器。
verifyRecorder := httptest.NewRecorder()
handler.ServeHTTP(verifyRecorder, verifyReq)
if verifyRecorder.Code != http.StatusOK {
t.Fatalf("versioned verify status=%d body=%s", verifyRecorder.Code, verifyRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, verifyReq, verifyRecorder)
// verifyResponseValue 是版本化会话校验响应 DTO。
var verifyResponseValue sessionVerificationResponse
// verifyDecodeErr 是版本化会话校验响应反序列化失败的原因。
@@ -72,9 +68,7 @@ func TestVersionedSessionRoutesPreserveLegacyContracts(t *testing.T) {
// logoutRecorder 是捕获版本化注销响应的记录器。
logoutRecorder := httptest.NewRecorder()
handler.ServeHTTP(logoutRecorder, logoutReq)
if logoutRecorder.Code != http.StatusOK {
t.Fatalf("versioned logout status=%d body=%s", logoutRecorder.Code, logoutRecorder.Body.String())
}
assertOpenAPISuccessResponse(t, logoutReq, logoutRecorder)
// legacyLoginReq 是验证旧登录入口仍可用的请求。
legacyLoginReq := httptest.NewRequest(http.MethodPost, "/login", strings.NewReader(loginBody))
@@ -32,6 +32,9 @@ func requestSettingsCardNotificationRoute(t *testing.T, handler http.Handler, se
// recorder 是捕获兼容入口响应的记录器。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, request)
if strings.HasPrefix(path, "/api/v1/") && recorder.Code >= http.StatusOK && recorder.Code < http.StatusMultipleChoices {
assertOpenAPIRecordedSuccessResponse(t, request, recorder)
}
return recorder.Code
}
@@ -0,0 +1,3 @@
import{b as ie,j as e,a as l,c as Me}from"./react-vendor-l-BBvuKH.js";import{r as T,c as L}from"./index-CiBUw4Te.js";import{c as Ae,o as Pe}from"./contract-COFcZjyb.js";import{n as de,X as ce,f as Be,L as J,o as qe,p as Ge,q as Oe,r as Te,s as Le,U as Ee,t as ae,u as ze,k as we,Q as _e,v as Ie,R as We,w as Ve,x as Ke,y as Ne,K as He,z as Je,F as Xe,e as Ye,H as Ze}from"./icons-vendor-Bgrth_9N.js";import"./vendor-cRYyTeIw.js";const Fe=(t,s)=>{const r=t.avatar_url||"";if(!r)return"";try{const a=new URL(r,window.location.origin);return a.hostname.endsWith("alicdn.com")&&a.searchParams.set("_v",s),a.toString()}catch{return r}},es=async t=>{const s=await T(n=>L.GET("/api/v1/accounts/details",{signal:n}),t),r=Ae(s,["data","accounts","details"]),a=Date.now().toString();return r.map(n=>({id:n.id,cookie_configured:n.has_cookie===!0,enabled:n.enabled,auto_confirm:n.auto_confirm,remark:n.remark,pause_duration:n.pause_duration,paused_until:Number(n.paused_until||0),paused:n.paused===!0,username:n.username||"",login_password_configured:void 0,show_browser:n.show_browser===!0||n.show_browser===1||n.show_browser==="1"||n.show_browser==="true",nickname:n.nickname||n.remark||`账号 ${n.id.substring(0,6)}`,avatar_url:Fe(n,a),profile_error:n.profile_error||"",ai_enabled:!1,auto_rate_enabled:n.auto_rate_enabled,rate_content:n.rate_content||"不错的买家,交易愉快",auto_polish_enabled:n.auto_polish_enabled,polish_time:n.polish_time||"03:00",last_rate_scan_at:Number(n.last_rate_scan_at||0),last_polish_date:n.last_polish_date||"",last_polish_at:Number(n.last_polish_at||0)}))},ve=async(t,s)=>T(r=>L.GET("/api/v1/account-tasks/{cid}",{params:{path:{cid:t}},signal:r}),s),ke=async(t,s,r)=>T(a=>L.PUT("/api/v1/account-tasks/{cid}",{params:{path:{cid:t}},body:s,signal:a}),r),ss=async(t,s,r)=>T(a=>L.POST("/api/v1/account-tasks/{cid}/run",{params:{path:{cid:t}},body:{task_type:s},signal:a}),{timeoutMs:12e4,...r}),ts=async t=>await T(r=>L.GET("/api/v1/accounts/runtime-status",{signal:r}),t),as=async t=>T(s=>L.POST("/api/v1/qr-login/generate",{signal:s}),{...t,timeoutMs:(t==null?void 0:t.timeoutMs)??13e4}),rs=async(t,s)=>T(r=>L.GET("/api/v1/qr-login/check/{session_id}",{params:{path:{session_id:t}},signal:r}),{signal:s,timeoutMs:1e4}),ns=async(t,s)=>T(r=>L.POST("/api/v1/qr-login/complete-verification/{session_id}",{params:{path:{session_id:t}},body:{target_account_id:s||""},signal:r})),ls=async(t,s)=>T(r=>L.PUT("/api/v1/accounts/{cid}/status",{params:{path:{cid:t}},body:{enabled:s},signal:r})),os=async t=>T(s=>L.DELETE("/api/v1/accounts/{cid}",{params:{path:{cid:t}},signal:s})),is=async(t,s,r)=>T(a=>L.PUT("/api/v1/accounts/{cid}/pause-duration",{params:{path:{cid:t}},body:{pause_duration:s},signal:a}),r),cs=async(t,s,r)=>T(a=>L.PUT("/api/v1/accounts/{cid}/settings",{params:{path:{cid:t}},body:s,signal:a}),r),ds=async(t,s)=>T(r=>L.GET("/api/v1/accounts/{cid}/long-login",{params:{path:{cid:t}},signal:r}),s),us=async(t,s,r)=>T(a=>L.PUT("/api/v1/accounts/{cid}/long-login",{params:{path:{cid:t}},body:{enabled:s},signal:a}),r),xs=async(t,s)=>T(r=>L.POST("/api/v1/password-login",{body:t,signal:r}),s),ms=async(t,s)=>T(a=>L.GET("/api/v1/password-login/check/{session_id}",{params:{path:{session_id:t}},signal:a}),{signal:s,timeoutMs:1e4}),bs=async(t,s)=>T(r=>L.DELETE("/api/v1/password-login/cancel/{session_id}",{params:{path:{session_id:t}},signal:r}),s),hs=async t=>T(s=>L.POST("/api/v1/accounts/{cid}/refresh-profile",{params:{path:{cid:t}},signal:s})),gs=async t=>{const s=await T(r=>L.GET("/api/v1/settings/ai-reply",{signal:r}),t);return Pe(s,["settings","data","result"])||{}},ps=async(t,s)=>T(r=>L.GET("/api/v1/settings/ai-reply/{cookie_id}",{params:{path:{cookie_id:t}},signal:r}),s),fs=async(t,s,r)=>{const a={ai_enabled:s.ai_enabled??!1,max_discount_percent:s.max_discount_percent??10,max_discount_amount:s.max_discount_amount??100,max_bargain_rounds:s.max_bargain_rounds??3,custom_prompts:s.custom_prompts??""};return T(n=>L.PUT("/api/v1/settings/ai-reply/{cookie_id}",{params:{path:{cookie_id:t}},body:a,signal:n}),r)},ys=t=>{if(Array.isArray(t))return t.filter(Boolean);if(typeof t!="string"||!t.trim())return[];try{const s=JSON.parse(t);if(Array.isArray(s))return s.filter(Boolean)}catch{}return t.split(/[,\s;]+/).map(s=>s.trim()).filter(Boolean)},js=async t=>{const s=await T(a=>L.GET("/api/v1/notifications/channels",{signal:a}),t);return{success:!0,data:Ae(s,["data","channels","items"]).map(a=>{const n={},c=a.type==="ding_talk"?"dingtalk":a.type==="lark"?"feishu":a.type;return{id:String(a.id),name:a.name,type:c,config:n,event_types:ys(a.event_types),enabled:a.enabled}})}},ws=async(t,s)=>{const r=await T(n=>L.GET("/api/v1/notifications/accounts/{cid}/bindings",{params:{path:{cid:t}},signal:n}),s),a=Pe(r,["data","result"])||{};return Array.isArray(a.channel_ids)?a.channel_ids:[]},_s=({account:t,settings:s,saving:r,onChange:a,onClose:n,onSave:c})=>{const i=u=>a({...s,...u}),d=()=>i({ai_enabled:!s.ai_enabled}),b=u=>i({max_discount_percent:parseInt(Line truncated
例如:回复时保持礼貌专业、使用简洁的语言、强调产品质量等`,className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none"})]}),e.jsxs("div",{className:"bg-blue-50 border border-blue-200 rounded-xl p-4",children:[e.jsxs("h4",{className:"font-bold text-blue-900 mb-2 flex items-center gap-2",children:[e.jsx(Be,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:n,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled: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(qe,{className:"w-4 h-4"}),r?"保存中...":"保存"]})]})})]})}),document.body)},Ce=t=>({account_id:t.id,auto_rate_enabled:t.auto_rate_enabled===!0,rate_content:t.rate_content||"不错的买家,交易愉快",auto_polish_enabled:t.auto_polish_enabled===!0,polish_time:t.polish_time||"03:00",last_rate_scan_at:t.last_rate_scan_at,last_polish_date:t.last_polish_date,last_polish_at:t.last_polish_at}),Z=(t,s,r)=>t===s&&!r.aborted,ye=(t,s)=>t instanceof Error?t.message:s,je=t=>t instanceof Error&&t.message==="请求已取消",Se=(t,s)=>!t&&s==="",Ns=({account:t,onSaved:s})=>{const[r,a]=l.useState(()=>Ce(t)),[n,c]=l.useState(!0),[i,d]=l.useState(!1),[b,m]=l.useState(""),[f,h]=l.useState(""),[u,A]=l.useState(null),[k,g]=l.useState(null),p=l.useRef(0),E=l.useRef(null);l.useEffect(()=>{var N;const S=++p.current;(N=E.current)==null||N.abort();const j=new AbortController;return E.current=j,a(Ce(t)),A(null),h(""),d(!1),m(""),g(null),c(!0),ve(t.id,{signal:j.signal}).then(R=>{Z(p.current,S,j.signal)&&a(R)}).catch(R=>{Z(p.current,S,j.signal)&&!je(R)&&h(ye(R,"加载任务设置失败"))}).finally(()=>{Z(p.current,S,j.signal)&&c(!1)}),(()=>j.abort())},[t.id]),l.useEffect(()=>(()=>{var S;return(S=E.current)==null?void 0:S.abort()}),[]);const B=l.useCallback(async()=>{var N;if(!Se(i,b))return;const S=++p.current;(N=E.current)==null||N.abort();const j=new AbortController;E.current=j,d(!0),h(""),g(null);try{const R=await ke(t.id,r,{signal:j.signal});if(!Z(p.current,S,j.signal))return;a(R),s(R)}catch(R){Z(p.current,S,j.signal)&&!je(R)&&(h(ye(R,"保存失败")),g(()=>B))}finally{Z(p.current,S,j.signal)&&d(!1)}},[t.id,r,s,b,i]),G=l.useCallback(async S=>{var R;if(!Se(i,b)||!t.enabled)return;const j=++p.current;(R=E.current)==null||R.abort();const N=new AbortController;E.current=N,m(S),h(""),A(null),g(null);try{await ke(t.id,r,{signal:N.signal});const w=await ss(t.id,S,{signal:N.signal}),P=await ve(t.id,{signal:N.signal});if(!Z(p.current,j,N.signal))return;A(w.summary),a(P),s(P)}catch(w){Z(p.current,j,N.signal)&&!je(w)&&(h(ye(w,"任务执行失败")),g(()=>(()=>G(S))))}finally{Z(p.current,j,N.signal)&&m("")}},[t.enabled,t.id,r,s,b,i]),D=l.useCallback(async()=>{k&&await k()},[k]);return{form:r,loading:n,saving:i,running:b,summary:u,error:f,retryAvailable:k!==null,setForm:a,save:B,run:G,retry:D}},Re=({checked:t,onChange:s,label:r})=>e.jsx("button",{type:"button","aria-label":r,"aria-pressed":t,onClick:s,className:`relative h-8 w-14 shrink-0 rounded-full transition-colors ${t?"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 ${t?"translate-x-6":""}`})}),vs=({account:t,onClose:s,onSaved:r})=>{const{form:a,loading:n,saving:c,running:i,error:d,summary:b,retryAvailable:m,setForm:f,save:h,run:u,retry:A}=Ns({account:t,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:t.nickname||t.remark||t.id})]}),e.jsx("button",{type:"button",onClick:s,className:"rounded-xl p-2 text-slate-400 hover:bg-slate-100 hover:text-slate-700","aria-label":"关闭",children:e.jsx(ce,{className:"h-5 w-5"})})]}),e.jsxs("div",{className:"modal-body space-y-5",children:[n&&e.jsx("div",{className:"rounded-xl bg-slate-50 px-4 py-3 text-sm text-slate-500",children:"正在读取任务设置..."}),e.jsx("section",{className:"rounded-2xl border border-slate-200 bg-white p-5" Line truncated
@@ -1,3 +0,0 @@
import{b as ie,j as e,a as n,c as Oe}from"./react-vendor-l-BBvuKH.js";import{r as O,c as Pe,g as ce,o as qe,p as Le,a as G,b as Ge}from"./index-WrujSo30.js";import{n as ue,X as de,f as ze,L as J,o as Te,p as We,q as Ve,r as Ie,s as Ee,U as De,t as ae,u as Ke,k as _e,Q as Ne,v as $e,R as He,w as Je,x as Xe,y as ve,K as Ye,z as Ze,F as Fe,e as es,H as ss}from"./icons-vendor-Bgrth_9N.js";import"./vendor-cRYyTeIw.js";const ts=(t,s)=>{const r=t.avatar_url||"";if(!r)return"";try{const a=new URL(r,window.location.origin);return a.hostname.endsWith("alicdn.com")&&a.searchParams.set("_v",s),a.toString()}catch{return r}},as=async t=>{const s=await O(l=>G.GET("/api/v1/accounts/details",{signal:l}),t),r=Pe(s,["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:ts(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)}))},rs=async t=>await O(r=>G.GET("/api/v1/accounts/runtime-status",{signal:r}),t),ns=async t=>O(s=>G.POST("/api/v1/qr-login/generate",{signal:s}),{...t,timeoutMs:(t==null?void 0:t.timeoutMs)??13e4}),ls=async(t,s)=>O(r=>G.GET("/api/v1/qr-login/check/{session_id}",{params:{path:{session_id:t}},signal:r}),{signal:s,timeoutMs:1e4}),os=async(t,s)=>O(r=>G.POST("/api/v1/qr-login/complete-verification/{session_id}",{params:{path:{session_id:t}},body:{target_account_id:s||""},signal:r})),is=async(t,s)=>O(r=>G.PUT("/api/v1/accounts/{cid}/status",{params:{path:{cid:t}},body:{enabled:s},signal:r})),cs=async t=>O(s=>G.DELETE("/api/v1/accounts/{cid}",{params:{path:{cid:t}},signal:s})),ds=async(t,s,r)=>O(a=>G.PUT("/api/v1/accounts/{cid}/pause-duration",{params:{path:{cid:t}},body:{pause_duration:s},signal:a}),r),us=async(t,s,r)=>O(a=>G.PUT("/api/v1/accounts/{cid}/settings",{params:{path:{cid:t}},body:s,signal:a}),r),xs=async(t,s)=>O(r=>G.GET("/api/v1/accounts/{cid}/long-login",{params:{path:{cid:t}},signal:r}),s),ms=async(t,s,r)=>O(a=>G.PUT("/api/v1/accounts/{cid}/long-login",{params:{path:{cid:t}},body:{enabled:s},signal:a}),r),bs=async(t,s)=>O(r=>G.POST("/api/v1/password-login",{body:t,signal:r}),s),hs=async(t,s)=>O(a=>G.GET("/api/v1/password-login/check/{session_id}",{params:{path:{session_id:t}},signal:a}),{signal:s,timeoutMs:1e4}),gs=async(t,s)=>O(r=>G.DELETE("/api/v1/password-login/cancel/{session_id}",{params:{path:{session_id:t}},signal:r}),s),ps=async t=>O(s=>G.POST("/api/v1/accounts/{cid}/refresh-profile",{params:{path:{cid:t}},signal:s})),fs=async t=>{const s=await ce("/api/v1/settings/ai-reply",void 0,t);return qe(s,["settings","data","result"])||{}},ys=async(t,s)=>ce(`/api/v1/settings/ai-reply/${t}`,void 0,s),js=async(t,s,r)=>{const a={ai_enabled:s.ai_enabled??!1,max_discount_percent:s.max_discount_percent??10,max_discount_amount:s.max_discount_amount??100,max_bargain_rounds:s.max_bargain_rounds??3,custom_prompts:s.custom_prompts??""};return Le(`/api/v1/settings/ai-reply/${t}`,a,r)},ws=t=>{if(Array.isArray(t))return t.filter(Boolean);if(typeof t!="string"||!t.trim())return[];try{const s=JSON.parse(t);if(Array.isArray(s))return s.filter(Boolean)}catch{}return t.split(/[,\s;]+/).map(s=>s.trim()).filter(Boolean)},_s=async t=>{const s=await ce("/api/v1/notifications/channels",void 0,t);return{success:!0,data:Pe(s,["data","channels","items"]).map(a=>{const l={},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:ws(a.event_types),enabled:a.enabled}})}},Ns=async(t,s)=>{const r=await ce(`/api/v1/notifications/accounts/${t}/bindings`,void 0,s),a=qe(r,["data","result"])||{};return Array.isArray(a.channel_ids)?a.channel_ids:[]},vs=({account:t,settings:s,saving:r,onChange:a,onClose:l,onSave:c})=>{const i=u=>a({...s,...u}),d=()=>i({ai_enabled:!s.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.jsLine 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(Te,{className:"w-4 h-4"}),r?"保存中...":"保存"]})]})})]})}),document.body)},ke=async(t,s)=>ce(`/api/v1/account-tasks/${t}`,void 0,s),Ce=async(t,s,r)=>Le(`/api/v1/account-tasks/${t}`,s,r),ks=async(t,s,r)=>Ge(`/api/v1/account-tasks/${t}/run`,{task_type:s},{timeoutMs:12e4,...r}),Se=t=>({account_id:t.id,auto_rate_enabled:t.auto_rate_enabled===!0,rate_content:t.rate_content||"不错的买家,交易愉快",auto_polish_enabled:t.auto_polish_enabled===!0,polish_time:t.polish_time||"03:00",last_rate_scan_at:t.last_rate_scan_at,last_polish_date:t.last_polish_date,last_polish_at:t.last_polish_at}),Z=(t,s,r)=>t===s&&!r.aborted,je=(t,s)=>t instanceof Error?t.message:s,we=t=>t instanceof Error&&t.message==="请求已取消",Re=(t,s)=>!t&&s==="",Cs=({account:t,onSaved:s})=>{const[r,a]=n.useState(()=>Se(t)),[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 N;const S=++p.current;(N=L.current)==null||N.abort();const j=new AbortController;return L.current=j,a(Se(t)),A(null),h(""),d(!1),m(""),g(null),c(!0),ke(t.id,{signal:j.signal}).then(R=>{Z(p.current,S,j.signal)&&a(R)}).catch(R=>{Z(p.current,S,j.signal)&&!we(R)&&h(je(R,"加载任务设置失败"))}).finally(()=>{Z(p.current,S,j.signal)&&c(!1)}),(()=>j.abort())},[t.id]),n.useEffect(()=>(()=>{var S;return(S=L.current)==null?void 0:S.abort()}),[]);const U=n.useCallback(async()=>{var N;if(!Re(i,b))return;const S=++p.current;(N=L.current)==null||N.abort();const j=new AbortController;L.current=j,d(!0),h(""),g(null);try{const R=await Ce(t.id,r,{signal:j.signal});if(!Z(p.current,S,j.signal))return;a(R),s(R)}catch(R){Z(p.current,S,j.signal)&&!we(R)&&(h(je(R,"保存失败")),g(()=>U))}finally{Z(p.current,S,j.signal)&&d(!1)}},[t.id,r,s,b,i]),M=n.useCallback(async S=>{var R;if(!Re(i,b)||!t.enabled)return;const j=++p.current;(R=L.current)==null||R.abort();const N=new AbortController;L.current=N,m(S),h(""),A(null),g(null);try{await Ce(t.id,r,{signal:N.signal});const w=await ks(t.id,S,{signal:N.signal}),P=await ke(t.id,{signal:N.signal});if(!Z(p.current,j,N.signal))return;A(w.summary),a(P),s(P)}catch(w){Z(p.current,j,N.signal)&&!we(w)&&(h(je(w,"任务执行失败")),g(()=>(()=>M(S))))}finally{Z(p.current,j,N.signal)&&m("")}},[t.enabled,t.id,r,s,b,i]),I=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:I}},Ae=({checked:t,onChange:s,label:r})=>e.jsx("button",{type:"button","aria-label":r,"aria-pressed":t,onClick:s,className:`relative h-8 w-14 shrink-0 rounded-full transition-colors ${t?"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 ${t?"translate-x-6":""}`})}),Ss=({account:t,onClose:s,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}=Cs({account:t,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:t.nickname||t.remark||t.id})]}),e.jsx("button",{type:"button",onClick:s,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,17 +1,17 @@
import{a as i,b as z,j as e}from"./react-vendor-l-BBvuKH.js";import{g as Z,c as ee,p as te,e as ae,b as H,d as se}from"./index-WrujSo30.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-Bgrth_9N.js";import"./vendor-cRYyTeIw.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
import{a as c,b as U,j as e}from"./react-vendor-l-BBvuKH.js";import{r as M,c as O,a as ee}from"./index-CiBUw4Te.js";import{c as te}from"./contract-COFcZjyb.js";import{X as V,W as ae,J as z,Y as se,L as q,N as J,C as X,_ as le,$ as Y,a0 as K,a1 as ne,I as re,a2 as oe,V as ce,y as ie,P as de,o as xe}from"./icons-vendor-Bgrth_9N.js";import"./vendor-cRYyTeIw.js";const pe=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}},Q=l=>({name:l.name,type:l.type,api_config:l.api_config?JSON.stringify(l.api_config):"",text_content:l.text_content,data_content:l.data_content,image_url:l.image_url,description:l.description,enabled:l.enabled,delay_seconds:l.delay_seconds,is_multi_spec:l.is_multi_spec,spec_name:l.spec_name,spec_value:l.spec_value}),me=async l=>{const n=await M(p=>O.GET("/api/v1/cards",{signal:p}),l);return te(n,["cards","data","items"]).map(pe)},he=async l=>M(n=>O.POST("/api/v1/cards",{body:Q(l),signal:n})),H=async(l,n)=>M(a=>O.PUT("/api/v1/cards/{card_id}",{params:{path:{card_id:String(l)}},body:Q(n),signal:a})),ue=async l=>M(n=>O.DELETE("/api/v1/cards/{card_id}",{params:{path:{card_id:String(l)}},signal:n})),be=async(l,n)=>{const a=new FormData;return a.append("file",l),M(p=>O.POST("/api/v1/cards/batch",{body:ee(a),signal:p}),n)},ge=async(l,n,a)=>M(p=>O.POST("/api/v1/cards/{card_id}/append-data",{params:{path:{card_id:String(l)}},body:{content:n},signal:p}),a),ye=(l,n,a)=>{const p=a.trim().toLocaleLowerCase();return l.filter(h=>(!n||h.type===n)&&(!p||h.name.toLocaleLowerCase().includes(p)))},Z=l=>l.split(`
`).map(n=>n.trim()).filter(Boolean),fe=(l,n,a)=>!!(l&&Z(n).length>0&&!a),F=(l,n,a,p)=>l===n&&a===p,W=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),G=(l,n)=>l instanceof Error?l.message:n,je=({cards:l,loadCards:n})=>{const[a,p]=c.useState(!1),[h,_]=c.useState(!1),[f,j]=c.useState(null),[d,T]=c.useState({}),[i,y]=c.useState(W),[N,b]=c.useState(""),[r,x]=c.useState(""),s=c.useMemo(()=>l.filter(o=>o.type==="data"),[l]),u=c.useMemo(()=>ye(l,N,r),[l,r,N]),I=c.useCallback(o=>{var t,g,k,S,C;j(o),T({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}),p(!0)},[]),L=c.useCallback(async()=>{var o,t,g,k,S,C,m,A;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=((m=d.data_content)==null?void 0:m.trim())||"":d.type==="image"&&(w.image_url=((A=d.image_url)==null?void 0:A.trim())||""),await H(f.id,w),p(!1),await n()}catch(w){console.error("更新卡密失败:",w),alert(G(w,"更新失败,请重试"))}}},[d,n,f]),P=c.useCallback(async o=>{if(confirm("确认删除该卡密吗?"))try{await ue(o),await n()}catch(t){console.error("删除卡密失败:",t),alert(G(t,"删除失败,请重试"))}},[n]),v=c.useCallback(async()=>{if(!i.name.trim()){alert("请输入卡密名称");return}if(!i.content.trim()){alert(i.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const o={name:i.name.trim(),type:i.type,description:i.description.trim(),enabled:i.enabled,delay_seconds:i.delay_seconds};i.type==="text"&&(o.text_content=i.content.trim()),i.type==="data"&&(o.data_content=i.content.trim()),i.type==="image"&&(o.image_url=i.content.trim()),i.type==="api"&&(o.api_config={url:i.content.trim(),method:i.api_method,timeout:i.api_timeout,headers:i.api_headers.trim()||void 0,params:i.api_params.trim()||void 0}),await he(o),_(!1),y(W()),await n()}catch(o){console.error("添加卡密失败:",o),alert(G(o,"添加失败,请重试"))}},[i,n]),B=c.useCallback(async o=>{try{await H(o.id,{...o,enabled:!o.enabled}),await n()}catch(t){console.error("切换状态失败:",t)}},[n]),R=c.useCallback(async o=>{try{await navigator.clipboard.writeText(String(o)),alert(`已复制卡密组ID:${o}`)}catch{prompt("复制卡密组ID",String(o))}},[]),D=c.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(`
`),k=new Blob(["\uFEFF"+g],{type:"text/csv;charset=utf-8"}),S=URL.createObjectURL(k),C=document.createElement("a");C.href=S,C.download="卡密组批量导入模板.csv",document.body.appendChild(C),C.click(),C.remove(),URL.revokeObjectURL(S)},[]);return{dataCards:s,filteredCards:h,typeFilter:N,setTypeFilter:b,nameSearch:r,setNameSearch:x,showEditModal:a,setShowEditModal:u,showAddModal:m,setShowAddModal:_,selectedCard:f,editForm:d,setEditForm:A,addForm:c,setAddForm:y,handleEdit:E,handleSaveEdit:M,handleDelete:R,handleAddCard:v,toggleCardStatus:T,copyCardID:P,downloadCardTemplate:$}},we=({dataCards:l,downloadCardTemplate:n,...a})=>{var x;const u=s=>{var h;a.setBatchFile(((h=s.target.files)==null?void 0:h[0])||null)},m=s=>{a.setAppendContent(s.target.value)},_=s=>{a.setAppendTargetId(s.target.value)},f=()=>a.closeBatchModal(),j=()=>a.setBatchTab("create"),d=()=>a.setBatchTab("append"),A=()=>void a.handleRetryBatchCreate(),c=()=>void a.handleRetryBatchAppend(),y=a.batchResult&&"rows"in a.batchResult?a.batchResult:null,N=s=>e.jsxs("option",{value:String(s.id),children:[s.name,"(ID: ",s.id,")"]},s.id),b=()=>void a.handleBatchCreate(),r=()=>void a.handleBatchAppend();return a.showBatchModal?z.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:f,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(G,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:j,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(le,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:d,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(O,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),a.batchTab==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),"。 类型填 text/data/image;data 类型的“内容”按行存卡密(CSV 单元格内换行需用引号包裹)。"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:n,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm transition-colors",children:[e.jsx(ne,{className:"w-4 h-4"}),"下载模板"]}),e.jsxs("label",{className:"flex-1 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm cursor-pointer transition-colors",children:[e.jsx(O,{className:"w-4 h-4"}),a.batchFile?a.batchFile.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:u})]})]}),((x=a.batchResult)==null?void 0:x.error)&&e.jsxs("div",{className:"rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.batchResult.error}),e.jsx("button",{type:"button",onClick:A,disabled:!a.batchFile||a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),y&&e.jsxs("div",{className:"rounded-xl border border-gray-200 p-4 space-y-2",children:[e.jsxs("div",{className:"text-sm font-bold text-gray-900",children:["共 ",y.total," 行 · 成功 ",y.created," · 失败 ",y.failed]}),y.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:y.rows.filter(s=>!s.success).map(s=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",s.row_no," 行「",s.name,"」:",s.error]},s.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:l.length===0?e.jsx("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 text-sm text-amber-800",children:"暂无 data(批量卡密)类型的卡密组,请先创建一个再充卡密。"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"选择卡密组"}),e.jsx("select",{value:a.appendTargetId,onChange:_,className:"w-full Line truncated
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(m=>m.map(A=>`"${String(A).replace(/"/g,'""')}"`).join(",")).join(`
`),k=new Blob(["\uFEFF"+g],{type:"text/csv;charset=utf-8"}),S=URL.createObjectURL(k),C=document.createElement("a");C.href=S,C.download="卡密组批量导入模板.csv",document.body.appendChild(C),C.click(),C.remove(),URL.revokeObjectURL(S)},[]);return{dataCards:s,filteredCards:u,typeFilter:N,setTypeFilter:b,nameSearch:r,setNameSearch:x,showEditModal:a,setShowEditModal:p,showAddModal:h,setShowAddModal:_,selectedCard:f,editForm:d,setEditForm:T,addForm:i,setAddForm:y,handleEdit:I,handleSaveEdit:L,handleDelete:P,handleAddCard:v,toggleCardStatus:B,copyCardID:R,downloadCardTemplate:D}},Ne=({dataCards:l,downloadCardTemplate:n,...a})=>{var x;const p=s=>{var u;a.setBatchFile(((u=s.target.files)==null?void 0:u[0])||null)},h=s=>{a.setAppendContent(s.target.value)},_=s=>{a.setAppendTargetId(s.target.value)},f=()=>a.closeBatchModal(),j=()=>a.setBatchTab("create"),d=()=>a.setBatchTab("append"),T=()=>void a.handleRetryBatchCreate(),i=()=>void a.handleRetryBatchAppend(),y=a.batchResult&&"rows"in a.batchResult?a.batchResult:null,N=s=>e.jsxs("option",{value:String(s.id),children:[s.name,"(ID: ",s.id,")"]},s.id),b=()=>void a.handleBatchCreate(),r=()=>void a.handleBatchAppend();return a.showBatchModal?U.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:f,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(V,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:j,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(ae,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:d,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(z,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),a.batchTab==="create"?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-xl bg-blue-50 border border-blue-100 p-4 text-xs text-blue-900 leading-5",children:["上传表格,每行一个卡密组。表头:",e.jsx("code",{className:"bg-blue-100/70 px-1.5 py-0.5 rounded",children:"名称,类型,内容,描述,启用,延迟秒,多规格,规格名,规格值"}),"。 类型填 text/data/image;data 类型的“内容”按行存卡密(CSV 单元格内换行需用引号包裹)。"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{onClick:n,className:"px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm transition-colors",children:[e.jsx(se,{className:"w-4 h-4"}),"下载模板"]}),e.jsxs("label",{className:"flex-1 px-4 py-2.5 bg-gray-100 hover:bg-gray-200 rounded-xl font-bold text-gray-700 flex items-center gap-2 text-sm cursor-pointer transition-colors",children:[e.jsx(z,{className:"w-4 h-4"}),a.batchFile?a.batchFile.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:p})]})]}),((x=a.batchResult)==null?void 0:x.error)&&e.jsxs("div",{className:"rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.batchResult.error}),e.jsx("button",{type:"button",onClick:T,disabled:!a.batchFile||a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),y&&e.jsxs("div",{className:"rounded-xl border border-gray-200 p-4 space-y-2",children:[e.jsxs("div",{className:"text-sm font-bold text-gray-900",children:["共 ",y.total," 行 · 成功 ",y.created," · 失败 ",y.failed]}),y.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:y.rows.filter(s=>!s.success).map(s=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",s.row_no," 行「",s.name,"」:",s.error]},s.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:l.length===0?e.jsx("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 text-sm text-amber-800",children:"暂无 data(批量卡密)类型的卡密组,请先创建一个再充卡密。"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"选择卡密组"}),e.jsx("select",{value:a.appendTargetId,onChange:_,className:"w-full Line truncated
VIP-002
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["预览:",a.appendPreview.length," 个有效卡密,空行自动忽略。"]})]}),a.appendError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-200 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.appendError}),e.jsx("button",{type:"button",onClick:c,disabled:a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),a.appendResult&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",a.appendResult.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:f,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),a.batchTab==="create"?e.jsxs("button",{onClick:b,disabled:!a.batchFile||a.batchBusy,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(V,{className:"w-4 h-4 animate-spin"}):e.jsx(O,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:r,disabled:!a.appendTargetId||a.appendPreview.length===0||a.batchBusy||l.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(V,{className:"w-4 h-4 animate-spin"}):e.jsx(U,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},Ce=({type:l})=>{switch(l){case"text":return e.jsx(Y,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(X,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(re,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(W,{className:"w-5 h-5 text-gray-500"})}},_e=()=>{const[l,n]=i.useState([]),[a,u]=i.useState(!0),m=i.useRef(0),_=i.useRef(null),f=i.useCallback(async()=>{var A;const j=++m.current;(A=_.current)==null||A.abort();const d=new AbortController;_.current=d,u(!0);try{const c=await ue({signal:d.signal});if(j!==m.current)return;n(c)}catch(c){j===m.current&&!d.signal.aborted&&console.error("加载卡密库存失败:",c)}finally{j===m.current&&u(!1)}},[]);return i.useEffect(()=>(f(),()=>{var d;m.current+=1,(d=_.current)==null||d.abort()}),[f]),{cards:l,setCards:n,loading:a,loadCards:f}},ke=l=>{const n=l.dataCards,a=l.loadCards,[u,m]=i.useState(!1),[_,f]=i.useState("create"),[j,d]=i.useState(null),[A,c]=i.useState(null),[y,N]=i.useState(!1),[b,r]=i.useState(""),[x,s]=i.useState(""),[h,E]=i.useState(null),[M,R]=i.useState(""),v=i.useRef(0),T=i.useRef(null),P=i.useRef("");i.useEffect(()=>(()=>{var p;v.current+=1,(p=T.current)==null||p.abort()}),[]);const $=i.useMemo(()=>Q(x),[x]),o=i.useCallback(()=>{var p;f("create"),d(null),c(null),r((p=n[0])!=null&&p.id?String(n[0].id):""),s(""),E(null),R(""),m(!0)},[n]),t=i.useCallback(()=>{var p;v.current+=1,(p=T.current)==null||p.abort(),N(!1),m(!1)},[]),g=i.useCallback(async()=>{var w;if(!j||y)return;const p=++v.current;(w=T.current)==null||w.abort();const B=new AbortController;T.current=B,N(!0),c(null);try{const I=await ye(j,{signal:B.signal});if(!F(p,v.current,"",""))return;c(I),I.created>0&&await a()}catch(I){if(!F(p,v.current,"",""))return;c({error:(I==null?void 0:I.message)||"上传失败"})}finally{F(p,v.current,"","")&&N(!1)}},[y,j,a]),k=i.useCallback(async()=>{var I;if(!Ne(b,x,y))return;const p=b,B=++v.current;P.current=p,(I=T.current)==null||I.abort();const w=new AbortController;T.current=w,N(!0),E(null),R("");try{const L=await fe(p,x,{signal:w.signal});if(!F(B,v.current,p,b))return;E({added:L.added}),s(""),await a()}catch(L){if(!F(B,v.current,p,b))return;R((L==null?void 0:L.message)||"追加失败")}finally{F(B,v.current,p,b)&&N(!1)}},[x,b,y,a]),S=i.useCallback(async()=>{await g()},[g]),C=i.useCallback(async()=>{P.current&&b!==P.current||await k()},[b,k]);return{showBatchModal:u,setShowBatchModal:m,batchTab:_,setBatchTab:f,batchFile:j,setBatchFile:d,batchResult:A,batchBusy:y,appendTargetId:b,setAppendTargetId:r,appendContent:x,setAppendContent:s,appendResult:h,appendError:M,appendPreview:$,openBatchModal:o,closeBatchModal:t,handleBatchCreate:g,handleBatchAppend:k,handleRetryBatchCreate:S,handleRetryBatchAppend:C}},Ie=()=>{const{cards:l,loadCards:n}=_e(),a=ve({cards:l,loadCards:n}),{dataCards:u,filteredCards:m,typeFilter:_,setTypeFilter:f,nameSearch:j,setNameSearch:d,showEditModal:A,setShowEditModal:c,showAddModal:y,setShowAddModal:N,selectedCard:b,editForm:r,setEditForm:x,addForm:s,setAddForm:h,handleEdit:E,handleSaveEdit:M,handleDelete:R,handleAddCard:v,toggleCardStatus:T,copyCardID:P,downloadCardTemplate:$}=a,o=ke({dataCards:u,loadCards:n});return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex- Line truncated
`).filter(S=>S.trim()).length} 条`:t.type==="text"&&t.text_content?g=t.text_content:t.type==="api"&&t.api_config?g=t.api_config.url:t.type==="image"&&t.image_url&&(g="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(Ce,{type:t.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:t.name,children:t.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:(()=>P(t.id)),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:t.id}),e.jsx(ce,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${t.type==="text"?"bg-blue-50 text-blue-600":t.type==="data"?"bg-purple-50 text-purple-600":t.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:t.type==="text"?"文本":t.type==="data"?"批量":t.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:g,children:g})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:t.description||"-",children:t.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:(()=>T(t)),"aria-label":`切换卡密 ${t.name} 状态`,className:`w-12 h-8 rounded-full relative transition-colors ${t.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${t.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:(()=>E(t)),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(de,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>R(t.id)),"aria-label":`删除卡密 ${t.name}`,className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(xe,{className:"h-4 w-4"})})]})})]},t.id)})})]})}),m.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(pe,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:l.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),A&&b&&z.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:(()=>c(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(G,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:r.name||"",onChange:(t=>x({...r,name:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:r.type||"text",onChange:(t=>x({...r,type:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(b==null?void 0:b.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),r.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:r.api_url||"",onChange:(t=>x({...r,api_url:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https:/Line truncated
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["预览:",a.appendPreview.length," 个有效卡密,空行自动忽略。"]})]}),a.appendError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-200 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.appendError}),e.jsx("button",{type:"button",onClick:i,disabled:a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),a.appendResult&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",a.appendResult.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:f,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),a.batchTab==="create"?e.jsxs("button",{onClick:b,disabled:!a.batchFile||a.batchBusy,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(q,{className:"w-4 h-4 animate-spin"}):e.jsx(z,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:r,disabled:!a.appendTargetId||a.appendPreview.length===0||a.batchBusy||l.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(q,{className:"w-4 h-4 animate-spin"}):e.jsx(J,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},ve=({type:l})=>{switch(l){case"text":return e.jsx(K,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(Y,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(le,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(X,{className:"w-5 h-5 text-gray-500"})}},we=()=>{const[l,n]=c.useState([]),[a,p]=c.useState(!0),h=c.useRef(0),_=c.useRef(null),f=c.useCallback(async()=>{var T;const j=++h.current;(T=_.current)==null||T.abort();const d=new AbortController;_.current=d,p(!0);try{const i=await me({signal:d.signal});if(j!==h.current)return;n(i)}catch(i){j===h.current&&!d.signal.aborted&&console.error("加载卡密库存失败:",i)}finally{j===h.current&&p(!1)}},[]);return c.useEffect(()=>(f(),()=>{var d;h.current+=1,(d=_.current)==null||d.abort()}),[f]),{cards:l,setCards:n,loading:a,loadCards:f}},Ce=l=>{const n=l.dataCards,a=l.loadCards,[p,h]=c.useState(!1),[_,f]=c.useState("create"),[j,d]=c.useState(null),[T,i]=c.useState(null),[y,N]=c.useState(!1),[b,r]=c.useState(""),[x,s]=c.useState(""),[u,I]=c.useState(null),[L,P]=c.useState(""),v=c.useRef(0),B=c.useRef(null),R=c.useRef("");c.useEffect(()=>(()=>{var m;v.current+=1,(m=B.current)==null||m.abort()}),[]);const D=c.useMemo(()=>Z(x),[x]),o=c.useCallback(()=>{var m;f("create"),d(null),i(null),r((m=n[0])!=null&&m.id?String(n[0].id):""),s(""),I(null),P(""),h(!0)},[n]),t=c.useCallback(()=>{var m;v.current+=1,(m=B.current)==null||m.abort(),N(!1),h(!1)},[]),g=c.useCallback(async()=>{var w;if(!j||y)return;const m=++v.current;(w=B.current)==null||w.abort();const A=new AbortController;B.current=A,N(!0),i(null);try{const E=await be(j,{signal:A.signal});if(!F(m,v.current,"",""))return;i(E),E.created>0&&await a()}catch(E){if(!F(m,v.current,"",""))return;i({error:(E==null?void 0:E.message)||"上传失败"})}finally{F(m,v.current,"","")&&N(!1)}},[y,j,a]),k=c.useCallback(async()=>{var E;if(!fe(b,x,y))return;const m=b,A=++v.current;R.current=m,(E=B.current)==null||E.abort();const w=new AbortController;B.current=w,N(!0),I(null),P("");try{const $=await ge(m,x,{signal:w.signal});if(!F(A,v.current,m,b))return;I({added:$.added}),s(""),await a()}catch($){if(!F(A,v.current,m,b))return;P(($==null?void 0:$.message)||"追加失败")}finally{F(A,v.current,m,b)&&N(!1)}},[x,b,y,a]),S=c.useCallback(async()=>{await g()},[g]),C=c.useCallback(async()=>{R.current&&b!==R.current||await k()},[b,k]);return{showBatchModal:p,setShowBatchModal:h,batchTab:_,setBatchTab:f,batchFile:j,setBatchFile:d,batchResult:T,batchBusy:y,appendTargetId:b,setAppendTargetId:r,appendContent:x,setAppendContent:s,appendResult:u,appendError:L,appendPreview:D,openBatchModal:o,closeBatchModal:t,handleBatchCreate:g,handleBatchAppend:k,handleRetryBatchCreate:S,handleRetryBatchAppend:C}},Be=()=>{const{cards:l,loadCards:n}=we(),a=je({cards:l,loadCards:n}),{dataCards:p,filteredCards:h,typeFilter:_,setTypeFilter:f,nameSearch:j,setNameSearch:d,showEditModal:T,setShowEditModal:i,showAddModal:y,setShowAddModal:N,selectedCard:b,editForm:r,setEditForm:x,addForm:s,setAddForm:u,handleEdit:I,handleSaveEdit:L,handleDelete:P,handleAddCard:v,toggleCardStatus:B,copyCardID:R,downloadCardTemplate:D}=a,o=Ce({dataCards:p,loadCards:n});return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex- Line truncated
`).filter(S=>S.trim()).length} 条`:t.type==="text"&&t.text_content?g=t.text_content:t.type==="api"&&t.api_config?g=t.api_config.url:t.type==="image"&&t.image_url&&(g="图片链接"),e.jsxs("tr",{className:"hover:bg-warning-50/50 transition-colors group",children:[e.jsx("td",{className:"px-5 py-5 align-middle",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"shrink-0 rounded-xl bg-gray-50 p-2 transition-colors group-hover:bg-white",children:e.jsx(ve,{type:t.type})}),e.jsx("span",{className:"line-clamp-3 min-w-0 text-[13px] font-bold leading-5 text-gray-900",title:t.name,children:t.name})]})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("button",{onClick:(()=>R(t.id)),className:"inline-flex max-w-full items-center gap-1 rounded-lg bg-gray-100 px-2 py-1.5 font-mono text-[11px] font-extrabold text-gray-700 transition-colors hover:bg-gray-200",title:"复制卡密组ID,用于批量铺货表格",children:[e.jsx("span",{className:"truncate",children:t.id}),e.jsx(oe,{className:"h-3 w-3 shrink-0"})]})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("span",{className:`inline-flex rounded-md px-2 py-1 text-[11px] font-bold ${t.type==="text"?"bg-blue-50 text-blue-600":t.type==="data"?"bg-purple-50 text-purple-600":t.type==="api"?"bg-blue-50 text-blue-600":"bg-pink-50 text-pink-600"}`,children:t.type==="text"?"文本":t.type==="data"?"批量":t.type==="api"?"API":"图片"})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"line-clamp-3 break-all font-mono text-sm leading-5 text-gray-600",title:g,children:g})}),e.jsx("td",{className:"px-5 py-5",children:e.jsx("span",{className:"block truncate text-sm text-gray-500",title:t.description||"-",children:t.description||"-"})}),e.jsx("td",{className:"px-2 py-5",children:e.jsx("button",{onClick:(()=>B(t)),"aria-label":`切换卡密 ${t.name} 状态`,className:`w-12 h-8 rounded-full relative transition-colors ${t.enabled?"bg-green-500":"bg-gray-300"}`,children:e.jsx("div",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-sm transition-transform ${t.enabled?"left-5":"left-1"}`})})}),e.jsx("td",{className:"px-3 py-5",children:e.jsxs("div",{className:"flex items-center justify-end gap-0.5",children:[e.jsx("button",{onClick:(()=>I(t)),className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-black",title:"编辑",children:e.jsx(ce,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>P(t.id)),"aria-label":`删除卡密 ${t.name}`,className:"rounded-lg p-1.5 text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",children:e.jsx(ie,{className:"h-4 w-4"})})]})})]},t.id)})})]})}),h.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(de,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:l.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),T&&b&&U.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsxs("div",{className:"modal-header",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"编辑卡密"}),e.jsx("button",{onClick:(()=>i(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(V,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:["卡密名称 ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx("input",{type:"text",value:r.name||"",onChange:(t=>x({...r,name:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",placeholder:"例如:游戏点卡、会员卡等"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡券类型"}),e.jsxs("select",{value:r.type||"text",onChange:(t=>x({...r,type:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"",children:"请选择类型"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"data",children:"批量数据"}),(b==null?void 0:b.type)==="api"&&e.jsx("option",{value:"api",children:"API接口(仅保留现有配置)"}),e.jsx("option",{value:"image",children:"图片"})]})]})]}),r.type==="api"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"API 地址"}),e.jsx("input",{type:"url",value:r.api_url||"",onChange:(t=>x({...r,api_url:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https:/Line truncated
卡号1:密码1
卡号2:密码2
或者
兑换码1
兑换码2`}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持格式:卡号:密码 或 单独的兑换码"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-blue-600",children:r.data_content?r.data_content.split(`
`).filter(t=>t.trim()).length:0})," 条"]})]})]}),r.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:r.image_url||"",onChange:(t=>x({...r,image_url:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"仅保存图片 URL;发货时会临时下载并上传到闲鱼"})]}),r.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:r.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:(t=>{t.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"})})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:r.delay_seconds||0,onChange:(t=>x({...r,delay_seconds:parseInt(t.target.value)||0})),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:r.description||"",onChange:(t=>x({...r,description:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:(()=>x({...r,enabled:!r.enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${r.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${r.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>c(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:M,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(me,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),y&&z.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:(()=>N(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(G,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:s.name,onChange:(t=>h({...s,name:t.target.value})),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:(()=>h({...s,type:"data",content:""})),className:`p-3 rounded-xl font-bold transition-all ${s.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(W,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:(()=>h({...s,type:"text",content:""})),className:`p-3 rounded-xl font-bold transition-all ${s.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(Y,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:(()=>h({...s,type:"image",content:""})),className:`p-3 rounded-xl font-bold transition-all ${s.type==="image"?"bg-brand tLine truncated
`).filter(t=>t.trim()).length:0})," 条"]})]})]}),r.type==="image"&&e.jsxs("div",{className:"border border-gray-200 rounded-xl p-4 bg-gray-50",children:[e.jsx("h3",{className:"font-bold text-gray-900 mb-3",children:"图片配置"}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片 URL"}),e.jsx("input",{type:"url",value:r.image_url||"",onChange:(t=>x({...r,image_url:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl font-mono text-sm",placeholder:"https://example.com/image.png"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"仅保存图片 URL;发货时会临时下载并上传到闲鱼"})]}),r.image_url&&e.jsxs("div",{className:"mt-3",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"图片预览"}),e.jsx("img",{src:r.image_url,alt:"预览",className:"max-w-full max-h-48 rounded-xl border border-gray-200",onError:(t=>{t.currentTarget.src="https://via.placeholder.com/400x200?text=图片加载失败"})})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"延时发货时间(秒)"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"number",value:r.delay_seconds||0,onChange:(t=>x({...r,delay_seconds:parseInt(t.target.value)||0})),className:"flex-1 ios-input px-4 py-3 rounded-xl",min:"0",max:"3600",placeholder:"0"}),e.jsx("span",{className:"text-sm text-gray-500 whitespace-nowrap",children:"秒"})]}),e.jsx("p",{className:"text-xs text-gray-500 mt-1",children:"0表示立即发货,最大3600秒(1小时)"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"备注信息"}),e.jsx("textarea",{value:r.description||"",onChange:(t=>x({...r,description:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-40 resize-none",placeholder:"可选的备注信息"})]}),e.jsxs("div",{className:"flex items-center justify-between p-4 bg-gray-50 rounded-xl",children:[e.jsx("span",{className:"font-bold text-gray-900",children:"启用状态"}),e.jsx("button",{type:"button",onClick:(()=>x({...r,enabled:!r.enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${r.enabled?"bg-brand":"bg-gray-300"}`,children:e.jsx("span",{className:`absolute top-1 w-6 h-6 bg-white rounded-full shadow-md transition-transform duration-300 block ${r.enabled?"translate-x-7":"translate-x-1"}`})})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>i(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:L,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(xe,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),y&&U.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"780px"},children:[e.jsxs("div",{className:"modal-header flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"添加新卡密"}),e.jsx("p",{className:"text-sm text-gray-500 mt-1",children:"选择交付方式并录入自动发货内容"})]}),e.jsx("button",{onClick:(()=>N(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(V,{className:"w-5 h-5 text-gray-500"})})]}),e.jsx("div",{className:"modal-body",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"卡密名称"}),e.jsx("input",{type:"text",value:s.name,onChange:(t=>u({...s,name:t.target.value})),placeholder:"例如:VIP会员卡密",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"类型"}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:[e.jsxs("button",{type:"button",onClick:(()=>u({...s,type:"data",content:""})),className:`p-3 rounded-xl font-bold transition-all ${s.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(X,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:(()=>u({...s,type:"text",content:""})),className:`p-3 rounded-xl font-bold transition-all ${s.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(K,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:(()=>u({...s,type:"image",content:""})),className:`p-3 rounded-xl font-bold transition-all ${s.type==="image"?"bg-brand tLine truncated
CODE-789012
...`:"请输入每次发货时发送的固定文字"}),s.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:s.content.split(`
`).filter(t=>t.trim()).length})," 条"]})]}),s.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:s.api_method,onChange:(t=>h({...s,api_method:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:s.api_timeout,onChange:(t=>h({...s,api_timeout:parseInt(t.target.value)||10})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:s.api_headers,onChange:(t=>h({...s,api_headers:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:s.api_params,onChange:(t=>h({...s,api_params:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:s.description,onChange:(t=>h({...s,description:t.target.value})),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:s.delay_seconds,onChange:(t=>h({...s,delay_seconds:parseInt(t.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>N(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:v,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(U,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(we,{dataCards:u,downloadCardTemplate:$,...o})]})};export{Ie as default};
`).filter(t=>t.trim()).length})," 条"]})]}),s.type==="api"&&e.jsxs("div",{className:"border-t border-gray-100 pt-5 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求方法"}),e.jsxs("select",{value:s.api_method,onChange:(t=>u({...s,api_method:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl",children:[e.jsx("option",{value:"GET",children:"GET"}),e.jsx("option",{value:"POST",children:"POST"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"超时时间(秒)"}),e.jsx("input",{type:"number",min:"1",max:"60",value:s.api_timeout,onChange:(t=>u({...s,api_timeout:parseInt(t.target.value)||10})),className:"w-full ios-input px-4 py-3 rounded-xl"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求头(JSON)"}),e.jsx("textarea",{value:s.api_headers,onChange:(t=>u({...s,api_headers:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"Authorization":"Bearer token"}'})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"请求参数(JSON)"}),e.jsx("textarea",{value:s.api_params,onChange:(t=>u({...s,api_params:t.target.value})),className:"w-full ios-input px-4 py-3 rounded-xl h-24 resize-none font-mono text-xs",placeholder:'{"order_id":"{order_id}"}'})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"描述"}),e.jsx("input",{value:s.description,onChange:(t=>u({...s,description:t.target.value})),placeholder:"卡密用途描述(可选)",className:"w-full ios-input px-4 py-3 rounded-xl"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700",children:"延时发货(秒)"}),e.jsx("input",{type:"number",value:s.delay_seconds,onChange:(t=>u({...s,delay_seconds:parseInt(t.target.value)||0})),className:"w-full ios-input px-4 py-3 rounded-xl",min:"0",max:"3600"})]})]})]})}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:(()=>N(!1)),className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",children:"取消"}),e.jsxs("button",{onClick:v,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(J,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(Ne,{dataCards:p,downloadCardTemplate:D,...o})]})};export{Be as default};
@@ -1 +1 @@
import{j as e,c as x0,a as i}from"./react-vendor-l-BBvuKH.js";import{L as re}from"./vendor-cRYyTeIw.js";import{f as M0,h as le,i as F0,m as P0,s as ce,j as oe,k as pe,l as me,n as z0}from"./index-WrujSo30.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-Bgrth_9N.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,a as i}from"./react-vendor-l-BBvuKH.js";import{L as re}from"./vendor-cRYyTeIw.js";import{g as M0,p as le,b as F0,m as P0,s as ce,d as oe,e as pe,f as me,h as z0}from"./index-CiBUw4Te.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-Bgrth_9N.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 +0,0 @@
import{j as e,a as c}from"./react-vendor-l-BBvuKH.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-Bgrth_9N.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-DlHaeEQJ.js";import{g as q,c as xe,o as De}from"./index-WrujSo30.js";import"./vendor-cRYyTeIw.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
@@ -0,0 +1 @@
import{j as e,a as c}from"./react-vendor-l-BBvuKH.js";import{f as ge}from"./dateTime-DDi7rqpW.js";import{j as xe,k as he,l as se,D as pe,c as be,P as fe,m as ae,E as ye,T as je}from"./icons-vendor-Bgrth_9N.js";import{R as q,B as ve,X as re,Y as ne,T as W,a as Ne,C as X,A as we,b as _e,c as ke,P as le,d as oe,L as De}from"./charts-vendor-DlHaeEQJ.js";import{r as M,c as K}from"./index-CiBUw4Te.js";import{c as ue,o as Se}from"./contract-COFcZjyb.js";import"./vendor-cRYyTeIw.js";const F=t=>{const a=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),l=String(t.getDate()).padStart(2,"0");return`${a}-${s}-${l}`},J=(t,a)=>{const s=new Date(t);return s.setHours(12,0,0,0),s.setDate(s.getDate()+a),s},H=(t,a)=>({startDate:F(J(t,-(a-1))),endDate:F(t)}),me=(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"?H(J(a,-1),1):H(a,t==="3days"?3:t==="30days"?30:t==="today"?1:7)},Ce=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=J(a,-1);return H(n,l)},i=(t,a)=>a===void 0?`rgb(var(--color-${t}))`:`rgb(var(--color-${t}) / ${a})`,$e=({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(xe,{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(q,{width:"100%",height:"100%",children:e.jsxs(ve,{data:t,margin:{top:30,right:20,left:0,bottom:30},barCategoryGap:"45%",children:[e.jsx(re,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-700"),fontSize:14,fontWeight:600},dy:10}),e.jsx(ne,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},tickFormatter:(l=>`¥${l}`)}),e.jsx(W,{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(Ne,{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(X,{fill:i("brand"),stroke:"none",strokeWidth:0},`cell-${n}`))})]})}):e.jsx(q,{width:"100%",height:"100%",children:e.jsxs(we,{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(re,{dataKey:"name",axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500},dy:15}),e.jsx(ne,{axisLine:!1,tickLine:!1,tick:{fill:i("neutral-400"),fontSize:13,fontWeight:500}}),e.jsx(_e,{vertical:!1,stroke:i("neutral-100"),strokeDasharray:"3 3"}),e.jsx(W,{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(ke,{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}})]})})})]}),ie=t=>{const a=String(t||"");return a==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(a)?a:"unknown"},Re=async t=>M(a=>K.GET("/api/v1/analytics/dashboard",{signal:a}),t),Le=async(t,a)=>{const s=await M(n=>K.GET("/api/v1/items",{params:{query:{cookie_id:t}},signal:n}),a);return ue(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}))},ce=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:F(n),end_date:F(l)}}else s=t;return M(l=>K.GET("/api/v1/analytics/orders",{params:{query:{...s,timezone_offset_minutes:-new Date().getTimezoneOffset()}},signal:l}),a)},Te=async(t,a)=>{const s=await M(u=>K.GET("/api/v1/analytics/orders/valid",{params:{query:{...t,timezone_oLine truncated
@@ -0,0 +1,2 @@
import{j as e,a as r,b as we}from"./react-vendor-l-BBvuKH.js";import{r as q,c as B,A as bt}from"./index-CiBUw4Te.js";import{c as Qe}from"./contract-COFcZjyb.js";import{a3 as gt,U as $e,R as Se,N as De,a4 as Pe,a5 as _e,V as yt,y as ft,B as jt,a6 as Oe,a7 as vt,a8 as Nt,A as wt,d as _t,X as ye,o as kt,a9 as Ue,I as ze}from"./icons-vendor-Bgrth_9N.js";import"./vendor-cRYyTeIw.js";const Ke="ydisks-amap-js-api",Ct="c9b68d4ce9a2a97f22a4a439404488ca";let fe=null;const It=()=>Ct,St=()=>window.AMap?Promise.resolve(window.AMap):fe||(fe=new Promise((s,a)=>{const n=document.getElementById(Ke),d=n||document.createElement("script"),u=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(G)},f=()=>{window.AMap?(u(),s(window.AMap)):(u(),a(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},G=window.setTimeout(()=>{u(),a(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=f,d.id=Ke,d.async=!0,d.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(It())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,d.onerror=()=>{u(),a(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},n||document.head.appendChild(d)}).catch(s=>{throw fe=null,s}),fe),ke=s=>Number.isFinite(s)&&s!==0,Pt=s=>{var u,f;const a=Number((u=s.location)==null?void 0:u.lng),n=Number((f=s.location)==null?void 0:f.lat),d={area:String(s.adname||"").trim(),city:String(s.cityname||"").trim(),division_id:String(s.adcode||"").trim(),longitude:a,latitude:n,poi_id:String(s.id||"").trim(),poi_name:String(s.name||"").trim(),province:String(s.pname||"").trim()};return!d.division_id||!d.province||!d.city||!d.poi_id||!d.poi_name||!ke(a)||!ke(n)||a<-180||a>180||n<-90||n>90?null:d},qt=async(s,a,n={})=>{if(!ke(s)||!ke(a)||s<-180||s>180||a<-90||a>90)throw new Error("经纬度无效");const d=await St();return new Promise((u,f)=>{var $,M;let G=!1;const k=Math.max(1,n.timeoutMs??1e4),R=F=>{var p;G||(G=!0,globalThis.clearTimeout(W),(p=n.signal)==null||p.removeEventListener("abort",I),F())},I=()=>R(()=>f(new DOMException("aborted","AbortError"))),W=globalThis.setTimeout(()=>R(()=>f(new Error("高德地图附近地址查询超时,请稍后重试"))),k);if(($=n.signal)!=null&&$.aborted){I();return}(M=n.signal)==null||M.addEventListener("abort",I,{once:!0}),new d.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[s,a],1e3,(F,p)=>{var x;if(G)return;if(F!=="complete"){if(F==="no_data"){R(()=>u([]));return}R(()=>f(new Error("高德地图附近地址查询失败,请稍后重试")));return}const E=(((x=p==null?void 0:p.poiList)==null?void 0:x.pois)||[]).map(Pt).filter(j=>j!==null);R(()=>u(E))})})},Bt=async s=>q(a=>B.GET("/api/v1/accounts/details",{signal:a}),s),Je=async s=>q(a=>B.GET("/api/v1/automation-rules",{signal:a}),s),Et=(s,a,n)=>qt(s,a,n),qe=(s,a)=>{if(s instanceof bt)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||a}if(s instanceof Error)return s.message;const n=typeof s=="object"&&s!==null&&"message"in s?s.message:void 0;return typeof n=="string"?n:a},Be=s=>s===!0||s===1||s==="1",Ze=async(s,a)=>{const n=await q(u=>B.GET("/api/v1/items",{params:{query:{cookie_id:s}},signal:u}),a);return Qe(n,["items","data","results"]).map(u=>({...u,id:u.id||`${u.cookie_id}-${u.item_id}`,is_multi_spec:Be(u.is_multi_spec),is_multi_qty_ship:Be(u.is_multi_qty_ship??u.multi_quantity_delivery),multi_quantity_delivery:Be(u.multi_quantity_delivery??u.is_multi_qty_ship)}))},Lt=async s=>q(a=>B.POST("/api/v1/items/get-all-from-account",{body:{cookie_id:s},signal:a})),At=async(s,a)=>q(n=>B.DELETE("/api/v1/items/{cookie_id}/{item_id}",{params:{path:{cookie_id:s,item_id:a}},signal:n})),Rt=async(s,a)=>q(n=>B.POST("/api/v1/items/{cookie_id}",{params:{path:{cookie_id:s}},body:a,signal:n})),Mt=async s=>{const a=new FormData;a.set("cookie_id",s.cookie_id),a.set("title",s.title),a.set("description",s.description),a.set("price",s.price),a.set("original_price",s.original_price||""),a.set("quantity",String(s.quantity)),a.set("postage_mode",s.postage_mode),a.set("postage",s.postage||""),s.location&&a.set("location",JSON.stringify(s.location));for(const n of s.images)a.append("images",n);return q(n=>B.POST("/api/v1/items/publish",{body:a,signal:n}))},Ft=async(s,a,n)=>q(d=>B.POST("/api/v1/items/publish-categories/recommend",{body:{cookie_id:s,keyword:a},signal:d}),n),Gt=async(s,a)=>{const n=new FormData;return n.set("file",s.file),s.imagesZip&&n.set("images_ziLine truncated
`),ee=new Blob(["\uFEFF"+A],{type:"text/csv;charset=utf-8"}),T=URL.createObjectURL(ee),P=document.createElement("a");P.href=T,P.download="批量铺货模板.csv",document.body.appendChild(P),P.click(),P.remove(),URL.revokeObjectURL(T)},[]),i=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})),x(!0)},[s]),L=r.useCallback(async o=>{if(!(o?s:g.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");O();const A=new AbortController;Q.current=A;const ee=++K.current;S(!0);try{const T=await new Promise((ue,he)=>{const Ce=te=>ue(te),ie=te=>he(te);navigator.geolocation.getCurrentPosition(Ce,ie,{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})});if(A.signal.aborted||ee!==K.current)return;const P=await Et(T.coords.longitude,T.coords.latitude,{signal:A.signal});if(A.signal.aborted||ee!==K.current)return;if(!P.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");o?(G(P),k(P[0])):(H(P),z(P[0]))}catch(T){if(A.signal.aborted||ee!==K.current)return;if(typeof T=="object"&&T!==null&&"code"in T){const P=T;alert(P.code===P.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")}else alert(qe(T,"获取发货地失败"))}finally{ee===K.current&&(Q.current=null,S(!1))}},[O,g.cookie_id,s,k,G]);return{selectedAccount:s,setSelectedAccount:a,loading:R,publishing:W,showEditModal:$,setShowEditModal:M,showAddModal:F,setShowAddModal:p,showPublishModal:E,setShowPublishModal:x,locationLoading:j,publishLocations:Y,setPublishLocations:H,publishLocation:X,setPublishLocation:z,selectedItem:D,editForm:C,setEditForm:le,addForm:b,setAddForm:y,publishForm:g,setPublishForm:v,publishImagePreviews:m,handleSync:ae,handleEdit:de,handleSaveEdit:ne,handleDelete:xe,handleAddItem:me,handlePublishItem:ve,downloadPublishTemplate:l,openAddModal:i,openPublishModal:h,locateForPublish:L}},Yt=s=>{const a=String(s||"").trim();return a?/^[¥¥]/.test(a)?a:`¥${a}`:"-"},ss=({onConfigureDelivery:s})=>{const[a,n]=r.useState([]),[d,u]=r.useState([]),[f,G]=r.useState([]),[k,R]=r.useState(""),[I,W]=r.useState(""),U=r.useRef(0),$=r.useRef(0),M=r.useCallback(async()=>{const t=++U.current,c=await Ze();t===U.current&&n(c)},[]),F=r.useCallback(async()=>{const t=++$.current,c=await Je();t===$.current&&u(c)},[]),p=Vt({selectedAccount:k,loadItems:M,loadShippingRules:F}),{showBatchModal:E,batchLoading:x,batchPhase:j,batchFile:S,setBatchFile:Y,batchImagesZip:H,setBatchImagesZip:X,batchCategoryKeyword:z,setBatchCategoryKeyword:D,batchCategoryLoading:Z,batchFallbackCategory:C,setBatchFallbackCategory:le,batchPreview:b,batchDetail:y,recentBatch:g,setRecentBatch:v,batchLocations:m,batchLocation:re,batchPublishIntervalSeconds:Q,setBatchPublishIntervalSeconds:K,setBatchLocations:O,setBatchLocation:ae,openBatchModal:de,handleRecommendBatchCategory:ne,openRecentBatchResult:xe,handlePreviewBatch:me,handleStartBatch:ve,handleCancelBatch:l,abandonBatchPreview:i,closeBatchModal:h,handleRetryBatchFailed:L}=p,o=Wt({selectedAccount:k,setSelectedAccount:R,setItems:n,loadItems:M,loadShippingRules:F,onConfigureDelivery:s,setBatchLocations:O,setBatchLocation:ae}),{loading:N,publishing:A,showEditModal:ee,setShowEditModal:T,showAddModal:P,setShowAddModal:ue,showPublishModal:he,setShowPublishModal:Ce,locationLoading:ie,publishLocations:te,setPublishLocations:tt,publishLocation:st,setPublishLocation:Ee,selectedItem:Le,editForm:se,setEditForm:Ne,addForm:J,setAddForm:pe,publishForm:w,setPublishForm:V,publishImagePreviews:Ae,handleSync:at,handleEdit:lt,handleSaveEdit:rt,handleDelete:nt,handleAddItem:it,handlePublishItem:ct,downloadPublishTemplate:ot,openAddModal:dt,openPublishModal:xt,locateForPublish:Re}=o;r.useEffect(()=>{const t=new AbortController,c=++U.current,_=++$.current;let ge=!0;return Promise.all([Bt({signal:t.signal}),Ze(void 0,{signal:t.signal}),Je({signal:t.signal}),et(20,{signal:t.signal})]).then(([ce,ut,ht,Te])=>{if(!ge||t.signal.aborted||c!==U.current||_!==$.current)return;G(ce),n(ut),u(ht);const pt=Te.find(Ie=>["running","canceling"].includes(Ie.status))||Te.find(Ie=>Ie.status!=="preview");v(pt||null)}).catch(ce=>{t.signal.aborted||console.error("加载商品配置失败:",ce)}),(()=>{ge=!1,t.abort()})},[]);const mt=t=>d.filter(c=>c.cookie_id===t.cookie_id&&c.item_id===t.item_id).length>0?d.filter(c=>c.cookie_id===t.cookie_id&&c.item_id===t.item_id):d.filter(c=>c.cookie_id===t.cookie_id&&!c.item_id),Me=r.useMemo(()=>new Map(f.map(t=>[t.id,t])),[f]),Fe=r.useMemo(()=>I?a.filter(t=>t.cookie_id===I):a,[I,a]),be=t=>{const c=Me.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=Me.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",{ Line truncated
Loaded 100 of 117 files, more files were not shown because too many files have changed in this diff. Show more