功能:完善 API 卡密发货与自动化日志
This commit is contained in:
1 parent
d92fb0f4cc
commit
f5064254dc
106 files changed
+4302
-600
No files matched your search
+114
-4
@@ -2012,6 +2012,42 @@ paths:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
"/api/v1/cards/test-api":
|
||||
post:
|
||||
operationId: postApiV1CardsTestApi
|
||||
summary: postApiV1CardsTestApi
|
||||
security: [{cookieAuth: []}]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/CardAPITestRequest'
|
||||
responses:
|
||||
'200':
|
||||
description: 测试完成
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/CardAPITestResponse'
|
||||
'400':
|
||||
description: 统一错误响应
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
'401':
|
||||
description: 统一错误响应
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
'503':
|
||||
description: 统一错误响应
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
"/api/v1/cards/{card_id}":
|
||||
delete:
|
||||
operationId: deleteApiV1CardsBycard_id
|
||||
@@ -6540,13 +6576,19 @@ paths:
|
||||
schema:
|
||||
type: string
|
||||
security: [{cookieAuth: []}]
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/SystemSettingSingleUpdateRequest'
|
||||
responses:
|
||||
'200':
|
||||
description: 成功
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ApiResponse'
|
||||
$ref: '#/components/schemas/OperationResponse'
|
||||
'400':
|
||||
description: 统一错误响应
|
||||
content:
|
||||
@@ -7278,7 +7320,10 @@ components:
|
||||
properties:
|
||||
name: {type: string}
|
||||
type: {type: string, enum: [api, text, data, image]}
|
||||
api_config: {type: string}
|
||||
api_config:
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/APICardConfigMutation'
|
||||
- type: string
|
||||
text_content: {type: string}
|
||||
data_content: {type: string}
|
||||
image_url: {type: string}
|
||||
@@ -7328,12 +7373,15 @@ components:
|
||||
id: {type: integer}
|
||||
CardResponse:
|
||||
type: object
|
||||
required: [id, name, type, api_config, text_content, data_content, image_url, description, enabled, delay_seconds, is_multi_spec, spec_name, spec_value]
|
||||
required: [id, name, type, text_content, data_content, image_url, description, enabled, delay_seconds, is_multi_spec, spec_name, spec_value]
|
||||
properties:
|
||||
id: {type: integer}
|
||||
name: {type: string}
|
||||
type: {type: string, enum: [api, text, data, image]}
|
||||
api_config: {type: string}
|
||||
api_config:
|
||||
allOf:
|
||||
- $ref: '#/components/schemas/APICardConfigResponse'
|
||||
nullable: true
|
||||
text_content: {type: string}
|
||||
data_content: {type: string}
|
||||
image_url: {type: string}
|
||||
@@ -7344,6 +7392,59 @@ components:
|
||||
spec_name: {type: string}
|
||||
spec_value: {type: string}
|
||||
user_id: {type: integer}
|
||||
APICardConfigMutation:
|
||||
type: object
|
||||
required: [url]
|
||||
properties:
|
||||
url: {type: string, format: uri}
|
||||
method: {type: string, enum: [GET, POST], default: GET}
|
||||
timeout_seconds: {type: integer, minimum: 1, maximum: 60, default: 10}
|
||||
headers:
|
||||
type: object
|
||||
additionalProperties: true
|
||||
params:
|
||||
type: object
|
||||
additionalProperties: true
|
||||
body:
|
||||
type: object
|
||||
additionalProperties: true
|
||||
content_type: {type: string, default: application/json}
|
||||
headers_action: {type: string, enum: [retain, replace, clear]}
|
||||
params_action: {type: string, enum: [retain, replace, clear]}
|
||||
response_path: {type: string}
|
||||
retry_enabled: {type: boolean}
|
||||
APICardConfigResponse:
|
||||
type: object
|
||||
required: [url, method, timeout_seconds, content_type, retry_enabled, headers_configured, params_configured, ready]
|
||||
properties:
|
||||
url: {type: string}
|
||||
method: {type: string, enum: [GET, POST]}
|
||||
timeout_seconds: {type: integer}
|
||||
content_type: {type: string}
|
||||
response_path: {type: string}
|
||||
retry_enabled: {type: boolean}
|
||||
headers_configured: {type: boolean}
|
||||
params_configured: {type: boolean}
|
||||
ready: {type: boolean}
|
||||
validation_error: {type: string}
|
||||
CardAPITestRequest:
|
||||
type: object
|
||||
required: [api_config]
|
||||
properties:
|
||||
api_config:
|
||||
oneOf:
|
||||
- $ref: '#/components/schemas/APICardConfigMutation'
|
||||
- type: string
|
||||
CardAPITestResponse:
|
||||
type: object
|
||||
required: [status, status_code, response_content_type, response_fields]
|
||||
properties:
|
||||
status: {type: string, enum: [success, failed]}
|
||||
status_code: {type: integer}
|
||||
response_content_type: {type: string}
|
||||
response_fields: {type: array, items: {type: string}}
|
||||
extracted_value: {type: string}
|
||||
response_preview: {type: string}
|
||||
ItemListResponse:
|
||||
type: object
|
||||
required: [id, cookie_id, item_id, item_title, item_description, item_category, item_price, item_detail, item_image, is_multi_spec, multi_quantity_delivery, is_multi_qty_ship]
|
||||
@@ -7759,6 +7860,15 @@ components:
|
||||
type: object
|
||||
additionalProperties:
|
||||
$ref: '#/components/schemas/SecretSettingChange'
|
||||
SystemSettingSingleUpdateRequest:
|
||||
type: object
|
||||
required: [value]
|
||||
properties:
|
||||
value:
|
||||
type: string
|
||||
action:
|
||||
type: string
|
||||
enum: [retain, replace, clear]
|
||||
SystemSettingsResponse:
|
||||
type: object
|
||||
additionalProperties:
|
||||
|
||||
@@ -26,6 +26,7 @@ import (
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/logging"
|
||||
"xianyu-go/internal/logsafe"
|
||||
"xianyu-go/internal/netguard"
|
||||
appversion "xianyu-go/internal/version"
|
||||
)
|
||||
|
||||
@@ -352,6 +353,13 @@ func openServerInfrastructure(ctx context.Context, startup serverStartupConfig,
|
||||
closeLog()
|
||||
return serverInfrastructure{}, fmt.Errorf("校验或升级数据库敏感字段失败: %w", err)
|
||||
}
|
||||
// outboundPublicOnly 保存用户可配置 HTTP 请求的启动期公网限制快照。
|
||||
if raw, settingErr := store.Settings.Get(ctx, "outbound_http_public_only"); settingErr == nil {
|
||||
netguard.SetDefaultPublicOnly(strings.EqualFold(strings.TrimSpace(raw), "true"))
|
||||
} else {
|
||||
logger.Warn("读取统一 HTTP 出站策略失败,按默认关闭处理", "err", settingErr)
|
||||
netguard.SetDefaultPublicOnly(false)
|
||||
}
|
||||
if !startup.explicitLogLevel {
|
||||
// level、levelErr 分别是数据库保存的日志等级及其读取错误;读取失败时保留进程默认值。
|
||||
if level, levelErr := store.Settings.Get(ctx, "log_level"); levelErr == nil && strings.TrimSpace(level) != "" {
|
||||
|
||||
@@ -6,6 +6,14 @@
|
||||
|
||||
本文记录 `internal/browser` 中当前滑块认证的完整行为契约。它是维护边界,不是待办方案。后续任务即使涉及登录、Cookie、浏览器自动化、风控恢复或代码清理,也必须保持本文行为逐项不变。
|
||||
|
||||
## 本次 API 发货 Feature 的远程服务网络补充
|
||||
|
||||
本次用户明确授权仅调整远程滑块服务的网络准入:远程滑块服务请求现在使用统一的用户配置 HTTP 出站策略。系统设置
|
||||
`outbound_http_public_only` 默认关闭;关闭时允许内网 HTTP(S) 地址,但仍限制协议、重定向次数和响应大小;开启时会在 DNS
|
||||
解析和每次重定向连接前拒绝回环、私网、链路本地、保留地址及元数据地址。该开关保存后立即生效。
|
||||
|
||||
这项补充不改变滑块选择器、轨迹、拖动距离、重试顺序、Cookie 合并、成功判定、本地浏览器回退或日志语义。除网络目标校验外,本文其余冻结条款继续优先适用。
|
||||
|
||||
## 1. 保护范围
|
||||
|
||||
以下文件为直接保护对象:
|
||||
|
||||
@@ -19,10 +19,16 @@
|
||||
| 文本 | 固定说明、链接 | 填写文本内容。 |
|
||||
| 批量卡密(`data`) | 一次性兑换码、序列号 | 每行一个卡密;发货会按库存消费。 |
|
||||
| 图片 | 固定图片资源 | 填写公开可访问的图片 URL。 |
|
||||
| API | 外部发码接口 | 填写 URL、GET/POST、超时、请求头和参数;先用无敏感测试数据验证。 |
|
||||
| API | 外部发码接口 | 填写 URL、GET/POST、超时、请求头、参数和响应路径;先用无敏感测试数据验证。 |
|
||||
|
||||
通用字段包括名称、描述、启用状态和默认延时秒数。保存后复制“卡密组 ID”;它是自动化规则和批量铺货表格引用库存的唯一标识。
|
||||
|
||||
API 卡支持 `{order_id}`、`{item_id}`、`{buyer_id}`、`{chat_id}`、`{account_id}`、`{cookie_id}`、`{spec_name}`、`{spec_value}`、`{quantity}`、`{order_quantity}`、`{amount}`、`{order_amount}`、`{item_detail}`、`{trigger_type}`、`{timestamp}`、`{delivery_unit_index}`、`{delivery_total_count}` 和 `{idempotency_key}`。变量只替换请求头和参数值,不替换 URL 或请求头名称;GET 将参数放入 query,POST 使用 JSON body。响应路径可写成 `data.card.code` 或 `data.cards[0].code`,为空时系统会按 `data`、`content`、`card` 顺序提取。
|
||||
|
||||
请求头和参数会整体加密保存,列表和规则接口只返回是否已配置,不回显密钥明文。编辑时“保留”不会覆盖旧模板,“替换”写入新模板,“清除”删除对应模板。启用幂等重试前必须在请求头或参数中显式写入 `{idempotency_key}`;最多请求 3 次,只重试网络错误、超时、408、429 和 5xx。
|
||||
|
||||
管理员可在系统设置开启“用户配置 HTTP 只能访问公网”。开启后 API 发货、AI、HTTP 通知、远程图片和远程滑块服务不能访问本机、内网、链路本地、保留或云元数据地址,并会在 DNS 解析和重定向时重复校验。该开关默认关闭且保存后立即生效;不要把它当作 API 密钥或请求模板的替代安全措施。
|
||||
|
||||
批量卡密可用“批量导入”创建,也可选择已有 `data` 类型卡密组追加新卡密。上架前检查库存余量;库存不足时应先补货,不要依赖人工补救。
|
||||
|
||||
## 3. 同步或发布商品
|
||||
|
||||
@@ -875,7 +875,7 @@ test('getCards 解析 JSON 和损坏 JSON 的卡密接口配置', /* 当前回
|
||||
stubContractFetch(fetchMock);
|
||||
// cards 是卡密配置归一化后的库存列表。
|
||||
const cards = await getCards();
|
||||
expect(cards[0].api_config).toEqual({ endpoint: 'https://example.com' });
|
||||
expect(cards[0].api_config).toEqual({ endpoint: 'https://example.com', content_type: 'application/json' });
|
||||
expect(cards[1].api_config).toBeUndefined();
|
||||
});
|
||||
|
||||
|
||||
@@ -2,6 +2,9 @@ import {
|
||||
Card,
|
||||
CardAppendResponse,
|
||||
CardBatchResponse,
|
||||
CardMutation,
|
||||
CardAPITestResult,
|
||||
CardAPIConfigInput,
|
||||
MutationIDResponse,OperationResponse
|
||||
} from './models';
|
||||
import { type RequestControlOptions } from '../../../shared/http/client';
|
||||
@@ -20,14 +23,37 @@ const normalizeCard = (item: any): Card => {
|
||||
apiConfig = undefined;
|
||||
}
|
||||
}
|
||||
if (apiConfig && typeof apiConfig === 'object' && apiConfig.timeout_seconds === undefined && apiConfig.timeout !== undefined) {
|
||||
// normalizedTimeout 将历史 timeout 字段迁移到新版摘要字段。
|
||||
apiConfig.timeout_seconds = Number(apiConfig.timeout) || 10;
|
||||
}
|
||||
if (apiConfig && typeof apiConfig === 'object' && !apiConfig.content_type) {
|
||||
apiConfig.content_type = 'application/json';
|
||||
}
|
||||
return {...item, api_config: apiConfig || undefined} as Card;
|
||||
};
|
||||
|
||||
// cardPayload 卡密请求载荷,用于当前 API 处理流程。
|
||||
const cardPayload = (data: Partial<Card>) => ({
|
||||
// parseTemplateJSON 将表单中的 JSON 模板转换为请求对象,空模板交给服务端执行保留语义。
|
||||
const parseTemplateJSON = (value: unknown): Record<string, unknown> | undefined => {
|
||||
if (value && typeof value === 'object' && !Array.isArray(value)) return value as Record<string, unknown>;
|
||||
if (typeof value !== 'string' || !value.trim()) return undefined;
|
||||
// parsed 保存表单 JSON 文本解析后的未知值,随后只接受对象。
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('请求头和请求参数必须是 JSON 对象');
|
||||
return parsed as Record<string, unknown>;
|
||||
};
|
||||
|
||||
// cardPayload 将 feature 表单映射为新版具名 API 请求载荷,并兼容旧字符串配置。
|
||||
const cardPayload = (data: CardMutation) => ({
|
||||
name: data.name,
|
||||
type: data.type,
|
||||
api_config: data.api_config ? JSON.stringify(data.api_config) : '',
|
||||
api_config: typeof data.api_config === 'string' ? data.api_config : data.api_config ? {
|
||||
...data.api_config,
|
||||
headers: parseTemplateJSON(data.api_config.headers),
|
||||
params: parseTemplateJSON(data.api_config.params),
|
||||
body: parseTemplateJSON(data.api_config.body),
|
||||
content_type: data.api_config.content_type || 'application/json',
|
||||
} : undefined,
|
||||
text_content: data.text_content,
|
||||
data_content: data.data_content,
|
||||
image_url: data.image_url,
|
||||
@@ -49,12 +75,12 @@ export const getCards = async (options?: RequestControlOptions): Promise<Card[]>
|
||||
};
|
||||
|
||||
// createCard 创建卡密组。
|
||||
export const createCard = async (data: Partial<Card>): Promise<MutationIDResponse> => {
|
||||
export const createCard = async (data: CardMutation): 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> => {
|
||||
export const updateCard = async (cardId: string | number, data: CardMutation): Promise<OperationResponse> => {
|
||||
return runContractRequest(/* signal 控制卡券更新请求的取消和超时。 */ signal => contractClient.PUT('/api/v1/cards/{card_id}', { params: { path: { card_id: String(cardId) } }, body: cardPayload(data), signal }));
|
||||
};
|
||||
|
||||
@@ -87,3 +113,11 @@ export const batchCreateCards = async (file: File, options?: RequestControlOptio
|
||||
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 }, signal }), options);
|
||||
};
|
||||
|
||||
// testCardAPI 发送一次临时 API 配置测试请求,不保存卡密配置。
|
||||
export const testCardAPI = async (data: CardAPIConfigInput): Promise<CardAPITestResult> => {
|
||||
return runContractRequest(/* signal 控制 API 测试请求的取消和超时。 */ signal => contractClient.POST('/api/v1/cards/test-api', {
|
||||
body: { api_config: cardPayload({ name: '', type: 'api', api_config: data }).api_config } as never,
|
||||
signal,
|
||||
}));
|
||||
};
|
||||
@@ -91,6 +91,42 @@ describe('useCardActions 卡密动作协调器', /* 当前回调验证卡密筛
|
||||
expect(hook.result.current.showAddModal).toBe(false);
|
||||
});
|
||||
|
||||
test('编辑 API 卡替换空模板时明确清空而不是保留旧模板', /* 当前回调验证敏感模板替换空值的显式清除语义。 */ async () => {
|
||||
// apiCard 保存只含脱敏摘要的 API 卡密组。
|
||||
const apiCard: Card = {
|
||||
...cardFixture,
|
||||
id: 4,
|
||||
name: '接口卡',
|
||||
type: 'api',
|
||||
api_config: {
|
||||
url: 'https://example.test/card',
|
||||
method: 'POST',
|
||||
timeout_seconds: 10,
|
||||
content_type: 'application/json',
|
||||
headers_configured: true,
|
||||
params_configured: true,
|
||||
retry_enabled: false,
|
||||
ready: true,
|
||||
},
|
||||
};
|
||||
// loadCards 是 API 卡编辑完成后的刷新替身。
|
||||
const loadCards = vi.fn().mockResolvedValue(undefined);
|
||||
// hook 是注入 API 卡测试数据的动作 Hook。
|
||||
const hook = renderHook(/* hookFactory 渲染注入 API 卡的动作 Hook。 */ () => useCardActions({ cards: [apiCard], loadCards }));
|
||||
act(/* editAction 打开 API 卡编辑表单。 */ () => hook.result.current.handleEdit(apiCard));
|
||||
act(/* templateAction 将两个敏感模板设置为显式替换。 */ () => hook.result.current.setEditForm(/* formUpdater 清空替换模板的表单值。 */ current => ({
|
||||
...current,
|
||||
api_headers_action: 'replace',
|
||||
api_params_action: 'replace',
|
||||
api_headers: '',
|
||||
api_params: '',
|
||||
})));
|
||||
await act(/* saveAction 提交 API 卡编辑并等待刷新完成。 */ async () => hook.result.current.handleSaveEdit());
|
||||
expect(cardActionMocks.updateCard).toHaveBeenCalledWith(4, expect.objectContaining({
|
||||
api_config: expect.objectContaining({ headers: {}, params: {} }),
|
||||
}));
|
||||
});
|
||||
|
||||
test('删除取消、删除失败和状态切换失败均不制造虚假成功', /* 当前回调验证卡密删除和启停异常分支。 */ async () => {
|
||||
// actionContext 保存卡密删除 Hook 和库存刷新替身。
|
||||
const { hook, loadCards } = createCardHook();
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useCallback,useMemo,useState,type Dispatch,type SetStateAction } from 'react';
|
||||
import type { Card } from './api';
|
||||
import type { Card,CardMutation } from './api';
|
||||
import { createCard,deleteCard,updateCard } from './api';
|
||||
import { filterCards } from './batchState';
|
||||
import type { AddCardForm,EditCardForm } from './types';
|
||||
@@ -16,6 +16,10 @@ export const emptyAddForm = (): AddCardForm => ({
|
||||
api_timeout: 10,
|
||||
api_headers: '',
|
||||
api_params: '',
|
||||
api_content_type: 'application/json',
|
||||
api_body: '',
|
||||
api_response_path: '',
|
||||
api_retry_enabled: false,
|
||||
});
|
||||
|
||||
// CardActionsOptions 描述卡密动作协调器依赖的库存状态和刷新操作。
|
||||
@@ -110,9 +114,15 @@ export const useCardActions = ({ cards, loadCards }: CardActionsOptions): CardAc
|
||||
type: card.type || 'text',
|
||||
api_url: card.api_config?.url || '',
|
||||
api_method: card.api_config?.method || 'GET',
|
||||
api_timeout: card.api_config?.timeout || 10,
|
||||
api_headers: card.api_config?.headers || '',
|
||||
api_params: card.api_config?.params || '',
|
||||
api_timeout: card.api_config?.timeout_seconds || 10,
|
||||
api_headers: '',
|
||||
api_params: '',
|
||||
api_content_type: card.api_config?.content_type || 'application/json',
|
||||
api_body: '',
|
||||
api_response_path: card.api_config?.response_path || '',
|
||||
api_retry_enabled: card.api_config?.retry_enabled || false,
|
||||
api_headers_action: 'retain',
|
||||
api_params_action: 'retain',
|
||||
text_content: card.text_content || '',
|
||||
data_content: card.data_content || '',
|
||||
image_url: card.image_url || '',
|
||||
@@ -136,7 +146,7 @@ export const useCardActions = ({ cards, loadCards }: CardActionsOptions): CardAc
|
||||
}
|
||||
try {
|
||||
// updateData 保存映射到卡密更新接口的字段。
|
||||
const updateData: Partial<Card> = {
|
||||
const updateData: CardMutation = {
|
||||
name: editForm.name.trim(),
|
||||
type: editForm.type,
|
||||
description: editForm.description?.trim(),
|
||||
@@ -147,9 +157,15 @@ export const useCardActions = ({ cards, loadCards }: CardActionsOptions): CardAc
|
||||
updateData.api_config = {
|
||||
url: editForm.api_url?.trim() || '',
|
||||
method: editForm.api_method || 'GET',
|
||||
timeout: editForm.api_timeout || 10,
|
||||
headers: editForm.api_headers?.trim() || undefined,
|
||||
params: editForm.api_params?.trim() || undefined,
|
||||
timeout_seconds: editForm.api_timeout || 10,
|
||||
headers: editForm.api_headers_action === 'clear' ? undefined : editForm.api_headers_action === 'replace' && !editForm.api_headers?.trim() ? {} : editForm.api_headers?.trim() || undefined,
|
||||
params: editForm.api_params_action === 'clear' ? undefined : editForm.api_params_action === 'replace' && !editForm.api_params?.trim() ? {} : editForm.api_params?.trim() || undefined,
|
||||
content_type: editForm.api_content_type || 'application/json',
|
||||
body: editForm.api_body?.trim() || undefined,
|
||||
headers_action: editForm.api_headers_action || 'retain',
|
||||
params_action: editForm.api_params_action || 'retain',
|
||||
response_path: editForm.api_response_path?.trim() || undefined,
|
||||
retry_enabled: editForm.api_retry_enabled || false,
|
||||
};
|
||||
} else if (editForm.type === 'text') {
|
||||
updateData.text_content = editForm.text_content?.trim() || '';
|
||||
@@ -191,7 +207,7 @@ export const useCardActions = ({ cards, loadCards }: CardActionsOptions): CardAc
|
||||
}
|
||||
try {
|
||||
// payload 保存新增卡密组的接口载荷。
|
||||
const payload: Partial<Card> = {
|
||||
const payload: CardMutation = {
|
||||
name: addForm.name.trim(),
|
||||
type: addForm.type,
|
||||
description: addForm.description.trim(),
|
||||
@@ -205,9 +221,13 @@ export const useCardActions = ({ cards, loadCards }: CardActionsOptions): CardAc
|
||||
payload.api_config = {
|
||||
url: addForm.content.trim(),
|
||||
method: addForm.api_method,
|
||||
timeout: addForm.api_timeout,
|
||||
timeout_seconds: addForm.api_timeout,
|
||||
headers: addForm.api_headers.trim() || undefined,
|
||||
params: addForm.api_params.trim() || undefined,
|
||||
content_type: addForm.api_content_type,
|
||||
body: addForm.api_body.trim() || undefined,
|
||||
response_path: addForm.api_response_path.trim() || undefined,
|
||||
retry_enabled: addForm.api_retry_enabled,
|
||||
};
|
||||
}
|
||||
await createCard(payload);
|
||||
|
||||
@@ -0,0 +1,357 @@
|
||||
import { Loader2, Play, Plus, Trash2 } from 'lucide-react';
|
||||
import { useEffect, useRef, useState, type ChangeEvent } from 'react';
|
||||
import type { CardAPITestResult } from '../models';
|
||||
|
||||
// APIRequestMethod 是 API 发货请求支持的 HTTP 方法。
|
||||
export type APIRequestMethod = 'GET' | 'POST';
|
||||
|
||||
// APISecretAction 描述编辑敏感模板时对服务端已保存值的处理方式。
|
||||
export type APISecretAction = 'retain' | 'replace' | 'clear';
|
||||
|
||||
// APIKeyValueRow 是 Postman 风格键值编辑器中的一行表单数据。
|
||||
export interface APIKeyValueRow {
|
||||
// key 是请求头、查询参数或表单字段名称。
|
||||
key: string;
|
||||
// value 是字段值;动态变量会以文本形式保留到服务端替换。
|
||||
value: string;
|
||||
}
|
||||
|
||||
// APIRequestBuilderProps 描述 API 请求编辑器的受控字段和保存动作。
|
||||
export interface APIRequestBuilderProps {
|
||||
// url 是远端 API 地址。
|
||||
url: string;
|
||||
// method 是远端 API 请求方法。
|
||||
method: APIRequestMethod;
|
||||
// timeout 是单次远端请求的超时秒数。
|
||||
timeout: number;
|
||||
// headers 是请求头 JSON 文本,组件以键值行展示。
|
||||
headers: string;
|
||||
// params 是 URL 查询参数 JSON 文本,组件以键值行展示。
|
||||
params: string;
|
||||
// contentType 是 POST 请求正文的 Content-Type。
|
||||
contentType: string;
|
||||
// body 是 JSON 正文或非 JSON 正文的键值 JSON 文本。
|
||||
body: string;
|
||||
// responsePath 是成功响应中的卡密提取路径。
|
||||
responsePath: string;
|
||||
// retryEnabled 表示是否启用带幂等键的重试。
|
||||
retryEnabled: boolean;
|
||||
// headersAction 是编辑时请求头敏感模板的三态处理方式。
|
||||
headersAction?: APISecretAction;
|
||||
// paramsAction 是编辑时查询参数敏感模板的三态处理方式。
|
||||
paramsAction?: APISecretAction;
|
||||
// onChange 更新指定 API 配置字段。
|
||||
onChange: (field: APIRequestField, value: string | number | boolean) => void;
|
||||
// onTest 使用当前配置执行临时测试请求。
|
||||
onTest?: () => Promise<CardAPITestResult>;
|
||||
}
|
||||
|
||||
// APIRequestField 是 APIRequestBuilder 可更新字段的联合类型。
|
||||
export type APIRequestField =
|
||||
| 'url'
|
||||
| 'method'
|
||||
| 'timeout'
|
||||
| 'headers'
|
||||
| 'params'
|
||||
| 'contentType'
|
||||
| 'body'
|
||||
| 'responsePath'
|
||||
| 'retryEnabled'
|
||||
| 'headersAction'
|
||||
| 'paramsAction';
|
||||
|
||||
// APITestState 保存 API 测试请求的加载状态、非敏感诊断结果与请求错误。
|
||||
interface APITestState {
|
||||
// loading 表示当前是否正在等待远端测试响应。
|
||||
loading: boolean;
|
||||
// result 是远端完成请求后返回的状态和响应结构诊断。
|
||||
result?: CardAPITestResult;
|
||||
// error 是本地请求、超时或配置错误的用户可见提示。
|
||||
error?: string;
|
||||
}
|
||||
|
||||
// contentTypes 保存常用且不依赖文件上传的请求正文类型。
|
||||
const contentTypes = [
|
||||
{ value: 'application/json', label: 'JSON(application/json)' },
|
||||
{ value: 'application/x-www-form-urlencoded', label: '表单键值(x-www-form-urlencoded)' },
|
||||
{ value: 'text/plain', label: '纯文本(text/plain)' },
|
||||
{ value: 'application/xml', label: 'XML(application/xml)' },
|
||||
];
|
||||
|
||||
// isJSONContentType 判断正文类型是否应该使用 JSON 编辑器。
|
||||
const isJSONContentType = (contentType: string): boolean => contentType.toLowerCase().includes('json');
|
||||
|
||||
// rowsFromJSON 将已保存的 JSON 对象转成适合键值编辑器展示的行。
|
||||
const rowsFromJSON = (value: string): APIKeyValueRow[] => {
|
||||
if (!value.trim()) return [{ key: '', value: '' }];
|
||||
try {
|
||||
// parsed 是配置模板解析后的未知 JSON 值。
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return [{ key: '', value: '' }];
|
||||
// entries 是对象中每个字段的键和值。
|
||||
const entries = Object.entries(parsed as Record<string, unknown>);
|
||||
if (entries.length === 0) return [{ key: '', value: '' }];
|
||||
return entries.map(/* entry 保存当前对象字段的键和值。 */ entry => {
|
||||
// key、entryValue 分别是当前模板字段名称和字段值。
|
||||
const [key, entryValue] = entry;
|
||||
return { key, value: typeof entryValue === 'string' ? entryValue : JSON.stringify(entryValue) };
|
||||
});
|
||||
} catch {
|
||||
return [{ key: '', value: value.trim() }];
|
||||
}
|
||||
};
|
||||
|
||||
// rowsToJSON 将键值行序列化为服务端使用的 JSON 对象文本。
|
||||
const rowsToJSON = (rows: APIKeyValueRow[]): string => {
|
||||
// object 是过滤空键后待提交的键值对象。
|
||||
const object = rows.reduce<Record<string, string>>(/* reduceCallback 汇总非空键名的模板字段。 */ (result, row) => {
|
||||
// key 是当前行清理空白后的字段名称。
|
||||
const key = row.key.trim();
|
||||
if (key) result[key] = row.value;
|
||||
return result;
|
||||
}, {});
|
||||
return JSON.stringify(object);
|
||||
};
|
||||
|
||||
// KeyValueEditorProps 描述一组 Postman 风格键值行编辑器。
|
||||
interface KeyValueEditorProps {
|
||||
// label 是当前键值区块的可见标题。
|
||||
label: string;
|
||||
// value 是当前键值对象的 JSON 文本。
|
||||
value: string;
|
||||
// placeholder 是第一行输入的示例文本。
|
||||
placeholder: string;
|
||||
// onChange 接收序列化后的键值对象。
|
||||
onChange: (value: string) => void;
|
||||
}
|
||||
|
||||
// KeyValueEditor 渲染可增删的键值对输入行。
|
||||
const KeyValueEditor = ({ label, value, placeholder, onChange }: KeyValueEditorProps) => {
|
||||
// rows 保存当前键值编辑行;空行也必须保留在本地状态中,才能支持连续添加。
|
||||
const [rows, setRows] = useState<APIKeyValueRow[]>(() => rowsFromJSON(value));
|
||||
// lastEmittedValue 记录本组件最近一次提交的 JSON,避免空行序列化为 {} 后被外部同步立即抹掉。
|
||||
const lastEmittedValue = useRef(value);
|
||||
|
||||
// syncRows 在父表单从外部载入新模板时重置编辑行;本组件自己的更新不重复覆盖空行。
|
||||
useEffect(/* syncRowsEffect 同步外部模板变更并保留本地新增空行。 */ () => {
|
||||
if (value !== lastEmittedValue.current) {
|
||||
setRows(rowsFromJSON(value));
|
||||
lastEmittedValue.current = value;
|
||||
}
|
||||
}, [value]);
|
||||
|
||||
// emitRows 保存本地键值行并通知父表单更新敏感模板 JSON。
|
||||
const emitRows = (nextRows: APIKeyValueRow[]) => {
|
||||
// serialized 是当前键值行转成的服务端 JSON 对象文本。
|
||||
const serialized = rowsToJSON(nextRows);
|
||||
setRows(nextRows);
|
||||
lastEmittedValue.current = serialized;
|
||||
onChange(serialized);
|
||||
};
|
||||
|
||||
// updateRow 修改某一行并把完整对象交回父表单。
|
||||
const updateRow = (index: number, field: keyof APIKeyValueRow, nextValue: string) => {
|
||||
// nextRows 是修改当前字段后的完整键值行列表。
|
||||
const nextRows = rows.map(/* rowUpdater 更新当前键值编辑行。 */ (row, rowIndex) => rowIndex === index ? { ...row, [field]: nextValue } : row);
|
||||
emitRows(nextRows);
|
||||
};
|
||||
|
||||
// addRow 在末尾追加一行空键值输入。
|
||||
const addRow = () => emitRows([...rows, { key: '', value: '' }]);
|
||||
|
||||
// removeRow 删除指定键值行,并确保编辑器始终保留一行可输入内容。
|
||||
const removeRow = (index: number) => emitRows(rows.filter(/* rowFilter 保留未被删除的键值行。 */ (_, rowIndex) => rowIndex !== index));
|
||||
|
||||
return (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<label className="text-sm font-bold text-gray-800">{label}</label>
|
||||
<button
|
||||
type="button"
|
||||
onClick={addRow}
|
||||
className="inline-flex items-center gap-1 rounded-lg px-2 py-1 text-xs font-bold text-blue-600 transition-colors hover:bg-blue-50"
|
||||
title={`添加${label}字段`}
|
||||
>
|
||||
<Plus className="h-3.5 w-3.5" />
|
||||
添加字段
|
||||
</button>
|
||||
</div>
|
||||
<div className="overflow-hidden rounded-xl border border-gray-200 bg-white">
|
||||
<div className="grid grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)_40px] gap-2 border-b border-gray-100 bg-gray-50 px-3 py-2 text-[11px] font-bold uppercase tracking-wide text-gray-400">
|
||||
<span>KEY</span>
|
||||
<span>VALUE</span>
|
||||
<span aria-hidden="true" />
|
||||
</div>
|
||||
<div className="divide-y divide-gray-100">
|
||||
{rows.map(/* rowRenderer 渲染当前键值编辑行。 */ (row, index) => (
|
||||
<div className="grid grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)_40px] items-center gap-2 px-3 py-2" key={`${label}-${index}`}>
|
||||
<input
|
||||
aria-label={`${label}第${index + 1}行键名`}
|
||||
value={row.key}
|
||||
onChange={/* 当前回调更新键值行的字段名称。 */ (event: ChangeEvent<HTMLInputElement>) => updateRow(index, 'key', event.target.value)}
|
||||
placeholder={index === 0 ? placeholder : '键名'}
|
||||
className="min-w-0 border-0 bg-transparent px-1 py-2 font-mono text-sm text-gray-800 outline-none ring-0 placeholder:text-gray-300"
|
||||
/>
|
||||
<input
|
||||
aria-label={`${label}第${index + 1}行值`}
|
||||
value={row.value}
|
||||
onChange={/* 当前回调更新键值行的字段值。 */ (event: ChangeEvent<HTMLInputElement>) => updateRow(index, 'value', event.target.value)}
|
||||
placeholder={index === 0 ? '输入值或动态变量,例如 {order_id}' : '值'}
|
||||
className="min-w-0 border-0 bg-transparent px-1 py-2 font-mono text-sm text-gray-800 outline-none ring-0 placeholder:text-gray-300"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={/* 当前回调删除指定键值编辑行。 */ () => removeRow(index)}
|
||||
className="inline-flex h-8 w-8 items-center justify-center rounded-lg text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500"
|
||||
title={`删除${label}第${index + 1}行`}
|
||||
aria-label={`删除${label}第${index + 1}行`}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// APIRequestBuilder 渲染 API 地址、元数据以及 Headers / Params / Body 三个请求区块。
|
||||
export const APIRequestBuilder = ({
|
||||
url,
|
||||
method,
|
||||
timeout,
|
||||
headers,
|
||||
params,
|
||||
contentType,
|
||||
body,
|
||||
responsePath,
|
||||
retryEnabled,
|
||||
headersAction,
|
||||
paramsAction,
|
||||
onChange,
|
||||
onTest,
|
||||
}: APIRequestBuilderProps) => {
|
||||
// jsonBody 表示当前正文类型是否使用 JSON 文本编辑器。
|
||||
const jsonBody = isJSONContentType(contentType);
|
||||
// testState 保存最近一次 API 测试的加载、结果和错误状态。
|
||||
const [testState, setTestState] = useState<APITestState>({ loading: false });
|
||||
// runTest 触发临时请求并保留结果在当前弹窗中。
|
||||
const runTest = async () => {
|
||||
if (!onTest) return;
|
||||
setTestState({ loading: true });
|
||||
try {
|
||||
setTestState({ loading: false, result: await onTest() });
|
||||
} catch (/* error 表示测试请求的本地错误或共享 HTTP 客户端返回的异常。 */ error) {
|
||||
setTestState({ loading: false, error: error instanceof Error ? error.message : 'API 测试请求失败' });
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-5 rounded-2xl border border-blue-100 bg-blue-50/40 p-4 sm:p-5">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div>
|
||||
<h3 className="font-bold text-gray-900">API 请求配置</h3>
|
||||
<p className="mt-1 text-xs text-gray-500">按 Postman 的请求结构填写,敏感模板只会加密保存在服务端。</p>
|
||||
</div>
|
||||
<span className="rounded-full bg-white px-2.5 py-1 text-[11px] font-bold text-blue-600 shadow-sm">API</span>
|
||||
</div>
|
||||
{onTest && (
|
||||
<div className="flex flex-wrap items-center gap-3">
|
||||
<button type="button" onClick={runTest} disabled={testState.loading} className="inline-flex items-center gap-2 rounded-xl bg-gray-900 px-4 py-2.5 text-sm font-bold text-white transition-colors hover:bg-gray-700 disabled:cursor-wait disabled:opacity-60">
|
||||
{testState.loading ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />}
|
||||
测试请求
|
||||
</button>
|
||||
{testState.error && <span className="text-sm font-semibold text-red-600">{testState.error}</span>}
|
||||
{testState.result && (
|
||||
<div className={`w-full rounded-xl border p-3 text-sm ${testState.result.status === 'success' ? 'border-green-200 bg-green-50' : 'border-red-200 bg-red-50'}`}>
|
||||
<div className="flex flex-wrap gap-x-5 gap-y-1 font-semibold">
|
||||
<span>{testState.result.status === 'success' ? '测试成功' : '测试失败'}</span>
|
||||
<span>HTTP 状态:{testState.result.status_code || '网络错误'}</span>
|
||||
<span>响应类型:{testState.result.response_content_type || '未知'}</span>
|
||||
</div>
|
||||
<div className="mt-2 grid gap-1 text-gray-700"><span>响应字段:{testState.result.response_fields.length ? testState.result.response_fields.join('、') : '未识别 JSON 字段'}</span><span>提取结果:{testState.result.extracted_value || '未提取到内容'}</span></div>
|
||||
{testState.result.response_preview && <pre className="mt-2 max-h-32 overflow-auto whitespace-pre-wrap rounded-lg bg-white/70 p-2 text-xs text-gray-600">{testState.result.response_preview}</pre>}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-[minmax(0,1fr)_130px_130px]">
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">API 地址</label>
|
||||
<input
|
||||
type="url"
|
||||
value={url}
|
||||
onChange={/* 当前回调更新远端 API 地址。 */ (event: ChangeEvent<HTMLInputElement>) => onChange('url', event.target.value)}
|
||||
className="w-full ios-input rounded-xl px-4 py-3 font-mono text-sm"
|
||||
placeholder="https://api.example.com/get-code"
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">请求方法</label>
|
||||
<select value={method} onChange={/* 当前回调切换 API 请求方法。 */ (event: ChangeEvent<HTMLSelectElement>) => onChange('method', event.target.value)} className="w-full ios-input rounded-xl px-3 py-3">
|
||||
<option value="GET">GET</option>
|
||||
<option value="POST">POST</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">超时(秒)</label>
|
||||
<input type="number" min="1" max="60" value={timeout} onChange={/* 当前回调更新 API 请求超时秒数。 */ (event: ChangeEvent<HTMLInputElement>) => onChange('timeout', Number(event.target.value) || 10)} className="w-full ios-input rounded-xl px-3 py-3" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-5 border-t border-blue-100 pt-5">
|
||||
<KeyValueEditor label="Headers / 请求头" value={headers} onChange={/* 当前回调保存请求头键值对象。 */ nextValue => onChange('headers', nextValue)} placeholder="Authorization" />
|
||||
{headersAction && (
|
||||
<select aria-label="请求头处理方式" value={headersAction} onChange={/* 当前回调选择请求头敏感模板处理方式。 */ (event: ChangeEvent<HTMLSelectElement>) => onChange('headersAction', event.target.value)} className="w-full ios-input rounded-xl px-3 py-2 text-sm sm:w-auto">
|
||||
<option value="retain">保留已保存请求头</option>
|
||||
<option value="replace">替换为上方字段</option>
|
||||
<option value="clear">清除已保存请求头</option>
|
||||
</select>
|
||||
)}
|
||||
|
||||
<KeyValueEditor label="Params / 查询参数" value={params} onChange={/* 当前回调保存查询参数键值对象。 */ nextValue => onChange('params', nextValue)} placeholder="order_id" />
|
||||
{paramsAction && (
|
||||
<select aria-label="查询参数处理方式" value={paramsAction} onChange={/* 当前回调选择查询参数敏感模板处理方式。 */ (event: ChangeEvent<HTMLSelectElement>) => onChange('paramsAction', event.target.value)} className="w-full ios-input rounded-xl px-3 py-2 text-sm sm:w-auto">
|
||||
<option value="retain">保留已保存查询参数</option>
|
||||
<option value="replace">替换为上方字段</option>
|
||||
<option value="clear">清除已保存查询参数</option>
|
||||
</select>
|
||||
)}
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
|
||||
<label className="text-sm font-bold text-gray-800">Body / 请求正文</label>
|
||||
<select aria-label="请求正文 Content-Type" value={contentType} onChange={/* 当前回调切换请求正文类型。 */ (event: ChangeEvent<HTMLSelectElement>) => onChange('contentType', event.target.value)} className="ios-input rounded-xl px-3 py-2 text-sm sm:w-[290px]">
|
||||
{contentTypes.map(/* 当前回调渲染一个常用 Content-Type 选项。 */ contentTypeOption => <option key={contentTypeOption.value} value={contentTypeOption.value}>{contentTypeOption.label}</option>)}
|
||||
</select>
|
||||
</div>
|
||||
{jsonBody ? (
|
||||
<textarea
|
||||
aria-label="JSON 请求正文"
|
||||
value={body}
|
||||
onChange={/* 当前回调更新 JSON 请求正文。 */ (event: ChangeEvent<HTMLTextAreaElement>) => onChange('body', event.target.value)}
|
||||
className="h-36 w-full resize-y ios-input rounded-xl px-4 py-3 font-mono text-sm"
|
||||
placeholder={'{\n "order_id": "{order_id}"\n}'}
|
||||
/>
|
||||
) : (
|
||||
<KeyValueEditor label="Body 字段" value={body} onChange={/* 当前回调保存非 JSON 正文键值对象。 */ nextValue => onChange('body', nextValue)} placeholder="field" />
|
||||
)}
|
||||
<p className="text-xs text-gray-500">GET 请求通常只使用 Params;POST 请求会按所选 Content-Type 发送 Body。</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 gap-4 border-t border-blue-100 pt-5 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">响应提取路径(可选)</label>
|
||||
<input value={responsePath} onChange={/* 当前回调更新响应提取路径。 */ (event: ChangeEvent<HTMLInputElement>) => onChange('responsePath', event.target.value)} className="w-full ios-input rounded-xl px-4 py-3 font-mono text-sm" placeholder="data.cards[0].code" />
|
||||
</div>
|
||||
<label className="flex items-center gap-2 self-end pb-3 text-sm font-bold text-gray-700">
|
||||
<input type="checkbox" checked={retryEnabled} onChange={/* 当前回调切换 API 幂等重试。 */ (event: ChangeEvent<HTMLInputElement>) => onChange('retryEnabled', event.target.checked)} />
|
||||
启用幂等重试(需配置 {'{idempotency_key}'})
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -15,19 +15,8 @@ export interface Card {
|
||||
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;
|
||||
};
|
||||
// API 类型配置只保存服务端返回的脱敏摘要。
|
||||
api_config?: CardAPIConfigSummary;
|
||||
// 图片类型
|
||||
/** 图片卡券地址。 */
|
||||
image_url?: string;
|
||||
@@ -43,6 +32,78 @@ export interface Card {
|
||||
spec_value?: string;
|
||||
}
|
||||
|
||||
/** API 卡券查询返回的脱敏摘要;请求头和参数永远不在此模型中。 */
|
||||
export interface CardAPIConfigSummary {
|
||||
/** API 卡券请求地址。 */
|
||||
url: string;
|
||||
/** API 卡券请求方法。 */
|
||||
method: 'GET' | 'POST';
|
||||
/** API 请求正文的 Content-Type。 */
|
||||
content_type: string;
|
||||
/** API 请求超时时间。 */
|
||||
timeout_seconds: number;
|
||||
/** API 响应提取路径。 */
|
||||
response_path?: string;
|
||||
/** 是否启用幂等重试。 */
|
||||
retry_enabled: boolean;
|
||||
/** 是否已配置请求头模板。 */
|
||||
headers_configured: boolean;
|
||||
/** 是否已配置请求参数模板。 */
|
||||
params_configured: boolean;
|
||||
/** 当前配置是否可以被规则使用。 */
|
||||
ready: boolean;
|
||||
/** 当前配置的非敏感校验错误。 */
|
||||
validation_error?: string;
|
||||
}
|
||||
|
||||
/** API 卡券提交用的具名配置;敏感模板为空时由服务端保留旧值。 */
|
||||
export interface CardAPIConfigInput {
|
||||
/** API 卡券请求地址。 */
|
||||
url: string;
|
||||
/** API 卡券请求方法。 */
|
||||
method: 'GET' | 'POST';
|
||||
/** API 请求超时时间。 */
|
||||
timeout_seconds: number;
|
||||
/** API 请求头 JSON 文本或对象。 */
|
||||
headers?: string | Record<string, unknown>;
|
||||
/** API 请求参数 JSON 文本或对象。 */
|
||||
params?: string | Record<string, unknown>;
|
||||
/** API 请求正文 JSON 文本或对象。 */
|
||||
body?: string | Record<string, unknown>;
|
||||
/** API 请求正文的 Content-Type。 */
|
||||
content_type?: string;
|
||||
/** 请求头的三态变更意图。 */
|
||||
headers_action?: 'retain' | 'replace' | 'clear';
|
||||
/** 请求参数的三态变更意图。 */
|
||||
params_action?: 'retain' | 'replace' | 'clear';
|
||||
/** API 响应提取路径。 */
|
||||
response_path?: string;
|
||||
/** 是否启用幂等重试。 */
|
||||
retry_enabled?: boolean;
|
||||
}
|
||||
|
||||
/** API 测试请求返回的非敏感诊断结果。 */
|
||||
export interface CardAPITestResult {
|
||||
/** 远端请求是否返回 2xx。 */
|
||||
status: 'success' | 'failed';
|
||||
/** 远端 HTTP 状态码。 */
|
||||
status_code: number;
|
||||
/** 远端响应媒体类型。 */
|
||||
response_content_type: string;
|
||||
/** JSON 响应顶层字段名称。 */
|
||||
response_fields: string[];
|
||||
/** 响应提取路径命中的值。 */
|
||||
extracted_value?: string;
|
||||
/** 限长响应预览。 */
|
||||
response_preview?: string;
|
||||
}
|
||||
|
||||
/** 卡券创建和更新所需的前端提交模型。 */
|
||||
export type CardMutation = Omit<Partial<Card>, 'api_config'> & {
|
||||
/** API 卡券具名请求配置或历史 JSON 字符串。 */
|
||||
api_config?: CardAPIConfigInput | string;
|
||||
};
|
||||
|
||||
/** 卡券批量创建接口的逐行结果。 */
|
||||
/** 由当前 feature adapter 归一后的 CardBatchResult UI 模型;不直接暴露 HTTP DTO。 */
|
||||
export interface CardBatchResult {
|
||||
|
||||
@@ -11,6 +11,7 @@ const cardListMocks = vi.hoisted(/* cardListMockFactory 创建卡密页面共享
|
||||
createCard: vi.fn(),
|
||||
deleteCard: vi.fn(),
|
||||
updateCard: vi.fn(),
|
||||
testCardAPI: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../hooks', /* cardsHooksMockFactory 提供卡密库存和批量 Hook 替身。 */ () => ({
|
||||
@@ -49,6 +50,7 @@ vi.mock('../api', /* cardsApiMockFactory 提供卡密页面动作 API 替身。
|
||||
createCard: cardListMocks.createCard,
|
||||
deleteCard: cardListMocks.deleteCard,
|
||||
updateCard: cardListMocks.updateCard,
|
||||
testCardAPI: cardListMocks.testCardAPI,
|
||||
}));
|
||||
|
||||
vi.mock('../components/BatchCardImportModal', /* batchModalMockFactory 提供批量弹窗替身。 */ () => ({
|
||||
@@ -86,6 +88,7 @@ describe('CardList 页面组合行为', /* 当前回调验证卡密筛选、批
|
||||
cardListMocks.createCard.mockResolvedValue({ success: true, id: 3 });
|
||||
cardListMocks.deleteCard.mockResolvedValue({ success: true });
|
||||
cardListMocks.updateCard.mockResolvedValue({ success: true });
|
||||
cardListMocks.testCardAPI.mockResolvedValue({ status: 'success', status_code: 200, response_content_type: 'application/json', response_fields: ['data', 'message'], extracted_value: 'TEST-CODE' });
|
||||
vi.spyOn(window, 'alert').mockImplementation(/* alertImplementation 屏蔽卡密页面提示。 */ () => undefined);
|
||||
vi.spyOn(window, 'confirm').mockReturnValue(true);
|
||||
});
|
||||
@@ -123,6 +126,33 @@ describe('CardList 页面组合行为', /* 当前回调验证卡密筛选、批
|
||||
expect(cardListMocks.loadCards).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test('API 卡密使用三段请求编辑器并支持切换正文类型', /* 当前回调验证 API 地址、Headers、Params、Body 和 Content-Type 控件。 */ () => {
|
||||
render(<CardList />);
|
||||
fireEvent.click(screen.getByText('添加新卡密'));
|
||||
fireEvent.click(screen.getByRole('button', { name: 'API 接口' }));
|
||||
expect(screen.getByRole('heading', { name: 'API 请求配置' })).toBeTruthy();
|
||||
expect(screen.getByLabelText('Headers / 请求头第1行键名')).toBeTruthy();
|
||||
expect(screen.getByLabelText('Params / 查询参数第1行键名')).toBeTruthy();
|
||||
expect(screen.getByLabelText('JSON 请求正文')).toBeTruthy();
|
||||
fireEvent.change(screen.getByRole('combobox', { name: '请求正文 Content-Type' }), { target: { value: 'application/x-www-form-urlencoded' } });
|
||||
expect(screen.getByLabelText('Body 字段第1行键名')).toBeTruthy();
|
||||
fireEvent.click(screen.getByTitle('添加Headers / 请求头字段'));
|
||||
expect(screen.getByLabelText('Headers / 请求头第2行键名')).toBeTruthy();
|
||||
});
|
||||
|
||||
test('新增卡密类型单行排列且 API 测试展示远端诊断', /* 当前回调验证类型顺序和 API 测试结果可见。 */ async () => {
|
||||
render(<CardList />);
|
||||
fireEvent.click(screen.getByText('添加新卡密'));
|
||||
// typeButtons 保存新增弹窗中按显示顺序排列的四种卡密类型按钮。
|
||||
const typeButtons = ['批量库存', '文本', '图片', 'API 接口'].map(/* typeButtonMapper 查找当前类型按钮。 */ typeName => screen.getByRole('button', { name: typeName }));
|
||||
expect(typeButtons.map(/* typeNameMapper 读取当前类型按钮名称。 */ button => button.textContent?.trim())).toEqual(['批量库存', '文本', '图片', 'API 接口']);
|
||||
fireEvent.click(typeButtons[3]);
|
||||
fireEvent.click(screen.getByRole('button', { name: '测试请求' }));
|
||||
await waitFor(/* testResultAssertion 等待 API 测试结果展示。 */ () => expect(screen.getByText('HTTP 状态:200')).toBeTruthy());
|
||||
expect(screen.getByText('响应字段:data、message')).toBeTruthy();
|
||||
expect(screen.getByText('提取结果:TEST-CODE')).toBeTruthy();
|
||||
});
|
||||
|
||||
test('启停、复制和删除按钮调用对应页面动作', /* 当前回调验证卡密行级动作边界。 */ async () => {
|
||||
render(<CardList />);
|
||||
fireEvent.click(screen.getByRole('button', { name: '切换卡密 库存一 状态' }));
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { Copy,CreditCard,Edit,FileText,Image as ImageIcon,Package,Plus,Save,Search,SlidersHorizontal,Trash2,Upload,X } from 'lucide-react';
|
||||
import { Copy,CreditCard,Edit,FileText,Globe,Image as ImageIcon,Package,Plus,Save,Search,SlidersHorizontal,Trash2,Upload,X } from 'lucide-react';
|
||||
import React from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Card } from '../api';
|
||||
import { Card, testCardAPI } from '../api';
|
||||
import { useCardActions } from '../cardActions';
|
||||
import { APIRequestBuilder } from '../components/APIRequestBuilder';
|
||||
import { BatchCardImportModal } from '../components/BatchCardImportModal';
|
||||
import { CardIcon } from '../components/CardIcon';
|
||||
import { useCardBatchActions,useCardsData } from '../hooks';
|
||||
@@ -256,71 +257,46 @@ const CardList: React.FC = () => {
|
||||
className="w-full ios-input px-4 py-3 rounded-xl"
|
||||
>
|
||||
<option value="">请选择类型</option>
|
||||
<option value="data">批量库存</option>
|
||||
<option value="text">固定文字</option>
|
||||
<option value="data">批量数据</option>
|
||||
{selectedCard?.type === 'api' && <option value="api">API接口(仅保留现有配置)</option>}
|
||||
<option value="image">图片</option>
|
||||
<option value="api">API 接口</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* API 配置 */}
|
||||
{editForm.type === 'api' && (
|
||||
<div className="border border-gray-200 rounded-xl p-4 space-y-4 bg-gray-50">
|
||||
<h3 className="font-bold text-gray-900">API 配置</h3>
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">API 地址</label>
|
||||
<input
|
||||
type="url"
|
||||
value={editForm.api_url || ''}
|
||||
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_url: e.target.value })}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl font-mono text-sm"
|
||||
placeholder="https://api.example.com/get-card"
|
||||
/>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">请求方法</label>
|
||||
<select
|
||||
value={editForm.api_method || 'GET'}
|
||||
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_method: e.target.value as 'GET' | 'POST' })}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl"
|
||||
>
|
||||
<option value="GET">GET</option>
|
||||
<option value="POST">POST</option>
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">超时时间(秒)</label>
|
||||
<input
|
||||
type="number"
|
||||
value={editForm.api_timeout || 10}
|
||||
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_timeout: parseInt(e.target.value) || 10 })}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl"
|
||||
min="1"
|
||||
max="60"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">请求头(JSON 格式)</label>
|
||||
<textarea
|
||||
value={editForm.api_headers || ''}
|
||||
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_headers: e.target.value })}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm"
|
||||
placeholder='{"Authorization": "Bearer token"}'
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">请求参数(JSON 格式)</label>
|
||||
<textarea
|
||||
value={editForm.api_params || ''}
|
||||
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setEditForm({ ...editForm, api_params: e.target.value })}
|
||||
className="w-full ios-input px-4 py-3 rounded-xl h-20 resize-none font-mono text-sm"
|
||||
placeholder='{"type": "card", "count": 1}'
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<>
|
||||
<APIRequestBuilder
|
||||
url={editForm.api_url || ''}
|
||||
method={editForm.api_method || 'GET'}
|
||||
timeout={editForm.api_timeout || 10}
|
||||
headers={editForm.api_headers || ''}
|
||||
params={editForm.api_params || ''}
|
||||
contentType={editForm.api_content_type || 'application/json'}
|
||||
body={editForm.api_body || ''}
|
||||
responsePath={editForm.api_response_path || ''}
|
||||
retryEnabled={editForm.api_retry_enabled || false}
|
||||
headersAction={editForm.api_headers_action || 'retain'}
|
||||
paramsAction={editForm.api_params_action || 'retain'}
|
||||
onTest={/* editAPITest 使用当前编辑草稿发起临时 API 测试,不保存草稿。 */ () => testCardAPI({ url: editForm.api_url || '', method: editForm.api_method || 'GET', timeout_seconds: editForm.api_timeout || 10, headers: editForm.api_headers || undefined, params: editForm.api_params || undefined, content_type: editForm.api_content_type || 'application/json', body: editForm.api_body || undefined, response_path: editForm.api_response_path || undefined, retry_enabled: editForm.api_retry_enabled || false })}
|
||||
onChange={/* 当前回调把 API 请求编辑器字段写回编辑草稿。 */ (field, value) => setEditForm(/* currentUpdater 基于最新编辑草稿合并 API 字段。 */ current => ({
|
||||
...current,
|
||||
...(field === 'url' ? { api_url: String(value) } : {}),
|
||||
...(field === 'method' ? { api_method: value as 'GET' | 'POST' } : {}),
|
||||
...(field === 'timeout' ? { api_timeout: Number(value) } : {}),
|
||||
...(field === 'headers' ? { api_headers: String(value) } : {}),
|
||||
...(field === 'params' ? { api_params: String(value) } : {}),
|
||||
...(field === 'contentType' ? { api_content_type: String(value) } : {}),
|
||||
...(field === 'body' ? { api_body: String(value) } : {}),
|
||||
...(field === 'responsePath' ? { api_response_path: String(value) } : {}),
|
||||
...(field === 'retryEnabled' ? { api_retry_enabled: Boolean(value) } : {}),
|
||||
...(field === 'headersAction' ? { api_headers_action: value as 'retain' | 'replace' | 'clear' } : {}),
|
||||
...(field === 'paramsAction' ? { api_params_action: value as 'retain' | 'replace' | 'clear' } : {}),
|
||||
}))}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* 固定文字配置 */}
|
||||
@@ -492,7 +468,7 @@ const CardList: React.FC = () => {
|
||||
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">类型</label>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 gap-2">
|
||||
<div className="grid grid-cols-4 gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setAddForm({ ...addForm, type: 'data', content: '' })}
|
||||
@@ -517,22 +493,22 @@ const CardList: React.FC = () => {
|
||||
<ImageIcon className="w-5 h-5 mx-auto mb-1" />
|
||||
图片
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={/* 当前回调处理用户交互或异步状态变化。 */ () => setAddForm({ ...addForm, type: 'api', content: '' })}
|
||||
className={`p-3 rounded-xl font-bold transition-all ${addForm.type === 'api' ? 'bg-brand text-white' : 'bg-gray-100 text-gray-600 hover:bg-gray-200'}`}
|
||||
>
|
||||
<Globe className="w-5 h-5 mx-auto mb-1" />
|
||||
API 接口
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{addForm.type !== 'api' && <div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700 mb-2">
|
||||
{addForm.type === 'data' ? '库存内容(一行一个)' : addForm.type === 'text' ? '固定回复内容' : addForm.type === 'image' ? '图片 URL' : 'API 地址'}
|
||||
{addForm.type === 'data' ? '库存内容(一行一个)' : addForm.type === 'text' ? '固定回复内容' : '图片 URL'}
|
||||
</label>
|
||||
{addForm.type === 'api' ? (
|
||||
<input
|
||||
type="url"
|
||||
value={addForm.content}
|
||||
onChange={/* 当前回调处理用户交互或异步状态变化。 */ (e) => setAddForm({ ...addForm, content: e.target.value })}
|
||||
placeholder="https://api.example.com/get-code"
|
||||
className="w-full ios-input px-4 py-3 rounded-xl"
|
||||
/>
|
||||
) : addForm.type === 'image' ? (
|
||||
{addForm.type === 'image' ? (
|
||||
<div className="space-y-2">
|
||||
<input
|
||||
type="url"
|
||||
@@ -554,34 +530,35 @@ const CardList: React.FC = () => {
|
||||
{addForm.type === 'data' && (
|
||||
<p className="text-xs text-gray-500">当前库存:<span className="font-bold text-brand">{addForm.content.split('\n').filter(/* 当前回调处理集合中的单个元素。 */ line => line.trim()).length}</span> 条</p>
|
||||
)}
|
||||
</div>
|
||||
</div>}
|
||||
|
||||
{addForm.type === 'api' && (
|
||||
<div className="border-t border-gray-100 pt-5 space-y-4">
|
||||
<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-700">请求方法</label>
|
||||
<select value={addForm.api_method} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, api_method: e.target.value as 'GET' | 'POST'})} className="w-full ios-input px-4 py-3 rounded-xl">
|
||||
<option value="GET">GET</option>
|
||||
<option value="POST">POST</option>
|
||||
</select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">超时时间(秒)</label>
|
||||
<input type="number" min="1" max="60" value={addForm.api_timeout} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, api_timeout: parseInt(e.target.value) || 10})} className="w-full ios-input px-4 py-3 rounded-xl" />
|
||||
</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-700">请求头(JSON)</label>
|
||||
<textarea value={addForm.api_headers} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, api_headers: e.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"}' />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<label className="block text-sm font-bold text-gray-700">请求参数(JSON)</label>
|
||||
<textarea value={addForm.api_params} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setAddForm({...addForm, api_params: e.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}"}' />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<>
|
||||
<APIRequestBuilder
|
||||
url={addForm.content}
|
||||
method={addForm.api_method}
|
||||
timeout={addForm.api_timeout}
|
||||
headers={addForm.api_headers}
|
||||
params={addForm.api_params}
|
||||
contentType={addForm.api_content_type}
|
||||
body={addForm.api_body}
|
||||
responsePath={addForm.api_response_path}
|
||||
retryEnabled={addForm.api_retry_enabled}
|
||||
onTest={/* addAPITest 使用当前新增草稿发起临时 API 测试,不创建卡密。 */ () => testCardAPI({ url: addForm.content, method: addForm.api_method, timeout_seconds: addForm.api_timeout, headers: addForm.api_headers || undefined, params: addForm.api_params || undefined, content_type: addForm.api_content_type, body: addForm.api_body || undefined, response_path: addForm.api_response_path || undefined, retry_enabled: addForm.api_retry_enabled })}
|
||||
onChange={/* 当前回调把 API 请求编辑器字段写回新增草稿。 */ (field, value) => setAddForm(/* currentUpdater 基于最新新增草稿合并 API 字段。 */ current => ({
|
||||
...current,
|
||||
...(field === 'url' ? { content: String(value) } : {}),
|
||||
...(field === 'method' ? { api_method: value as 'GET' | 'POST' } : {}),
|
||||
...(field === 'timeout' ? { api_timeout: Number(value) } : {}),
|
||||
...(field === 'headers' ? { api_headers: String(value) } : {}),
|
||||
...(field === 'params' ? { api_params: String(value) } : {}),
|
||||
...(field === 'contentType' ? { api_content_type: String(value) } : {}),
|
||||
...(field === 'body' ? { api_body: String(value) } : {}),
|
||||
...(field === 'responsePath' ? { api_response_path: String(value) } : {}),
|
||||
...(field === 'retryEnabled' ? { api_retry_enabled: Boolean(value) } : {}),
|
||||
}))}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div className="grid grid-cols-1 sm:grid-cols-[1fr_180px] gap-4">
|
||||
|
||||
@@ -23,6 +23,14 @@ export interface AddCardForm {
|
||||
api_headers: string;
|
||||
// api_params 是 API 请求参数 JSON 文本。
|
||||
api_params: string;
|
||||
// api_content_type 是 API 请求正文的 Content-Type。
|
||||
api_content_type: string;
|
||||
// api_body 是 API 请求正文 JSON 文本或键值对象 JSON 文本。
|
||||
api_body: string;
|
||||
// api_response_path 是 API 响应提取路径。
|
||||
api_response_path: string;
|
||||
// api_retry_enabled 表示是否启用带幂等键的重试。
|
||||
api_retry_enabled: boolean;
|
||||
}
|
||||
|
||||
// EditCardForm 描述编辑卡密组时的表单字段和 API 扩展字段。
|
||||
@@ -37,6 +45,18 @@ export type EditCardForm = Partial<Card> & {
|
||||
api_headers?: string;
|
||||
// api_params 是编辑中的 API 请求参数 JSON 文本。
|
||||
api_params?: string;
|
||||
// api_content_type 是编辑中的 API 请求正文 Content-Type。
|
||||
api_content_type?: string;
|
||||
// api_body 是编辑中的 API 请求正文 JSON 文本或键值对象 JSON 文本。
|
||||
api_body?: string;
|
||||
// api_response_path 是编辑中的 API 响应提取路径。
|
||||
api_response_path?: string;
|
||||
// api_retry_enabled 表示编辑中是否启用带幂等键的重试。
|
||||
api_retry_enabled?: boolean;
|
||||
// api_headers_action 保存请求头模板的三态变更意图。
|
||||
api_headers_action?: 'retain' | 'replace' | 'clear';
|
||||
// api_params_action 保存请求参数模板的三态变更意图。
|
||||
api_params_action?: 'retain' | 'replace' | 'clear';
|
||||
};
|
||||
|
||||
// CardBatchTab 表示批量导入弹窗当前展示的操作页签。
|
||||
|
||||
@@ -108,11 +108,19 @@ export interface Card {
|
||||
/** API 卡券请求方法。 */
|
||||
method: 'GET' | 'POST';
|
||||
/** API 请求超时时间。 */
|
||||
timeout?: number;
|
||||
/** API 请求头 JSON。 */
|
||||
headers?: string;
|
||||
/** API 请求参数 JSON。 */
|
||||
params?: string;
|
||||
timeout_seconds: number;
|
||||
/** API 响应提取路径。 */
|
||||
response_path?: string;
|
||||
/** 是否启用幂等重试。 */
|
||||
retry_enabled: boolean;
|
||||
/** 是否配置了请求头模板;具体值不会进入前端。 */
|
||||
headers_configured: boolean;
|
||||
/** 是否配置了请求参数模板;具体值不会进入前端。 */
|
||||
params_configured: boolean;
|
||||
/** 配置是否可用于规则发货。 */
|
||||
ready: boolean;
|
||||
/** 配置无效时的脱敏错误说明。 */
|
||||
validation_error?: string;
|
||||
};
|
||||
// 图片类型
|
||||
/** 图片卡券地址。 */
|
||||
|
||||
@@ -835,7 +835,7 @@ const Rules: React.FC<RulesProps> = ({ initialDeliveryTarget, onDeliveryTargetHa
|
||||
className="w-full ios-input px-3 py-2.5 rounded-lg"
|
||||
>
|
||||
<option value="">请选择卡密库存</option>
|
||||
{cards.filter(/* 当前回调处理集合中的单个元素。 */ card => card.enabled && card.type !== 'api').map(/* 当前回调处理集合中的单个元素。 */ card => (
|
||||
{cards.filter(/* 当前回调处理集合中的单个元素。 */ card => card.enabled && (card.type !== 'api' || card.api_config?.ready === true)).map(/* 当前回调处理集合中的单个元素。 */ card => (
|
||||
<option key={card.id} value={card.id}>{card.name}</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
@@ -36,6 +36,10 @@ const normalizeSettings = (settings: Record<string, unknown>): SystemSettings =>
|
||||
const days = Number(result.renewal_log_retention_days);
|
||||
result.renewal_log_retention_days = Number.isFinite(days) ? days : 10;
|
||||
}
|
||||
if ('outbound_http_public_only' in result) {
|
||||
// publicOnly 保存统一出站策略的布尔状态,兼容旧服务端返回的字符串。
|
||||
result.outbound_http_public_only = result.outbound_http_public_only === true || result.outbound_http_public_only === 'true';
|
||||
}
|
||||
return result as SystemSettings;
|
||||
};
|
||||
|
||||
|
||||
@@ -23,6 +23,8 @@ export interface SystemSettings {
|
||||
log_level?: 'debug' | 'info' | 'warn' | 'error' | string;
|
||||
/** 服务端日志格式。 */
|
||||
log_format?: 'text' | 'json' | string;
|
||||
/** 是否阻止用户配置的服务端 HTTP 请求访问内网地址。 */
|
||||
outbound_http_public_only?: boolean;
|
||||
/** 续期日志保留天数。 */
|
||||
renewal_log_retention_days?: number;
|
||||
/** 远程验证码服务地址。 */
|
||||
|
||||
@@ -126,6 +126,14 @@ const Settings: React.FC = () => {
|
||||
/>
|
||||
<p className="text-xs text-gray-500">0 表示不自动清理续期日志</p>
|
||||
</div>
|
||||
|
||||
<label className="flex items-start gap-3 rounded-xl border border-amber-200 bg-amber-50 p-4 cursor-pointer">
|
||||
<input type="checkbox" className="mt-1" checked={settings.outbound_http_public_only || false} onChange={/* 当前回调处理用户交互或异步状态变化。 */ event => setSettings({ ...settings, outbound_http_public_only: event.target.checked })} />
|
||||
<span>
|
||||
<span className="block text-sm font-bold text-amber-900">限制用户配置的 HTTP 出站请求只能访问公网</span>
|
||||
<span className="mt-1 block text-xs leading-5 text-amber-800">开启后会同时约束 API 发货、AI、HTTP 通知、远程图片和远程滑块服务;保存后立即生效,可能使内网服务不可用。</span>
|
||||
</span>
|
||||
</label>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
@@ -541,6 +541,23 @@ export interface paths {
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/cards/test-api": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
get?: never;
|
||||
put?: never;
|
||||
/** postApiV1CardsTestApi */
|
||||
post: operations["postApiV1CardsTestApi"];
|
||||
delete?: never;
|
||||
options?: never;
|
||||
head?: never;
|
||||
patch?: never;
|
||||
trace?: never;
|
||||
};
|
||||
"/api/v1/cards/{card_id}": {
|
||||
parameters: {
|
||||
query?: never;
|
||||
@@ -2220,7 +2237,7 @@ export interface components {
|
||||
name?: string;
|
||||
/** @enum {string} */
|
||||
type?: "api" | "text" | "data" | "image";
|
||||
api_config?: string;
|
||||
api_config?: components["schemas"]["APICardConfigMutation"] | string;
|
||||
text_content?: string;
|
||||
data_content?: string;
|
||||
image_url?: string;
|
||||
@@ -2262,7 +2279,7 @@ export interface components {
|
||||
name: string;
|
||||
/** @enum {string} */
|
||||
type: "api" | "text" | "data" | "image";
|
||||
api_config: string;
|
||||
api_config?: components["schemas"]["APICardConfigResponse"] | null;
|
||||
text_content: string;
|
||||
data_content: string;
|
||||
image_url: string;
|
||||
@@ -2274,6 +2291,59 @@ export interface components {
|
||||
spec_value: string;
|
||||
user_id?: number;
|
||||
};
|
||||
APICardConfigMutation: {
|
||||
/** Format: uri */
|
||||
url: string;
|
||||
/**
|
||||
* @default GET
|
||||
* @enum {string}
|
||||
*/
|
||||
method: "GET" | "POST";
|
||||
/** @default 10 */
|
||||
timeout_seconds: number;
|
||||
headers?: {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
params?: {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
body?: {
|
||||
[key: string]: unknown;
|
||||
};
|
||||
/** @default application/json */
|
||||
content_type: string;
|
||||
/** @enum {string} */
|
||||
headers_action?: "retain" | "replace" | "clear";
|
||||
/** @enum {string} */
|
||||
params_action?: "retain" | "replace" | "clear";
|
||||
response_path?: string;
|
||||
retry_enabled?: boolean;
|
||||
};
|
||||
APICardConfigResponse: {
|
||||
url: string;
|
||||
/** @enum {string} */
|
||||
method: "GET" | "POST";
|
||||
timeout_seconds: number;
|
||||
content_type: string;
|
||||
response_path?: string;
|
||||
retry_enabled: boolean;
|
||||
headers_configured: boolean;
|
||||
params_configured: boolean;
|
||||
ready: boolean;
|
||||
validation_error?: string;
|
||||
};
|
||||
CardAPITestRequest: {
|
||||
api_config: components["schemas"]["APICardConfigMutation"] | string;
|
||||
};
|
||||
CardAPITestResponse: {
|
||||
/** @enum {string} */
|
||||
status: "success" | "failed";
|
||||
status_code: number;
|
||||
response_content_type: string;
|
||||
response_fields: string[];
|
||||
extracted_value?: string;
|
||||
response_preview?: string;
|
||||
};
|
||||
ItemListResponse: {
|
||||
id: number;
|
||||
cookie_id: string;
|
||||
@@ -2502,6 +2572,11 @@ export interface components {
|
||||
[key: string]: components["schemas"]["SecretSettingChange"];
|
||||
};
|
||||
};
|
||||
SystemSettingSingleUpdateRequest: {
|
||||
value: string;
|
||||
/** @enum {string} */
|
||||
action?: "retain" | "replace" | "clear";
|
||||
};
|
||||
SystemSettingsResponse: {
|
||||
[key: string]: string | number | boolean;
|
||||
};
|
||||
@@ -5673,6 +5748,57 @@ export interface operations {
|
||||
};
|
||||
};
|
||||
};
|
||||
postApiV1CardsTestApi: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
header?: never;
|
||||
path?: never;
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": components["schemas"]["CardAPITestRequest"];
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description 测试完成 */
|
||||
200: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["CardAPITestResponse"];
|
||||
};
|
||||
};
|
||||
/** @description 统一错误响应 */
|
||||
400: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["ErrorResponse"];
|
||||
};
|
||||
};
|
||||
/** @description 统一错误响应 */
|
||||
401: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["ErrorResponse"];
|
||||
};
|
||||
};
|
||||
/** @description 统一错误响应 */
|
||||
503: {
|
||||
headers: {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["ErrorResponse"];
|
||||
};
|
||||
};
|
||||
};
|
||||
};
|
||||
getApiV1CardsBycard_id: {
|
||||
parameters: {
|
||||
query?: never;
|
||||
@@ -12119,7 +12245,11 @@ export interface operations {
|
||||
};
|
||||
cookie?: never;
|
||||
};
|
||||
requestBody?: never;
|
||||
requestBody: {
|
||||
content: {
|
||||
"application/json": components["schemas"]["SystemSettingSingleUpdateRequest"];
|
||||
};
|
||||
};
|
||||
responses: {
|
||||
/** @description 成功 */
|
||||
200: {
|
||||
@@ -12127,7 +12257,7 @@ export interface operations {
|
||||
[name: string]: unknown;
|
||||
};
|
||||
content: {
|
||||
"application/json": components["schemas"]["ApiResponse"];
|
||||
"application/json": components["schemas"]["OperationResponse"];
|
||||
};
|
||||
};
|
||||
/** @description 统一错误响应 */
|
||||
|
||||
@@ -163,6 +163,7 @@ func NewRuntimeBundle(store *db.Store, bm *browser.Manager, logger *slog.Logger)
|
||||
autoCenter := automation.NewWithDependencies(store, automationSenders, logger, automation.CenterDependencies{
|
||||
OrderDetailFetcher: runtimeAdapter,
|
||||
Notifier: notifier,
|
||||
APICardFetcher: newAPIDeliveryClient(store, logger),
|
||||
})
|
||||
runtimeAdapter.chat = chatService
|
||||
runtimeAdapter.automation = autoCenter
|
||||
|
||||
@@ -313,7 +313,8 @@ func (a *Adapter) HandleSystemEvent(ctx context.Context, task automation.Task) e
|
||||
if a.automation == nil {
|
||||
return nil
|
||||
}
|
||||
a.logger.Info("系统自动化事件", "account", task.AccountID, "trigger", task.TriggerType, "order_id", task.OrderID)
|
||||
// 入口日志只表示收到平台卡片,不代表已经匹配规则或执行动作;统一使用 DEBUG 避免半成品和重复推送污染业务 INFO 日志。
|
||||
a.logger.Debug("收到系统自动化事件", "account", task.AccountID, "trigger", task.TriggerType, "order_id", task.OrderID)
|
||||
return a.automation.HandleTask(ctx, task)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
@@ -382,6 +384,36 @@ func TestHandleSystemEvent_UninjectedSafe(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestHandleSystemEventIngressUsesDebugLog 验证系统卡片入口日志不会把尚未匹配规则的事件伪装成业务 INFO。
|
||||
func TestHandleSystemEventIngressUsesDebugLog(t *testing.T) {
|
||||
// store、cleanup 保存自动化中心测试数据库及清理函数。
|
||||
store, cleanup := newAdapterTestStore(t)
|
||||
defer cleanup()
|
||||
// logBuffer 收集适配器入口日志,用于检查日志级别而不依赖全局日志输出。
|
||||
var logBuffer bytes.Buffer
|
||||
// logger 将 DEBUG 及以上日志写入内存,便于断言空订单和完整订单事件的入口记录。
|
||||
logger := slog.New(slog.NewTextHandler(&logBuffer, &slog.HandlerOptions{Level: slog.LevelDebug}))
|
||||
// adapter 是装配自动化中心后的事件转发适配器。
|
||||
adapter := New(store, nil, logger)
|
||||
adapter.automation = automation.New(store, nil, logger)
|
||||
// firstErr 是空订单创建卡片进入自动化中心后不应产生的处理错误。
|
||||
if firstErr := adapter.HandleSystemEvent(context.Background(), automation.Task{AccountID: "cid", TriggerType: automation.TriggerOrderCreated}); firstErr != nil {
|
||||
t.Fatal(firstErr)
|
||||
}
|
||||
// secondErr 是带订单 ID 的无规则付款卡片进入自动化中心后不应产生的处理错误。
|
||||
if secondErr := adapter.HandleSystemEvent(context.Background(), automation.Task{AccountID: "cid", TriggerType: automation.TriggerOrderPaid, OrderID: "order-log"}); secondErr != nil {
|
||||
t.Fatal(secondErr)
|
||||
}
|
||||
// output 是入口和中心日志的文本结果;入口事件必须以 DEBUG 记录,不得出现旧的 INFO 文案。
|
||||
output := logBuffer.String()
|
||||
if !strings.Contains(output, "msg=收到系统自动化事件") || !strings.Contains(output, "level=DEBUG") {
|
||||
t.Fatalf("入口事件应记录为 DEBUG: %s", output)
|
||||
}
|
||||
if strings.Contains(output, "level=INFO msg=系统自动化事件") {
|
||||
t.Fatalf("入口事件不应继续记录旧 INFO 日志: %s", output)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFetchOrderDetail_LocalHitShortCircuits 本地订单字段齐全时不启动浏览器。
|
||||
func TestFetchOrderDetail_LocalHitShortCircuits(t *testing.T) {
|
||||
// store、cleanup 用于本次流程后续判断的store、cleanup
|
||||
|
||||
@@ -25,7 +25,7 @@ type AIModelClient struct {
|
||||
func NewAIModelClient() *AIModelClient {
|
||||
// client 保存生产环境使用的模型目录客户端。
|
||||
client := &AIModelClient{newHTTPClient: func(baseURL string) (*http.Client, error) {
|
||||
return netguard.TrustedEndpointHTTPClient(baseURL, 20*time.Second)
|
||||
return netguard.ConfiguredEndpointHTTPClient(baseURL, 20*time.Second)
|
||||
}}
|
||||
return client
|
||||
}
|
||||
|
||||
@@ -0,0 +1,636 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
cardsapp "xianyu-go/internal/application/cards"
|
||||
"xianyu-go/internal/automation"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/netguard"
|
||||
)
|
||||
|
||||
// apiDeliveryResponseLimit 是 API 发货允许读取的最大响应体大小,避免远端响应耗尽服务端内存。
|
||||
const apiDeliveryResponseLimit int64 = 1 << 20
|
||||
|
||||
// apiTestPreviewLimit 限制测试响应返回给浏览器的预览长度,避免把大响应或敏感内容扩散到前端。
|
||||
const apiTestPreviewLimit = 4096
|
||||
|
||||
// apiDeliveryRetryLimit 是开启幂等重试后允许的总请求次数。
|
||||
const apiDeliveryRetryLimit = 3
|
||||
|
||||
// apiDeliveryRetryGaps 是第 2、3 次 API 发货请求前的退避间隔;测试可临时替换它。
|
||||
var apiDeliveryRetryGaps = []time.Duration{time.Second, 2 * time.Second}
|
||||
|
||||
// apiDeliveryClient 实现自动化中心要求的普通 API 卡发货能力。
|
||||
type apiDeliveryClient struct {
|
||||
// store 读取模板变量所需的商品详情,不读取账号凭证明文。
|
||||
store *db.Store
|
||||
// logger 只记录请求元数据,不记录 URL 查询串、请求模板或响应内容。
|
||||
logger *slog.Logger
|
||||
// client 是共享的策略 HTTP 客户端;单次超时由请求 Context 控制,避免每个单位创建 Transport。
|
||||
client *http.Client
|
||||
// clientOnce 保证测试构造的零值客户端只初始化一次共享 Transport。
|
||||
clientOnce sync.Once
|
||||
}
|
||||
|
||||
// newAPIDeliveryClient 创建 API 发货适配器。
|
||||
func newAPIDeliveryClient(store *db.Store, logger *slog.Logger) automation.APICardFetcher {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
return &apiDeliveryClient{store: store, logger: logger, client: netguard.ConfiguredHTTPClient(0)}
|
||||
}
|
||||
|
||||
// NewAPICardTester 创建卡密 API 测试适配器;它与自动发货共享出站策略但不会执行重试或写入库存。
|
||||
func NewAPICardTester(store *db.Store, logger *slog.Logger) cardsapp.APIRequestTester {
|
||||
if logger == nil {
|
||||
logger = slog.Default()
|
||||
}
|
||||
return &apiDeliveryClient{store: store, logger: logger, client: netguard.ConfiguredHTTPClient(0)}
|
||||
}
|
||||
|
||||
// Test 发送一次不带真实订单数据的 API 测试请求,并返回状态和响应结构诊断。
|
||||
func (c *apiDeliveryClient) Test(ctx context.Context, input cardsapp.APIRequestTestInput) (cardsapp.APIRequestTestResult, error) {
|
||||
// config、err 分别是规范化后的临时测试配置及其输入校验错误。
|
||||
config, err := cardsapp.ParseAPIConfig(input.Config)
|
||||
if err != nil {
|
||||
return cardsapp.APIRequestTestResult{}, err
|
||||
}
|
||||
// variables 是测试环境稳定占位符,绝不使用真实订单、买家或账号数据。
|
||||
variables := map[string]string{
|
||||
"{order_id}": "test-order", "{item_id}": "test-item", "{buyer_id}": "test-buyer",
|
||||
"{chat_id}": "test-chat", "{account_id}": "test-account", "{cookie_id}": "test-account",
|
||||
"{spec_name}": "", "{spec_value}": "", "{quantity}": "1", "{order_quantity}": "1",
|
||||
"{amount}": "0", "{order_amount}": "0", "{item_detail}": "", "{trigger_type}": "test",
|
||||
"{timestamp}": time.Now().UTC().Format(time.RFC3339Nano), "{delivery_unit_index}": "1",
|
||||
"{delivery_total_count}": "1", "{idempotency_key}": "test-idempotency-key",
|
||||
}
|
||||
// headers、params 分别是已用测试变量替换的请求头和查询参数。
|
||||
headers := replaceAPIJSONMap(config.Headers, variables)
|
||||
// params 是已用测试变量替换的查询参数。
|
||||
params := replaceAPIJSONMap(config.Params, variables)
|
||||
// requestURL、err 分别是待请求 URL 和解析错误;错误文本不回显原始地址。
|
||||
requestURL, err := url.Parse(config.URL)
|
||||
if err != nil {
|
||||
return cardsapp.APIRequestTestResult{}, errors.New("API 地址无效")
|
||||
}
|
||||
if config.Method == http.MethodGet {
|
||||
// query 保存基础地址与模板参数合并后的查询字符串。
|
||||
query := requestURL.Query()
|
||||
// key、value 分别是查询字段名称和已替换的字段值。
|
||||
for key, value := range params {
|
||||
query.Set(key, apiJSONScalar(value))
|
||||
}
|
||||
requestURL.RawQuery = query.Encode()
|
||||
}
|
||||
// bodyValues 是已替换的正文模板;为空时沿用历史 Params 正文兼容规则。
|
||||
bodyValues := replaceAPIJSONMap(config.Body, variables)
|
||||
if len(bodyValues) == 0 {
|
||||
bodyValues = params
|
||||
}
|
||||
// body、err 分别是按 Content-Type 编码后的正文和编码错误。
|
||||
body, err := encodeAPIDeliveryBody(bodyValues, config.ContentType)
|
||||
if err != nil {
|
||||
return cardsapp.APIRequestTestResult{}, fmt.Errorf("编码 API 请求参数: %w", err)
|
||||
}
|
||||
// requestCtx、cancel 限制本次测试请求的最长耗时,并在函数返回时释放计时器。
|
||||
requestCtx, cancel := context.WithTimeout(ctx, time.Duration(config.Timeout)*time.Second)
|
||||
defer cancel()
|
||||
// requestBody 仅用于 POST 的可重复读取正文,GET 请求保持为空。
|
||||
var requestBody io.Reader
|
||||
if config.Method == http.MethodPost {
|
||||
requestBody = bytes.NewReader(body)
|
||||
}
|
||||
// request、err 分别是受上下文控制的远端请求和构造错误。
|
||||
request, err := http.NewRequestWithContext(requestCtx, config.Method, requestURL.String(), requestBody)
|
||||
if err != nil {
|
||||
return cardsapp.APIRequestTestResult{}, errors.New("API 请求地址无效")
|
||||
}
|
||||
// key、value 分别是请求头名称和经过模板替换的字段值。
|
||||
for key, value := range headers {
|
||||
request.Header.Set(key, apiJSONScalar(value))
|
||||
}
|
||||
if config.Method == http.MethodPost && request.Header.Get("Content-Type") == "" {
|
||||
request.Header.Set("Content-Type", config.ContentType)
|
||||
}
|
||||
// response、err 分别是远端响应和不含请求秘密的网络错误。
|
||||
response, err := c.httpClient().Do(request)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return cardsapp.APIRequestTestResult{}, ctx.Err()
|
||||
}
|
||||
return cardsapp.APIRequestTestResult{}, errors.New("API 测试请求失败")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
// rawBody、err 分别是受 1 MiB 限制的响应内容和读取错误。
|
||||
rawBody, err := readAPIDeliveryBody(response.Body)
|
||||
if err != nil {
|
||||
return cardsapp.APIRequestTestResult{Status: "failed", StatusCode: response.StatusCode, ResponseContentType: response.Header.Get("Content-Type")}, err
|
||||
}
|
||||
// result 是返回给前端的非敏感状态、类型和限长响应预览。
|
||||
result := cardsapp.APIRequestTestResult{Status: "success", StatusCode: response.StatusCode, ResponseContentType: response.Header.Get("Content-Type"), ResponsePreview: truncateAPITestPreview(string(rawBody))}
|
||||
if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
|
||||
result.Status = "failed"
|
||||
return result, nil
|
||||
}
|
||||
// document 只在当前函数内持有 JSON 响应,用于字段名和路径提取。
|
||||
var document any
|
||||
// decoder 使用 JSON Number 以保持卡密等大整数的原始精度。
|
||||
decoder := json.NewDecoder(bytes.NewReader(rawBody))
|
||||
decoder.UseNumber()
|
||||
if decoder.Decode(&document) == nil {
|
||||
// object、ok 分别是 JSON 顶层对象视图和类型判断结果。
|
||||
if object, ok := document.(map[string]any); ok {
|
||||
result.ResponseFields = make([]string, 0, len(object))
|
||||
// key 是当前 JSON 顶层字段名称,只返回名称不返回全部字段值。
|
||||
for key := range object {
|
||||
result.ResponseFields = append(result.ResponseFields, key)
|
||||
}
|
||||
sort.Strings(result.ResponseFields)
|
||||
}
|
||||
if config.ResponsePath != "" {
|
||||
// value、found 分别是响应路径命中的值和是否存在标记。
|
||||
if value, found := lookupAPIResponsePath(document, config.ResponsePath); found {
|
||||
result.ExtractedValue = truncateAPITestPreview(apiJSONScalar(value))
|
||||
}
|
||||
} else {
|
||||
result.ExtractedValue = truncateAPITestPreview(apiJSONScalar(document))
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
// truncateAPITestPreview 限制测试结果文本长度并标记被截断的响应。
|
||||
func truncateAPITestPreview(value string) string {
|
||||
if len(value) <= apiTestPreviewLimit {
|
||||
return value
|
||||
}
|
||||
return value[:apiTestPreviewLimit] + "..."
|
||||
}
|
||||
|
||||
// Fetch 根据单个订单单位构造并发送一次 API 请求;重试仍复用同一幂等键。
|
||||
func (c *apiDeliveryClient) Fetch(ctx context.Context, request automation.APICardRequest) (automation.APICardResult, error) {
|
||||
// config 是从专用卡券读取路径得到的完整 API 配置。
|
||||
config, err := cardsapp.ParseAPIConfig(request.Config)
|
||||
if err != nil {
|
||||
return automation.APICardResult{}, err
|
||||
}
|
||||
// itemDetail 是本地已保存的商品详情;查询不到时保持空字符串,不凭空补造内容。
|
||||
itemDetail := ""
|
||||
if c.store != nil && c.store.Items != nil && request.ItemID != "" {
|
||||
// item、itemErr 保存商品详情查询结果及不存在/数据库错误的区分。
|
||||
if item, itemErr := c.store.Items.GetByCookieItem(ctx, request.AccountID, request.ItemID); itemErr == nil {
|
||||
itemDetail = item.ItemDetail
|
||||
} else if !errors.Is(itemErr, db.ErrNotFound) {
|
||||
return automation.APICardResult{}, fmt.Errorf("读取商品详情: %w", itemErr)
|
||||
}
|
||||
}
|
||||
// idempotencyKey 是由触发键、动作、卡券和单位序号稳定生成的请求幂等键。
|
||||
idempotencyKey := apiDeliveryIdempotencyKey(request.TriggerKey, request.ActionID, request.CardID, request.UnitIndex)
|
||||
// variables 保存可用于请求头和参数值替换的订单上下文。
|
||||
variables := map[string]string{
|
||||
"{order_id}": request.OrderID,
|
||||
"{item_id}": request.ItemID,
|
||||
"{buyer_id}": request.BuyerID,
|
||||
"{chat_id}": request.ChatID,
|
||||
"{account_id}": request.AccountID,
|
||||
"{cookie_id}": request.AccountID,
|
||||
"{spec_name}": request.SpecName,
|
||||
"{spec_value}": request.SpecValue,
|
||||
"{quantity}": request.Quantity,
|
||||
"{order_quantity}": request.Quantity,
|
||||
"{amount}": request.Amount,
|
||||
"{order_amount}": request.Amount,
|
||||
"{item_detail}": itemDetail,
|
||||
"{trigger_type}": request.TriggerType,
|
||||
"{timestamp}": time.Now().UTC().Format(time.RFC3339Nano),
|
||||
"{delivery_unit_index}": strconv.Itoa(request.UnitIndex),
|
||||
"{delivery_total_count}": strconv.Itoa(request.TotalUnits),
|
||||
"{idempotency_key}": idempotencyKey,
|
||||
}
|
||||
// headers、params 是递归替换后的请求模板,模板键名保持不变。
|
||||
headers := replaceAPIJSONMap(config.Headers, variables)
|
||||
// params 保存递归替换后的请求参数模板。
|
||||
params := replaceAPIJSONMap(config.Params, variables)
|
||||
// requestURL 是不包含动态替换的固定 API 地址;GET 参数随后编码到查询部分。
|
||||
requestURL, err := url.Parse(config.URL)
|
||||
if err != nil {
|
||||
return automation.APICardResult{}, err
|
||||
}
|
||||
if config.Method == http.MethodGet {
|
||||
// query 保存固定 URL 查询参数与 API 模板参数合并后的结果。
|
||||
query := requestURL.Query()
|
||||
// key、value 分别是不会动态替换的参数名及已经替换的参数值。
|
||||
for key, value := range params {
|
||||
query.Set(key, apiJSONScalar(value))
|
||||
}
|
||||
requestURL.RawQuery = query.Encode()
|
||||
}
|
||||
// bodyValues 保存 POST 正文模板;旧配置没有 body 时继续把 params 作为正文,保持兼容。
|
||||
bodyValues := replaceAPIJSONMap(config.Body, variables)
|
||||
if len(bodyValues) == 0 {
|
||||
bodyValues = params
|
||||
}
|
||||
// body 保存 POST 请求编码后的正文;GET 请求不把参数复制到请求体。
|
||||
body, err := encodeAPIDeliveryBody(bodyValues, config.ContentType)
|
||||
if err != nil {
|
||||
return automation.APICardResult{}, fmt.Errorf("编码 API 请求参数: %w", err)
|
||||
}
|
||||
// attempts 是本次请求允许执行的总次数;未开启重试时固定为一次。
|
||||
attempts := 1
|
||||
if config.RetryEnabled {
|
||||
attempts = apiDeliveryRetryLimit
|
||||
}
|
||||
// attempt 表示当前已执行的请求次数,最多不超过配置允许的总次数。
|
||||
for attempt := 1; attempt <= attempts; attempt++ {
|
||||
// result、attemptErr 保存本次 HTTP 调用的结果及响应提取错误。
|
||||
result, attemptErr := c.doAPIRequest(ctx, config, requestURL.String(), headers, body, attempt)
|
||||
if attemptErr == nil {
|
||||
return result, nil
|
||||
}
|
||||
if !shouldRetryAPIDelivery(attemptErr, attempt, attempts) {
|
||||
return result, attemptErr
|
||||
}
|
||||
// retryTimer 在上下文取消时立即终止退避,避免自动化工作线程被无意义占用。
|
||||
retryGap := apiDeliveryRetryGaps[attempt-1]
|
||||
// retryTimer 控制下一次请求前的有限退避时间。
|
||||
retryTimer := time.NewTimer(retryGap)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
if !retryTimer.Stop() {
|
||||
select {
|
||||
case <-retryTimer.C:
|
||||
default:
|
||||
}
|
||||
}
|
||||
return automation.APICardResult{Dispatched: result.Dispatched}, ctx.Err()
|
||||
case <-retryTimer.C:
|
||||
}
|
||||
}
|
||||
return automation.APICardResult{Dispatched: true}, errors.New("API 发货请求重试次数耗尽")
|
||||
}
|
||||
|
||||
// doAPIRequest 执行一次不含重试的 HTTP 请求,并把状态码映射为可安全分类的结果。
|
||||
func (c *apiDeliveryClient) doAPIRequest(ctx context.Context, config cardsapp.APIConfig, rawURL string, headers map[string]any, body []byte, attempt int) (automation.APICardResult, error) {
|
||||
// requestBody 保存 POST 的可重复读取请求体;GET 请求传入空体。
|
||||
var requestBody io.Reader
|
||||
if config.Method == http.MethodPost {
|
||||
requestBody = bytes.NewReader(body)
|
||||
}
|
||||
// request、err 保存当前尝试的 HTTP 请求及构造错误。
|
||||
requestCtx, cancel := context.WithTimeout(ctx, time.Duration(config.Timeout)*time.Second)
|
||||
defer cancel()
|
||||
// request、err 保存当前尝试的 HTTP 请求及构造错误。
|
||||
request, err := http.NewRequestWithContext(requestCtx, config.Method, rawURL, requestBody)
|
||||
if err != nil {
|
||||
return automation.APICardResult{}, err
|
||||
}
|
||||
// key、value 分别是请求头名称及递归替换后的请求头值。
|
||||
for key, value := range headers {
|
||||
request.Header.Set(key, apiJSONScalar(value))
|
||||
}
|
||||
if config.Method == http.MethodPost && request.Header.Get("Content-Type") == "" {
|
||||
// contentType 是用户选择的正文媒体类型;缺省时使用 JSON 兼容旧配置。
|
||||
contentType := config.ContentType
|
||||
if contentType == "" {
|
||||
contentType = "application/json"
|
||||
}
|
||||
request.Header.Set("Content-Type", contentType)
|
||||
}
|
||||
// response、err 保存远端响应及网络调用错误。
|
||||
client := c.httpClient()
|
||||
// response、err 保存远端响应及网络调用错误。
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return automation.APICardResult{}, ctx.Err()
|
||||
}
|
||||
return automation.APICardResult{Dispatched: true}, &apiDeliveryRetryableError{kind: "network", err: err}
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if c.logger != nil {
|
||||
c.logger.Info("API 卡发货请求完成", "method", config.Method, "attempt", attempt, "status", response.StatusCode)
|
||||
}
|
||||
if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
|
||||
// readErr 保存受限读取暂时性错误,不读取响应正文到日志。
|
||||
if _, readErr := readAPIDeliveryBody(response.Body); readErr != nil {
|
||||
return automation.APICardResult{Dispatched: response.StatusCode == http.StatusRequestTimeout || response.StatusCode == http.StatusTooManyRequests || response.StatusCode >= 500}, readErr
|
||||
}
|
||||
// dispatched 表示暂时性状态可能伴随服务端处理;明确的其他 4xx 视为确定拒绝。
|
||||
dispatched := response.StatusCode == http.StatusRequestTimeout || response.StatusCode == http.StatusTooManyRequests || response.StatusCode >= 500
|
||||
return automation.APICardResult{Dispatched: dispatched}, &apiDeliveryHTTPError{statusCode: response.StatusCode}
|
||||
}
|
||||
// content、readErr 保存成功响应的提取结果及解析错误。
|
||||
content, readErr := readAPIDeliveryResponse(response.Body, response.Header.Get("Content-Type"), config.ResponsePath)
|
||||
if readErr != nil {
|
||||
return automation.APICardResult{Dispatched: true}, readErr
|
||||
}
|
||||
if strings.TrimSpace(content) == "" {
|
||||
return automation.APICardResult{Dispatched: true}, errors.New("API 响应提取结果为空")
|
||||
}
|
||||
return automation.APICardResult{Content: content}, nil
|
||||
}
|
||||
|
||||
// encodeAPIDeliveryBody 按用户选择的 Content-Type 编码 API 请求正文。
|
||||
func encodeAPIDeliveryBody(values map[string]any, contentType string) ([]byte, error) {
|
||||
// lowerContentType 保存忽略大小写后的媒体类型,供正文编码分支判断。
|
||||
lowerContentType := strings.ToLower(contentType)
|
||||
if strings.Contains(lowerContentType, "x-www-form-urlencoded") {
|
||||
// formValues 保存表单编码所需的字符串字段。
|
||||
formValues := url.Values{}
|
||||
// key、value 分别是表单字段名称和待编码的模板值。
|
||||
// key、value 分别是纯文本字段名称和字段值。
|
||||
for key, value := range values {
|
||||
formValues.Set(key, apiJSONScalar(value))
|
||||
}
|
||||
return []byte(formValues.Encode()), nil
|
||||
}
|
||||
if strings.Contains(lowerContentType, "text/plain") {
|
||||
// lines 保存纯文本键值正文,每行一个字段,便于普通 Web 服务直接读取。
|
||||
lines := make([]string, 0, len(values))
|
||||
// key、value 分别是 XML 字段名称和字段值。
|
||||
for key, value := range values {
|
||||
lines = append(lines, key+"="+apiJSONScalar(value))
|
||||
}
|
||||
sort.Strings(lines)
|
||||
return []byte(strings.Join(lines, "\n")), nil
|
||||
}
|
||||
if strings.Contains(lowerContentType, "application/xml") {
|
||||
// xmlParts 保存经过 XML 转义的简单字段元素。
|
||||
xmlParts := make([]string, 0, len(values))
|
||||
// key、value 分别是 XML 字段名称和待转义字段值。
|
||||
for key, value := range values {
|
||||
if !isXMLTagName(key) {
|
||||
key = "field"
|
||||
}
|
||||
xmlParts = append(xmlParts, fmt.Sprintf("<%s>%s</%s>", key, xmlEscape(apiJSONScalar(value)), key))
|
||||
}
|
||||
sort.Strings(xmlParts)
|
||||
return []byte("<body>" + strings.Join(xmlParts, "") + "</body>"), nil
|
||||
}
|
||||
return json.Marshal(values)
|
||||
}
|
||||
|
||||
// isXMLTagName 判断用户填写的键名是否可以作为 XML 标签名使用。
|
||||
func isXMLTagName(value string) bool {
|
||||
if value == "" || (value[0] >= '0' && value[0] <= '9') {
|
||||
return false
|
||||
}
|
||||
// character 表示当前键名中的一个 Unicode 字符。
|
||||
for _, character := range value {
|
||||
if character != '_' && character != '-' && character != ':' && character != '.' &&
|
||||
(character < 'a' || character > 'z') && (character < 'A' || character > 'Z') && (character < '0' || character > '9') {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// xmlEscape 转义 XML 正文中的五类保留字符,避免用户输入破坏请求结构。
|
||||
func xmlEscape(value string) string {
|
||||
return strings.NewReplacer("&", "&", "<", "<", ">", ">", "\"", """, "'", "'").Replace(value)
|
||||
}
|
||||
|
||||
// httpClient 返回 API 发货共享的出站客户端;客户端策略会在每次请求时读取运行时开关。
|
||||
func (c *apiDeliveryClient) httpClient() *http.Client {
|
||||
if c == nil {
|
||||
return netguard.ConfiguredHTTPClient(0)
|
||||
}
|
||||
c.clientOnce.Do(func() {
|
||||
if c.client == nil {
|
||||
c.client = netguard.ConfiguredHTTPClient(0)
|
||||
}
|
||||
})
|
||||
return c.client
|
||||
}
|
||||
|
||||
// apiDeliveryRetryableError 标记可按网络错误策略重试的单次调用失败。
|
||||
type apiDeliveryRetryableError struct {
|
||||
// kind 记录失败类别,不包含请求地址或响应秘密。
|
||||
kind string
|
||||
// err 保存底层网络错误供日志外的调用链诊断。
|
||||
err error
|
||||
}
|
||||
|
||||
// Error 返回不含请求秘密的网络错误文本。
|
||||
func (e *apiDeliveryRetryableError) Error() string { return "API 发货网络请求失败" }
|
||||
|
||||
// Unwrap 返回底层错误供上下文取消和超时判断使用。
|
||||
func (e *apiDeliveryRetryableError) Unwrap() error { return e.err }
|
||||
|
||||
// apiDeliveryHTTPError 保存可用于重试判断的 HTTP 状态码。
|
||||
type apiDeliveryHTTPError struct {
|
||||
// statusCode 是远端返回的 HTTP 状态码。
|
||||
statusCode int
|
||||
}
|
||||
|
||||
// Error 返回不包含响应正文的 HTTP 错误。
|
||||
func (e *apiDeliveryHTTPError) Error() string {
|
||||
return fmt.Sprintf("API 发货 HTTP 状态异常: %d", e.statusCode)
|
||||
}
|
||||
|
||||
// shouldRetryAPIDelivery 判断错误是否属于幂等重试允许的网络、超时或暂时性 HTTP 错误。
|
||||
func shouldRetryAPIDelivery(err error, attempt, limit int) bool {
|
||||
if err == nil || attempt >= limit {
|
||||
return false
|
||||
}
|
||||
// httpErr 保存可按状态码判断的 HTTP 失败。
|
||||
var httpErr *apiDeliveryHTTPError
|
||||
if errors.As(err, &httpErr) {
|
||||
return httpErr.statusCode == http.StatusRequestTimeout || httpErr.statusCode == http.StatusTooManyRequests || httpErr.statusCode >= 500
|
||||
}
|
||||
// networkErr 保存可按幂等策略重试的网络失败。
|
||||
var networkErr *apiDeliveryRetryableError
|
||||
return errors.As(err, &networkErr) && (networkErr.kind == "network" || errors.Is(networkErr, context.DeadlineExceeded))
|
||||
}
|
||||
|
||||
// readAPIDeliveryResponse 读取受限响应并按路径提取卡密文本。
|
||||
func readAPIDeliveryResponse(reader io.Reader, contentType, responsePath string) (string, error) {
|
||||
// body 保存受大小限制读取的完整响应体。
|
||||
body, err := readAPIDeliveryBody(reader)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
// trimmed 保存去除空白后的响应内容,用于空值和 JSON 判断。
|
||||
trimmed := strings.TrimSpace(string(body))
|
||||
if trimmed == "" {
|
||||
return "", errors.New("API 响应为空")
|
||||
}
|
||||
// document 保存 JSON 响应的动态结构,仅在当前函数内用于提取文本。
|
||||
var document any
|
||||
// decoder 保留 JSON 数字的原始文本,避免大数型卡密经过 float64 发生舍入。
|
||||
decoder := json.NewDecoder(bytes.NewReader(body))
|
||||
decoder.UseNumber()
|
||||
if decoder.Decode(&document) != nil {
|
||||
return trimmed, nil
|
||||
}
|
||||
if responsePath != "" {
|
||||
// value、found 保存响应路径命中的节点及命中状态。
|
||||
value, found := lookupAPIResponsePath(document, responsePath)
|
||||
if !found || value == nil {
|
||||
return "", errors.New("API 响应路径不存在或为空")
|
||||
}
|
||||
return apiJSONScalar(value), nil
|
||||
}
|
||||
// object、ok 保存可按默认字段提取的 JSON 对象及类型判断。
|
||||
if object, ok := document.(map[string]any); ok {
|
||||
// key 表示默认响应提取候选字段名。
|
||||
for _, key := range []string{"data", "content", "card"} {
|
||||
// value、found 保存候选字段的值及是否存在。
|
||||
if value, found := object[key]; found && value != nil {
|
||||
return apiJSONScalar(value), nil
|
||||
}
|
||||
}
|
||||
}
|
||||
return apiJSONScalar(document), nil
|
||||
}
|
||||
|
||||
// readAPIDeliveryBody 读取 API 响应体并拒绝超过 1 MiB 的内容,不返回正文到日志或 HTTP 响应。
|
||||
func readAPIDeliveryBody(reader io.Reader) ([]byte, error) {
|
||||
// limited 保存多读取一个字节以检测超大响应的受限读取器。
|
||||
limited := io.LimitReader(reader, apiDeliveryResponseLimit+1)
|
||||
// body、err 保存受限读取的响应体和读取错误。
|
||||
body, err := io.ReadAll(limited)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取 API 响应失败: %w", err)
|
||||
}
|
||||
if int64(len(body)) > apiDeliveryResponseLimit {
|
||||
return nil, errors.New("API 响应超过 1 MiB 限制")
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// lookupAPIResponsePath 按点号字段和数组下标解析响应路径。
|
||||
func lookupAPIResponsePath(document any, path string) (any, bool) {
|
||||
// current 保存逐段路径解析的当前 JSON 节点。
|
||||
current := document
|
||||
// segment 表示当前响应路径的字段或数组段。
|
||||
for _, segment := range strings.Split(strings.TrimPrefix(path, "$."), ".") {
|
||||
if segment == "" {
|
||||
return nil, false
|
||||
}
|
||||
// name、index、hasIndex、ok 保存当前路径段的字段名、数组下标和解析状态。
|
||||
name, index, hasIndex, ok := parseAPIPathSegment(segment)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
if name != "" {
|
||||
// object、objectOK 保存当前节点的对象视图及类型判断。
|
||||
object, objectOK := current.(map[string]any)
|
||||
if !objectOK {
|
||||
return nil, false
|
||||
}
|
||||
current, ok = object[name]
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
if hasIndex {
|
||||
// array、arrayOK 保存当前节点的数组视图及类型判断。
|
||||
array, arrayOK := current.([]any)
|
||||
if !arrayOK || index < 0 || index >= len(array) {
|
||||
return nil, false
|
||||
}
|
||||
current = array[index]
|
||||
}
|
||||
}
|
||||
return current, true
|
||||
}
|
||||
|
||||
// parseAPIPathSegment 把字段名和可选数组下标拆分为结构化路径段。
|
||||
func parseAPIPathSegment(segment string) (string, int, bool, bool) {
|
||||
// bracket 保存数组下标左括号位置。
|
||||
bracket := strings.IndexByte(segment, '[')
|
||||
if bracket < 0 {
|
||||
return segment, 0, false, true
|
||||
}
|
||||
if !strings.HasSuffix(segment, "]") || bracket == len(segment)-2 {
|
||||
return "", 0, false, false
|
||||
}
|
||||
// index、err 保存括号内数组下标及其解析错误。
|
||||
index, err := strconv.Atoi(segment[bracket+1 : len(segment)-1])
|
||||
if err != nil || index < 0 {
|
||||
return "", 0, false, false
|
||||
}
|
||||
return segment[:bracket], index, true, true
|
||||
}
|
||||
|
||||
// replaceAPIJSONMap 递归替换模板值,保持 JSON 对象键名原样不变。
|
||||
func replaceAPIJSONMap(input map[string]any, variables map[string]string) map[string]any {
|
||||
// output 保存替换后的新对象,避免修改卡券配置缓存。
|
||||
output := make(map[string]any, len(input))
|
||||
// key、value 分别是模板字段名和待替换模板值。
|
||||
for key, value := range input {
|
||||
output[key] = replaceAPIJSONValue(value, variables)
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
// replaceAPIJSONValue 递归处理对象、数组和字符串模板值。
|
||||
func replaceAPIJSONValue(value any, variables map[string]string) any {
|
||||
// current 保存当前递归节点的动态 JSON 值。
|
||||
switch current := value.(type) {
|
||||
case string:
|
||||
// key、replacement 分别是动态变量和订单上下文替换值。
|
||||
for key, replacement := range variables {
|
||||
current = strings.ReplaceAll(current, key, replacement)
|
||||
}
|
||||
return current
|
||||
case map[string]any:
|
||||
return replaceAPIJSONMap(current, variables)
|
||||
case []any:
|
||||
// output 保存数组中每个值的递归替换结果。
|
||||
output := make([]any, len(current))
|
||||
// index、child 分别是数组位置和当前递归节点。
|
||||
for index, child := range current {
|
||||
output[index] = replaceAPIJSONValue(child, variables)
|
||||
}
|
||||
return output
|
||||
default:
|
||||
return value
|
||||
}
|
||||
}
|
||||
|
||||
// apiJSONScalar 将响应或查询参数的 JSON 值转换为 API 发货使用的紧凑文本。
|
||||
func apiJSONScalar(value any) string {
|
||||
// current 保存当前需要转换为紧凑文本的动态值。
|
||||
switch current := value.(type) {
|
||||
case string:
|
||||
return current
|
||||
case json.Number:
|
||||
return current.String()
|
||||
case nil:
|
||||
return ""
|
||||
default:
|
||||
// encoded、err 保存复杂响应值的紧凑 JSON 表示及编码错误。
|
||||
encoded, err := json.Marshal(current)
|
||||
if err != nil {
|
||||
return fmt.Sprint(current)
|
||||
}
|
||||
return string(encoded)
|
||||
}
|
||||
}
|
||||
|
||||
// apiDeliveryIdempotencyKey 生成跨进程稳定且不暴露订单内容的幂等键。
|
||||
func apiDeliveryIdempotencyKey(triggerKey string, actionID, cardID int64, unitIndex int) string {
|
||||
// sum 保存幂等键输入的 SHA-256 摘要,不包含可逆订单秘密。
|
||||
sum := sha256.Sum256([]byte(fmt.Sprintf("%s\x00%d\x00%d\x00%d", triggerKey, actionID, cardID, unitIndex)))
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
var _ automation.APICardFetcher = (*apiDeliveryClient)(nil)
|
||||
@@ -0,0 +1,238 @@
|
||||
package adapter
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
cardsapp "xianyu-go/internal/application/cards"
|
||||
"xianyu-go/internal/automation"
|
||||
)
|
||||
|
||||
// TestAPICardTesterReturnsResponseDiagnostics 验证测试请求返回状态码、JSON 顶层字段和响应路径提取结果。
|
||||
func TestAPICardTesterReturnsResponseDiagnostics(t *testing.T) {
|
||||
// server 是返回固定 JSON 结构的本地 API 测试端点。
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
writer.Header().Set("Content-Type", "application/json")
|
||||
_, _ = writer.Write([]byte(`{"data":{"code":"TEST-CODE"},"message":"ok"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
// client 是不访问数据库的临时 API 测试适配器。
|
||||
client := &apiDeliveryClient{}
|
||||
// result、err 保存测试请求返回的诊断和错误。
|
||||
result, err := client.Test(context.Background(), cardsapp.APIRequestTestInput{Config: fmt.Sprintf(`{"url":%q,"method":"GET","timeout_seconds":10,"response_path":"data.code"}`, server.URL)})
|
||||
if err != nil {
|
||||
t.Fatalf("API 测试请求失败: %v", err)
|
||||
}
|
||||
if result.Status != "success" || result.StatusCode != http.StatusOK || result.ExtractedValue != "TEST-CODE" {
|
||||
t.Fatalf("API 测试诊断错误: %+v", result)
|
||||
}
|
||||
if strings.Join(result.ResponseFields, ",") != "data,message" {
|
||||
t.Fatalf("API 测试响应字段错误: %v", result.ResponseFields)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPICardTesterPreservesRemoteFailureDiagnostics 验证远端非 2xx 仍作为完成结果返回状态码和限长预览。
|
||||
func TestAPICardTesterPreservesRemoteFailureDiagnostics(t *testing.T) {
|
||||
// server 是返回明确失败状态的本地 API 端点。
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
writer.WriteHeader(http.StatusBadGateway)
|
||||
_, _ = writer.Write([]byte("remote failure"))
|
||||
}))
|
||||
defer server.Close()
|
||||
// client 是不访问数据库的临时 API 测试适配器。
|
||||
client := &apiDeliveryClient{}
|
||||
// result、err 保存远端失败诊断和错误。
|
||||
result, err := client.Test(context.Background(), cardsapp.APIRequestTestInput{Config: fmt.Sprintf(`{"url":%q,"method":"GET","timeout_seconds":10}`, server.URL)})
|
||||
if err != nil {
|
||||
t.Fatalf("远端失败不应变为本地错误: %v", err)
|
||||
}
|
||||
if result.Status != "failed" || result.StatusCode != http.StatusBadGateway || result.ResponsePreview != "remote failure" {
|
||||
t.Fatalf("远端失败诊断错误: %+v", result)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPIDeliveryClientGETAndTemplateReplacement 验证 GET 查询参数、递归变量替换和响应路径提取。
|
||||
func TestAPIDeliveryClientGETAndTemplateReplacement(t *testing.T) {
|
||||
// receivedQuery、receivedHeader 保存服务端观察到的动态请求字段。
|
||||
var receivedQuery, receivedHeader string
|
||||
// server 是接收 GET 模板请求的本地测试服务。
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
receivedQuery = request.URL.Query().Get("order")
|
||||
receivedHeader = request.Header.Get("X-Unit")
|
||||
_, _ = writer.Write([]byte(`{"data":{"cards":[{"code":"CODE-1"}]}}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
// client 是使用测试 HTTP 服务的普通 API 发货客户端。
|
||||
client := &apiDeliveryClient{}
|
||||
// result、err 保存单件 API 请求的提取结果及错误。
|
||||
result, err := client.Fetch(context.Background(), automation.APICardRequest{
|
||||
Config: fmt.Sprintf(`{"url":%q,"method":"GET","timeout_seconds":10,"headers":{"X-Unit":"{delivery_unit_index}"},"params":{"order":"{order_id}","nested":{"buyer":"{buyer_id}"}},"response_path":"data.cards[0].code"}`, server.URL),
|
||||
TriggerKey: "trigger-1", ActionID: 2, CardID: 3, UnitIndex: 1, TotalUnits: 2,
|
||||
AccountID: "account", OrderID: "order-7", BuyerID: "buyer-8",
|
||||
})
|
||||
if err != nil || result.Content != "CODE-1" {
|
||||
t.Fatalf("GET API 发货结果错误 result=%+v err=%v", result, err)
|
||||
}
|
||||
if receivedQuery != "order-7" || receivedHeader != "1" {
|
||||
t.Fatalf("动态字段未替换 query=%q header=%q", receivedQuery, receivedHeader)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPIDeliveryClientPOSTRetryAndStableIdempotencyKey 验证 POST JSON、三次重试和幂等键稳定复用。
|
||||
func TestAPIDeliveryClientPOSTRetryAndStableIdempotencyKey(t *testing.T) {
|
||||
// oldGaps 保存全局退避配置,避免测试等待真实秒数。
|
||||
oldGaps := apiDeliveryRetryGaps
|
||||
apiDeliveryRetryGaps = []time.Duration{time.Millisecond, time.Millisecond}
|
||||
defer func() { apiDeliveryRetryGaps = oldGaps }()
|
||||
// calls 记录服务端实际收到的请求次数。
|
||||
var calls int32
|
||||
// keys 保存每次请求观察到的幂等键。
|
||||
var keys []string
|
||||
// server 是返回暂时性失败并记录幂等键的本地测试服务。
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
atomic.AddInt32(&calls, 1)
|
||||
// body 保存 POST 参数对象。
|
||||
var body map[string]any
|
||||
// err 表示测试服务解析 POST body 的错误。
|
||||
if err := json.NewDecoder(request.Body).Decode(&body); err != nil {
|
||||
t.Errorf("POST JSON 解码失败: %v", err)
|
||||
}
|
||||
keys = append(keys, fmt.Sprint(body["key"]))
|
||||
if calls < 3 {
|
||||
writer.WriteHeader(http.StatusBadGateway)
|
||||
return
|
||||
}
|
||||
_, _ = writer.Write([]byte(`{"content":"POST-CODE"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
// client 是使用测试 HTTP 服务的普通 API 发货客户端。
|
||||
client := &apiDeliveryClient{}
|
||||
// result、err 保存带重试的 API 请求结果。
|
||||
result, err := client.Fetch(context.Background(), automation.APICardRequest{
|
||||
Config: fmt.Sprintf(`{"url":%q,"method":"POST","timeout_seconds":10,"params":{"key":"{idempotency_key}","unit":"{delivery_unit_index}"},"retry_enabled":true}`, server.URL),
|
||||
TriggerKey: "trigger-2", ActionID: 4, CardID: 5, UnitIndex: 2, TotalUnits: 2,
|
||||
})
|
||||
if err != nil || result.Content != "POST-CODE" {
|
||||
t.Fatalf("POST API 发货结果错误 result=%+v err=%v", result, err)
|
||||
}
|
||||
if atomic.LoadInt32(&calls) != 3 || len(keys) != 3 || keys[0] == "" || keys[0] != keys[1] || keys[1] != keys[2] {
|
||||
t.Fatalf("重试次数或幂等键错误 calls=%d keys=%v", atomic.LoadInt32(&calls), keys)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPIDeliveryClientFormBodyAndContentType 验证非 JSON Content-Type 使用键值表单正文,而不是上传文件格式。
|
||||
func TestAPIDeliveryClientFormBodyAndContentType(t *testing.T) {
|
||||
// receivedContentType、receivedBody 保存测试服务观察到的正文元数据和内容。
|
||||
var receivedContentType, receivedBody string
|
||||
// server 是接收表单正文并返回固定卡密的本地服务。
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
receivedContentType = request.Header.Get("Content-Type")
|
||||
// body、readErr 保存服务端读取到的正文和读取错误。
|
||||
body, readErr := io.ReadAll(request.Body)
|
||||
if readErr != nil {
|
||||
t.Errorf("读取表单正文失败: %v", readErr)
|
||||
}
|
||||
receivedBody = string(body)
|
||||
_, _ = writer.Write([]byte(`{"content":"FORM-CODE"}`))
|
||||
}))
|
||||
defer server.Close()
|
||||
// client 是使用本地测试服务的 API 发货客户端。
|
||||
client := &apiDeliveryClient{}
|
||||
// result、err 保存表单请求的发货结果及错误。
|
||||
result, err := client.Fetch(context.Background(), automation.APICardRequest{
|
||||
Config: fmt.Sprintf(`{"url":%q,"method":"POST","timeout_seconds":10,"content_type":"application/x-www-form-urlencoded","body":{"order_id":"{order_id}","quantity":"{quantity}"}}`, server.URL),
|
||||
OrderID: "order-form", Quantity: "2",
|
||||
})
|
||||
if err != nil || result.Content != "FORM-CODE" {
|
||||
t.Fatalf("表单 API 发货结果错误 result=%+v err=%v", result, err)
|
||||
}
|
||||
if receivedContentType != "application/x-www-form-urlencoded" || receivedBody != "order_id=order-form&quantity=2" {
|
||||
t.Fatalf("表单正文编码错误 content_type=%q body=%q", receivedContentType, receivedBody)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEncodeAPIDeliveryBodyTextAndXML 验证非表单 Content-Type 的键值正文编码和转义边界。
|
||||
func TestEncodeAPIDeliveryBodyTextAndXML(t *testing.T) {
|
||||
// values 保存测试使用的普通字段和包含 XML 特殊字符的字段。
|
||||
values := map[string]any{"z": "last", "a": "<&"}
|
||||
// textBody、textErr 保存纯文本正文和编码错误。
|
||||
textBody, textErr := encodeAPIDeliveryBody(values, "text/plain")
|
||||
if textErr != nil || string(textBody) != "a=<&\nz=last" {
|
||||
t.Fatalf("纯文本正文错误 body=%q err=%v", textBody, textErr)
|
||||
}
|
||||
// xmlBody、xmlErr 保存 XML 正文和编码错误。
|
||||
xmlBody, xmlErr := encodeAPIDeliveryBody(values, "application/xml")
|
||||
if xmlErr != nil || string(xmlBody) != "<body><a><&</a><z>last</z></body>" {
|
||||
t.Fatalf("XML 正文错误 body=%q err=%v", xmlBody, xmlErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPIDeliveryClientResponseAndSizeErrors 验证文本响应、非 2xx 和超大响应不会泄漏正文且不误提取。
|
||||
func TestAPIDeliveryClientResponseAndSizeErrors(t *testing.T) {
|
||||
// cases 保存不同响应场景及预期错误判定。
|
||||
cases := []struct {
|
||||
// name 是场景名称。
|
||||
name string
|
||||
// status 是服务端返回状态码。
|
||||
status int
|
||||
// body 是服务端返回的响应体。
|
||||
body string
|
||||
// wantContent 是预期的成功文本。
|
||||
wantContent string
|
||||
// wantError 表示是否应返回错误。
|
||||
wantError bool
|
||||
}{
|
||||
{name: "plain", status: http.StatusOK, body: "PLAIN-CODE", wantContent: "PLAIN-CODE"},
|
||||
{name: "bad-request", status: http.StatusBadRequest, body: "secret-error", wantError: true},
|
||||
{name: "too-large", status: http.StatusOK, body: strings.Repeat("x", int(apiDeliveryResponseLimit)+1), wantError: true},
|
||||
}
|
||||
// testCase 保存当前响应场景及其预期行为。
|
||||
for _, testCase := range cases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
// server 是当前场景使用的本地响应服务器。
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
writer.WriteHeader(testCase.status)
|
||||
_, _ = writer.Write([]byte(testCase.body))
|
||||
}))
|
||||
defer server.Close()
|
||||
// client 是当前场景使用的 API 发货客户端。
|
||||
client := &apiDeliveryClient{}
|
||||
// result、err 保存当前场景的执行结果。
|
||||
result, err := client.Fetch(context.Background(), automation.APICardRequest{
|
||||
Config: fmt.Sprintf(`{"url":%q,"method":"GET","timeout_seconds":10}`, server.URL),
|
||||
})
|
||||
if (err != nil) != testCase.wantError || result.Content != testCase.wantContent {
|
||||
t.Fatalf("响应判定错误 result=%+v err=%v", result, err)
|
||||
}
|
||||
if testCase.name == "bad-request" && result.Dispatched {
|
||||
t.Fatal("明确 4xx 拒绝不应被标记为结果未知")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPIDeliveryClientPreservesJSONNumbers 验证大整数卡密不会因 JSON 浮点转换发生舍入。
|
||||
func TestAPIDeliveryClientPreservesJSONNumbers(t *testing.T) {
|
||||
// server 是返回超出 float64 精确整数范围的 JSON 数字端点。
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = writer.Write([]byte(`{"data":{"card":{"code":9007199254740993}}}`))
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
// client 是本测试使用的零值 API 发货客户端。
|
||||
client := &apiDeliveryClient{}
|
||||
// result、err 保存 JSON 数字提取结果及错误。
|
||||
result, err := client.Fetch(context.Background(), automation.APICardRequest{
|
||||
Config: fmt.Sprintf(`{"url":%q,"method":"GET","response_path":"data.card.code"}`, server.URL),
|
||||
})
|
||||
if err != nil || result.Content != "9007199254740993" {
|
||||
t.Fatalf("JSON 大整数被错误转换 result=%+v err=%v", result, err)
|
||||
}
|
||||
}
|
||||
@@ -85,6 +85,19 @@ func (s automationImageSender) SendText(ctx context.Context, chatID, toUserID, t
|
||||
return s.sender.SendText(ctx, chatID, toUserID, text)
|
||||
}
|
||||
|
||||
// AutomationReady 透传账号运行时的 WebSocket 就绪状态,使自动化能在请求 API 卡密前阻止尚未完成注册的账号。
|
||||
func (s automationImageSender) AutomationReady() bool {
|
||||
if s.sender == nil {
|
||||
return false
|
||||
}
|
||||
// readySender 是实现连接就绪报告能力的账号运行时发送器。
|
||||
readySender, ok := s.sender.(interface{ AutomationReady() bool })
|
||||
if !ok {
|
||||
return true
|
||||
}
|
||||
return readySender.AutomationReady()
|
||||
}
|
||||
|
||||
// SendImage 将图片卡密 URL 在内存中下载、上传到闲鱼图片服务后,再交给账号运行时发送。
|
||||
// 下载或上传失败发生在 WebSocket 写入之前,必须标记为确定未发送以允许自动化安全重试。
|
||||
func (s automationImageSender) SendImage(ctx context.Context, chatID, toUserID, imageURL string, cardID int64, _, _ int) error {
|
||||
@@ -127,7 +140,7 @@ func downloadAutomationImage(ctx context.Context, rawURL string) ([]byte, string
|
||||
return nil, "", "", fmt.Errorf("创建图片下载请求失败")
|
||||
}
|
||||
// client 只允许访问公网地址,并在重定向时重复校验目标,避免卡密 URL 触发 SSRF。
|
||||
client := netguard.PublicHTTPClient(30 * time.Second)
|
||||
client := netguard.ConfiguredHTTPClient(30 * time.Second)
|
||||
// response、err 保存远程图片响应及网络访问失败原因。
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
|
||||
@@ -19,6 +19,8 @@ type automationImageSenderStub struct {
|
||||
width, height int
|
||||
// imageCalls 记录最终 WebSocket 图片发送次数。
|
||||
imageCalls int
|
||||
// ready 表示模拟账号的 WebSocket 是否完成自动化消息注册。
|
||||
ready bool
|
||||
}
|
||||
|
||||
// SendText 满足自动化发送契约;本测试只验证图片链路。
|
||||
@@ -36,6 +38,27 @@ func (s *automationImageSenderStub) SendImage(_ context.Context, _, _, imageURL
|
||||
// UpdateCookie 满足自动化发送契约;凭证写回由图片上传适配器自身负责。
|
||||
func (s *automationImageSenderStub) UpdateCookie(string) {}
|
||||
|
||||
// AutomationReady 返回测试替身配置的 WebSocket 自动化就绪状态。
|
||||
func (s *automationImageSenderStub) AutomationReady() bool { return s.ready }
|
||||
|
||||
// TestAutomationImageSenderReportsWrappedWebSocketReadiness 验证图片/API 卡密包装器不会掩盖账号运行时的连接未就绪状态。
|
||||
func TestAutomationImageSenderReportsWrappedWebSocketReadiness(t *testing.T) {
|
||||
// unavailableSender 是尚未完成 WebSocket 注册的账号发送器。
|
||||
unavailableSender := &automationImageSenderStub{ready: false}
|
||||
// unavailableWrapper 包装未就绪发送器后仍必须报告不可发送。
|
||||
unavailableWrapper := automationImageSender{sender: unavailableSender}
|
||||
if unavailableWrapper.AutomationReady() {
|
||||
t.Fatal("包装器不应把未就绪 WebSocket 误报为可发送")
|
||||
}
|
||||
// readySender 是已经完成 WebSocket 注册的账号发送器。
|
||||
readySender := &automationImageSenderStub{ready: true}
|
||||
// readyWrapper 包装已就绪发送器后必须保留可发送状态。
|
||||
readyWrapper := automationImageSender{sender: readySender}
|
||||
if !readyWrapper.AutomationReady() {
|
||||
t.Fatal("包装器应保留已就绪 WebSocket 状态")
|
||||
}
|
||||
}
|
||||
|
||||
// automationImageUploaderStub 记录上传输入并返回可控的平台图片结果。
|
||||
type automationImageUploaderStub struct {
|
||||
// accountID 保存上传时实际使用的发货账号。
|
||||
|
||||
@@ -198,14 +198,14 @@ func (r *AutomationRepository) OwnsItem(ctx context.Context, userID int64, accou
|
||||
// GetCard 返回用户拥有的卡密组类型,不将卡密内容传入应用层。
|
||||
func (r *AutomationRepository) GetCard(ctx context.Context, userID, cardID int64) (automationapp.CardInfo, error) {
|
||||
// card、err 保存卡密组摘要及读取失败原因;卡密正文不会进入应用层。
|
||||
card, err := r.store.Cards.Get(ctx, cardID)
|
||||
card, err := r.store.Cards.GetSummary(ctx, cardID)
|
||||
if errors.Is(err, db.ErrNotFound) || (err == nil && (card == nil || card.UserID != userID)) {
|
||||
return automationapp.CardInfo{}, automationapp.ErrRuleNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return automationapp.CardInfo{}, err
|
||||
}
|
||||
return automationapp.CardInfo{Type: card.Type}, nil
|
||||
return automationapp.CardInfo{Type: card.Type, APIReady: card.Type != "api" || card.APIConfigSummary != nil && card.APIConfigSummary.Ready}, nil
|
||||
}
|
||||
|
||||
// AIReplyEnabled 判断账号是否启用了 AI 议价,不读取任何 API 密钥或平台凭证。
|
||||
|
||||
@@ -26,7 +26,7 @@ func (r *CardsRepository) ListForUser(ctx context.Context, userID int64) ([]card
|
||||
return nil, err
|
||||
}
|
||||
// records 是数据库仓储按倒序返回的卡券完整记录。
|
||||
records, err := r.store.Cards.AllForUser(ctx, userID)
|
||||
records, err := r.store.Cards.AllForUserSummary(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -46,7 +46,24 @@ func (r *CardsRepository) Get(ctx context.Context, cardID int64) (cardsapp.Card,
|
||||
return cardsapp.Card{}, err
|
||||
}
|
||||
// record 是数据库返回的完整卡券记录。
|
||||
record, err := r.store.Cards.Get(ctx, cardID)
|
||||
record, err := r.store.Cards.GetSummary(ctx, cardID)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
return cardsapp.Card{}, cardsapp.ErrNotFound
|
||||
}
|
||||
return cardsapp.Card{}, err
|
||||
}
|
||||
return cardApplicationModel(*record), nil
|
||||
}
|
||||
|
||||
// GetFull 读取更新时需要保留的完整 API 模板,禁止用于普通查询响应。
|
||||
func (r *CardsRepository) GetFull(ctx context.Context, cardID int64) (cardsapp.Card, error) {
|
||||
// err 表示卡券适配器依赖缺失时的装配错误。
|
||||
if err := r.validate(); err != nil {
|
||||
return cardsapp.Card{}, err
|
||||
}
|
||||
// record、err 保存自动发货专用完整卡券及读取错误。
|
||||
record, err := r.store.Cards.GetForDelivery(ctx, cardID)
|
||||
if err != nil {
|
||||
if errors.Is(err, db.ErrNotFound) {
|
||||
return cardsapp.Card{}, cardsapp.ErrNotFound
|
||||
@@ -106,8 +123,21 @@ func (r *CardsRepository) validate() error {
|
||||
|
||||
// cardApplicationModel 将数据库卡券记录转换为基础设施无关的应用模型。
|
||||
func cardApplicationModel(record db.CardFull) cardsapp.Card {
|
||||
// summary 保存数据库摘要对应的应用层脱敏摘要。
|
||||
var summary *cardsapp.APIConfigSummary
|
||||
if record.APIConfigSummary != nil {
|
||||
// summaryValue 保存当前记录的独立摘要副本,避免共享数据库对象。
|
||||
summaryValue := cardsapp.APIConfigSummary{
|
||||
URL: record.APIConfigSummary.URL, Method: record.APIConfigSummary.Method,
|
||||
TimeoutSeconds: record.APIConfigSummary.TimeoutSeconds, ResponsePath: record.APIConfigSummary.ResponsePath,
|
||||
RetryEnabled: record.APIConfigSummary.RetryEnabled, HeadersConfigured: record.APIConfigSummary.HeadersConfigured,
|
||||
ParamsConfigured: record.APIConfigSummary.ParamsConfigured, Ready: record.APIConfigSummary.Ready,
|
||||
ValidationError: record.APIConfigSummary.ValidationError,
|
||||
}
|
||||
summary = &summaryValue
|
||||
}
|
||||
return cardsapp.Card{
|
||||
ID: record.ID, Name: record.Name, Type: record.Type, APIConfig: record.APIConfig,
|
||||
ID: record.ID, Name: record.Name, Type: record.Type, APIConfig: record.APIConfig, APIConfigSummary: summary,
|
||||
TextContent: record.TextContent, DataContent: record.DataContent, ImageURL: record.ImageURL,
|
||||
Description: record.Description, Enabled: record.Enabled, DelaySeconds: record.DelaySeconds,
|
||||
IsMultiSpec: record.IsMultiSpec, SpecName: record.SpecName, SpecValue: record.SpecValue, UserID: record.UserID,
|
||||
|
||||
@@ -2,7 +2,9 @@ package adapter
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
|
||||
cardsapp "xianyu-go/internal/application/cards"
|
||||
notificationsapp "xianyu-go/internal/application/notifications"
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
@@ -53,3 +55,11 @@ func (d *MiscDependencies) NewCardsRepository() *CardsRepository {
|
||||
}
|
||||
return NewCardsRepository(d.store)
|
||||
}
|
||||
|
||||
// NewAPICardTester 创建卡券 API 测试适配器,供组合根投影给 HTTP transport。
|
||||
func (d *MiscDependencies) NewAPICardTester(logger *slog.Logger) cardsapp.APIRequestTester {
|
||||
if d == nil {
|
||||
return nil
|
||||
}
|
||||
return NewAPICardTester(d.store, logger)
|
||||
}
|
||||
@@ -86,7 +86,11 @@ func (r *SettingsRepository) ApplySystemChanges(ctx context.Context, values map[
|
||||
for key, change := range secrets {
|
||||
dbSecrets[key] = db.SensitiveSettingChange{Action: change.Action, Value: change.Value}
|
||||
}
|
||||
return r.store.Settings.ApplyChanges(ctx, values, dbSecrets)
|
||||
// err 表示普通设置与敏感设置原子保存错误。
|
||||
if err := r.store.Settings.ApplyChanges(ctx, values, dbSecrets); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetSystem 保存一项普通系统设置。
|
||||
|
||||
@@ -6,11 +6,11 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/netguard"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
)
|
||||
|
||||
@@ -80,21 +80,7 @@ func (a *Adapter) loadRemoteCaptchaConfig(ctx context.Context, cookieID string)
|
||||
|
||||
// newRemoteCaptchaHTTPClient 封装newRemoteCaptchaHTTPClient业务协调。
|
||||
func newRemoteCaptchaHTTPClient() *http.Client {
|
||||
// dialer 用于本次流程后续判断的dialer
|
||||
dialer := &net.Dialer{Timeout: 8 * time.Second, KeepAlive: 30 * time.Second}
|
||||
return &http.Client{
|
||||
Transport: &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: dialer.DialContext,
|
||||
ForceAttemptHTTP2: true,
|
||||
MaxIdleConns: 20,
|
||||
MaxIdleConnsPerHost: 4,
|
||||
IdleConnTimeout: 30 * time.Second,
|
||||
TLSHandshakeTimeout: 8 * time.Second,
|
||||
ResponseHeaderTimeout: 90 * time.Second,
|
||||
},
|
||||
Timeout: 90 * time.Second,
|
||||
}
|
||||
return netguard.PolicyHTTPClientWithTimeouts(nil, 90*time.Second, 90*time.Second, 8*time.Second)
|
||||
}
|
||||
|
||||
// callRemoteCaptcha 封装callRemoteCaptcha业务协调。
|
||||
|
||||
@@ -2,6 +2,7 @@ package adapter
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
|
||||
adminapp "xianyu-go/internal/application/admin"
|
||||
analyticsapp "xianyu-go/internal/application/analytics"
|
||||
@@ -29,6 +30,8 @@ type TransportApplicationServiceOptions struct {
|
||||
ChannelSender notificationsapp.ChannelSender
|
||||
// ModelClient 读取远端 AI 模型目录,不得记录 API 密钥。
|
||||
ModelClient settingsapp.ModelClient
|
||||
// OutboundPolicy 提供系统设置切换用户可配置 HTTP 出站策略的运行时 Port。
|
||||
OutboundPolicy settingsapp.OutboundPolicy
|
||||
}
|
||||
|
||||
// TransportApplicationServices 是由进程组合根一次性构造并注入 Server 的应用服务集合。
|
||||
@@ -52,6 +55,8 @@ type TransportApplicationServices struct {
|
||||
AutomationRules *automationapp.RuleService
|
||||
// Cards 提供卡券库存 CRUD 用例。
|
||||
Cards *cardsapp.Service
|
||||
// APICardTester 提供卡券 API 临时测试请求能力。
|
||||
APICardTester cardsapp.APIRequestTester
|
||||
// PublishAutomationRules 提供发布后自动化规则准备流程。
|
||||
PublishAutomationRules *automationapp.PublishRuleService
|
||||
// DefaultReplies 提供默认回复配置与投递记录用例。
|
||||
@@ -84,7 +89,7 @@ func NewTransportApplicationServices(options TransportApplicationServiceOptions)
|
||||
}
|
||||
// services 是进程启动期完成构造、随后作为只读依赖交给 Server 的服务集合。
|
||||
services := &TransportApplicationServices{
|
||||
Settings: settingsapp.NewService(options.AdminSettingsDependencies.NewSettingsRepository(), options.ModelClient),
|
||||
Settings: settingsapp.NewService(options.AdminSettingsDependencies.NewSettingsRepository(), options.ModelClient, options.OutboundPolicy),
|
||||
Admin: adminapp.NewServiceWithRuntime(options.AdminSettingsDependencies.NewAdminRepository(), options.AdminRuntime),
|
||||
AccountTasks: automationapp.NewService(options.AutomationDependencies.NewAccountTaskRepository(), options.AccountTaskRunner),
|
||||
UncertainNotifications: notificationsapp.New(options.MiscDependencies.NewNotificationUncertainRepository()),
|
||||
@@ -93,6 +98,7 @@ func NewTransportApplicationServices(options TransportApplicationServiceOptions)
|
||||
AutomationIssues: automationapp.NewIssueService(automationRepository),
|
||||
AutomationRules: automationapp.NewRuleService(automationRepository, automationRepository),
|
||||
Cards: cardsapp.NewService(options.MiscDependencies.NewCardsRepository()),
|
||||
APICardTester: options.MiscDependencies.NewAPICardTester(slog.Default()),
|
||||
PublishAutomationRules: automationapp.NewPublishRuleService(automationRepository),
|
||||
DefaultReplies: defaultreplyapp.NewService(options.AutomationDependencies.NewDefaultReplyRepository()),
|
||||
Keywords: keywordsapp.NewService(options.AutomationDependencies.NewKeywordRepository()),
|
||||
@@ -109,7 +115,7 @@ func (services *TransportApplicationServices) Validate() error {
|
||||
if services == nil {
|
||||
return fmt.Errorf("transport 应用服务集合不能为空")
|
||||
}
|
||||
if services.Settings == nil || services.Admin == nil || services.AccountTasks == nil || services.UncertainNotifications == nil || services.NotificationChannels == nil || services.Analytics == nil || services.AutomationIssues == nil || services.AutomationRules == nil || services.Cards == nil || services.PublishAutomationRules == nil || services.DefaultReplies == nil || services.Keywords == nil {
|
||||
if services.Settings == nil || services.Admin == nil || services.AccountTasks == nil || services.UncertainNotifications == nil || services.NotificationChannels == nil || services.Analytics == nil || services.AutomationIssues == nil || services.AutomationRules == nil || services.Cards == nil || services.APICardTester == nil || services.PublishAutomationRules == nil || services.DefaultReplies == nil || services.Keywords == nil {
|
||||
return fmt.Errorf("transport 应用服务集合存在未装配服务")
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -198,6 +198,8 @@ type RuleFilter struct {
|
||||
type CardInfo struct {
|
||||
// Type 是卡密组类型。
|
||||
Type string
|
||||
// APIReady 表示 API 卡券配置已通过完整校验且允许被规则选择。
|
||||
APIReady bool
|
||||
}
|
||||
|
||||
// RuleRepository 定义规则持久化所需的窄接口。
|
||||
@@ -408,7 +410,7 @@ func (s *RuleService) normalizeDraftActions(ctx context.Context, userID int64, d
|
||||
return actions, flags, nil
|
||||
}
|
||||
|
||||
// validateSendCardAction 校验发卡动作的卡密选择、归属和类型限制。
|
||||
// validateSendCardAction 校验发卡动作的卡密选择和归属;具体卡券类型由执行器处理。
|
||||
func (s *RuleService) validateSendCardAction(ctx context.Context, userID int64, draftAction ActionDraft) error {
|
||||
if draftAction.CardID <= 0 {
|
||||
return errors.New("发送卡密动作必须选择卡密组")
|
||||
@@ -421,8 +423,8 @@ func (s *RuleService) validateSendCardAction(ctx context.Context, userID int64,
|
||||
}
|
||||
return errors.New("卡密组不存在或不属于当前用户")
|
||||
}
|
||||
if card.Type == "api" {
|
||||
return errors.New("API 卡密暂不支持自动发货,请选择文本、批量数据或图片卡密")
|
||||
if card.Type == "api" && !card.APIReady {
|
||||
return errors.New("API 卡券配置无效,请重新保存后再选择")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -157,7 +157,7 @@ func TestRuleServiceNormalizeAppliesDefaults(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRuleServiceRejectsInvalidAction 验证不支持的动作和 API 卡密被拒绝。
|
||||
// TestRuleServiceRejectsInvalidAction 验证不支持的动作会被拒绝。
|
||||
func TestRuleServiceRejectsInvalidAction(t *testing.T) {
|
||||
// cases 保存非法规则输入和预期错误。
|
||||
cases := []struct {
|
||||
@@ -171,7 +171,6 @@ func TestRuleServiceRejectsInvalidAction(t *testing.T) {
|
||||
want string
|
||||
}{
|
||||
{name: "unknown action", ownership: &ruleOwnershipFake{}, draft: RuleDraft{CookieID: "a", TriggerType: TriggerBuyerReviewed, Actions: []ActionDraft{{ActionType: "unknown"}}}, want: "不支持的动作"},
|
||||
{name: "api card", ownership: &ruleOwnershipFake{cardType: "api"}, draft: RuleDraft{CookieID: "a", TriggerType: TriggerOrderPaid, Actions: []ActionDraft{{ActionType: ActionSendCard, CardID: 1}}}, want: "API 卡密"},
|
||||
}
|
||||
// testCase 是当前非法规则分支及其预期错误的测试样例。
|
||||
for _, testCase /* testCase 是当前非法规则分支及其预期错误的测试样例。 */ := range cases {
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
package cards
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// APIRequestTestInput 保存前端临时测试的完整配置文本;测试不会写入卡券库存。
|
||||
type APIRequestTestInput struct {
|
||||
// Config 是与卡券保存接口相同的 API 配置 JSON 文本。
|
||||
Config string
|
||||
}
|
||||
|
||||
// APIRequestTestResult 保存一次测试请求的非敏感诊断结果。
|
||||
type APIRequestTestResult struct {
|
||||
// Status 表示远端请求是否返回 2xx。
|
||||
Status string `json:"status"`
|
||||
// StatusCode 是远端 HTTP 状态码;网络错误时为 0。
|
||||
StatusCode int `json:"status_code"`
|
||||
// ResponseContentType 是远端响应声明的媒体类型。
|
||||
ResponseContentType string `json:"response_content_type"`
|
||||
// ResponseFields 是 JSON 顶层字段名称,不包含字段值。
|
||||
ResponseFields []string `json:"response_fields"`
|
||||
// ExtractedValue 是按响应路径提取的限长文本。
|
||||
ExtractedValue string `json:"extracted_value,omitempty"`
|
||||
// ResponsePreview 是限长响应预览,便于用户诊断返回格式。
|
||||
ResponsePreview string `json:"response_preview,omitempty"`
|
||||
}
|
||||
|
||||
// APIRequestTester 定义卡密 API 测试请求的最小应用能力。
|
||||
type APIRequestTester interface {
|
||||
Test(context.Context, APIRequestTestInput) (APIRequestTestResult, error)
|
||||
}
|
||||
|
||||
// apiConfigDocument 是 API 卡券持久化使用的规范化 JSON 文档。
|
||||
type apiConfigDocument struct {
|
||||
URL string `json:"url"`
|
||||
Method string `json:"method"`
|
||||
Timeout int `json:"timeout_seconds"`
|
||||
Headers map[string]any `json:"headers"`
|
||||
Params map[string]any `json:"params"`
|
||||
Body map[string]any `json:"body"`
|
||||
ContentType string `json:"content_type"`
|
||||
ResponsePath string `json:"response_path,omitempty"`
|
||||
RetryEnabled bool `json:"retry_enabled,omitempty"`
|
||||
}
|
||||
|
||||
// APIConfig 是自动发货适配器读取的规范化 API 请求配置;Headers 与 Params 只在服务端内部流转。
|
||||
type APIConfig = apiConfigDocument
|
||||
|
||||
// ParseAPIConfig 解析并校验完整 API 卡券配置,供自动化适配器读取已解密的专用配置。
|
||||
func ParseAPIConfig(raw string) (APIConfig, error) {
|
||||
// normalized 保存兼容旧字段、补齐默认值后的规范化 JSON。
|
||||
normalized, err := normalizeAPIConfig(raw, "")
|
||||
if err != nil {
|
||||
return APIConfig{}, err
|
||||
}
|
||||
// fields 保存规范化 API 配置的 JSON 字段。
|
||||
var fields map[string]json.RawMessage
|
||||
// err 表示规范化配置 JSON 的解析错误。
|
||||
if err := json.Unmarshal([]byte(normalized), &fields); err != nil {
|
||||
return APIConfig{}, fmt.Errorf("API 配置 JSON 无效: %w", err)
|
||||
}
|
||||
// document 保存解码后的 API 执行配置。
|
||||
var document APIConfig
|
||||
// err 表示兼容字段解码错误。
|
||||
if err := decodeAPIConfig(fields, &document); err != nil {
|
||||
return APIConfig{}, err
|
||||
}
|
||||
// err 表示 URL、方法、超时或重试条件校验错误。
|
||||
if err := validateAPIConfig(document); err != nil {
|
||||
return APIConfig{}, err
|
||||
}
|
||||
return document, nil
|
||||
}
|
||||
|
||||
// APIConfigSummary 是卡券查询接口允许返回的 API 配置脱敏摘要。
|
||||
type APIConfigSummary struct {
|
||||
URL string `json:"url"`
|
||||
Method string `json:"method"`
|
||||
TimeoutSeconds int `json:"timeout_seconds"`
|
||||
ContentType string `json:"content_type"`
|
||||
ResponsePath string `json:"response_path,omitempty"`
|
||||
RetryEnabled bool `json:"retry_enabled"`
|
||||
HeadersConfigured bool `json:"headers_configured"`
|
||||
ParamsConfigured bool `json:"params_configured"`
|
||||
Ready bool `json:"ready"`
|
||||
ValidationError string `json:"validation_error,omitempty"`
|
||||
}
|
||||
|
||||
// SummarizeAPIConfig 将完整配置转换为不含请求模板、密钥或响应正文的查询摘要。
|
||||
func SummarizeAPIConfig(raw string) APIConfigSummary {
|
||||
// summary 保存不包含请求模板值的脱敏状态。
|
||||
var summary APIConfigSummary
|
||||
// normalized 保存兼容旧字段、补齐默认值后的规范化 JSON。
|
||||
normalized, err := normalizeAPIConfig(raw, "")
|
||||
if err != nil {
|
||||
summary.ValidationError = err.Error()
|
||||
return summary
|
||||
}
|
||||
// fields 保存规范化配置的 JSON 字段。
|
||||
var fields map[string]json.RawMessage
|
||||
// err 表示规范化配置 JSON 的解析错误。
|
||||
if err := json.Unmarshal([]byte(normalized), &fields); err != nil {
|
||||
summary.ValidationError = "API 配置解析失败"
|
||||
return summary
|
||||
}
|
||||
// document、err 保存摘要解析出的执行配置和解析错误。
|
||||
document, err := decodeAPIConfigForSummary(fields)
|
||||
if err != nil {
|
||||
summary.ValidationError = "API 配置解析失败"
|
||||
return summary
|
||||
}
|
||||
summary.URL, summary.Method, summary.TimeoutSeconds = document.URL, document.Method, document.Timeout
|
||||
summary.ResponsePath, summary.RetryEnabled = document.ResponsePath, document.RetryEnabled
|
||||
summary.ContentType = document.ContentType
|
||||
summary.HeadersConfigured, summary.ParamsConfigured = len(document.Headers) > 0, len(document.Params) > 0
|
||||
// validationErr 保存摘要配置的非敏感校验错误。
|
||||
if validationErr := validateAPIConfig(document); validationErr != nil {
|
||||
summary.ValidationError = validationErr.Error()
|
||||
return summary
|
||||
}
|
||||
summary.Ready = true
|
||||
return summary
|
||||
}
|
||||
|
||||
// decodeAPIConfigForSummary 在不泄漏字段值的前提下解析摘要所需的配置结构。
|
||||
func decodeAPIConfigForSummary(fields map[string]json.RawMessage) (apiConfigDocument, error) {
|
||||
// document 保存摘要使用的执行配置模型。
|
||||
var document apiConfigDocument
|
||||
// err 表示配置字段解码错误。
|
||||
if err := decodeAPIConfig(fields, &document); err != nil {
|
||||
return apiConfigDocument{}, err
|
||||
}
|
||||
return document, nil
|
||||
}
|
||||
|
||||
// normalizeAPIConfig 将新旧 API 配置归一化,并在更新时保留未提交的敏感模板。
|
||||
func normalizeAPIConfig(raw, existing string) (string, error) {
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
raw = existing
|
||||
}
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
return "", errors.New("API 卡密缺少配置")
|
||||
}
|
||||
// fields 保存新旧 API 配置字段,后续会清理兼容控制字段。
|
||||
var fields map[string]json.RawMessage
|
||||
// err 表示配置 JSON 解析错误。
|
||||
if err := json.Unmarshal([]byte(raw), &fields); err != nil {
|
||||
return "", fmt.Errorf("API 配置 JSON 无效: %w", err)
|
||||
}
|
||||
if fields == nil {
|
||||
return "", errors.New("API 配置必须是 JSON 对象")
|
||||
}
|
||||
// previous 保存更新前的敏感模板,用于 retain 三态操作。
|
||||
var previous map[string]json.RawMessage
|
||||
if strings.TrimSpace(existing) != "" {
|
||||
_ = json.Unmarshal([]byte(existing), &previous)
|
||||
}
|
||||
// action 表示请求头模板的三态更新意图。
|
||||
if err := mergeAPISecretField(fields, previous, "headers"); err != nil {
|
||||
return "", err
|
||||
}
|
||||
// action 表示请求参数模板的三态更新意图。
|
||||
if err := mergeAPISecretField(fields, previous, "params"); err != nil {
|
||||
return "", err
|
||||
}
|
||||
delete(fields, "headers_action")
|
||||
delete(fields, "params_action")
|
||||
// timeout 表示历史配置使用的兼容超时字段。
|
||||
if timeout := rawString(fields["timeout"]); timeout != "" && fields["timeout_seconds"] == nil {
|
||||
fields["timeout_seconds"] = json.RawMessage(strconv.Itoa(parseIntDefault(timeout, 10)))
|
||||
}
|
||||
if fields["method"] == nil {
|
||||
fields["method"] = json.RawMessage(`"GET"`)
|
||||
}
|
||||
if fields["timeout_seconds"] == nil {
|
||||
fields["timeout_seconds"] = json.RawMessage("10")
|
||||
}
|
||||
if fields["headers"] == nil {
|
||||
fields["headers"] = json.RawMessage(`{}`)
|
||||
}
|
||||
if fields["params"] == nil {
|
||||
fields["params"] = json.RawMessage(`{}`)
|
||||
}
|
||||
if fields["body"] == nil {
|
||||
fields["body"] = json.RawMessage(`{}`)
|
||||
}
|
||||
if fields["content_type"] == nil {
|
||||
fields["content_type"] = json.RawMessage(`"application/json"`)
|
||||
}
|
||||
// document 保存规范化后的 API 执行配置。
|
||||
var document apiConfigDocument
|
||||
// err 表示兼容字段解码错误。
|
||||
if err := decodeAPIConfig(fields, &document); err != nil {
|
||||
return "", err
|
||||
}
|
||||
// err 表示规范化配置校验错误。
|
||||
if err := validateAPIConfig(document); err != nil {
|
||||
return "", err
|
||||
}
|
||||
// encoded、err 保存规范化 JSON 文本及编码错误。
|
||||
encoded, err := json.Marshal(document)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("编码 API 配置失败: %w", err)
|
||||
}
|
||||
return string(encoded), nil
|
||||
}
|
||||
|
||||
// mergeAPISecretField 在请求没有提交敏感模板时保留数据库中的旧值。
|
||||
func mergeAPISecretField(fields, previous map[string]json.RawMessage, name string) error {
|
||||
// action 表示当前模板字段的三态更新意图。
|
||||
action := strings.ToLower(strings.TrimSpace(rawString(fields[name+"_action"])))
|
||||
switch action {
|
||||
case "":
|
||||
if fields[name] == nil && previous != nil && previous[name] != nil {
|
||||
fields[name] = previous[name]
|
||||
}
|
||||
case "retain":
|
||||
if previous != nil && previous[name] != nil {
|
||||
fields[name] = previous[name]
|
||||
} else if fields[name] == nil {
|
||||
fields[name] = json.RawMessage(`{}`)
|
||||
}
|
||||
case "replace":
|
||||
if fields[name] == nil {
|
||||
return fmt.Errorf("%s_action=replace 时必须提供 JSON 对象", name)
|
||||
}
|
||||
case "clear":
|
||||
fields[name] = json.RawMessage(`{}`)
|
||||
default:
|
||||
return fmt.Errorf("%s_action 必须是 retain、replace 或 clear", name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// decodeAPIConfig 把兼容字段映射为执行器使用的规范化模型。
|
||||
func decodeAPIConfig(fields map[string]json.RawMessage, document *apiConfigDocument) error {
|
||||
// name 表示需要兼容旧版 JSON 字符串表示的敏感模板字段。
|
||||
for _, name := range []string{"headers", "params"} {
|
||||
// raw 保存当前模板字段的原始 JSON。
|
||||
raw := fields[name]
|
||||
if len(bytes.TrimSpace(raw)) == 0 {
|
||||
continue
|
||||
}
|
||||
// encodedString、encodedObject 分别保存旧字符串模板和规范对象模板。
|
||||
var encodedString string
|
||||
// encodedObject 保存旧版字符串字段解析后的 JSON 对象。
|
||||
var encodedObject map[string]any
|
||||
if json.Unmarshal(raw, &encodedString) == nil {
|
||||
if strings.TrimSpace(encodedString) == "" {
|
||||
fields[name] = json.RawMessage(`{}`)
|
||||
continue
|
||||
}
|
||||
// err 表示旧版模板字符串不是 JSON 对象的错误。
|
||||
if err := json.Unmarshal([]byte(encodedString), &encodedObject); err != nil {
|
||||
return fmt.Errorf("解析 API %s 模板失败: %w", name, err)
|
||||
}
|
||||
// converted、err 保存旧版对象转换后的 JSON 和编码错误。
|
||||
converted, err := json.Marshal(encodedObject)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fields[name] = converted
|
||||
}
|
||||
}
|
||||
// encoded、err 保存字段集合重新编码后的 JSON 和编码错误。
|
||||
encoded, err := json.Marshal(fields)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// err 表示规范字段解码到执行模型时的错误。
|
||||
if err := json.Unmarshal(encoded, document); err != nil {
|
||||
return fmt.Errorf("解析 API 配置失败: %w", err)
|
||||
}
|
||||
if document.Headers == nil {
|
||||
document.Headers = map[string]any{}
|
||||
}
|
||||
if document.Params == nil {
|
||||
document.Params = map[string]any{}
|
||||
}
|
||||
document.Method = strings.ToUpper(strings.TrimSpace(document.Method))
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateAPIConfig 校验 API 地址、方法、超时和幂等重试约束。
|
||||
func validateAPIConfig(document apiConfigDocument) error {
|
||||
// parsed、err 保存 API 地址解析结果及地址格式错误。
|
||||
parsed, err := url.Parse(strings.TrimSpace(document.URL))
|
||||
if err != nil || parsed.Hostname() == "" || parsed.User != nil || (parsed.Scheme != "http" && parsed.Scheme != "https") {
|
||||
return errors.New("API 地址必须是 HTTP(S) 地址且不能包含用户凭据")
|
||||
}
|
||||
if document.Method != "GET" && document.Method != "POST" {
|
||||
return errors.New("API 请求方法只能是 GET 或 POST")
|
||||
}
|
||||
if document.Timeout < 1 || document.Timeout > 60 {
|
||||
return errors.New("API 超时时间必须在 1 到 60 秒之间")
|
||||
}
|
||||
if document.RetryEnabled && !containsAPIPlaceholder(document.Headers, "{idempotency_key}") && !containsAPIPlaceholder(document.Params, "{idempotency_key}") {
|
||||
return errors.New("启用 API 重试时,请求头或请求参数必须包含 {idempotency_key}")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// containsAPIPlaceholder 递归判断 JSON 模板中是否包含指定占位符。
|
||||
func containsAPIPlaceholder(value any, placeholder string) bool {
|
||||
// current 保存当前递归节点,用于查找幂等键变量。
|
||||
switch current := value.(type) {
|
||||
case string:
|
||||
return strings.Contains(current, placeholder)
|
||||
case map[string]any:
|
||||
// child 表示对象中的递归模板值。
|
||||
for _, child := range current {
|
||||
if containsAPIPlaceholder(child, placeholder) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
// child 表示数组中的递归模板值。
|
||||
for _, child := range current {
|
||||
if containsAPIPlaceholder(child, placeholder) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// rawString 读取 JSON 字段的字符串表示,兼容数字和旧版字符串字段。
|
||||
func rawString(raw json.RawMessage) string {
|
||||
if len(bytes.TrimSpace(raw)) == 0 {
|
||||
return ""
|
||||
}
|
||||
// value 保存字符串类型的 JSON 字段值。
|
||||
var value string
|
||||
if json.Unmarshal(raw, &value) == nil {
|
||||
return value
|
||||
}
|
||||
// generic 保存非字符串 JSON 字段的通用值。
|
||||
var generic any
|
||||
if json.Unmarshal(raw, &generic) == nil {
|
||||
return fmt.Sprint(generic)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// parseIntDefault 将兼容字符串数字转为整数并提供稳定默认值。
|
||||
func parseIntDefault(raw string, fallback int) int {
|
||||
// value、err 保存兼容超时字段的整数值及解析错误。
|
||||
value, err := strconv.Atoi(strings.TrimSpace(raw))
|
||||
if err != nil {
|
||||
return fallback
|
||||
}
|
||||
return value
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package cards
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestParseAPIConfigCompatibilityAndRetryGuard 验证历史字段归一、合法路径和幂等重试前置条件。
|
||||
func TestParseAPIConfigCompatibilityAndRetryGuard(t *testing.T) {
|
||||
// legacy 保存历史项目使用的 timeout、headers 和 params 字符串字段。
|
||||
legacy := `{"url":"https://example.com/card","method":"get","timeout":"12","headers":"{\"Authorization\":\"Bearer secret\"}","params":"{\"order\":\"{order_id}\"}"}`
|
||||
// config、err 保存历史配置归一结果及错误。
|
||||
config, err := normalizeAPIConfig(legacy, "")
|
||||
if err != nil || config == "" {
|
||||
t.Fatalf("历史 API 配置应可归一 config=%q err=%v", config, err)
|
||||
}
|
||||
// document、parseErr 保存归一配置的执行模型。
|
||||
document, parseErr := ParseAPIConfig(config)
|
||||
if parseErr != nil || document.Method != "GET" || document.Timeout != 12 || document.Params["order"] != "{order_id}" {
|
||||
t.Fatalf("历史 API 配置归一错误 document=%+v err=%v", document, parseErr)
|
||||
}
|
||||
// _, retryErr 验证缺少稳定幂等键时拒绝开启重试。
|
||||
if _, retryErr := normalizeAPIConfig(`{"url":"https://example.com","retry_enabled":true,"params":{"order_id":"{order_id}"}}`, ""); retryErr == nil {
|
||||
t.Fatal("启用重试但没有幂等键时必须拒绝保存")
|
||||
}
|
||||
// summary 保存脱敏摘要,确认模板秘密不会进入查询模型。
|
||||
summary := SummarizeAPIConfig(config)
|
||||
if !summary.Ready || !summary.HeadersConfigured || !summary.ParamsConfigured || summary.ValidationError != "" {
|
||||
t.Fatalf("API 摘要错误: %+v", summary)
|
||||
}
|
||||
}
|
||||
|
||||
// TestNormalizeAPIConfigThreeStateAndNullGuard 验证敏感模板三态更新及 null 配置不会触发 panic。
|
||||
func TestNormalizeAPIConfigThreeStateAndNullGuard(t *testing.T) {
|
||||
// existing 是包含秘密模板的旧配置,仅用于验证保留和清除语义。
|
||||
existing := `{"url":"https://example.com","headers":{"Authorization":"secret"},"params":{"token":"value"}}`
|
||||
// retained、retainErr 保存 retain 操作的归一结果及错误。
|
||||
retained, retainErr := normalizeAPIConfig(`{"url":"https://example.com","headers_action":"retain","params_action":"retain"}`, existing)
|
||||
if retainErr != nil || retained == "" {
|
||||
t.Fatalf("retain 应保留旧模板 config=%q err=%v", retained, retainErr)
|
||||
}
|
||||
// cleared、clearErr 保存 clear 操作的归一结果及错误。
|
||||
cleared, clearErr := normalizeAPIConfig(`{"url":"https://example.com","headers_action":"clear","params_action":"clear"}`, existing)
|
||||
if clearErr != nil || !containsJSONEmptyObject(cleared, "headers") || !containsJSONEmptyObject(cleared, "params") {
|
||||
t.Fatalf("clear 应清空旧模板 config=%q err=%v", cleared, clearErr)
|
||||
}
|
||||
// replaceErr 保存缺少替换模板时的校验错误。
|
||||
if _, replaceErr := normalizeAPIConfig(`{"url":"https://example.com","headers_action":"replace"}`, existing); replaceErr == nil {
|
||||
t.Fatal("replace 未提供模板时必须拒绝而不是默默保留")
|
||||
}
|
||||
// nullErr 保存 null 配置的校验错误。
|
||||
if _, nullErr := normalizeAPIConfig("null", existing); nullErr == nil {
|
||||
t.Fatal("null API 配置必须返回校验错误")
|
||||
}
|
||||
}
|
||||
|
||||
// containsJSONEmptyObject 判断规范 JSON 中指定模板是否为显式空对象。
|
||||
func containsJSONEmptyObject(raw, key string) bool {
|
||||
// fields 保存规范 JSON 对象,测试只检查模板是否为空而不输出秘密值。
|
||||
var fields map[string]any
|
||||
// err 表示测试 JSON 解析错误。
|
||||
if err := json.Unmarshal([]byte(raw), &fields); err != nil {
|
||||
return false
|
||||
}
|
||||
// value、ok 保存指定字段的对象值及类型判断。
|
||||
value, ok := fields[key].(map[string]any)
|
||||
return ok && len(value) == 0
|
||||
}
|
||||
@@ -21,9 +21,6 @@ var ErrNotFound = errors.New("卡券不存在")
|
||||
// ErrForbidden 表示卡券组存在但不属于当前用户。
|
||||
var ErrForbidden = errors.New("无权操作该卡密组")
|
||||
|
||||
// ErrUnsupportedAPIType 表示当前自动发货链路不允许新建或转换为 API 卡券。
|
||||
var ErrUnsupportedAPIType = errors.New("API 卡密暂不支持自动发货")
|
||||
|
||||
// ErrNotDataType 表示只有 data 类型卡券组允许追加逐行卡密。
|
||||
var ErrNotDataType = errors.New("只有 data(批量卡密)类型支持追加卡密")
|
||||
|
||||
@@ -49,8 +46,10 @@ type Card struct {
|
||||
Name string
|
||||
// Type 是 text、data、image 或历史兼容的 api 类型。
|
||||
Type string
|
||||
// APIConfig 是历史 API 卡券配置;当前仅允许读取或更新既有 API 卡券。
|
||||
// APIConfig 是 API 卡券的规范化 JSON 配置;敏感请求模板由仓储加密保存。
|
||||
APIConfig string
|
||||
// APIConfigSummary 是普通卡券查询可见的 API 配置摘要,不含请求头、参数或密钥。
|
||||
APIConfigSummary *APIConfigSummary
|
||||
// TextContent 是 text 类型自动发货时发送的文本内容。
|
||||
TextContent string
|
||||
// DataContent 是 data 类型尚未消费的逐行卡密库存。
|
||||
@@ -79,7 +78,7 @@ type Draft struct {
|
||||
Name string
|
||||
// Type 是 text、data、image 或历史兼容的 api 类型。
|
||||
Type string
|
||||
// APIConfig 是历史 API 卡券配置;新建 API 卡券仍被业务规则禁止。
|
||||
// APIConfig 是 API 卡券的规范化 JSON 配置。
|
||||
APIConfig string
|
||||
// TextContent 是 text 类型必须提供的非空发货内容。
|
||||
TextContent string
|
||||
@@ -107,6 +106,8 @@ type Repository interface {
|
||||
ListForUser(ctx context.Context, userID int64) ([]Card, error)
|
||||
// Get 按标识读取卡券组;资源缺失时返回 ErrNotFound。
|
||||
Get(ctx context.Context, cardID int64) (Card, error)
|
||||
// GetFull 仅供更新时读取需要保留的敏感 API 模板,调用方不得将结果作为普通响应返回。
|
||||
GetFull(ctx context.Context, cardID int64) (Card, error)
|
||||
// Create 持久化已校验且带所有者的卡券组,并返回新标识。
|
||||
Create(ctx context.Context, card Card) (int64, error)
|
||||
// Update 覆盖指定卡券组的可编辑字段,但不得改变所有者。
|
||||
@@ -168,33 +169,43 @@ func (s *Service) Create(ctx context.Context, userID int64, draft Draft) (int64,
|
||||
if err := s.validateUser(userID); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if draft.Type == "api" {
|
||||
// normalized、normalizeErr 是新建 API 卡配置的规范化结果和校验错误。
|
||||
normalized, normalizeErr := normalizeAPIConfig(draft.APIConfig, "")
|
||||
if normalizeErr != nil {
|
||||
return 0, &ValidationError{Message: normalizeErr.Error()}
|
||||
}
|
||||
draft.APIConfig = normalized
|
||||
}
|
||||
// err 表示卡券草稿未满足类型、内容或延迟范围约束的校验错误。
|
||||
if err := validateDraft(draft); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if draft.Type == "api" {
|
||||
return 0, ErrUnsupportedAPIType
|
||||
}
|
||||
return s.repository.Create(ctx, cardFromDraft(0, userID, draft))
|
||||
}
|
||||
|
||||
// Update 校验 draft 和所有权后更新 cardID;既有 API 卡券可继续编辑,但其他类型不能转换为 API。
|
||||
// Update 校验 draft 和所有权后更新 cardID;API 配置未提交的敏感模板会保留原值。
|
||||
func (s *Service) Update(ctx context.Context, userID, cardID int64, draft Draft) error {
|
||||
// err 表示用户身份或应用仓储未满足执行条件的错误。
|
||||
if err := s.validateUser(userID); err != nil {
|
||||
return err
|
||||
}
|
||||
// err 表示卡券草稿未满足类型、内容或延迟范围约束的校验错误。
|
||||
if err := validateDraft(draft); err != nil {
|
||||
return err
|
||||
}
|
||||
// existing 是已经通过当前用户归属校验的卡券组。
|
||||
existing, err := s.ownedCard(ctx, userID, cardID)
|
||||
existing, err := s.ownedCardFull(ctx, userID, cardID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if draft.Type == "api" && existing.Type != "api" {
|
||||
return ErrUnsupportedAPIType
|
||||
if draft.Type == "api" {
|
||||
// normalized、normalizeErr 合并脱敏编辑请求与数据库中未展示的旧模板。
|
||||
normalized, normalizeErr := normalizeAPIConfig(draft.APIConfig, existing.APIConfig)
|
||||
if normalizeErr != nil {
|
||||
return &ValidationError{Message: normalizeErr.Error()}
|
||||
}
|
||||
draft.APIConfig = normalized
|
||||
}
|
||||
// err 表示卡券草稿未满足类型、内容或延迟范围约束的校验错误。
|
||||
if err := validateDraft(draft); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.repository.Update(ctx, cardFromDraft(existing.ID, existing.UserID, draft))
|
||||
}
|
||||
@@ -260,6 +271,22 @@ func (s *Service) ownedCard(ctx context.Context, userID, cardID int64) (Card, er
|
||||
return card, nil
|
||||
}
|
||||
|
||||
// ownedCardFull 读取更新所需的完整卡券配置并验证所有权,敏感内容只在应用内部短暂流转。
|
||||
func (s *Service) ownedCardFull(ctx context.Context, userID, cardID int64) (Card, error) {
|
||||
if cardID <= 0 {
|
||||
return Card{}, ErrInvalidCardID
|
||||
}
|
||||
// card 是更新保留敏感模板所需的完整卡券记录。
|
||||
card, err := s.repository.GetFull(ctx, cardID)
|
||||
if err != nil {
|
||||
return Card{}, err
|
||||
}
|
||||
if card.UserID != userID {
|
||||
return Card{}, ErrForbidden
|
||||
}
|
||||
return card, nil
|
||||
}
|
||||
|
||||
// validateDraft 校验类型、必填内容和延迟范围,保持创建与更新使用同一套规则。
|
||||
func validateDraft(draft Draft) error {
|
||||
if draft.Name == "" || draft.Type == "" {
|
||||
@@ -291,6 +318,10 @@ func validateDraft(draft Draft) error {
|
||||
if err != nil || imageURL.Hostname() == "" || imageURL.User != nil || (imageURL.Scheme != "http" && imageURL.Scheme != "https") {
|
||||
return &ValidationError{Message: "图片卡密 URL 必须是 HTTP(S) 地址"}
|
||||
}
|
||||
case "api":
|
||||
if strings.TrimSpace(draft.APIConfig) == "" {
|
||||
return &ValidationError{Message: "API 卡密配置不能为空"}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -44,6 +44,12 @@ func (r *cardRepositoryStub) Get(_ context.Context, cardID int64) (Card, error)
|
||||
return r.card, r.getErr
|
||||
}
|
||||
|
||||
// GetFull 返回更新用的完整卡券并复用测试替身的错误控制。
|
||||
func (r *cardRepositoryStub) GetFull(_ context.Context, cardID int64) (Card, error) {
|
||||
r.gotCardID = cardID
|
||||
return r.card, r.getErr
|
||||
}
|
||||
|
||||
// Create 记录待创建卡券并返回预设标识或错误。
|
||||
func (r *cardRepositoryStub) Create(_ context.Context, card Card) (int64, error) {
|
||||
r.createdCard = card
|
||||
@@ -146,13 +152,13 @@ func TestServiceCreateValidation(t *testing.T) {
|
||||
}
|
||||
})
|
||||
}
|
||||
// err 表示创建 API 卡券时的业务限制错误。
|
||||
if _, err := service.Create(context.Background(), 7, Draft{Name: "API", Type: "api"}); !errors.Is(err, ErrUnsupportedAPIType) {
|
||||
t.Fatalf("新建 API 卡券应拒绝,err=%v", err)
|
||||
// err 表示创建合法 API 卡券时的业务校验结果。
|
||||
if _, err := service.Create(context.Background(), 7, Draft{Name: "API", Type: "api", APIConfig: `{"url":"https://example.com/card"}`}); err != nil {
|
||||
t.Fatalf("新建 API 卡券应允许,err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestServiceUpdateAndDeleteOwnership 验证更新、删除不会接受请求覆盖所有者,并覆盖 API 转换限制与错误阶段。
|
||||
// TestServiceUpdateAndDeleteOwnership 验证更新、删除不会接受请求覆盖所有者,并覆盖 API 转换与错误阶段。
|
||||
func TestServiceUpdateAndDeleteOwnership(t *testing.T) {
|
||||
// updateErr 是更新持久化失败的预设错误。
|
||||
updateErr := errors.New("update failed")
|
||||
@@ -169,12 +175,13 @@ func TestServiceUpdateAndDeleteOwnership(t *testing.T) {
|
||||
if repository.updatedCard.ID != 5 || repository.updatedCard.UserID != 7 || repository.updatedCard.Name != "new" {
|
||||
t.Fatalf("更新模型未保留标识和所有者:%+v", repository.updatedCard)
|
||||
}
|
||||
// err 表示非 API 卡券转换为 API 类型时的业务错误。
|
||||
if err := service.Update(context.Background(), 7, 5, Draft{Name: "api", Type: "api"}); !errors.Is(err, ErrUnsupportedAPIType) {
|
||||
t.Fatalf("非 API 卡券转换为 API 应拒绝,err=%v", err)
|
||||
}
|
||||
repository.updateErr = nil
|
||||
// err 表示非 API 卡券转换为 API 类型时的业务校验结果。
|
||||
if err := service.Update(context.Background(), 7, 5, Draft{Name: "api", Type: "api", APIConfig: `{"url":"https://example.com/card"}`}); err != nil {
|
||||
t.Fatalf("非 API 卡券转换为 API 应允许,err=%v", err)
|
||||
}
|
||||
repository.card.Type = "api"
|
||||
repository.card.APIConfig = `{"url":"https://example.com/card"}`
|
||||
// err 表示既有 API 卡券继续编辑时的更新结果。
|
||||
if err := service.Update(context.Background(), 7, 5, Draft{Name: "legacy", Type: "api"}); err != nil {
|
||||
t.Fatalf("既有 API 卡券应允许继续编辑,err=%v", err)
|
||||
|
||||
@@ -108,12 +108,20 @@ type ModelClient interface {
|
||||
Fetch(ctx context.Context, baseURL, apiKey string) ([]string, error)
|
||||
}
|
||||
|
||||
// OutboundPolicy 定义系统设置切换用户可配置 HTTP 出站策略所需的最小运行时 Port。
|
||||
type OutboundPolicy interface {
|
||||
// SetPublicOnly 立即切换公网地址限制,不负责持久化设置值。
|
||||
SetPublicOnly(publicOnly bool)
|
||||
}
|
||||
|
||||
// Service 编排设置读取、校验、审计和持久化,不依赖 HTTP 或数据库类型。
|
||||
type Service struct {
|
||||
// repository 提供设置持久化与敏感访问审计能力。
|
||||
repository Repository
|
||||
// modelClient 提供远端模型目录读取能力。
|
||||
modelClient ModelClient
|
||||
// outboundPolicy 保存运行时 HTTP 策略端口,数据库仓储不直接依赖基础设施实现。
|
||||
outboundPolicy OutboundPolicy
|
||||
}
|
||||
|
||||
// IsSensitiveSettingKey 判断 HTTP 兼容层中的设置键是否属于敏感白名单。
|
||||
@@ -122,9 +130,14 @@ func (s *Service) IsSensitiveSettingKey(key string) bool {
|
||||
}
|
||||
|
||||
// NewService 构造设置应用服务。
|
||||
func NewService(repository Repository, modelClient ModelClient) *Service {
|
||||
func NewService(repository Repository, modelClient ModelClient, policies ...OutboundPolicy) *Service {
|
||||
// service 保存调用方提供的设置 Port 与模型客户端。
|
||||
service := &Service{repository: repository, modelClient: modelClient}
|
||||
var policy OutboundPolicy
|
||||
if len(policies) > 0 {
|
||||
policy = policies[0]
|
||||
}
|
||||
// service 保存调用方提供的设置 Port、模型客户端和运行时策略端口。
|
||||
service := &Service{repository: repository, modelClient: modelClient, outboundPolicy: policy}
|
||||
return service
|
||||
}
|
||||
|
||||
@@ -183,7 +196,12 @@ func (s *Service) ApplySystemChanges(ctx context.Context, userID int64, values m
|
||||
return err
|
||||
}
|
||||
}
|
||||
return s.repository.ApplySystemChanges(ctx, values, secrets)
|
||||
// err 表示普通设置和敏感设置原子保存失败。
|
||||
if err := s.repository.ApplySystemChanges(ctx, values, secrets); err != nil {
|
||||
return err
|
||||
}
|
||||
s.applyOutboundPolicy(values)
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetSystem 保存单项系统设置,并把敏感设置的三态命令统一交给应用层校验。
|
||||
@@ -208,7 +226,16 @@ func (s *Service) SetSystem(ctx context.Context, userID int64, key, value, actio
|
||||
}
|
||||
return s.repository.ApplySystemChanges(ctx, nil, map[string]SecretChange{key: change})
|
||||
}
|
||||
return s.repository.SetSystem(ctx, key, value)
|
||||
// err 表示单项普通设置的业务值校验错误。
|
||||
if err := validateSystemValue(key, value); err != nil {
|
||||
return err
|
||||
}
|
||||
// err 表示单项普通设置持久化失败。
|
||||
if err := s.repository.SetSystem(ctx, key, value); err != nil {
|
||||
return err
|
||||
}
|
||||
s.applyOutboundPolicy(map[string]string{key: value})
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListUser 读取当前用户的全部偏好设置。
|
||||
@@ -380,10 +407,33 @@ func (s *Service) validateValues(values map[string]string) error {
|
||||
if s.repository.IsSensitiveSettingKey(key) {
|
||||
return errors.New("敏感设置必须放入 secrets 命令")
|
||||
}
|
||||
// err 表示批量普通设置的业务值校验错误。
|
||||
if err := validateSystemValue(key, values[key]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateSystemValue 校验具有运行时语义的普通系统设置,避免非法值落库或切换策略。
|
||||
func validateSystemValue(key, value string) error {
|
||||
if key == "outbound_http_public_only" && !strings.EqualFold(strings.TrimSpace(value), "true") && !strings.EqualFold(strings.TrimSpace(value), "false") {
|
||||
return errors.New("outbound_http_public_only 必须是布尔值")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// applyOutboundPolicy 在系统设置成功持久化后立即同步运行时策略。
|
||||
func (s *Service) applyOutboundPolicy(values map[string]string) {
|
||||
if s == nil || s.outboundPolicy == nil {
|
||||
return
|
||||
}
|
||||
// raw、ok 保存公网限制值及本次变更是否包含该设置。
|
||||
if raw, ok := values["outbound_http_public_only"]; ok {
|
||||
s.outboundPolicy.SetPublicOnly(strings.EqualFold(strings.TrimSpace(raw), "true"))
|
||||
}
|
||||
}
|
||||
|
||||
// validSecretAction 判断敏感设置命令是否具有受支持的三态语义。
|
||||
func validSecretAction(change SecretChange) bool {
|
||||
switch change.Action {
|
||||
|
||||
@@ -29,6 +29,20 @@ type settingsRepositoryFake struct {
|
||||
adjustRuleEnabled bool
|
||||
}
|
||||
|
||||
// outboundPolicyFake 记录应用服务要求立即生效的公网限制状态。
|
||||
type outboundPolicyFake struct {
|
||||
// publicOnly 保存最近一次运行时公网限制状态。
|
||||
publicOnly bool
|
||||
// calls 保存策略切换次数,用于确认数据库保存成功后才切换。
|
||||
calls int
|
||||
}
|
||||
|
||||
// SetPublicOnly 记录测试中的运行时策略切换。
|
||||
func (p *outboundPolicyFake) SetPublicOnly(publicOnly bool) {
|
||||
p.publicOnly = publicOnly
|
||||
p.calls++
|
||||
}
|
||||
|
||||
// IsSensitiveSettingKey 判断测试设置键是否属于敏感集合。
|
||||
func (r *settingsRepositoryFake) IsSensitiveSettingKey(key string) bool {
|
||||
// candidate 是测试敏感键集合中的当前候选值。
|
||||
@@ -192,6 +206,30 @@ func TestServiceRejectsSensitivePlainValue(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestServiceAppliesOutboundPolicyAfterValidation 验证公网限制设置校验和运行时即时生效边界。
|
||||
func TestServiceAppliesOutboundPolicyAfterValidation(t *testing.T) {
|
||||
// repository 是保存系统设置的内存 Port。
|
||||
repository := &settingsRepositoryFake{}
|
||||
// policy 是记录运行时开关状态的测试 Port。
|
||||
policy := &outboundPolicyFake{}
|
||||
// service 是注入策略 Port 的设置应用服务。
|
||||
service := NewService(repository, nil, policy)
|
||||
// err 表示合法公网限制设置的保存错误。
|
||||
if err := service.ApplySystemChanges(context.Background(), 7, map[string]string{"outbound_http_public_only": "true"}, nil); err != nil {
|
||||
t.Fatalf("保存公网限制失败: %v", err)
|
||||
}
|
||||
if !policy.publicOnly || policy.calls != 1 {
|
||||
t.Fatalf("公网限制未即时生效 policy=%+v", policy)
|
||||
}
|
||||
// err 表示非法公网限制设置的保存结果。
|
||||
if err := service.ApplySystemChanges(context.Background(), 7, map[string]string{"outbound_http_public_only": "maybe"}, nil); err == nil {
|
||||
t.Fatal("非法公网限制值必须拒绝")
|
||||
}
|
||||
if policy.calls != 1 {
|
||||
t.Fatalf("非法值不应切换运行时策略 policy=%+v", policy)
|
||||
}
|
||||
}
|
||||
|
||||
// TestServiceAIReplyOwnershipAndValidation 验证账号 AI 设置的归属和数值约束。
|
||||
func TestServiceAIReplyOwnershipAndValidation(t *testing.T) {
|
||||
// repository 保存测试账号所有者及配置。
|
||||
|
||||
@@ -33,6 +33,8 @@ type automationActionExecutor struct {
|
||||
cookieSource func(context.Context, string) (string, error)
|
||||
// wakeCredentialBlocked 在 Cookie 更新后唤醒凭证阻塞的自动化任务。
|
||||
wakeCredentialBlocked func(context.Context, string)
|
||||
// apiFetcher 为 API 卡发货提供外部请求能力;业务执行器不直接依赖 net/http。
|
||||
apiFetcher func() APICardFetcher
|
||||
// cardLocks 串行化同一卡密组的数据库存取和消费。
|
||||
cardLocks sync.Map
|
||||
}
|
||||
@@ -502,7 +504,7 @@ func (e *automationActionExecutor) sendCard(ctx context.Context, task Task, acti
|
||||
// count 是当前订单需要发送的卡密数量。
|
||||
count := deliverySendCount(task, action)
|
||||
// card 是待发送的卡密组完整配置。
|
||||
card, err := e.store.Cards.Get(ctx, action.CardID)
|
||||
card, err := e.store.Cards.GetForDelivery(ctx, action.CardID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
@@ -512,6 +514,9 @@ func (e *automationActionExecutor) sendCard(ctx context.Context, task Task, acti
|
||||
if card.Type == "data" {
|
||||
return e.sendDataCard(ctx, task, card, count)
|
||||
}
|
||||
if card.Type == "api" {
|
||||
return e.sendAPICard(ctx, task, action, card, count)
|
||||
}
|
||||
// sent 是已经成功发送的卡密数量。
|
||||
sent := 0
|
||||
// i 表示当前卡密发送序号。
|
||||
@@ -541,6 +546,45 @@ func (e *automationActionExecutor) sendCard(ctx context.Context, task Task, acti
|
||||
return sent, nil
|
||||
}
|
||||
|
||||
// sendAPICard 按发货单位逐次调用普通 API,并在消息发送失败时保留结果未知状态。
|
||||
func (e *automationActionExecutor) sendAPICard(ctx context.Context, task Task, action db.AutomationAction, card *db.CardFull, count int) (int, error) {
|
||||
// fetcher 是构造期固定的 API 卡发货客户端。
|
||||
var fetcher APICardFetcher
|
||||
if e.apiFetcher != nil {
|
||||
fetcher = e.apiFetcher()
|
||||
}
|
||||
if fetcher == nil {
|
||||
return 0, errors.New("API 卡发货客户端未初始化")
|
||||
}
|
||||
// sent 是已经完成 API 获取和买家消息发送的单位数量。
|
||||
sent := 0
|
||||
// unitIndex 表示从 1 开始的当前 API 发货单位序号。
|
||||
for unitIndex := 1; unitIndex <= count; unitIndex++ {
|
||||
// result、fetchErr 保存当前单位的 API 响应与请求错误。
|
||||
result, fetchErr := fetcher.Fetch(ctx, APICardRequest{
|
||||
Config: card.APIConfig, TriggerKey: buildTriggerKey(task), ActionID: action.ID, CardID: card.ID,
|
||||
UnitIndex: unitIndex, TotalUnits: count, AccountID: task.AccountID, OrderID: task.OrderID,
|
||||
ItemID: task.ItemID, BuyerID: task.BuyerID, ChatID: task.ChatID, SpecName: task.SpecName,
|
||||
SpecValue: task.SpecValue, Quantity: task.Quantity, Amount: task.Amount, TriggerType: task.TriggerType,
|
||||
})
|
||||
if fetchErr != nil {
|
||||
if result.Dispatched {
|
||||
return sent, uncertainAction(fetchErr)
|
||||
}
|
||||
return sent, noRetryAction(fetchErr)
|
||||
}
|
||||
if strings.TrimSpace(result.Content) == "" {
|
||||
return sent, uncertainAction(errors.New("API 卡发货响应没有可发送内容"))
|
||||
}
|
||||
// sendErr 保存已取得卡密后向买家发送消息的结果;此时失败不能安全重放 API 请求。
|
||||
if sendErr := e.sendText(ctx, task, result.Content); sendErr != nil {
|
||||
return sent, uncertainAction(sendErr)
|
||||
}
|
||||
sent++
|
||||
}
|
||||
return sent, nil
|
||||
}
|
||||
|
||||
// sendDataCard 只在卡券锁内完成库存预留与恢复,把外部消息发送放到锁外。
|
||||
func (e *automationActionExecutor) sendDataCard(ctx context.Context, task Task, card *db.CardFull, count int) (int, error) {
|
||||
// sent 是已经成功发送的数据卡密数量。
|
||||
@@ -626,7 +670,7 @@ func (e *automationActionExecutor) cardContent(_ context.Context, card *db.CardF
|
||||
}
|
||||
return "", card.ImageURL, nil
|
||||
case "api":
|
||||
return "", "", fmt.Errorf("自动化中心暂不支持 API 卡密动作")
|
||||
return "", "", fmt.Errorf("API 卡密必须通过 sendAPICard 发送")
|
||||
default:
|
||||
return "", "", fmt.Errorf("未知卡密类型: %s", card.Type)
|
||||
}
|
||||
|
||||
@@ -73,6 +73,54 @@ func TestAutomationActionExecutorPreservesMessageNotSent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// apiCardFetcherStub 记录 API 卡发货请求,供逐单位执行测试使用。
|
||||
type apiCardFetcherStub struct {
|
||||
// requests 保存自动化执行器提交的每个发货单位上下文。
|
||||
requests []APICardRequest
|
||||
}
|
||||
|
||||
// Fetch 返回按单位序号生成的测试卡密,不执行真实网络请求。
|
||||
func (s *apiCardFetcherStub) Fetch(_ context.Context, request APICardRequest) (APICardResult, error) {
|
||||
s.requests = append(s.requests, request)
|
||||
return APICardResult{Content: fmt.Sprintf("API-CODE-%d", request.UnitIndex)}, nil
|
||||
}
|
||||
|
||||
// TestSendAPICardDeliversEachUnit 验证规则数量乘订单数量后逐单位获取并立即发送 API 卡密。
|
||||
func TestSendAPICardDeliversEachUnit(t *testing.T) {
|
||||
// store、cleanup 保存测试数据库和清理函数。
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 保存数据库与执行器共用的测试上下文。
|
||||
ctx := context.Background()
|
||||
// admin 是测试卡券的所有者。
|
||||
admin, err := store.Users.GetByUsername(ctx, "admin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// cardID 保存测试 API 卡券组标识。
|
||||
cardID, err := store.Cards.Create(ctx, &db.CardFull{Name: "API", Type: "api", APIConfig: `{"url":"https://example.com"}`, Enabled: true, UserID: admin.ID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// fetcher 记录每个单位的 API 请求上下文。
|
||||
fetcher := &apiCardFetcherStub{}
|
||||
// sender 保存已经发送给买家的 API 卡密文本。
|
||||
sender := &testSender{}
|
||||
// executor 是注入 API 客户端和在线发送器的动作执行器。
|
||||
executor := automationActionExecutor{store: store, senders: testSenderProvider{sender: sender}, apiFetcher: func() APICardFetcher { return fetcher }}
|
||||
// sent、sendErr 保存四个单位的执行统计和最终错误。
|
||||
sent, sendErr := executor.sendCard(ctx, Task{AccountID: "cid", OrderID: "order", ChatID: "chat", BuyerID: "buyer", Quantity: "2", TriggerType: TriggerOrderPaid}, db.AutomationAction{ID: 8, ActionType: ActionSendCard, CardID: cardID, DeliveryCount: 2, ConfigJSON: "{}"})
|
||||
if sendErr != nil || sent != 4 || len(fetcher.requests) != 4 || len(sender.texts) != 4 {
|
||||
t.Fatalf("API 卡未逐单位发送 sent=%d requests=%d texts=%v err=%v", sent, len(fetcher.requests), sender.texts, sendErr)
|
||||
}
|
||||
// index、request 分别表示发货单位序号和对应的 API 请求上下文。
|
||||
for index, request := range fetcher.requests {
|
||||
if request.UnitIndex != index+1 || request.TotalUnits != 4 {
|
||||
t.Fatalf("单位上下文错误 index=%d request=%+v", index, request)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestSendDataCardReleasesInventoryLockBeforeExternalSend 验证第二个库存操作不会等待第一个外部发送完成。
|
||||
func TestSendDataCardReleasesInventoryLockBeforeExternalSend(t *testing.T) {
|
||||
// store、cleanup 保存测试数据库及其清理函数。
|
||||
|
||||
@@ -23,11 +23,11 @@ func (c *Center) handleAIPricingMode(ctx context.Context, task Task) (bool, erro
|
||||
return false, nil
|
||||
}
|
||||
if !autoAdjustEnabled {
|
||||
c.logger.Info("AI 议价已接管订单价格,但商家未开启真实自动改价", "account", task.AccountID, "order_id", task.OrderID)
|
||||
c.logger.Debug("AI 议价已接管订单价格,但商家未开启真实自动改价", "account", task.AccountID, "order_id", task.OrderID)
|
||||
return true, nil
|
||||
}
|
||||
if task.OrderID == "" || task.ChatID == "" || task.BuyerID == "" || task.ItemID == "" {
|
||||
c.logger.Warn("订单事实不足,无法匹配 AI 报价", "account", task.AccountID, "order_id", task.OrderID)
|
||||
c.logger.Debug("订单事实不足,无法匹配 AI 报价", "account", task.AccountID, "order_id", task.OrderID)
|
||||
return true, nil
|
||||
}
|
||||
// quote 是与账号、买家、商品、会话和有效期匹配后原子领取的最新报价;claimErr 是领取错误。
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
package automation
|
||||
|
||||
import "context"
|
||||
|
||||
// APICardFetcher 是自动化消费者定义的普通 API 卡发货最小接口。
|
||||
type APICardFetcher interface {
|
||||
// Fetch 为一个发货单位获取卡密内容;Dispatched 表示远端可能已经产生副作用。
|
||||
Fetch(context.Context, APICardRequest) (APICardResult, error)
|
||||
}
|
||||
|
||||
// APICardRequest 描述一次 API 卡发货单位的完整业务上下文,不包含账号 Cookie。
|
||||
type APICardRequest struct {
|
||||
// Config 是已由专用仓储读取的完整 API 配置 JSON。
|
||||
Config string
|
||||
// TriggerKey 是本次自动化运行的稳定防重键。
|
||||
TriggerKey string
|
||||
// ActionID 是规则动作稳定标识。
|
||||
ActionID int64
|
||||
// CardID 是 API 卡券组稳定标识。
|
||||
CardID int64
|
||||
// UnitIndex 是从 1 开始的当前发货单位序号。
|
||||
UnitIndex int
|
||||
// TotalUnits 是本动作本次应发出的总单位数。
|
||||
TotalUnits int
|
||||
// AccountID 是账号或 Cookie 稳定标识。
|
||||
AccountID string
|
||||
// OrderID 是订单稳定标识。
|
||||
OrderID string
|
||||
// ItemID 是商品稳定标识。
|
||||
ItemID string
|
||||
// BuyerID 是买家稳定标识。
|
||||
BuyerID string
|
||||
// ChatID 是聊天会话稳定标识。
|
||||
ChatID string
|
||||
// SpecName 是订单规格名称。
|
||||
SpecName string
|
||||
// SpecValue 是订单规格值。
|
||||
SpecValue string
|
||||
// Quantity 是订单购买数量文本。
|
||||
Quantity string
|
||||
// Amount 是订单金额文本。
|
||||
Amount string
|
||||
// TriggerType 是触发事件类型。
|
||||
TriggerType string
|
||||
}
|
||||
|
||||
// APICardResult 保存 API 卡请求取得的内容及远端副作用状态。
|
||||
type APICardResult struct {
|
||||
// Content 是成功提取并准备发送给买家的卡密文本。
|
||||
Content string
|
||||
// Dispatched 表示请求已发出但最终结果可能不明。
|
||||
Dispatched bool
|
||||
}
|
||||
@@ -135,20 +135,8 @@ type centerDependencies struct {
|
||||
notifier Notifier
|
||||
// cookieSrc 是构造期注入的 Cookie 读取函数。
|
||||
cookieSrc func(context.Context, string) (string, error)
|
||||
}
|
||||
|
||||
// CenterDependencies 保存自动化中心启动时必须固定的外部协作依赖。
|
||||
type CenterDependencies struct {
|
||||
// MTop 提供确认发货使用的 MTOP 协议客户端;为空时使用默认实现。
|
||||
MTop mtop.Client
|
||||
// AccountTaskClient 提供自动评价与商品擦亮的协议调用;使用默认 MTOP 时可自动复用其任务能力。
|
||||
AccountTaskClient AccountTaskClient
|
||||
// OrderDetailFetcher 提供自动发货前的订单详情查询能力。
|
||||
OrderDetailFetcher OrderDetailFetcher
|
||||
// Notifier 接收发货结果通知;为空时不发送通知。
|
||||
Notifier Notifier
|
||||
// CookieSource 提供自动发货读取 Cookie 的可替换边界;为空时读取仓储。
|
||||
CookieSource func(context.Context, string) (string, error)
|
||||
// apiFetcher 提供普通 API 卡发货请求能力。
|
||||
apiFetcher APICardFetcher
|
||||
}
|
||||
|
||||
// New 构造使用默认协议实现的自动化中心。
|
||||
@@ -189,6 +177,7 @@ func NewWithDependencies(store *db.Store, senders SenderProvider, logger *slog.L
|
||||
fetcher: dependencies.OrderDetailFetcher,
|
||||
notifier: dependencies.Notifier,
|
||||
cookieSrc: dependencies.CookieSource,
|
||||
apiFetcher: dependencies.APICardFetcher,
|
||||
},
|
||||
logger: logger.With("subsys", "automation"),
|
||||
}
|
||||
@@ -213,6 +202,7 @@ func NewWithDependencies(store *db.Store, senders SenderProvider, logger *slog.L
|
||||
}
|
||||
return center.store.Cookies.GetValue(ctx, cookieID)
|
||||
},
|
||||
apiFetcher: func() APICardFetcher { return center.dependencies.apiFetcher },
|
||||
wakeCredentialBlocked: center.wakeCredentialBlockedAutomation,
|
||||
}
|
||||
center.notifications = deliveryNotifier{
|
||||
@@ -236,6 +226,7 @@ func NewWithDependencies(store *db.Store, senders SenderProvider, logger *slog.L
|
||||
prepareTask: center.prepareTask,
|
||||
actionDelaySeconds: center.actionDelaySeconds,
|
||||
accountAutomationAllowed: center.accountAutomationAllowed,
|
||||
accountSenderReady: center.accountSenderReady,
|
||||
deferTask: center.deferTask,
|
||||
executeAction: center.executeAction,
|
||||
hasNotifier: func() bool { return center.dependencies.notifier != nil },
|
||||
@@ -272,6 +263,11 @@ func (c *Center) handleTask(ctx context.Context, task Task) (bool, error) {
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := c.facts.record(ctx, task); err != nil {
|
||||
if errors.Is(err, db.ErrForbidden) {
|
||||
// 同一平台交易卡片可能同时送到卖家和买家登录账号;订单已归属其他账号时,绝不能覆盖或执行该副本。
|
||||
c.logger.Debug("跨账号重复订单事件,忽略", "account", task.AccountID, "trigger", task.TriggerType, "order_id", task.OrderID)
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
if task.OrderID != "" {
|
||||
@@ -314,7 +310,7 @@ func (c *Center) handleTask(ctx context.Context, task Task) (bool, error) {
|
||||
return false, err
|
||||
}
|
||||
if len(rules) == 0 {
|
||||
c.logger.Info("无匹配自动化规则,忽略事件", "trigger", task.TriggerType, "order_id", task.OrderID, "item_id", task.ItemID)
|
||||
c.logger.Debug("无匹配自动化规则,忽略事件", "trigger", task.TriggerType, "order_id", task.OrderID, "item_id", task.ItemID)
|
||||
return false, nil
|
||||
}
|
||||
// firstErr 用于本次流程后续判断的firstErr
|
||||
@@ -593,7 +589,7 @@ func (c *Center) actionDelaySeconds(ctx context.Context, action db.AutomationAct
|
||||
}
|
||||
_ = json.Unmarshal([]byte(action.ConfigJSON), &cfg)
|
||||
// card、err 用于本次流程后续判断的card、err
|
||||
card, err := c.store.Cards.Get(ctx, action.CardID)
|
||||
card, err := c.store.Cards.GetSummary(ctx, action.CardID)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
package automation
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"xianyu-go/internal/xianyu/mtop"
|
||||
)
|
||||
|
||||
// CenterDependencies 保存自动化中心启动时必须固定的外部协作依赖。
|
||||
type CenterDependencies struct {
|
||||
// MTop 提供确认发货使用的 MTOP 协议客户端;为空时使用默认实现。
|
||||
MTop mtop.Client
|
||||
// AccountTaskClient 提供自动评价与商品擦亮的协议调用;使用默认 MTOP 时可自动复用其任务能力。
|
||||
AccountTaskClient AccountTaskClient
|
||||
// OrderDetailFetcher 提供自动发货前的订单详情查询能力。
|
||||
OrderDetailFetcher OrderDetailFetcher
|
||||
// Notifier 接收发货结果通知;为空时不发送通知。
|
||||
Notifier Notifier
|
||||
// CookieSource 提供自动发货读取 Cookie 的可替换边界;为空时读取仓储。
|
||||
CookieSource func(context.Context, string) (string, error)
|
||||
// APICardFetcher 提供普通 API 卡发货请求能力;为空时 API 卡执行会明确失败。
|
||||
APICardFetcher APICardFetcher
|
||||
}
|
||||
@@ -237,6 +237,58 @@ func TestMessageDefinitelyNotSentIsRetried(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestCenterDoesNotRequestAPICardBeforeWebSocketReady 验证 API 卡密在账号 WebSocket 未就绪时不会先请求外部供应商,避免领到卡密后无法投递。
|
||||
func TestCenterDoesNotRequestAPICardBeforeWebSocketReady(t *testing.T) {
|
||||
// store、cleanup 是本测试使用的 SQLite 自动化存储及资源清理函数。
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 是创建规则、执行事件和查询运行记录共用的上下文。
|
||||
ctx := context.Background()
|
||||
// admin 是 API 卡密组和自动化规则的所属用户。
|
||||
admin, adminErr := store.Users.GetByUsername(ctx, "admin")
|
||||
if adminErr != nil {
|
||||
t.Fatal(adminErr)
|
||||
}
|
||||
// cardID 是供付款后发货规则引用的 API 卡密组标识。
|
||||
cardID, cardErr := store.Cards.Create(ctx, &db.CardFull{Name: "API", Type: "api", APIConfig: `{"url":"https://example.com"}`, Enabled: true, UserID: admin.ID})
|
||||
if cardErr != nil {
|
||||
t.Fatal(cardErr)
|
||||
}
|
||||
// ruleErr 是创建 API 卡密自动发货规则的数据库错误。
|
||||
if _, ruleErr := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", Name: "api-before-websocket", TriggerType: TriggerOrderPaid, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{{ActionType: ActionSendCard, CardID: cardID, DeliveryCount: 1, Enabled: true}},
|
||||
}); ruleErr != nil {
|
||||
t.Fatal(ruleErr)
|
||||
}
|
||||
// fetcher 记录外部 API 是否被执行;未就绪时其请求列表必须保持为空。
|
||||
fetcher := &apiCardFetcherStub{}
|
||||
// sender 模拟存在账号实例但尚未完成闲鱼 WebSocket 注册的短暂状态。
|
||||
sender := &readinessTestSender{testSender: &testSender{}, ready: false}
|
||||
// center 注入可报告连接就绪状态的发送器和记录 API 请求的测试客户端。
|
||||
center := NewWithDependencies(store, readinessTestProvider{sender: sender}, nil, CenterDependencies{APICardFetcher: fetcher})
|
||||
// task 是需要调用 API 卡密发货的付款事件。
|
||||
task := Task{AccountID: "cid", TriggerType: TriggerOrderPaid, OrderID: "api-wait-websocket", ChatID: "chat", BuyerID: "buyer", Quantity: "1"}
|
||||
// runErr 是连接未就绪时的预期安全重试错误。
|
||||
runErr := center.HandleTask(ctx, task)
|
||||
if !errors.Is(runErr, ErrMessageNotSent) {
|
||||
t.Fatalf("连接未就绪应返回确定未发送错误: %v", runErr)
|
||||
}
|
||||
if len(fetcher.requests) != 0 {
|
||||
t.Fatalf("WebSocket 未就绪时不应请求 API 卡密: %+v", fetcher.requests)
|
||||
}
|
||||
// status、errorMessage 分别是持久化运行状态和用于恢复的错误分类标记。
|
||||
var status, errorMessage string
|
||||
// queryErr 是读取本次付款事件运行状态失败的数据库错误。
|
||||
queryErr := store.DB.QueryRowContext(ctx, `SELECT status,error_message FROM automation_runs WHERE order_id=?`, task.OrderID).Scan(&status, &errorMessage)
|
||||
if queryErr != nil {
|
||||
t.Fatal(queryErr)
|
||||
}
|
||||
if status != "failed" || !strings.HasPrefix(errorMessage, db.SafeRetryErrorPrefix) {
|
||||
t.Fatalf("未就绪 API 发货应进入安全重试: status=%q error=%q", status, errorMessage)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAbortRunActionFailureQuarantinesRun 封装TestAbort运行动作FailureQuarantines运行业务协调。
|
||||
func TestAbortRunActionFailureQuarantinesRun(t *testing.T) {
|
||||
// store、cleanup 用于本次流程后续判断的store、cleanup
|
||||
@@ -1014,10 +1066,12 @@ func TestCenterOrderPaidFetchesOrderDetailMatchesSpecAndQuantity(t *testing.T) {
|
||||
}},
|
||||
})
|
||||
|
||||
err = center.HandleTask(ctx, Task{
|
||||
// task 是模拟 WebSocket 重复投递时保持不变的订单支付事件。
|
||||
task := Task{
|
||||
Source: "ws", AccountID: "cid", CookieStr: "unb=123; _m_h5_tk=tk_1;", TriggerType: TriggerOrderPaid,
|
||||
ChatID: "chat-1", OrderID: "order-1", ItemID: "item-1", BuyerID: "buyer-1", Raw: map[string]any{"message_id": "m1"},
|
||||
})
|
||||
}
|
||||
err = center.HandleTask(ctx, task)
|
||||
if err != nil {
|
||||
t.Fatalf("HandleTask: %v", err)
|
||||
}
|
||||
@@ -1032,6 +1086,15 @@ func TestCenterOrderPaidFetchesOrderDetailMatchesSpecAndQuantity(t *testing.T) {
|
||||
t.Fatalf("texts[%d]=%q want %q", i, sender.texts[i], want)
|
||||
}
|
||||
}
|
||||
// duplicateErr 是同一支付事件被重复投递时不应出现的执行错误;测试同时确保不会重复发卡。
|
||||
duplicateErr := center.HandleTask(ctx, task)
|
||||
if duplicateErr != nil {
|
||||
t.Fatalf("重复支付事件不应执行或报错: %v", duplicateErr)
|
||||
}
|
||||
// got 与 want 分别是重复事件处理后的实际和预期发卡消息数量。
|
||||
if got, want := len(sender.texts), 4; got != want {
|
||||
t.Fatalf("重复支付事件不应重复发送卡密: got=%d want=%d texts=%v", got, want, sender.texts)
|
||||
}
|
||||
// order、err 用于本次流程后续判断的order、err
|
||||
order, err := store.Orders.Get(ctx, "order-1")
|
||||
if err != nil {
|
||||
@@ -1832,6 +1895,87 @@ func TestCenterNoNotifyWhenNoMatchingRule(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestCenterSkipsWebSocketOrderEventWithoutIdempotencyKey 验证没有订单 ID 和 updateKey 的卡片不会执行动作,但中心不能因此丢弃含 updateKey 的合法付款事件。
|
||||
func TestCenterSkipsWebSocketOrderEventWithoutIdempotencyKey(t *testing.T) {
|
||||
// store、cleanup 保存测试自动化仓储及其关闭函数。
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 是创建规则和处理空订单事件共用的上下文。
|
||||
ctx := context.Background()
|
||||
// admin 是创建测试规则的账号所属用户。
|
||||
admin, adminErr := store.Users.GetByUsername(ctx, "admin")
|
||||
if adminErr != nil {
|
||||
t.Fatal(adminErr)
|
||||
}
|
||||
// ruleErr 是创建本应由空防重键跳过的付款后文本动作失败原因。
|
||||
_, ruleErr := store.Automation.Create(ctx, db.AutomationRuleInput{
|
||||
UserID: admin.ID, CookieID: "cid", Name: "empty-ws-order", TriggerType: TriggerBuyerReviewed, Enabled: true,
|
||||
Actions: []db.AutomationActionInput{{ActionType: ActionSendText, MessageTemplate: "must-not-send", Enabled: true}},
|
||||
})
|
||||
if ruleErr != nil {
|
||||
t.Fatal(ruleErr)
|
||||
}
|
||||
// sender 记录所有实际投递;空订单事件必须使其保持为空。
|
||||
sender := &testSender{}
|
||||
// center 是注入可观察发送器的自动化中心。
|
||||
center := New(store, testSenderProvider{sender: sender}, nil)
|
||||
// handleErr 是空防重键事件被安全跳过时不应出现的处理错误。
|
||||
handleErr := center.HandleTask(ctx, Task{Source: "ws", AccountID: "cid", TriggerType: TriggerOrderPaid})
|
||||
if handleErr != nil {
|
||||
t.Fatalf("空防重键 WebSocket 事件应被安全跳过,err=%v", handleErr)
|
||||
}
|
||||
if len(sender.texts) != 0 {
|
||||
t.Fatalf("空防重键 WebSocket 事件不得触发发送动作: %v", sender.texts)
|
||||
}
|
||||
// updateKeyErr 是只有平台业务键、尚未解析出订单 ID 的合法付款事件处理错误。
|
||||
updateKeyErr := center.HandleTask(ctx, Task{Source: "ws", AccountID: "cid", TriggerType: TriggerBuyerReviewed, ChatID: "chat", BuyerID: "buyer", UpdateKey: "chat:platform-order:10:BUYER_RATE_SELLER:26"})
|
||||
if updateKeyErr != nil {
|
||||
t.Fatalf("带 updateKey 的付款事件不应被空订单门禁拦截,err=%v", updateKeyErr)
|
||||
}
|
||||
if len(sender.texts) != 1 || sender.texts[0] != "must-not-send" {
|
||||
t.Fatalf("带 updateKey 的付款事件应继续执行规则动作: %v", sender.texts)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCenterIgnoresOrderEventOwnedByAnotherAccount 验证同一平台订单被另一登录账号重复推送时,中心不会把归属保护当作系统错误。
|
||||
func TestCenterIgnoresOrderEventOwnedByAnotherAccount(t *testing.T) {
|
||||
// store、cleanup 保存自动化中心使用的 SQLite 仓储及关闭函数。
|
||||
store, cleanup := newAutomationTestStore(t)
|
||||
defer cleanup()
|
||||
// ctx 是写入账号、订单和处理重复事件共用的上下文。
|
||||
ctx := context.Background()
|
||||
// admin 是测试中两个账号的共同所有者。
|
||||
admin, adminErr := store.Users.GetByUsername(ctx, "admin")
|
||||
if adminErr != nil {
|
||||
t.Fatal(adminErr)
|
||||
}
|
||||
// saveErr 是创建第二个已连接账号的持久化错误。
|
||||
saveErr := store.Cookies.Save(ctx, "other-account", "unb=456; _m_h5_tk=tk_2;", admin.ID)
|
||||
if saveErr != nil {
|
||||
t.Fatal(saveErr)
|
||||
}
|
||||
// orderErr 是预先归属给实际卖家账号的订单事实写入错误。
|
||||
orderErr := store.Orders.Upsert(ctx, "cross-account-order", db.OrderUpsertOpts{CookieID: "cid", ItemID: "item-owner"})
|
||||
if orderErr != nil {
|
||||
t.Fatal(orderErr)
|
||||
}
|
||||
// center 是处理另一账号收到的重复付款卡片的自动化中心。
|
||||
center := New(store, testSenderProvider{sender: &testSender{}}, nil)
|
||||
// handleErr 是跨账号重复副本被安全忽略时不应出现的处理错误。
|
||||
handleErr := center.HandleTask(ctx, Task{Source: "ws", AccountID: "other-account", TriggerType: TriggerOrderPaid, OrderID: "cross-account-order"})
|
||||
if handleErr != nil {
|
||||
t.Fatalf("跨账号重复订单事件应被忽略,err=%v", handleErr)
|
||||
}
|
||||
// order、getErr 分别是处理后的归属记录和读取它的错误;归属必须仍保留在原卖家账号。
|
||||
order, getErr := store.Orders.Get(ctx, "cross-account-order")
|
||||
if getErr != nil {
|
||||
t.Fatal(getErr)
|
||||
}
|
||||
if order.CookieID != "cid" {
|
||||
t.Fatalf("跨账号重复事件不应改写订单归属: cookie_id=%q", order.CookieID)
|
||||
}
|
||||
}
|
||||
|
||||
// TestDueReviewRequestOrdersHandlesNullSpecColumns 验证订单 spec_name/spec_value 为 NULL
|
||||
// 时(旧库升级数据常见)DueReviewRequestOrders 不报扫描错误。
|
||||
// TestDueReviewRequestOrdersHandlesNullSpecColumns 封装TestDueReview请求订单列表HandlesNullSpecColumns业务协调。
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package automation
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// noRetryAction 标记外部动作确定未执行且不应被通用恢复队列再次调用的错误。
|
||||
func noRetryAction(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
if strings.HasPrefix(err.Error(), db.NoRetryErrorPrefix) {
|
||||
return err
|
||||
}
|
||||
return fmt.Errorf("%s: %w", db.NoRetryErrorPrefix, err)
|
||||
}
|
||||
@@ -66,7 +66,7 @@ type OrderDetail struct {
|
||||
}
|
||||
|
||||
// ExtractTaskFromWS 从一条解密后的 WS 消息中提取系统事件。
|
||||
// 这里只做事实解析:识别平台告诉了我们什么;是否执行自动化由 Center 根据规则决定。
|
||||
// 这里只做事实解析:识别平台告诉了我们什么;是否执行自动化由 Center 根据规则和可用的订单或 updateKey 防重键决定。
|
||||
// ExtractTaskFromWS 封装Extract任务FromWS业务协调。
|
||||
func ExtractTaskFromWS(accountID, cookieStr string, raw map[string]any) *Task {
|
||||
if raw == nil {
|
||||
@@ -203,11 +203,9 @@ func fieldsFromRaw(raw map[string]any) rawFields {
|
||||
f.orderID = matchOrderID(f.reminderURL)
|
||||
}
|
||||
}
|
||||
// 平台交易卡片会随客户端版本把订单事实移动到不同嵌套层级或 JSON 字符串中;
|
||||
// 固定路径未命中时,只补齐仍为空的明确业务字段,不能覆盖已按优先路径解析出的事实。
|
||||
if f.chatID == "" || f.orderID == "" || f.itemID == "" || f.buyerID == "" {
|
||||
supplementEventFacts(&f, raw, 0)
|
||||
}
|
||||
// 平台交易卡片会随客户端版本把订单事实或买卖角色移动到不同嵌套层级或 JSON 字符串中;
|
||||
// 固定路径已取到全部事实时仍需识别角色,避免买家侧卡片被误投递为卖家自动化。
|
||||
supplementEventFacts(&f, raw, 0)
|
||||
return f
|
||||
}
|
||||
|
||||
@@ -288,6 +286,18 @@ func supplementEventFactByKey(fields *rawFields, key string, value any) {
|
||||
if fields.buyerID == "" {
|
||||
fields.buyerID = text
|
||||
}
|
||||
case "role", "orderrole":
|
||||
if fields.orderRole == "" {
|
||||
fields.orderRole = normalizedOrderRole(text)
|
||||
}
|
||||
case "taskname":
|
||||
if fields.orderRole == "" {
|
||||
fields.orderRole = orderRoleFromTaskName(text)
|
||||
}
|
||||
case "biztag":
|
||||
if fields.orderRole == "" {
|
||||
fields.orderRole = orderRoleFromTaskName(bizTaskName(text))
|
||||
}
|
||||
case "reminderurl", "targeturl", "url", "deeplink", "link":
|
||||
supplementEventFactsFromURL(fields, text)
|
||||
}
|
||||
@@ -314,7 +324,7 @@ func directOrderID(value string) string {
|
||||
return value
|
||||
}
|
||||
|
||||
// supplementEventFactsFromURL 从交易跳转链接补齐订单、商品、买家和会话标识。
|
||||
// supplementEventFactsFromURL 从交易跳转链接补齐订单、商品、买家、会话和买卖角色。
|
||||
func supplementEventFactsFromURL(fields *rawFields, rawURL string) {
|
||||
if fields == nil || strings.TrimSpace(rawURL) == "" {
|
||||
return
|
||||
@@ -331,6 +341,9 @@ func supplementEventFactsFromURL(fields *rawFields, rawURL string) {
|
||||
if fields.orderID == "" {
|
||||
fields.orderID = matchOrderID(rawURL)
|
||||
}
|
||||
if fields.orderRole == "" {
|
||||
fields.orderRole = orderRoleFromURL(rawURL)
|
||||
}
|
||||
}
|
||||
|
||||
// isOrderPaidEvent 封装is订单PaidEvent业务协调。
|
||||
@@ -515,9 +528,16 @@ func orderRoleFromURL(rawURL string) string {
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
switch strings.ToLower(strings.TrimSpace(u.Query().Get("role"))) {
|
||||
return normalizedOrderRole(u.Query().Get("role"))
|
||||
}
|
||||
|
||||
// normalizedOrderRole 只接受平台协议中可识别的买卖双方角色,未知值不得影响事件归属判断。
|
||||
func normalizedOrderRole(value string) string {
|
||||
// role 是去除大小写和空白差异后的平台角色字段。
|
||||
role := strings.ToLower(strings.TrimSpace(value))
|
||||
switch role {
|
||||
case "seller", "buyer":
|
||||
return strings.ToLower(strings.TrimSpace(u.Query().Get("role")))
|
||||
return role
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -176,6 +176,40 @@ func TestExtractTaskFromWS_OrderCreatedUsesNestedFallbackFacts(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestExtractTaskFromWS_OrderEventWithoutOrderIDRetained 验证订单 ID 尚未出现在卡片中时仍保留事件,供后续使用 updateKey 作为防重键完成卡密投递。
|
||||
func TestExtractTaskFromWS_OrderEventWithoutOrderIDRetained(t *testing.T) {
|
||||
// raw 是仅含待付款展示文案、没有订单链接或业务键的非完整交易提示。
|
||||
raw := mustMap(t, `{
|
||||
"1": {"2": "63107041124@goofish", "10": {
|
||||
"redReminder": "等待买家付款",
|
||||
"reminderContent": "[我已拍下,待付款]"
|
||||
}}
|
||||
}`)
|
||||
// task 是解析结果;订单 ID 缺失不应吞掉系统卡片,协调器仍可根据 updateKey 或最终的空键门禁决定是否执行。
|
||||
task := ExtractTaskFromWS("acc1", "cookie", raw)
|
||||
if task == nil || task.TriggerType != TriggerOrderCreated || task.OrderID != "" {
|
||||
t.Fatalf("缺少订单 ID 的交易提示应保留为待协调事件: %+v", task)
|
||||
}
|
||||
}
|
||||
|
||||
// TestExtractTaskFromWS_NestedBuyerRoleIgnored 验证角色仅存在于备用嵌套链接时,买家侧付款卡片仍不会进入卖家自动化。
|
||||
func TestExtractTaskFromWS_NestedBuyerRoleIgnored(t *testing.T) {
|
||||
// raw 保留完整订单事实,但买卖角色位于新版嵌套 targetUrl,而非旧固定路径。
|
||||
raw := mustMap(t, `{
|
||||
"1": {"2": "63107041124@goofish", "10": {
|
||||
"redReminder": "等待卖家发货",
|
||||
"reminderContent": "[我已付款,等待你发货]",
|
||||
"extJson": "{\"updateKey\":\"63107041124:3310145690545023994:10:TRADE_PAID:26\"}"
|
||||
}},
|
||||
"payload": {"targetUrl": "fleamarket://order_detail?id=3310145690545023994&role=buyer"}
|
||||
}`)
|
||||
// task 是解析结果;当前账号作为买家时不能触发其卖家发货规则。
|
||||
task := ExtractTaskFromWS("acc1", "cookie", raw)
|
||||
if task != nil {
|
||||
t.Fatalf("嵌套买家角色不应进入卖家自动化: %+v", task)
|
||||
}
|
||||
}
|
||||
|
||||
// TestExtractTaskFromWS_PriceModifiedEventIgnored 验证改价确认卡片不会因“等待买家付款”提示被重复识别为订单创建。
|
||||
func TestExtractTaskFromWS_PriceModifiedEventIgnored(t *testing.T) {
|
||||
// raw 是闲鱼在卖家改价成功后推送的确认卡片,沿用待付款提醒但业务键明确为改价。
|
||||
|
||||
@@ -25,6 +25,8 @@ type automationRunCoordinator struct {
|
||||
actionDelaySeconds func(context.Context, db.AutomationAction) (int, error)
|
||||
// accountAutomationAllowed 检查账号是否仍允许执行外部自动化动作。
|
||||
accountAutomationAllowed func(context.Context, string) (bool, error)
|
||||
// accountSenderReady 判断账号是否已具备可立即发送消息的闲鱼 WebSocket 连接。
|
||||
accountSenderReady func(string) bool
|
||||
// deferTask 持久化等待延迟后继续执行的任务。
|
||||
deferTask func(context.Context, Task, int64) error
|
||||
// executeAction 执行一个已经通过账号门禁的具体外部动作。
|
||||
@@ -45,6 +47,9 @@ func (r automationRunCoordinator) executeRule(ctx context.Context, task Task, ru
|
||||
if skipped {
|
||||
return nil
|
||||
}
|
||||
if run == nil {
|
||||
return errors.New("自动化运行记录缺失,已停止执行外部动作")
|
||||
}
|
||||
task = preparedTask
|
||||
// status 是运行完成时写入数据库的结果状态。
|
||||
status := "success"
|
||||
@@ -190,9 +195,13 @@ func (r automationRunCoordinator) prepareRuleRun(ctx context.Context, task Task,
|
||||
}
|
||||
// runID 是新建运行的数据库主键;started 表示当前事件是否抢到唯一执行权。
|
||||
runID, started, startErr := r.store.Automation.TryStartRun(ctx, newRun)
|
||||
if startErr != nil || !started {
|
||||
if startErr != nil {
|
||||
return Task{}, nil, false, startErr
|
||||
}
|
||||
if !started {
|
||||
// 同一规则的同一事件已由其他投递处理或已完成,不能把空运行记录交给执行阶段。
|
||||
return preparedTask, nil, true, nil
|
||||
}
|
||||
// createdRun 是重新读取的完整运行状态,包含动作游标和累计发送数。
|
||||
createdRun, getErr := r.store.Automation.GetRun(ctx, runID)
|
||||
if getErr != nil {
|
||||
@@ -297,5 +306,18 @@ func (r automationRunCoordinator) executeActionNow(ctx context.Context, task Tas
|
||||
if !allowed {
|
||||
return 0, fmt.Errorf("账号已暂停或停用,取消自动化动作")
|
||||
}
|
||||
if actionNeedsOnlineSender(action) && r.accountSenderReady != nil && !r.accountSenderReady(task.AccountID) {
|
||||
return 0, fmt.Errorf("%w: 账号 %s 的 WebSocket 尚未就绪,未执行消息或卡密动作", ErrMessageNotSent, task.AccountID)
|
||||
}
|
||||
return r.executeAction(ctx, task, action)
|
||||
}
|
||||
|
||||
// actionNeedsOnlineSender 判断动作是否会向买家发送消息;这类动作必须先确认账号 WebSocket 已就绪,避免 API 卡密已领取但无法投递。
|
||||
func actionNeedsOnlineSender(action db.AutomationAction) bool {
|
||||
switch action.ActionType {
|
||||
case ActionSendCard, ActionSendText:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -114,6 +114,8 @@ type Services struct {
|
||||
automationRules *automationapp.RuleService
|
||||
// cards 是卡券 CRUD、输入校验和所有权编排应用服务。
|
||||
cards *cardsapp.Service
|
||||
// apiCardTester 是卡券 API 测试请求端口。
|
||||
apiCardTester cardsapp.APIRequestTester
|
||||
// publishAutomationRules 是批量发布成功后幂等准备自动化规则的应用服务。
|
||||
publishAutomationRules *automationapp.PublishRuleService
|
||||
// defaultReplies 是默认回复配置与投递记录应用服务。
|
||||
@@ -311,11 +313,13 @@ type TransportPorts struct {
|
||||
AutomationIssues *automationapp.IssueService
|
||||
AutomationRules *automationapp.RuleService
|
||||
Cards *cardsapp.Service
|
||||
PublishAutomationRules *automationapp.PublishRuleService
|
||||
DefaultReplies *defaultreplyapp.Service
|
||||
Keywords *keywordsapp.Service
|
||||
Settings *settingsapp.Service
|
||||
Admin *adminapp.Service
|
||||
// APICardTester 是卡券 API 测试请求应用端口。
|
||||
APICardTester cardsapp.APIRequestTester
|
||||
PublishAutomationRules *automationapp.PublishRuleService
|
||||
DefaultReplies *defaultreplyapp.Service
|
||||
Keywords *keywordsapp.Service
|
||||
Settings *settingsapp.Service
|
||||
Admin *adminapp.Service
|
||||
}
|
||||
|
||||
// TransportPorts 返回已完成构造的只读服务引用;调用方不得在运行期替换任何字段。
|
||||
@@ -335,7 +339,7 @@ func (services *Services) TransportPorts() TransportPorts {
|
||||
AccountSummaries: services.accountSummaries, AccountTasks: services.accountTasks, Chat: services.chat,
|
||||
UncertainNotifications: services.uncertainNotifications, NotificationChannels: services.notificationChannels,
|
||||
Analytics: services.analytics, AutomationIssues: services.automationIssues, AutomationRules: services.automationRules,
|
||||
Cards: services.cards, PublishAutomationRules: services.publishAutomationRules, DefaultReplies: services.defaultReplies,
|
||||
Cards: services.cards, APICardTester: services.apiCardTester, PublishAutomationRules: services.publishAutomationRules, DefaultReplies: services.defaultReplies,
|
||||
Keywords: services.keywords, Settings: services.settings, Admin: services.admin,
|
||||
}
|
||||
}
|
||||
@@ -499,6 +503,7 @@ func New(dependencies Dependencies) (*Services, error) {
|
||||
analytics: dependencies.TransportApplications.Analytics,
|
||||
automationRules: dependencies.TransportApplications.AutomationRules,
|
||||
cards: dependencies.TransportApplications.Cards,
|
||||
apiCardTester: dependencies.TransportApplications.APICardTester,
|
||||
publishAutomationRules: dependencies.TransportApplications.PublishAutomationRules,
|
||||
automationIssues: dependencies.TransportApplications.AutomationIssues,
|
||||
defaultReplies: dependencies.TransportApplications.DefaultReplies,
|
||||
@@ -593,7 +598,7 @@ func downloadImageURL(ctx context.Context, rawURL string) ([]byte, string, error
|
||||
return nil, "", fmt.Errorf("图片 URL 无效: %s", rawURL)
|
||||
}
|
||||
// client 是限制内网访问的公网 HTTP 客户端;response、responseErr 是下载响应及其网络错误。
|
||||
client := netguard.PublicHTTPClient(30 * time.Second)
|
||||
client := netguard.ConfiguredHTTPClient(30 * time.Second)
|
||||
// response、responseErr 分别是远端图片响应及网络失败;正文必须在本函数返回前关闭。
|
||||
response, responseErr := client.Do(request)
|
||||
if responseErr != nil {
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"xianyu-go/internal/browser"
|
||||
composition "xianyu-go/internal/composition"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/netguard"
|
||||
"xianyu-go/internal/renewal"
|
||||
"xianyu-go/internal/server"
|
||||
)
|
||||
@@ -147,7 +148,7 @@ func BuildRuntime(options RuntimeOptions, infrastructure RuntimeInfrastructure)
|
||||
// transportApplications、transportErr 分别是通知等共享应用服务集合及其构造错误。
|
||||
transportApplications, transportErr := adapter.NewTransportApplicationServices(adapter.TransportApplicationServiceOptions{
|
||||
AutomationDependencies: automationDependencies, MiscDependencies: miscDependencies, AdminSettingsDependencies: adminSettingsDependencies,
|
||||
AdminRuntime: runtimeBundle.Manager, AccountTaskRunner: adapter.NewAccountTaskRunner(runtimeBundle.Automation), ChannelSender: runtimeBundle.Notifier, ModelClient: adapter.NewAIModelClient(),
|
||||
AdminRuntime: runtimeBundle.Manager, AccountTaskRunner: adapter.NewAccountTaskRunner(runtimeBundle.Automation), ChannelSender: runtimeBundle.Notifier, ModelClient: adapter.NewAIModelClient(), OutboundPolicy: netguard.DefaultPolicy(),
|
||||
})
|
||||
if transportErr != nil {
|
||||
return Runtime{}, fmt.Errorf("构造 transport 应用服务失败: %w", transportErr)
|
||||
|
||||
@@ -216,7 +216,7 @@ func ServerDependencies(services *composition.Services, base HTTPDependencies, s
|
||||
AccountSummaries: ports.AccountSummaries, AccountTasks: ports.AccountTasks, Chat: ports.Chat,
|
||||
UncertainNotifications: ports.UncertainNotifications, NotificationChannels: ports.NotificationChannels,
|
||||
Analytics: ports.Analytics, AutomationIssues: ports.AutomationIssues, AutomationRules: ports.AutomationRules,
|
||||
Cards: ports.Cards, PublishAutomationRules: ports.PublishAutomationRules, DefaultReplies: ports.DefaultReplies,
|
||||
Cards: ports.Cards, APIRequestTester: ports.APICardTester, PublishAutomationRules: ports.PublishAutomationRules, DefaultReplies: ports.DefaultReplies,
|
||||
Keywords: ports.Keywords, Settings: ports.Settings, Admin: ports.Admin,
|
||||
}),
|
||||
}, nil
|
||||
|
||||
@@ -14,6 +14,9 @@ var ErrAutomationRunActive = errors.New("规则仍有待处理的自动化运行
|
||||
// SafeRetryErrorPrefix 标记当前动作明确没有产生外部副作用,可以从动作游标安全恢复。
|
||||
const SafeRetryErrorPrefix = "[safe_retry]"
|
||||
|
||||
// NoRetryErrorPrefix 标记当前动作明确不应进入自动化恢复队列。
|
||||
const NoRetryErrorPrefix = "[no_retry]"
|
||||
|
||||
// AutomationRules 管理自动化规则、动作和执行记录。
|
||||
//
|
||||
// 自动化中心不区分触发来源:WS 系统事件、计划任务、后台手动触发都通过
|
||||
@@ -466,7 +469,7 @@ func (a *AutomationRules) Delete(ctx context.Context, userID, ruleID int64) erro
|
||||
SET deleted_at=CURRENT_TIMESTAMP, enabled=0, updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND user_id=? AND deleted_at IS NULL AND NOT EXISTS (
|
||||
SELECT 1 FROM automation_runs ar WHERE ar.rule_id=automation_rules.id
|
||||
AND (ar.status IN ('running','needs_review') OR (ar.status='failed' AND ar.sent_count=0 AND ar.attempt_count<3)))`, ruleID, userID)
|
||||
AND (ar.status IN ('running','needs_review') OR (ar.status='failed' AND ar.sent_count=0 AND ar.attempt_count<3 AND ar.error_message NOT LIKE '[no_retry]%')))`, ruleID, userID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -575,7 +578,7 @@ func (a *AutomationRules) reclaimRun(ctx context.Context, ruleID int64, triggerK
|
||||
WHERE rule_id=? AND trigger_key=?
|
||||
AND ((status='running' AND action_started=0 AND (lease_expires_at=0 OR lease_expires_at<?))
|
||||
OR (status='failed' AND action_started=0 AND attempt_count<3 AND next_retry_at<=?
|
||||
AND (sent_count=0 OR error_message LIKE '[safe_retry]%')))`,
|
||||
AND ((sent_count=0 AND error_message NOT LIKE '[no_retry]%') OR error_message LIKE '[safe_retry]%')))`,
|
||||
leaseExpiresAt, ruleID, triggerKey, now, now)
|
||||
if err != nil {
|
||||
return 0, false, err
|
||||
@@ -708,7 +711,7 @@ func (a *AutomationRules) ClaimRecoveryRun(ctx context.Context, runID, leaseExpi
|
||||
SET status='running',error_message='',lease_expires_at=?,next_retry_at=0,attempt_count=attempt_count+1,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND action_started=0 AND ((status='running' AND (lease_expires_at=0 OR lease_expires_at<?))
|
||||
OR (status='failed' AND attempt_count<3 AND next_retry_at<=?
|
||||
AND (sent_count=0 OR error_message LIKE '[safe_retry]%')))`, leaseExpiresAt, runID, now, now)
|
||||
AND ((sent_count=0 AND error_message NOT LIKE '[no_retry]%') OR error_message LIKE '[safe_retry]%')))`, leaseExpiresAt, runID, now, now)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
@@ -721,7 +724,7 @@ func (a *AutomationRules) ClaimRecoveryRun(ctx context.Context, runID, leaseExpi
|
||||
func (a *AutomationRules) FinishRun(ctx context.Context, id int64, attempt int, status string, sentCount int, errMsg string) error {
|
||||
// nextRetryAt 用于本次流程后续判断的next重试At
|
||||
nextRetryAt := int64(0)
|
||||
if status == "failed" && (sentCount == 0 || strings.HasPrefix(errMsg, SafeRetryErrorPrefix)) {
|
||||
if status == "failed" && (strings.HasPrefix(errMsg, SafeRetryErrorPrefix) || sentCount == 0 && !strings.HasPrefix(errMsg, NoRetryErrorPrefix)) {
|
||||
nextRetryAt = time.Now().UTC().Add(time.Minute).Unix()
|
||||
}
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
@@ -764,7 +767,7 @@ SELECT id,rule_id,cookie_id,item_id,order_id,buyer_id,chat_id,trigger_type,trigg
|
||||
FROM automation_runs
|
||||
WHERE (status='running' AND (lease_expires_at=0 OR lease_expires_at<?))
|
||||
OR (status='failed' AND action_started=0 AND attempt_count<3 AND next_retry_at<=?
|
||||
AND (sent_count=0 OR error_message LIKE '[safe_retry]%'))
|
||||
AND ((sent_count=0 AND error_message NOT LIKE '[no_retry]%') OR error_message LIKE '[safe_retry]%'))
|
||||
ORDER BY updated_at,id LIMIT ?`, now, now, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -325,7 +325,7 @@ func (a *AutomationRules) WakeCredentialBlocked(ctx context.Context, cookieID st
|
||||
_, err := a.DB.ExecContext(ctx, `UPDATE automation_runs
|
||||
SET next_retry_at=0,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE cookie_id=? AND status='failed' AND action_started=0
|
||||
AND (sent_count=0 OR error_message LIKE '[safe_retry]%')
|
||||
AND ((sent_count=0 AND error_message NOT LIKE '[no_retry]%') OR error_message LIKE '[safe_retry]%')
|
||||
AND (LOWER(error_message) LIKE '%session%' OR error_message LIKE '%登录凭证%'
|
||||
OR error_message LIKE '%Cookie%' OR error_message LIKE '%cookie%'
|
||||
OR LOWER(error_message) LIKE '%websocket%' OR LOWER(error_message) LIKE '%token%'
|
||||
|
||||
@@ -537,6 +537,50 @@ func TestAutomation_TryStartRunRecoversStaleAndUnsentFailedRuns(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomation_NoRetryFailureIsNotRecovered 验证明确不可重试的外部失败不会因零发送量重新入队。
|
||||
func TestAutomation_NoRetryFailureIsNotRecovered(t *testing.T) {
|
||||
// s、cleanup 是本测试使用的临时 SQLite 数据库及清理函数。
|
||||
s, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
// ctx 是本测试数据库操作使用的非取消上下文。
|
||||
ctx := context.Background()
|
||||
// userID、cookieID 是规则所属用户和账号标识。
|
||||
userID, cookieID := seedAccount(t, s)
|
||||
// ruleID 是用于创建自动化运行的规则标识。
|
||||
ruleID, err := s.Automation.Create(ctx, makeAutomationRule(cookieID, userID, "i-no-retry", "paid", true, 100))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// runID、started 是新建运行记录的标识和启动结果。
|
||||
runID, started, err := s.Automation.TryStartRun(ctx, AutomationRun{
|
||||
RuleID: ruleID, CookieID: cookieID, OrderID: "order-no-retry", TriggerType: "paid", TriggerKey: "paid:order-no-retry",
|
||||
})
|
||||
if err != nil || !started {
|
||||
t.Fatalf("TryStartRun: id=%d started=%v err=%v", runID, started, err)
|
||||
}
|
||||
// run 是当前运行的尝试信息。
|
||||
run, err := s.Automation.GetRun(ctx, runID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// err 表示完成不可重试运行的持久化错误。
|
||||
if err := s.Automation.FinishRun(ctx, runID, run.AttemptCount, "failed", 0, NoRetryErrorPrefix+": HTTP 400"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// err 表示清除退避时间测试数据的 SQL 错误。
|
||||
if _, err := s.DB.ExecContext(ctx, `UPDATE automation_runs SET next_retry_at=0 WHERE id=?`, runID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// recoveredStarted 表示清除退避时间后是否错误地重新启动了不可重试运行。
|
||||
_, recoveredStarted, err := s.Automation.TryStartRun(ctx, AutomationRun{RuleID: ruleID, CookieID: cookieID, OrderID: "order-no-retry", TriggerType: "paid", TriggerKey: "paid:order-no-retry"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if recoveredStarted {
|
||||
t.Fatal("不可重试失败不应被自动恢复")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationRunAttemptFencesStaleWorker 封装Test自动化运行尝试次数FencesStale工作器业务协调。
|
||||
func TestAutomationRunAttemptFencesStaleWorker(t *testing.T) {
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// CardAPIConfigSummary 是数据库向普通查询路径提供的 API 卡脱敏摘要。
|
||||
type CardAPIConfigSummary struct {
|
||||
// URL 是 API 端点地址,不包含请求模板内容。
|
||||
URL string `json:"url"`
|
||||
// Method 是 API 请求方法。
|
||||
Method string `json:"method"`
|
||||
// TimeoutSeconds 是请求超时时间,单位为秒。
|
||||
TimeoutSeconds int `json:"timeout_seconds"`
|
||||
// ResponsePath 是响应提取路径。
|
||||
ResponsePath string `json:"response_path,omitempty"`
|
||||
// RetryEnabled 表示是否启用幂等重试。
|
||||
RetryEnabled bool `json:"retry_enabled"`
|
||||
// HeadersConfigured 表示是否配置了请求头模板。
|
||||
HeadersConfigured bool `json:"headers_configured"`
|
||||
// ParamsConfigured 表示是否配置了请求参数模板。
|
||||
ParamsConfigured bool `json:"params_configured"`
|
||||
// Ready 表示配置能否进入自动化规则选择。
|
||||
Ready bool `json:"ready"`
|
||||
// ValidationError 是不包含秘密值的配置错误。
|
||||
ValidationError string `json:"validation_error,omitempty"`
|
||||
}
|
||||
|
||||
// GetForDelivery 读取自动发货专用的完整卡券配置,普通查询不得调用此方法。
|
||||
func (c *Cards) GetForDelivery(ctx context.Context, cardID int64) (*CardFull, error) {
|
||||
return c.Get(ctx, cardID)
|
||||
}
|
||||
|
||||
// GetSummary 读取单个卡券的脱敏摘要,完整 API 模板不会离开数据库层。
|
||||
func (c *Cards) GetSummary(ctx context.Context, cardID int64) (*CardFull, error) {
|
||||
// card 是内部完整读取后立即脱敏的卡券记录。
|
||||
card, err := c.Get(ctx, cardID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if card.Type == "api" {
|
||||
card.APIConfigSummary = summarizeCardAPIConfig(card.Type, card.APIConfig)
|
||||
card.APIConfig = ""
|
||||
}
|
||||
return card, nil
|
||||
}
|
||||
|
||||
// AllForUserSummary 读取用户卡券列表的脱敏摘要,避免把 API 模板带入应用层。
|
||||
func (c *Cards) AllForUserSummary(ctx context.Context, userID int64) ([]CardFull, error) {
|
||||
// cards 是内部完整读取后逐条脱敏的卡券记录。
|
||||
cards, err := c.AllForUser(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// i 表示当前需要脱敏处理的卡券列表下标。
|
||||
for i := range cards {
|
||||
if cards[i].Type == "api" {
|
||||
cards[i].APIConfigSummary = summarizeCardAPIConfig(cards[i].Type, cards[i].APIConfig)
|
||||
cards[i].APIConfig = ""
|
||||
}
|
||||
}
|
||||
return cards, nil
|
||||
}
|
||||
|
||||
// summarizeCardAPIConfig 将已解密的 API 配置转换为不含敏感模板的摘要。
|
||||
func summarizeCardAPIConfig(cardType, raw string) *CardAPIConfigSummary {
|
||||
if cardType != "api" {
|
||||
return nil
|
||||
}
|
||||
// summary 是普通卡券查询使用的脱敏结果。
|
||||
summary := &CardAPIConfigSummary{}
|
||||
// fields 是只用于解析非敏感字段和模板是否存在的 JSON 对象。
|
||||
var fields map[string]json.RawMessage
|
||||
// err 表示 API 配置 JSON 解析错误。
|
||||
if err := json.Unmarshal([]byte(raw), &fields); err != nil || fields == nil {
|
||||
summary.ValidationError = "API 配置 JSON 无效"
|
||||
return summary
|
||||
}
|
||||
summary.URL = summaryRawString(fields["url"])
|
||||
summary.Method = strings.ToUpper(summaryRawString(fields["method"]))
|
||||
if summary.Method == "" {
|
||||
summary.Method = "GET"
|
||||
}
|
||||
summary.TimeoutSeconds = parseSummaryTimeout(fields)
|
||||
summary.ResponsePath = summaryRawString(fields["response_path"])
|
||||
summary.RetryEnabled = strings.EqualFold(summaryRawString(fields["retry_enabled"]), "true")
|
||||
summary.HeadersConfigured = templateConfigured(fields["headers"])
|
||||
summary.ParamsConfigured = templateConfigured(fields["params"])
|
||||
// templates 是只在本地校验幂等占位符的临时 JSON 值,不进入返回结构。
|
||||
templates := make(map[string]any, 2)
|
||||
// name 表示当前待读取的敏感模板字段名。
|
||||
for _, name := range []string{"headers", "params"} {
|
||||
// value 保存模板的临时 JSON 值,函数返回前不会写入摘要。
|
||||
var value any
|
||||
// err 表示模板字段解析错误;错误模板不影响公开字段读取。
|
||||
if err := json.Unmarshal(fields[name], &value); err == nil {
|
||||
templates[name] = value
|
||||
}
|
||||
}
|
||||
// err 表示摘要公开字段或重试约束校验错误。
|
||||
if err := validateSummaryAPIConfig(*summary, templates); err != nil {
|
||||
summary.ValidationError = err.Error()
|
||||
return summary
|
||||
}
|
||||
summary.Ready = true
|
||||
return summary
|
||||
}
|
||||
|
||||
// parseSummaryTimeout 兼容历史配置中的 timeout 字段并返回摘要超时。
|
||||
func parseSummaryTimeout(fields map[string]json.RawMessage) int {
|
||||
// raw 保存优先使用的新字段或历史字段。
|
||||
raw := fields["timeout_seconds"]
|
||||
if len(raw) == 0 {
|
||||
raw = fields["timeout"]
|
||||
}
|
||||
// value 保存兼容超时字段的文本值。
|
||||
value := summaryRawString(raw)
|
||||
if value == "" {
|
||||
return 10
|
||||
}
|
||||
// timeout 保存解析后的秒数。
|
||||
timeout, err := strconv.Atoi(strings.TrimSpace(value))
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return timeout
|
||||
}
|
||||
|
||||
// summaryRawString 读取摘要解析所需的 JSON 标量文本,不保留原始模板值。
|
||||
func summaryRawString(raw json.RawMessage) string {
|
||||
if len(raw) == 0 {
|
||||
return ""
|
||||
}
|
||||
// value 保存字符串类型 JSON 标量。
|
||||
var value string
|
||||
if json.Unmarshal(raw, &value) == nil {
|
||||
return value
|
||||
}
|
||||
// generic 保存数字或布尔类型 JSON 标量。
|
||||
var generic any
|
||||
if json.Unmarshal(raw, &generic) == nil {
|
||||
return fmt.Sprint(generic)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// templateConfigured 判断模板字段是否存在且不是空对象或空字符串。
|
||||
func templateConfigured(raw json.RawMessage) bool {
|
||||
// value 保存模板字段的紧凑 JSON 形式,仅用于判断是否已配置。
|
||||
value := strings.TrimSpace(string(raw))
|
||||
return value != "" && value != "null" && value != "{}" && value != `""`
|
||||
}
|
||||
|
||||
// validateSummaryAPIConfig 校验摘要中的公开字段及重试占位符约束。
|
||||
func validateSummaryAPIConfig(summary CardAPIConfigSummary, templates map[string]any) error {
|
||||
// parsed 保存公开 API 地址解析结果。
|
||||
parsed, err := url.Parse(strings.TrimSpace(summary.URL))
|
||||
if err != nil || parsed.Hostname() == "" || parsed.User != nil || parsed.Scheme != "http" && parsed.Scheme != "https" {
|
||||
return errors.New("API 地址必须是 HTTP(S) 地址且不能包含用户凭据")
|
||||
}
|
||||
if summary.Method != "GET" && summary.Method != "POST" {
|
||||
return errors.New("API 请求方法只能是 GET 或 POST")
|
||||
}
|
||||
if summary.TimeoutSeconds < 1 || summary.TimeoutSeconds > 60 {
|
||||
return errors.New("API 超时时间必须在 1 到 60 秒之间")
|
||||
}
|
||||
if summary.RetryEnabled && !summaryTemplateContains(templates, "{idempotency_key}") {
|
||||
return errors.New("启用 API 重试时,请求头或请求参数必须包含 {idempotency_key}")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// summaryTemplateContains 递归检查模板是否包含指定占位符。
|
||||
func summaryTemplateContains(value any, placeholder string) bool {
|
||||
// current 保存当前递归节点的模板值。
|
||||
switch current := value.(type) {
|
||||
case string:
|
||||
return strings.Contains(current, placeholder)
|
||||
case map[string]any:
|
||||
// child 表示当前对象中的模板子节点。
|
||||
for _, child := range current {
|
||||
if summaryTemplateContains(child, placeholder) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
case []any:
|
||||
// child 表示当前数组中的模板子节点。
|
||||
for _, child := range current {
|
||||
if summaryTemplateContains(child, placeholder) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -163,6 +163,8 @@ func (i *Items) MultiQuantityDelivery(ctx context.Context, cookieID, itemID stri
|
||||
type Cards struct {
|
||||
DB *sql.DB
|
||||
Dialect Dialect
|
||||
// codec 负责 API 卡请求模板的静态加密与解密;只有完整卡券读取和写入路径使用它。
|
||||
codec *secretCodec
|
||||
}
|
||||
|
||||
// ConsumeBatchData 原子预留一条批量数据卡券(data 类型),返回内容。
|
||||
|
||||
@@ -22,6 +22,30 @@ func (i *Items) AllForCookie(ctx context.Context, cookieID string) ([]ItemInfoRo
|
||||
return scanItemInfoRows(rows)
|
||||
}
|
||||
|
||||
// GetByCookieItem 读取账号下指定商品的详情文本,供 API 发货模板使用;不存在时返回空记录而非猜测商品内容。
|
||||
func (i *Items) GetByCookieItem(ctx context.Context, cookieID, itemID string) (ItemInfoRow, error) {
|
||||
// row 保存当前账号与商品标识匹配到的本地商品详情。
|
||||
var row ItemInfoRow
|
||||
// isMulti、multiQty 保存数据库整数标记的布尔转换中间值。
|
||||
var isMulti, multiQty int
|
||||
// err 表示商品详情查询或扫描错误。
|
||||
err := i.DB.QueryRowContext(ctx,
|
||||
`SELECT id, cookie_id, item_id, COALESCE(item_title,''), COALESCE(item_description,''),
|
||||
COALESCE(item_category,''), COALESCE(item_price,''), COALESCE(item_detail,''),
|
||||
is_multi_spec, COALESCE(multi_quantity_delivery,0)
|
||||
FROM item_info WHERE cookie_id=? AND item_id=? AND deleted_at IS NULL`, cookieID, itemID).Scan(
|
||||
&row.ID, &row.CookieID, &row.ItemID, &row.ItemTitle, &row.ItemDescription,
|
||||
&row.ItemCategory, &row.ItemPrice, &row.ItemDetail, &isMulti, &multiQty)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return ItemInfoRow{}, ErrNotFound
|
||||
}
|
||||
return ItemInfoRow{}, err
|
||||
}
|
||||
row.IsMultiSpec, row.MultiQuantityDelivery = isMulti != 0, multiQty != 0
|
||||
return row, nil
|
||||
}
|
||||
|
||||
// ListForUser 一次查询用户范围内的全部商品,可选按账号 ID 过滤。
|
||||
func (i *Items) ListForUser(ctx context.Context, userID int64, cookieID string) ([]ItemInfoRow, error) {
|
||||
// rows、err 保存用户范围商品查询结果及错误。
|
||||
|
||||
@@ -146,13 +146,13 @@ func TestMigrate_UpgradesDatabaseWithMainChatVersions(t *testing.T) {
|
||||
if !tableExists(t, rawDB, "chat_quick_replies") || !tableExists(t, rawDB, "chat_buyer_notes") {
|
||||
t.Fatal("chat quick reply and buyer note tables should be created by the latest migration")
|
||||
}
|
||||
// finalVersion 验证迁移账本已推进到包含聊天元数据的最新 dev schema 版本。
|
||||
// finalVersion 验证迁移账本已推进到包含 API 发货策略的最新 dev schema 版本。
|
||||
finalVersion, versionErr := goose.GetDBVersion(rawDB)
|
||||
if versionErr != nil {
|
||||
t.Fatalf("read final migration version: %v", versionErr)
|
||||
}
|
||||
if finalVersion != 36 {
|
||||
t.Fatalf("final migration version=%d, want 36", finalVersion)
|
||||
if finalVersion != 37 {
|
||||
t.Fatalf("final migration version=%d, want 37", finalVersion)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ CREATE TABLE ai_bargain_quotes (
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
CONSTRAINT fk_ai_bargain_quotes_cookie FOREIGN KEY (cookie_id) REFERENCES cookies(id) ON DELETE CASCADE,
|
||||
UNIQUE KEY uq_ai_bargain_quotes_order (cookie_id, order_id),
|
||||
KEY idx_ai_bargain_quotes_pending (cookie_id, buyer_id, item_id, chat_id, status, expires_at, id)
|
||||
KEY idx_ai_bargain_quotes_pending (cookie_id(64), buyer_id(64), item_id(64), chat_id(64), status, expires_at, id)
|
||||
);
|
||||
|
||||
-- +goose Down
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
-- +goose Up
|
||||
INSERT INTO system_settings (`key`, value, description)
|
||||
VALUES ('outbound_http_public_only', 'false', '是否限制用户配置的 HTTP 出站请求只能访问公网地址')
|
||||
ON DUPLICATE KEY UPDATE `key`=`key`;
|
||||
-- +goose Down
|
||||
DELETE FROM system_settings WHERE `key` = 'outbound_http_public_only';
|
||||
@@ -0,0 +1,6 @@
|
||||
-- +goose Up
|
||||
INSERT INTO "system_settings" ("key", value, description)
|
||||
VALUES ('outbound_http_public_only', 'false', '是否限制用户配置的 HTTP 出站请求只能访问公网地址')
|
||||
ON CONFLICT ("key") DO NOTHING;
|
||||
-- +goose Down
|
||||
DELETE FROM "system_settings" WHERE "key" = 'outbound_http_public_only';
|
||||
@@ -0,0 +1,5 @@
|
||||
-- +goose Up
|
||||
INSERT OR IGNORE INTO system_settings (key, value, description)
|
||||
VALUES ('outbound_http_public_only', 'false', '是否限制用户配置的 HTTP 出站请求只能访问公网地址');
|
||||
-- +goose Down
|
||||
DELETE FROM system_settings WHERE key = 'outbound_http_public_only';
|
||||
+52
-19
@@ -4,6 +4,7 @@ import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -364,20 +365,22 @@ func (i *Items) AllTitles(ctx context.Context) (map[string]string, error) {
|
||||
|
||||
// CardFull 卡券完整信息(CRUD 用)。
|
||||
type CardFull struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
APIConfig string `json:"api_config"`
|
||||
TextContent string `json:"text_content"`
|
||||
DataContent string `json:"data_content"`
|
||||
ImageURL string `json:"image_url"`
|
||||
Description string `json:"description"`
|
||||
Enabled bool `json:"enabled"`
|
||||
DelaySeconds int `json:"delay_seconds"`
|
||||
IsMultiSpec bool `json:"is_multi_spec"`
|
||||
SpecName string `json:"spec_name"`
|
||||
SpecValue string `json:"spec_value"`
|
||||
UserID int64 `json:"user_id"`
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Type string `json:"type"`
|
||||
APIConfig string `json:"api_config"`
|
||||
// APIConfigSummary 是脱敏查询路径使用的摘要;数据库层不会把完整模板交给上层。
|
||||
APIConfigSummary *CardAPIConfigSummary `json:"-"`
|
||||
TextContent string `json:"text_content"`
|
||||
DataContent string `json:"data_content"`
|
||||
ImageURL string `json:"image_url"`
|
||||
Description string `json:"description"`
|
||||
Enabled bool `json:"enabled"`
|
||||
DelaySeconds int `json:"delay_seconds"`
|
||||
IsMultiSpec bool `json:"is_multi_spec"`
|
||||
SpecName string `json:"spec_name"`
|
||||
SpecValue string `json:"spec_value"`
|
||||
UserID int64 `json:"user_id"`
|
||||
}
|
||||
|
||||
// ExistsOwned 判断卡密组是否属于指定用户。
|
||||
@@ -410,7 +413,9 @@ func (c *Cards) Get(ctx context.Context, cardID int64) (*CardFull, error) {
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
cf.APIConfig = apiCfg.String
|
||||
if cf.APIConfig, err = c.decryptAPIConfig(cf.Type, cf.UserID, apiCfg.String); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cf.TextContent = textContent.String
|
||||
cf.DataContent = dataContent.String
|
||||
cf.ImageURL = imageURL.String
|
||||
@@ -447,7 +452,9 @@ func (c *Cards) AllForUser(ctx context.Context, userID int64) ([]CardFull, error
|
||||
&enabled, &cf.DelaySeconds, &isMultiSpec, &specName, &specValue, &cf.UserID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cf.APIConfig = apiCfg.String
|
||||
if cf.APIConfig, err = c.decryptAPIConfig(cf.Type, cf.UserID, apiCfg.String); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cf.TextContent = textContent.String
|
||||
cf.DataContent = dataContent.String
|
||||
cf.ImageURL = imageURL.String
|
||||
@@ -463,28 +470,54 @@ func (c *Cards) AllForUser(ctx context.Context, userID int64) ([]CardFull, error
|
||||
|
||||
// Create 创建卡券,返回新 ID。
|
||||
func (c *Cards) Create(ctx context.Context, cf *CardFull) (int64, error) {
|
||||
// apiConfig 保存写入数据库前按用户所有权加密后的 API 请求模板。
|
||||
apiConfig, err := c.encryptAPIConfig(cf.Type, cf.UserID, cf.APIConfig)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return insertReturningID(ctx, c.DB, c.Dialect,
|
||||
`INSERT INTO cards (name, type, api_config, text_content, data_content, image_url, description,
|
||||
enabled, delay_seconds, is_multi_spec, spec_name, spec_value, user_id)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
cf.Name, cf.Type, nullable(cf.APIConfig), nullable(cf.TextContent), nullable(cf.DataContent),
|
||||
cf.Name, cf.Type, nullable(apiConfig), nullable(cf.TextContent), nullable(cf.DataContent),
|
||||
nullable(cf.ImageURL), nullable(cf.Description), boolToInt(cf.Enabled), cf.DelaySeconds,
|
||||
boolToInt(cf.IsMultiSpec), nullable(cf.SpecName), nullable(cf.SpecValue), cf.UserID)
|
||||
}
|
||||
|
||||
// Update 更新卡券。
|
||||
func (c *Cards) Update(ctx context.Context, cf *CardFull) error {
|
||||
// apiConfig 保存更新写入数据库前按用户所有权加密后的 API 请求模板。
|
||||
apiConfig, err := c.encryptAPIConfig(cf.Type, cf.UserID, cf.APIConfig)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// err 用于本次流程后续判断的err
|
||||
_, err := c.DB.ExecContext(ctx,
|
||||
_, err = c.DB.ExecContext(ctx,
|
||||
`UPDATE cards SET name=?, type=?, api_config=?, text_content=?, data_content=?, image_url=?,
|
||||
description=?, enabled=?, delay_seconds=?, is_multi_spec=?, spec_name=?, spec_value=?, updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=?`,
|
||||
cf.Name, cf.Type, nullable(cf.APIConfig), nullable(cf.TextContent), nullable(cf.DataContent),
|
||||
cf.Name, cf.Type, nullable(apiConfig), nullable(cf.TextContent), nullable(cf.DataContent),
|
||||
nullable(cf.ImageURL), nullable(cf.Description), boolToInt(cf.Enabled), cf.DelaySeconds,
|
||||
boolToInt(cf.IsMultiSpec), nullable(cf.SpecName), nullable(cf.SpecValue), cf.ID)
|
||||
return err
|
||||
}
|
||||
|
||||
// encryptAPIConfig 仅对 API 卡券的完整请求模板做静态加密,其他卡券类型保持原有存储语义。
|
||||
func (c *Cards) encryptAPIConfig(cardType string, userID int64, value string) (string, error) {
|
||||
if strings.ToLower(strings.TrimSpace(cardType)) != "api" || strings.TrimSpace(value) == "" {
|
||||
return value, nil
|
||||
}
|
||||
return c.codec.encrypt(cardAPIConfigScope, fmt.Sprint(userID), value)
|
||||
}
|
||||
|
||||
// decryptAPIConfig 读取完整 API 卡券配置;数据库密钥错误时拒绝继续执行自动化。
|
||||
func (c *Cards) decryptAPIConfig(cardType string, userID int64, value string) (string, error) {
|
||||
if strings.ToLower(strings.TrimSpace(cardType)) != "api" || strings.TrimSpace(value) == "" {
|
||||
return value, nil
|
||||
}
|
||||
return c.codec.decrypt(cardAPIConfigScope, fmt.Sprint(userID), value)
|
||||
}
|
||||
|
||||
// Delete 删除卡券。
|
||||
func (c *Cards) Delete(ctx context.Context, cardID int64) error {
|
||||
// err 用于本次流程后续判断的err
|
||||
|
||||
+11
-156
@@ -19,6 +19,7 @@ import (
|
||||
const (
|
||||
encryptedValuePrefix = "enc:v1:"
|
||||
cookieMetadataScope = "cookie-metadata"
|
||||
cardAPIConfigScope = "card-api-config"
|
||||
)
|
||||
|
||||
// secretCodec 对数据库敏感字段做 AES-256-GCM 信封加密。未配置密钥时保持
|
||||
@@ -95,173 +96,27 @@ func (s *Store) EncryptLegacySecrets(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
defer tx.Rollback()
|
||||
// cookieSecret 用于本次流程后续判断的登录凭证Secret
|
||||
type cookieSecret struct{ id, value, password, metadata string }
|
||||
// rows、err 用于本次流程后续判断的rows、err
|
||||
rows, err := tx.QueryContext(ctx, `SELECT id,value,COALESCE(password,''),COALESCE(metadata_json,'') FROM cookies`)
|
||||
if err != nil {
|
||||
// err 表示历史账号秘密迁移错误。
|
||||
if err := migrateLegacyCookies(ctx, tx, codec); err != nil {
|
||||
return err
|
||||
}
|
||||
// cookies 用于本次流程后续判断的cookies
|
||||
var cookies []cookieSecret
|
||||
for rows.Next() {
|
||||
// row 用于本次流程后续判断的row
|
||||
var row cookieSecret
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Scan(&row.id, &row.value, &row.password, &row.metadata); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
cookies = append(cookies, row)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Close(); err != nil {
|
||||
// err 表示历史账号令牌迁移错误。
|
||||
if err := migrateLegacyTokens(ctx, tx, codec); err != nil {
|
||||
return err
|
||||
}
|
||||
// row 表示当前遍历过程中的row
|
||||
for _, row := range cookies {
|
||||
// value、err 用于本次流程后续判断的value、err
|
||||
value, err := codec.encrypt("cookie", row.id, row.value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("校验账号 %s Cookie: %w", row.id, err)
|
||||
}
|
||||
// password、err 用于本次流程后续判断的password、err
|
||||
password, err := codec.encrypt("login-password", row.id, row.password)
|
||||
if err != nil {
|
||||
return fmt.Errorf("校验账号 %s 登录密码: %w", row.id, err)
|
||||
}
|
||||
// metadata、err 用于本次流程后续判断的metadata、err
|
||||
metadata, err := codec.encrypt(cookieMetadataScope, row.id, row.metadata)
|
||||
if err != nil {
|
||||
return fmt.Errorf("校验账号 %s Cookie metadata: %w", row.id, err)
|
||||
}
|
||||
if value != row.value || password != row.password || metadata != row.metadata {
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := tx.ExecContext(ctx, `UPDATE cookies SET value=?,password=?,metadata_json=? WHERE id=?`, value, password, metadata, row.id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
// tokenSecret 用于本次流程后续判断的令牌Secret
|
||||
type tokenSecret struct{ cookieID, deviceID, accessToken string }
|
||||
rows, err = tx.QueryContext(ctx, `SELECT cookie_id,device_id,access_token FROM account_tokens`)
|
||||
if err != nil {
|
||||
// err 表示历史敏感系统设置迁移错误。
|
||||
if err := migrateLegacySettings(ctx, tx, codec, s.Dialect); err != nil {
|
||||
return err
|
||||
}
|
||||
// tokens 用于本次流程后续判断的tokens
|
||||
var tokens []tokenSecret
|
||||
for rows.Next() {
|
||||
// row 用于本次流程后续判断的row
|
||||
var row tokenSecret
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Scan(&row.cookieID, &row.deviceID, &row.accessToken); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
tokens = append(tokens, row)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Close(); err != nil {
|
||||
// err 表示历史通知渠道迁移错误。
|
||||
if err := migrateLegacyNotificationChannels(ctx, tx, codec); err != nil {
|
||||
return err
|
||||
}
|
||||
// row 表示当前遍历过程中的row
|
||||
for _, row := range tokens {
|
||||
// deviceID、err 用于本次流程后续判断的deviceID、err
|
||||
deviceID, err := codec.encrypt("device-id", row.cookieID, row.deviceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// accessToken、err 用于本次流程后续判断的accessToken、err
|
||||
accessToken, err := codec.encrypt("access-token", row.cookieID, row.accessToken)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if deviceID != row.deviceID || accessToken != row.accessToken {
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := tx.ExecContext(ctx, `UPDATE account_tokens SET device_id=?,access_token=? WHERE cookie_id=?`, deviceID, accessToken, row.cookieID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// keyCol 用于本次流程后续判断的keyCol
|
||||
keyCol := dialectQuote(s.Dialect, "key")
|
||||
rows, err = tx.QueryContext(ctx, `SELECT `+keyCol+`,value FROM system_settings`)
|
||||
if err != nil {
|
||||
// err 表示历史 API 卡券配置迁移错误。
|
||||
if err := migrateLegacyCardAPIConfigs(ctx, tx, codec); err != nil {
|
||||
return err
|
||||
}
|
||||
// settings 用于本次流程后续判断的设置
|
||||
settings := make(map[string]string)
|
||||
for rows.Next() {
|
||||
// key、value 用于本次流程后续判断的key、value
|
||||
var key, value string
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Scan(&key, &value); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
if isSensitiveSettingKey(key) {
|
||||
settings[key] = value
|
||||
}
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
// key、value 表示当前遍历过程中的key、value
|
||||
for key, value := range settings {
|
||||
// encrypted、err 用于本次流程后续判断的encrypted、err
|
||||
encrypted, err := codec.encrypt("system-setting", key, value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if encrypted != value {
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := tx.ExecContext(ctx, `UPDATE system_settings SET value=? WHERE `+keyCol+`=?`, encrypted, key); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// channelSecret 用于本次流程后续判断的渠道Secret
|
||||
type channelSecret struct {
|
||||
id, userID int64
|
||||
config string
|
||||
}
|
||||
rows, err = tx.QueryContext(ctx, `SELECT id,COALESCE(user_id,1),config FROM notification_channels`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// channels 用于本次流程后续判断的渠道列表
|
||||
var channels []channelSecret
|
||||
for rows.Next() {
|
||||
// row 用于本次流程后续判断的row
|
||||
var row channelSecret
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Scan(&row.id, &row.userID, &row.config); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
channels = append(channels, row)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Close(); err != nil {
|
||||
return err
|
||||
}
|
||||
// row 表示当前遍历过程中的row
|
||||
for _, row := range channels {
|
||||
// encrypted、err 用于本次流程后续判断的encrypted、err
|
||||
encrypted, err := codec.encrypt("notification-config", fmt.Sprint(row.userID), row.config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if encrypted != row.config {
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := tx.ExecContext(ctx, `UPDATE notification_channels SET config=? WHERE id=?`, encrypted, row.id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// legacyCardAPIConfig 保存待迁移 API 卡券的所属用户和完整请求模板。
|
||||
type legacyCardAPIConfig struct {
|
||||
// id 是 API 卡券数据库主键。
|
||||
id int64
|
||||
// userID 是卡券所属用户,用于绑定加密附加数据。
|
||||
userID int64
|
||||
// config 是尚未迁移或待校验的完整配置文本。
|
||||
config string
|
||||
}
|
||||
|
||||
// migrateLegacyCardAPIConfigs 在启动事务中迁移并校验历史 API 卡券配置。
|
||||
func migrateLegacyCardAPIConfigs(ctx context.Context, tx *sql.Tx, codec *secretCodec) error {
|
||||
// rows、err 保存 API 卡券迁移查询游标及查询错误。
|
||||
rows, err := tx.QueryContext(ctx, `SELECT id,user_id,COALESCE(api_config,'') FROM cards WHERE type='api' AND api_config IS NOT NULL AND api_config<>''`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
// cards 保存需要迁移或校验的 API 卡券配置。
|
||||
var cards []legacyCardAPIConfig
|
||||
for rows.Next() {
|
||||
// row 保存当前 API 卡券的持久化敏感字段。
|
||||
var row legacyCardAPIConfig
|
||||
// err 表示当前 API 卡券敏感字段扫描错误。
|
||||
if err := rows.Scan(&row.id, &row.userID, &row.config); err != nil {
|
||||
return err
|
||||
}
|
||||
cards = append(cards, row)
|
||||
}
|
||||
// err 表示查询游标遍历过程中的错误。
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
// row 表示当前需要加密或校验的 API 卡券配置。
|
||||
for _, row := range cards {
|
||||
// encrypted、err 保存 API 配置密文及加密错误。
|
||||
encrypted, err := codec.encrypt(cardAPIConfigScope, fmt.Sprint(row.userID), row.config)
|
||||
if err != nil {
|
||||
return fmt.Errorf("校验卡券 %d API 配置: %w", row.id, err)
|
||||
}
|
||||
if encrypted != row.config {
|
||||
// err 表示回写 API 卡券密文时的数据库错误。
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE cards SET api_config=? WHERE id=?`, encrypted, row.id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// legacyCookieSecret 保存历史账号凭证和登录元数据,迁移时只在事务内部使用。
|
||||
type legacyCookieSecret struct {
|
||||
// id 是账号稳定标识。
|
||||
id string
|
||||
// value 是闲鱼 Cookie 或其密文。
|
||||
value string
|
||||
// password 是密码登录秘密或其密文。
|
||||
password string
|
||||
// metadata 是账号登录元数据或其密文。
|
||||
metadata string
|
||||
}
|
||||
|
||||
// migrateLegacyCookies 加密并校验历史账号 Cookie、密码和登录元数据。
|
||||
func migrateLegacyCookies(ctx context.Context, tx *sql.Tx, codec *secretCodec) error {
|
||||
// rows、err 保存账号秘密查询游标及查询错误。
|
||||
rows, err := tx.QueryContext(ctx, `SELECT id,value,COALESCE(password,''),COALESCE(metadata_json,'') FROM cookies`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
// cookies 保存待迁移的账号秘密。
|
||||
var cookies []legacyCookieSecret
|
||||
for rows.Next() {
|
||||
// row 保存当前账号的全部敏感字段。
|
||||
var row legacyCookieSecret
|
||||
// err 表示账号秘密扫描错误。
|
||||
if err := rows.Scan(&row.id, &row.value, &row.password, &row.metadata); err != nil {
|
||||
return err
|
||||
}
|
||||
cookies = append(cookies, row)
|
||||
}
|
||||
// err 表示账号秘密查询游标遍历错误。
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
// row 表示当前需要加密或校验的账号秘密。
|
||||
for _, row := range cookies {
|
||||
// value、err 保存 Cookie 密文及加密错误。
|
||||
value, err := codec.encrypt("cookie", row.id, row.value)
|
||||
if err != nil {
|
||||
return fmt.Errorf("校验账号 %s Cookie: %w", row.id, err)
|
||||
}
|
||||
// password、err 保存登录密码密文及加密错误。
|
||||
password, err := codec.encrypt("login-password", row.id, row.password)
|
||||
if err != nil {
|
||||
return fmt.Errorf("校验账号 %s 登录密码: %w", row.id, err)
|
||||
}
|
||||
// metadata、err 保存登录元数据密文及加密错误。
|
||||
metadata, err := codec.encrypt(cookieMetadataScope, row.id, row.metadata)
|
||||
if err != nil {
|
||||
return fmt.Errorf("校验账号 %s Cookie metadata: %w", row.id, err)
|
||||
}
|
||||
if value != row.value || password != row.password || metadata != row.metadata {
|
||||
// err 表示回写账号敏感字段时的数据库错误。
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE cookies SET value=?,password=?,metadata_json=? WHERE id=?`, value, password, metadata, row.id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// legacyTokenSecret 保存历史账号令牌,迁移时只在事务内部使用。
|
||||
type legacyTokenSecret struct {
|
||||
// cookieID 是令牌所属账号标识。
|
||||
cookieID string
|
||||
// deviceID 是设备标识或其密文。
|
||||
deviceID string
|
||||
// accessToken 是访问令牌或其密文。
|
||||
accessToken string
|
||||
}
|
||||
|
||||
// migrateLegacyTokens 加密并校验历史账号设备标识和访问令牌。
|
||||
func migrateLegacyTokens(ctx context.Context, tx *sql.Tx, codec *secretCodec) error {
|
||||
// rows、err 保存令牌查询游标及查询错误。
|
||||
rows, err := tx.QueryContext(ctx, `SELECT cookie_id,device_id,access_token FROM account_tokens`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
// tokens 保存待迁移的账号令牌。
|
||||
var tokens []legacyTokenSecret
|
||||
for rows.Next() {
|
||||
// row 保存当前账号令牌。
|
||||
var row legacyTokenSecret
|
||||
// err 表示账号令牌扫描错误。
|
||||
if err := rows.Scan(&row.cookieID, &row.deviceID, &row.accessToken); err != nil {
|
||||
return err
|
||||
}
|
||||
tokens = append(tokens, row)
|
||||
}
|
||||
// err 表示账号令牌查询游标遍历错误。
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
// row 表示当前需要加密或校验的账号令牌。
|
||||
for _, row := range tokens {
|
||||
// deviceID、err 保存设备标识密文及加密错误。
|
||||
deviceID, err := codec.encrypt("device-id", row.cookieID, row.deviceID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// accessToken、err 保存访问令牌密文及加密错误。
|
||||
accessToken, err := codec.encrypt("access-token", row.cookieID, row.accessToken)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if deviceID != row.deviceID || accessToken != row.accessToken {
|
||||
// err 表示回写账号令牌时的数据库错误。
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE account_tokens SET device_id=?,access_token=? WHERE cookie_id=?`, deviceID, accessToken, row.cookieID); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// migrateLegacySettings 加密并校验历史敏感系统设置。
|
||||
func migrateLegacySettings(ctx context.Context, tx *sql.Tx, codec *secretCodec, dialect Dialect) error {
|
||||
// keyCol 是当前数据库方言的设置键列引用。
|
||||
keyCol := dialectQuote(dialect, "key")
|
||||
// rows、err 保存系统设置查询游标及查询错误。
|
||||
rows, err := tx.QueryContext(ctx, `SELECT `+keyCol+`,value FROM system_settings`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
// settings 保存需要迁移的敏感设置。
|
||||
settings := make(map[string]string)
|
||||
for rows.Next() {
|
||||
// key、value 保存当前系统设置键和值。
|
||||
var key, value string
|
||||
// err 表示系统设置扫描错误。
|
||||
if err := rows.Scan(&key, &value); err != nil {
|
||||
return err
|
||||
}
|
||||
if isSensitiveSettingKey(key) {
|
||||
settings[key] = value
|
||||
}
|
||||
}
|
||||
// err 表示系统设置查询游标遍历错误。
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
// key、value 表示当前需要迁移的敏感设置。
|
||||
for key, value := range settings {
|
||||
// encrypted、err 保存设置密文及加密错误。
|
||||
encrypted, err := codec.encrypt("system-setting", key, value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if encrypted != value {
|
||||
// err 表示回写系统设置时的数据库错误。
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE system_settings SET value=? WHERE `+keyCol+`=?`, encrypted, key); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// legacyNotificationChannel 保存历史通知渠道的所属用户和完整配置。
|
||||
type legacyNotificationChannel struct {
|
||||
// id 是渠道数据库主键。
|
||||
id int64
|
||||
// userID 是渠道所属用户。
|
||||
userID int64
|
||||
// config 是渠道配置或其密文。
|
||||
config string
|
||||
}
|
||||
|
||||
// migrateLegacyNotificationChannels 加密并校验历史通知渠道配置。
|
||||
func migrateLegacyNotificationChannels(ctx context.Context, tx *sql.Tx, codec *secretCodec) error {
|
||||
// rows、err 保存通知渠道查询游标及查询错误。
|
||||
rows, err := tx.QueryContext(ctx, `SELECT id,COALESCE(user_id,1),config FROM notification_channels`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
// channels 保存待迁移的通知渠道。
|
||||
var channels []legacyNotificationChannel
|
||||
for rows.Next() {
|
||||
// row 保存当前通知渠道的敏感字段。
|
||||
var row legacyNotificationChannel
|
||||
// err 表示通知渠道扫描错误。
|
||||
if err := rows.Scan(&row.id, &row.userID, &row.config); err != nil {
|
||||
return err
|
||||
}
|
||||
channels = append(channels, row)
|
||||
}
|
||||
// err 表示通知渠道查询游标遍历错误。
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
// row 表示当前需要加密或校验的通知渠道。
|
||||
for _, row := range channels {
|
||||
// encrypted、err 保存渠道密文及加密错误。
|
||||
encrypted, err := codec.encrypt("notification-config", fmt.Sprint(row.userID), row.config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if encrypted != row.config {
|
||||
// err 表示回写通知渠道配置时的数据库错误。
|
||||
if _, err := tx.ExecContext(ctx, `UPDATE notification_channels SET config=? WHERE id=?`, encrypted, row.id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -363,6 +363,16 @@ func TestEncryptLegacySecretsUpgradesPlaintextAndValidatesKey(t *testing.T) {
|
||||
_, err := store.DB.ExecContext(ctx, `INSERT INTO cookies (id,value,user_id,password) VALUES (?,?,?,?)`, "legacy-secret", "legacy-cookie", owner.ID, "legacy-password"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// cardResult、cardInsertErr 保存插入历史明文 API 卡券配置的结果。
|
||||
cardResult, cardInsertErr := store.DB.ExecContext(ctx, `INSERT INTO cards (name,type,api_config,user_id) VALUES (?,?,?,?)`, "legacy-api", "api", `{"url":"https://example.com","headers":{"Authorization":"legacy-card-secret"}}`, owner.ID)
|
||||
if cardInsertErr != nil {
|
||||
t.Fatal(cardInsertErr)
|
||||
}
|
||||
// cardID 保存需要启动迁移的历史 API 卡券标识。
|
||||
cardID, cardIDErr := cardResult.LastInsertId()
|
||||
if cardIDErr != nil {
|
||||
t.Fatal(cardIDErr)
|
||||
}
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := store.EncryptLegacySecrets(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -376,6 +386,20 @@ func TestEncryptLegacySecretsUpgradesPlaintextAndValidatesKey(t *testing.T) {
|
||||
if !strings.HasPrefix(raw, encryptedValuePrefix) {
|
||||
t.Fatalf("legacy value was not upgraded: %q", raw)
|
||||
}
|
||||
// cardRaw 保存 API 卡券数据库中的原始配置,确认请求模板没有以明文留存。
|
||||
var cardRaw string
|
||||
// err 表示读取 API 卡券密文时的数据库错误。
|
||||
if err := store.DB.QueryRowContext(ctx, `SELECT api_config FROM cards WHERE id=?`, cardID).Scan(&cardRaw); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.HasPrefix(cardRaw, encryptedValuePrefix) || strings.Contains(cardRaw, "legacy-card-secret") {
|
||||
t.Fatalf("legacy API config was not encrypted: %q", cardRaw)
|
||||
}
|
||||
// card、cardErr 保存专用完整读取路径解密后的 API 配置。
|
||||
card, cardErr := store.Cards.Get(ctx, cardID)
|
||||
if cardErr != nil || card == nil || !strings.Contains(card.APIConfig, "legacy-card-secret") {
|
||||
t.Fatalf("API config decrypt failed card=%+v err=%v", card, cardErr)
|
||||
}
|
||||
// wrongCodec 用于本次流程后续判断的wrongCodec
|
||||
wrongCodec, _ := newSecretCodec("wrong-key")
|
||||
// wrongStore 用于本次流程后续判断的wrongStore
|
||||
|
||||
@@ -80,7 +80,7 @@ func NewStore(db *sql.DB, dialect Dialect) *Store {
|
||||
Sessions: &Sessions{DB: db},
|
||||
Cookies: &Cookies{DB: db, Dialect: dialect, codec: codec},
|
||||
Items: items,
|
||||
Cards: &Cards{DB: db, Dialect: dialect},
|
||||
Cards: &Cards{DB: db, Dialect: dialect, codec: codec},
|
||||
Automation: &AutomationRules{DB: db, Dialect: dialect},
|
||||
Orders: orders,
|
||||
OrderWrites: newOrderWriteUnitOfWork(db, orders, items),
|
||||
|
||||
@@ -28,7 +28,7 @@ const (
|
||||
|
||||
// newAIHTTPClient 用于本次流程后续判断的newAIHTTPClient
|
||||
var newAIHTTPClient = func(baseURL string) (*http.Client, error) {
|
||||
return netguard.TrustedEndpointHTTPClient(baseURL, 30*time.Second)
|
||||
return netguard.ConfiguredEndpointHTTPClient(baseURL, 30*time.Second)
|
||||
}
|
||||
|
||||
// AIReplierImpl AI 回复实现。
|
||||
|
||||
@@ -343,16 +343,16 @@ func mustRefundTradeCard(t *testing.T) map[string]any {
|
||||
return m
|
||||
}
|
||||
|
||||
// mustPaidDeliveryCard 封装mustPaid发货卡密业务协调。
|
||||
// mustPaidDeliveryCard 构造卖家收到的完整付款待发货卡片,包含自动化防重和订单归属所需的 updateKey。
|
||||
func mustPaidDeliveryCard(t *testing.T) map[string]any {
|
||||
t.Helper()
|
||||
// s 用于本次流程后续判断的s
|
||||
// s 是模拟闲鱼付款系统卡片的 JSON;订单 ID 由 extJson 中的 updateKey 提供。
|
||||
s := "{" +
|
||||
"\"1\":{" +
|
||||
"\"2\":\"63107041124@goofish\"," +
|
||||
"\"10\":{" +
|
||||
"\"bizTag\":\"{\\\"sourceId\\\":\\\"C2C:4Ytd4BSQKIiz\\\",\\\"taskName\\\":\\\"付款完成待发货_卖家-正向升级\\\"}\"," +
|
||||
"\"extJson\":\"{\\\"msgArg1\\\":\\\"MsgCard\\\",\\\"contentType\\\":\\\"26\\\",\\\"messageId\\\":\\\"4e449a32c59c499594c4c5dffa5ddef0\\\"}\"," +
|
||||
"\"extJson\":\"{\\\"msgArg1\\\":\\\"MsgCard\\\",\\\"contentType\\\":\\\"26\\\",\\\"messageId\\\":\\\"4e449a32c59c499594c4c5dffa5ddef0\\\",\\\"updateKey\\\":\\\"63107041124:3310145690545023994:10:TRADE_PAID:26\\\"}\"," +
|
||||
"\"redReminder\":\"等待卖家发货\"," +
|
||||
"\"reminderContent\":\"[我已付款,等待你发货]\"," +
|
||||
"\"senderUserId\":\"2222315258815\"," +
|
||||
|
||||
+160
-4
@@ -5,14 +5,63 @@ import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
// ConfiguredResponseBodyLimit 是用户可配置 HTTP 客户端允许读取的最大响应体大小。
|
||||
const ConfiguredResponseBodyLimit int64 = 10 << 20
|
||||
|
||||
// OutboundPolicy 保存服务端用户可配置 HTTP 请求的公网访问策略。
|
||||
type OutboundPolicy struct {
|
||||
// publicOnly 表示是否只允许解析到公网 IP 的目标地址。
|
||||
publicOnly atomic.Bool
|
||||
}
|
||||
|
||||
// defaultOutboundPolicy 是进程内所有用户可配置 HTTP 客户端共享的策略快照。
|
||||
var defaultOutboundPolicy = NewOutboundPolicy(false)
|
||||
|
||||
// NewOutboundPolicy 创建一个出站访问策略;默认值由调用方明确传入。
|
||||
func NewOutboundPolicy(publicOnly bool) *OutboundPolicy {
|
||||
// policy 保存新建的原子出站策略对象。
|
||||
policy := &OutboundPolicy{}
|
||||
policy.publicOnly.Store(publicOnly)
|
||||
return policy
|
||||
}
|
||||
|
||||
// SetPublicOnly 原子切换是否只允许访问公网地址。
|
||||
func (p *OutboundPolicy) SetPublicOnly(publicOnly bool) {
|
||||
if p != nil {
|
||||
p.publicOnly.Store(publicOnly)
|
||||
}
|
||||
}
|
||||
|
||||
// PublicOnly 返回当前是否启用公网地址限制。
|
||||
func (p *OutboundPolicy) PublicOnly() bool {
|
||||
return p != nil && p.publicOnly.Load()
|
||||
}
|
||||
|
||||
// SetDefaultPublicOnly 更新默认策略,供进程组合根和系统设置保存后调用。
|
||||
func SetDefaultPublicOnly(publicOnly bool) {
|
||||
defaultOutboundPolicy.SetPublicOnly(publicOnly)
|
||||
}
|
||||
|
||||
// DefaultPolicy 返回进程默认出站策略,供组合根注入应用服务而非让仓储修改全局状态。
|
||||
func DefaultPolicy() *OutboundPolicy {
|
||||
return defaultOutboundPolicy
|
||||
}
|
||||
|
||||
// DefaultPublicOnly 返回默认策略当前是否只允许公网地址。
|
||||
func DefaultPublicOnly() bool {
|
||||
return defaultOutboundPolicy.PublicOnly()
|
||||
}
|
||||
|
||||
// nonPublicPrefixes 用于本次流程后续判断的nonPublicPrefixes
|
||||
var nonPublicPrefixes = []netip.Prefix{
|
||||
netip.MustParsePrefix("0.0.0.0/8"), netip.MustParsePrefix("10.0.0.0/8"),
|
||||
@@ -29,15 +78,70 @@ var nonPublicPrefixes = []netip.Prefix{
|
||||
|
||||
// PublicHTTPClient 返回只允许连接公网 IP 的客户端。DNS 与每次重定向都会重新校验。
|
||||
func PublicHTTPClient(timeout time.Duration) *http.Client {
|
||||
// transport 用于本次流程后续判断的transport
|
||||
return policyHTTPClient(NewOutboundPolicy(true), timeout, 10*time.Second, 10*time.Second)
|
||||
}
|
||||
|
||||
// ConfiguredHTTPClient 返回遵循默认运行时策略的用户配置 HTTP 客户端。
|
||||
func ConfiguredHTTPClient(timeout time.Duration) *http.Client {
|
||||
return policyHTTPClient(defaultOutboundPolicy, timeout, 10*time.Second, 10*time.Second)
|
||||
}
|
||||
|
||||
// ConfiguredEndpointHTTPClient 校验用户配置的 HTTP(S) 基础地址并返回策略客户端。
|
||||
func ConfiguredEndpointHTTPClient(rawBaseURL string, timeout time.Duration) (*http.Client, error) {
|
||||
// baseURL、err 保存用户配置地址的解析结果及格式错误。
|
||||
baseURL, err := url.Parse(strings.TrimSpace(rawBaseURL))
|
||||
if err != nil || baseURL.Hostname() == "" {
|
||||
return nil, fmt.Errorf("服务地址无效")
|
||||
}
|
||||
if baseURL.Scheme != "http" && baseURL.Scheme != "https" {
|
||||
return nil, fmt.Errorf("服务地址只支持 http 或 https")
|
||||
}
|
||||
return ConfiguredHTTPClient(timeout), nil
|
||||
}
|
||||
|
||||
// PolicyHTTPClient 返回绑定指定运行时策略的 HTTP 客户端,测试和组合根可使用它隔离全局默认值。
|
||||
func PolicyHTTPClient(policy *OutboundPolicy, timeout time.Duration) *http.Client {
|
||||
if policy == nil {
|
||||
policy = defaultOutboundPolicy
|
||||
}
|
||||
return policyHTTPClient(policy, timeout, 10*time.Second, 10*time.Second)
|
||||
}
|
||||
|
||||
// PolicyHTTPClientWithTimeouts 返回可保留特殊响应头和 TLS 超时约束的策略客户端。
|
||||
func PolicyHTTPClientWithTimeouts(policy *OutboundPolicy, timeout, responseHeaderTimeout, tlsHandshakeTimeout time.Duration) *http.Client {
|
||||
if policy == nil {
|
||||
policy = defaultOutboundPolicy
|
||||
}
|
||||
return policyHTTPClient(policy, timeout, responseHeaderTimeout, tlsHandshakeTimeout)
|
||||
}
|
||||
|
||||
// policyHTTPClient 创建每次连接和重定向都遵循同一公网策略的 HTTP 客户端。
|
||||
func policyHTTPClient(policy *OutboundPolicy, timeout, responseHeaderTimeout, tlsHandshakeTimeout time.Duration) *http.Client {
|
||||
// transport 保存统一出站策略客户端的连接和重定向规则。
|
||||
transport := &http.Transport{
|
||||
Proxy: func(request *http.Request) (*url.URL, error) {
|
||||
if policy.PublicOnly() {
|
||||
return nil, nil
|
||||
}
|
||||
return http.ProxyFromEnvironment(request)
|
||||
},
|
||||
// 禁用连接复用,确保公网开关切换后每个新请求都重新解析并校验目标地址。
|
||||
DisableKeepAlives: true,
|
||||
ForceAttemptHTTP2: false,
|
||||
TLSHandshakeTimeout: tlsHandshakeTimeout,
|
||||
ResponseHeaderTimeout: responseHeaderTimeout,
|
||||
ExpectContinueTimeout: 1 * time.Second,
|
||||
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
return DialPublicContext(ctx, network, address, 10*time.Second)
|
||||
if policy.PublicOnly() {
|
||||
return DialPublicContext(ctx, network, address, 10*time.Second)
|
||||
}
|
||||
// dialer 保存允许内网模式下的普通 TCP 拨号器。
|
||||
dialer := &net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}
|
||||
return dialer.DialContext(ctx, network, address)
|
||||
},
|
||||
TLSHandshakeTimeout: 10 * time.Second,
|
||||
}
|
||||
return &http.Client{
|
||||
Transport: transport,
|
||||
Transport: limitedResponseBodyTransport{base: transport},
|
||||
Timeout: timeout,
|
||||
CheckRedirect: func(req *http.Request, via []*http.Request) error {
|
||||
if len(via) >= 5 {
|
||||
@@ -46,11 +150,63 @@ func PublicHTTPClient(timeout time.Duration) *http.Client {
|
||||
if req.URL.Scheme != "http" && req.URL.Scheme != "https" {
|
||||
return fmt.Errorf("重定向协议不安全")
|
||||
}
|
||||
if len(via) > 0 && req.URL.Host != via[0].URL.Host {
|
||||
return fmt.Errorf("不允许跨主机重定向")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// limitedResponseBody 把用户可配置端点的响应体限制在固定大小以内。
|
||||
type limitedResponseBody struct {
|
||||
// body 是底层远端响应体,关闭责任仍由当前 HTTP 客户端持有。
|
||||
body io.ReadCloser
|
||||
// remaining 是尚未读取的允许字节数。
|
||||
remaining int64
|
||||
}
|
||||
|
||||
// Read 读取响应体并在尝试读取超限内容时返回错误。
|
||||
func (b *limitedResponseBody) Read(p []byte) (int, error) {
|
||||
if b.remaining == 0 {
|
||||
// probe 用于探测底层响应是否仍有超出上限的字节。
|
||||
var probe [1]byte
|
||||
// n、err 保存探测读取的字节数及底层读取结果。
|
||||
n, err := b.body.Read(probe[:])
|
||||
if n > 0 {
|
||||
return 0, errors.New("HTTP 响应超过大小限制")
|
||||
}
|
||||
return 0, err
|
||||
}
|
||||
if int64(len(p)) > b.remaining {
|
||||
p = p[:int(b.remaining)]
|
||||
}
|
||||
// n、err 保存本次受限读取的字节数及底层读取结果。
|
||||
n, err := b.body.Read(p)
|
||||
b.remaining -= int64(n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// Close 关闭底层响应体并释放远端连接资源。
|
||||
func (b *limitedResponseBody) Close() error { return b.body.Close() }
|
||||
|
||||
// limitedResponseBodyTransport 为响应体附加统一大小边界。
|
||||
type limitedResponseBodyTransport struct {
|
||||
// base 是执行 DNS、连接和重定向策略的底层 Transport。
|
||||
base http.RoundTripper
|
||||
}
|
||||
|
||||
// RoundTrip 执行请求并包装远端响应体,不改变状态码和响应头语义。
|
||||
func (t limitedResponseBodyTransport) RoundTrip(req *http.Request) (*http.Response, error) {
|
||||
// response、err 保存底层传输返回的响应和网络错误。
|
||||
response, err := t.base.RoundTrip(req)
|
||||
if err != nil || response == nil || response.Body == nil {
|
||||
return response, err
|
||||
}
|
||||
response.Body = &limitedResponseBody{body: response.Body, remaining: ConfiguredResponseBodyLimit}
|
||||
return response, nil
|
||||
}
|
||||
|
||||
// TrustedEndpointHTTPClient 用于管理员明确配置的集成端点。目标地址完全由管理员
|
||||
// 信任并负责,因此不限制 IP 类型、DNS 结果或 HTTP 重定向;仅校验 HTTP(S) URL。
|
||||
// TrustedEndpointHTTPClient 封装TrustedEndpointHTTPClient业务协调。
|
||||
|
||||
@@ -2,6 +2,7 @@ package netguard
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -99,3 +100,77 @@ func TestTrustedEndpointHTTPClientValidatesBaseURL(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestConfiguredHTTPClientSwitchesRuntimePolicy 验证用户配置 HTTP 客户端可在运行时即时切换公网限制。
|
||||
func TestConfiguredHTTPClientSwitchesRuntimePolicy(t *testing.T) {
|
||||
// server 是本地测试端点,用于代表默认关闭时允许的内网地址。
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
|
||||
writer.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
// policy 是本次测试独立持有的运行时策略。
|
||||
policy := NewOutboundPolicy(false)
|
||||
// allowedClient 是关闭公网限制时创建的策略客户端。
|
||||
allowedClient := PolicyHTTPClient(policy, 0)
|
||||
// allowedResponse、allowedErr 保存关闭公网限制时的本地请求结果。
|
||||
allowedResponse, allowedErr := allowedClient.Get(server.URL)
|
||||
if allowedErr != nil {
|
||||
t.Fatalf("关闭公网限制时本地端点应可访问: %v", allowedErr)
|
||||
}
|
||||
allowedResponse.Body.Close()
|
||||
policy.SetPublicOnly(true)
|
||||
// blockedResponse、blockedErr 保存同一 HTTP 客户端在开启公网限制后的本地请求结果。
|
||||
blockedResponse, blockedErr := allowedClient.Get(server.URL)
|
||||
if blockedResponse != nil {
|
||||
blockedResponse.Body.Close()
|
||||
}
|
||||
if blockedErr == nil {
|
||||
t.Fatal("打开公网限制后回环端点必须被拒绝")
|
||||
}
|
||||
}
|
||||
|
||||
// TestConfiguredHTTPClientRejectsCrossHostRedirect 验证用户配置端点不能借助跳转切换到另一主机。
|
||||
func TestConfiguredHTTPClientRejectsCrossHostRedirect(t *testing.T) {
|
||||
// target 是不应被跨主机跳转访问的第二个本地端点。
|
||||
target := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
|
||||
writer.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
t.Cleanup(target.Close)
|
||||
// redirector 是返回跨主机跳转响应的第一个本地端点。
|
||||
redirector := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
|
||||
http.Redirect(writer, request, target.URL, http.StatusFound)
|
||||
}))
|
||||
t.Cleanup(redirector.Close)
|
||||
// client 是使用独立运行时策略的用户配置客户端。
|
||||
client := PolicyHTTPClient(NewOutboundPolicy(false), 0)
|
||||
// response、err 保存跳转请求的响应和错误。
|
||||
response, err := client.Get(redirector.URL)
|
||||
if response != nil {
|
||||
response.Body.Close()
|
||||
}
|
||||
// errText 保存跳转错误的非敏感文本,用于稳定断言拒绝原因。
|
||||
if err == nil || !strings.Contains(err.Error(), "不允许跨主机重定向") {
|
||||
t.Fatalf("跨主机跳转应被拒绝 response=%v err=%v", response, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestConfiguredHTTPClientLimitsResponseBody 验证统一用户配置客户端拒绝超出响应体上限的内容。
|
||||
func TestConfiguredHTTPClientLimitsResponseBody(t *testing.T) {
|
||||
// server 是返回刚好超过统一响应上限的本地端点。
|
||||
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = writer.Write(make([]byte, ConfiguredResponseBodyLimit+1))
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
// client 是使用关闭公网限制的用户配置客户端。
|
||||
client := PolicyHTTPClient(NewOutboundPolicy(false), 0)
|
||||
// response、err 保存读取超大响应的结果。
|
||||
response, err := client.Get(server.URL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
// err 表示读取超大响应时返回的大小限制错误。
|
||||
if _, err := io.ReadAll(response.Body); err == nil {
|
||||
t.Fatal("超大响应应返回大小限制错误")
|
||||
}
|
||||
}
|
||||
@@ -58,7 +58,7 @@ type Notifier struct {
|
||||
}
|
||||
|
||||
// newOutboundHTTPClient 用于本次流程后续判断的newOutboundHTTPClient
|
||||
var newOutboundHTTPClient = func() *http.Client { return netguard.PublicHTTPClient(10 * time.Second) }
|
||||
var newOutboundHTTPClient = func() *http.Client { return netguard.ConfiguredHTTPClient(10 * time.Second) }
|
||||
|
||||
// dialPublicSMTP 用于本次流程后续判断的dialPublicSMTP
|
||||
var dialPublicSMTP = netguard.DialPublicContext
|
||||
|
||||
@@ -302,6 +302,11 @@ type CardsPort interface {
|
||||
AppendData(context.Context, int64, int64, string) (int, error)
|
||||
}
|
||||
|
||||
// APIRequestTesterPort 定义卡券 API 测试请求所需的最小应用能力。
|
||||
type APIRequestTesterPort interface {
|
||||
Test(context.Context, cardsapp.APIRequestTestInput) (cardsapp.APIRequestTestResult, error)
|
||||
}
|
||||
|
||||
// DefaultRepliesPort 定义默认回复配置能力。
|
||||
type DefaultRepliesPort interface {
|
||||
Get(context.Context, int64, string) (defaultreplyapp.Reply, error)
|
||||
@@ -415,6 +420,8 @@ type ApplicationPorts struct {
|
||||
automationRules AutomationRulesPort
|
||||
// cards 是卡券库存用例。
|
||||
cards CardsPort
|
||||
// apiRequestTester 执行临时 API 测试请求并返回非敏感诊断。
|
||||
apiRequestTester APIRequestTesterPort
|
||||
// publishAutomationRules 是发布后自动化规则用例。
|
||||
publishAutomationRules PublishAutomationRulesPort
|
||||
// defaultReplies 是默认回复用例。
|
||||
@@ -462,6 +469,7 @@ type ApplicationPortsInput struct {
|
||||
AutomationIssues AutomationIssuesPort
|
||||
AutomationRules AutomationRulesPort
|
||||
Cards CardsPort
|
||||
APIRequestTester APIRequestTesterPort
|
||||
PublishAutomationRules PublishAutomationRulesPort
|
||||
DefaultReplies DefaultRepliesPort
|
||||
Keywords KeywordsPort
|
||||
@@ -484,7 +492,7 @@ func NewApplicationPorts(input ApplicationPortsInput) *ApplicationPorts {
|
||||
accountSummaries: input.AccountSummaries, accountTasks: input.AccountTasks, chat: input.Chat,
|
||||
uncertainNotifications: input.UncertainNotifications, notificationChannels: input.NotificationChannels,
|
||||
analytics: input.Analytics, automationIssues: input.AutomationIssues, automationRules: input.AutomationRules,
|
||||
cards: input.Cards, publishAutomationRules: input.PublishAutomationRules, defaultReplies: input.DefaultReplies,
|
||||
cards: input.Cards, apiRequestTester: input.APIRequestTester, publishAutomationRules: input.PublishAutomationRules, defaultReplies: input.DefaultReplies,
|
||||
keywords: input.Keywords, settings: input.Settings, admin: input.Admin,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -241,8 +241,8 @@ func TestAutomationRuleBadActionType(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutomationRuleRejectsAPICard 封装Test自动化规则RejectsAPI卡密业务协调。
|
||||
func TestAutomationRuleRejectsAPICard(t *testing.T) {
|
||||
// TestAutomationRuleAcceptsAPICard 验证已配置的 API 卡券可以加入自动化规则。
|
||||
func TestAutomationRuleAcceptsAPICard(t *testing.T) {
|
||||
// srv、store、cleanup 用于本次流程后续判断的srv、store、cleanup
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
@@ -265,7 +265,7 @@ func TestAutomationRuleRejectsAPICard(t *testing.T) {
|
||||
// rec 用于本次流程后续判断的rec
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "API 卡密暂不支持") {
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,13 +89,9 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
|
||||
continue
|
||||
}
|
||||
switch cardType {
|
||||
case "text", "data", "image":
|
||||
case "api":
|
||||
results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "API 卡密暂不支持自动发货,不能新建"})
|
||||
failed++
|
||||
continue
|
||||
case "text", "data", "image", "api":
|
||||
default:
|
||||
results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "类型必须为 text/data/image"})
|
||||
results = append(results, cardBatchResultRow{RowNo: rowNo, Success: false, Name: name, Type: cardType, Error: "类型必须为 text/data/image/api"})
|
||||
failed++
|
||||
continue
|
||||
}
|
||||
@@ -132,6 +128,8 @@ func (s *Server) batchCreateCards(w http.ResponseWriter, r *http.Request) {
|
||||
draft.TextContent = content
|
||||
case "data":
|
||||
draft.DataContent = content
|
||||
case "api":
|
||||
draft.APIConfig = content
|
||||
case "image":
|
||||
draft.ImageURL = content
|
||||
}
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
package server
|
||||
|
||||
import cardsapp "xianyu-go/internal/application/cards"
|
||||
|
||||
// apiCardConfigResponse 是 API 卡券查询接口的脱敏响应 DTO。
|
||||
type apiCardConfigResponse struct {
|
||||
// URL 是固定的 HTTP(S) 请求地址,不包含请求凭据。
|
||||
URL string `json:"url"`
|
||||
// Method 是 GET 或 POST。
|
||||
Method string `json:"method"`
|
||||
// TimeoutSeconds 是单次 API 请求超时秒数。
|
||||
TimeoutSeconds int `json:"timeout_seconds"`
|
||||
// ContentType 是 POST 请求正文的 Content-Type。
|
||||
ContentType string `json:"content_type"`
|
||||
// ResponsePath 是可选的响应提取路径。
|
||||
ResponsePath string `json:"response_path,omitempty"`
|
||||
// RetryEnabled 表示是否启用带幂等键的暂时性失败重试。
|
||||
RetryEnabled bool `json:"retry_enabled"`
|
||||
// HeadersConfigured 表示服务端是否保存了请求头模板,但不返回模板内容。
|
||||
HeadersConfigured bool `json:"headers_configured"`
|
||||
// ParamsConfigured 表示服务端是否保存了请求参数模板,但不返回模板内容。
|
||||
ParamsConfigured bool `json:"params_configured"`
|
||||
// Ready 表示当前配置可被规则选择和自动化执行。
|
||||
Ready bool `json:"ready"`
|
||||
// ValidationError 保存脱敏后的配置校验错误。
|
||||
ValidationError string `json:"validation_error,omitempty"`
|
||||
}
|
||||
|
||||
// newCardResponse 将应用层卡券模型转换为 HTTP DTO。
|
||||
func newCardResponse(card cardsapp.Card) cardResponse {
|
||||
// apiConfig 是仅对 API 卡券生成的脱敏配置摘要。
|
||||
var apiConfig *apiCardConfigResponse
|
||||
if card.Type == "api" {
|
||||
// summary 保存应用层校验后的非敏感 API 配置状态。
|
||||
var summary cardsapp.APIConfigSummary
|
||||
if card.APIConfigSummary != nil {
|
||||
summary = *card.APIConfigSummary
|
||||
} else {
|
||||
summary = cardsapp.SummarizeAPIConfig(card.APIConfig)
|
||||
}
|
||||
apiConfig = &apiCardConfigResponse{
|
||||
URL: summary.URL, Method: summary.Method, TimeoutSeconds: summary.TimeoutSeconds, ContentType: summary.ContentType,
|
||||
ResponsePath: summary.ResponsePath, RetryEnabled: summary.RetryEnabled,
|
||||
HeadersConfigured: summary.HeadersConfigured, ParamsConfigured: summary.ParamsConfigured,
|
||||
Ready: summary.Ready, ValidationError: summary.ValidationError,
|
||||
}
|
||||
}
|
||||
return cardResponse{
|
||||
ID: card.ID, Name: card.Name, Type: card.Type, APIConfig: apiConfig,
|
||||
TextContent: card.TextContent, DataContent: card.DataContent, ImageURL: card.ImageURL,
|
||||
Description: card.Description, Enabled: card.Enabled, DelaySeconds: card.DelaySeconds,
|
||||
IsMultiSpec: card.IsMultiSpec, SpecName: card.SpecName, SpecValue: card.SpecValue, UserID: card.UserID,
|
||||
}
|
||||
}
|
||||
|
||||
// newCardResponses 批量转换应用层卡券列表,避免 HTTP 层暴露数据库模型。
|
||||
func newCardResponses(cards []cardsapp.Card) []cardResponse {
|
||||
// result 是转换后的卡券 DTO 列表。
|
||||
result := make([]cardResponse, 0, len(cards))
|
||||
// card 是当前待转换的卡券应用模型。
|
||||
for _, card := range cards {
|
||||
result = append(result, newCardResponse(card))
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
@@ -17,8 +19,8 @@ type cardMutationRequest struct {
|
||||
Name string `json:"name"`
|
||||
// Type 是 text、data、image 或历史兼容的 api 类型。
|
||||
Type string `json:"type"`
|
||||
// APIConfig 是历史 API 卡券配置文本。
|
||||
APIConfig string `json:"api_config"`
|
||||
// APIConfig 同时接收新版具名对象和历史完整 JSON 字符串。
|
||||
APIConfig json.RawMessage `json:"api_config"`
|
||||
// TextContent 是 text 类型自动发货时发送的文本内容。
|
||||
TextContent string `json:"text_content"`
|
||||
// DataContent 是 data 类型尚未消费的逐行卡密库存。
|
||||
@@ -45,10 +47,33 @@ type cardAppendRequest struct {
|
||||
Content string `json:"content"`
|
||||
}
|
||||
|
||||
// cardAPITestRequest 是临时 API 测试请求的具名 DTO。
|
||||
type cardAPITestRequest struct {
|
||||
// APIConfig 是与卡券保存接口一致的 API 配置对象或历史 JSON 字符串。
|
||||
APIConfig json.RawMessage `json:"api_config"`
|
||||
}
|
||||
|
||||
// cardAPITestResponse 是临时 API 测试结果的具名脱敏 DTO。
|
||||
type cardAPITestResponse struct {
|
||||
// Status 表示远端请求是否成功。
|
||||
Status string `json:"status"`
|
||||
// StatusCode 是远端 HTTP 状态码。
|
||||
StatusCode int `json:"status_code"`
|
||||
// ResponseContentType 是远端响应媒体类型。
|
||||
ResponseContentType string `json:"response_content_type"`
|
||||
// ResponseFields 是 JSON 顶层字段名称。
|
||||
ResponseFields []string `json:"response_fields"`
|
||||
// ExtractedValue 是按配置路径提取的值。
|
||||
ExtractedValue string `json:"extracted_value,omitempty"`
|
||||
// ResponsePreview 是限长响应预览。
|
||||
ResponsePreview string `json:"response_preview,omitempty"`
|
||||
}
|
||||
|
||||
// mountCardsReal 挂载卡券 CRUD、批量创建和库存追加路由;发货规则由 automation_rules 负责。
|
||||
func (s *Server) mountCardsReal(r chi.Router) {
|
||||
r.Get("/cards", s.listCards)
|
||||
r.Post("/cards", s.createCard)
|
||||
r.Post("/cards/test-api", s.testCardAPI)
|
||||
r.Post("/cards/batch", s.batchCreateCards)
|
||||
r.Post("/cards/{card_id}/append-data", s.appendCardData)
|
||||
r.Get("/cards/{card_id}/details", s.getCard)
|
||||
@@ -57,6 +82,34 @@ func (s *Server) mountCardsReal(r chi.Router) {
|
||||
r.Delete("/cards/{card_id}", s.deleteCard)
|
||||
}
|
||||
|
||||
// testCardAPI 发送一次临时 API 请求并返回状态、字段和提取结果诊断。
|
||||
func (s *Server) testCardAPI(w http.ResponseWriter, r *http.Request) {
|
||||
if s.applications == nil || s.applications.apiRequestTester == nil {
|
||||
writeErr(w, http.StatusServiceUnavailable, "API 测试服务不可用")
|
||||
return
|
||||
}
|
||||
// request 是当前 API 测试请求的具名 HTTP DTO。
|
||||
var request cardAPITestRequest
|
||||
// err 是当前请求 JSON 解码错误,不包含用户填写的敏感模板值。
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
// config、err 分别是可供应用 Port 解析的配置文本和兼容解码错误。
|
||||
config, err := decodeCardAPIConfig(request.APIConfig)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
// result、err 分别是临时远端调用的脱敏诊断和本地配置或网络错误。
|
||||
result, err := s.applications.apiRequestTester.Test(r.Context(), cardsapp.APIRequestTestInput{Config: config})
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, cardAPITestResponse{Status: result.Status, StatusCode: result.StatusCode, ResponseContentType: result.ResponseContentType, ResponseFields: result.ResponseFields, ExtractedValue: result.ExtractedValue, ResponsePreview: result.ResponsePreview})
|
||||
}
|
||||
|
||||
// listCards 将认证用户交给应用服务,并把卡券应用模型转换为 HTTP DTO。
|
||||
func (s *Server) listCards(w http.ResponseWriter, r *http.Request) {
|
||||
// session 是认证中间件注入的当前用户会话。
|
||||
@@ -110,8 +163,6 @@ func (s *Server) createCard(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case errors.As(err, &validationError):
|
||||
writeErr(w, http.StatusBadRequest, validationError.Error())
|
||||
case errors.Is(err, cardsapp.ErrUnsupportedAPIType):
|
||||
writeErr(w, http.StatusBadRequest, "API 卡密暂不支持自动发货,不能新建")
|
||||
default:
|
||||
writeErr(w, http.StatusInternalServerError, "创建失败")
|
||||
}
|
||||
@@ -144,8 +195,6 @@ func (s *Server) updateCard(w http.ResponseWriter, r *http.Request) {
|
||||
switch {
|
||||
case errors.As(err, &validationError):
|
||||
writeErr(w, http.StatusBadRequest, validationError.Error())
|
||||
case errors.Is(err, cardsapp.ErrUnsupportedAPIType):
|
||||
writeErr(w, http.StatusBadRequest, "API 卡密暂不支持自动发货,不能转换为该类型")
|
||||
case errors.Is(err, cardsapp.ErrNotFound) || errors.Is(err, cardsapp.ErrInvalidCardID):
|
||||
writeErr(w, http.StatusNotFound, "卡券不存在")
|
||||
case errors.Is(err, cardsapp.ErrForbidden):
|
||||
@@ -192,14 +241,49 @@ func decodeCardDraft(r *http.Request) (cardsapp.Draft, error) {
|
||||
if err := decodeJSON(r, &request); err != nil {
|
||||
return cardsapp.Draft{}, err
|
||||
}
|
||||
// apiConfig、apiConfigErr 保存兼容解码后的 API 配置文本及格式错误。
|
||||
apiConfig, apiConfigErr := decodeCardAPIConfig(request.APIConfig)
|
||||
if apiConfigErr != nil {
|
||||
return cardsapp.Draft{}, apiConfigErr
|
||||
}
|
||||
return cardsapp.Draft{
|
||||
Name: request.Name, Type: request.Type, APIConfig: request.APIConfig,
|
||||
Name: request.Name, Type: request.Type, APIConfig: apiConfig,
|
||||
TextContent: request.TextContent, DataContent: request.DataContent, ImageURL: request.ImageURL,
|
||||
Description: request.Description, Enabled: request.Enabled, DelaySeconds: request.DelaySeconds,
|
||||
IsMultiSpec: request.IsMultiSpec, SpecName: request.SpecName, SpecValue: request.SpecValue,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// decodeCardAPIConfig 兼容历史字符串配置,并把新版对象保持为 JSON 文本交给应用服务校验。
|
||||
func decodeCardAPIConfig(raw json.RawMessage) (string, error) {
|
||||
// trimmed 保存去除空白后的请求字段。
|
||||
trimmed := bytes.TrimSpace(raw)
|
||||
if len(trimmed) == 0 || bytes.Equal(trimmed, []byte("null")) {
|
||||
return "", nil
|
||||
}
|
||||
if trimmed[0] == '"' {
|
||||
// legacy 保存旧客户端提交的完整 JSON 字符串。
|
||||
var legacy string
|
||||
// err 表示历史字符串字段解码错误。
|
||||
if err := json.Unmarshal(trimmed, &legacy); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return legacy, nil
|
||||
}
|
||||
// object 保存新版具名 API 配置对象的字段。
|
||||
var object map[string]json.RawMessage
|
||||
// err 表示新版 API 配置对象解码错误。
|
||||
if err := json.Unmarshal(trimmed, &object); err != nil {
|
||||
return "", err
|
||||
}
|
||||
// encoded、err 保存新版 API 配置对象的规范 JSON 和编码错误。
|
||||
encoded, err := json.Marshal(object)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(encoded), nil
|
||||
}
|
||||
|
||||
// writeCardReadError 将详情查询的应用错误映射为既有 HTTP 状态和统一错误响应。
|
||||
func writeCardReadError(w http.ResponseWriter, err error) {
|
||||
switch {
|
||||
|
||||
@@ -198,5 +198,48 @@ func TestCardCRUD(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestCardAPIDTOIsRedacted 验证 API 卡券支持具名配置请求,响应只返回脱敏摘要而不回显模板秘密。
|
||||
func TestCardAPIDTOIsRedacted(t *testing.T) {
|
||||
// srv、cleanup 保存契约测试服务器及其清理函数。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// handler 是本次测试使用的完整路由处理器。
|
||||
handler := srv.Router()
|
||||
// cookie 是已认证管理员会话。
|
||||
cookie := loginHelper(t, handler)
|
||||
// request 是提交请求头和参数模板的新版 API 卡请求。
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/cards", strings.NewReader(`{"name":"API 脱敏卡","type":"api","api_config":{"url":"https://example.com/card","method":"POST","timeout_seconds":10,"headers":{"Authorization":"Bearer super-secret"},"params":{"code":"{order_id}"},"response_path":"data.card.code"},"enabled":true}`))
|
||||
request.AddCookie(cookie)
|
||||
// response 保存创建请求的 HTTP 响应。
|
||||
response := httptest.NewRecorder()
|
||||
handler.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("API 卡创建失败 status=%d body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
// listRequest 是读取卡券摘要的请求。
|
||||
listRequest := httptest.NewRequest(http.MethodGet, "/api/v1/cards", nil)
|
||||
listRequest.AddCookie(cookie)
|
||||
// listResponse 保存卡券列表响应。
|
||||
listResponse := httptest.NewRecorder()
|
||||
handler.ServeHTTP(listResponse, listRequest)
|
||||
if listResponse.Code != http.StatusOK {
|
||||
t.Fatalf("API 卡列表失败 status=%d body=%s", listResponse.Code, listResponse.Body.String())
|
||||
}
|
||||
// rows 保存脱敏卡券列表。
|
||||
var rows []map[string]any
|
||||
// err 表示脱敏卡券列表 JSON 解码错误。
|
||||
if err := json.Unmarshal(listResponse.Body.Bytes(), &rows); err != nil || len(rows) != 1 {
|
||||
t.Fatalf("API 卡列表格式错误 rows=%v err=%v", rows, err)
|
||||
}
|
||||
// summary 保存响应中的 API 脱敏摘要。
|
||||
summary, ok := rows[0]["api_config"].(map[string]any)
|
||||
if !ok || summary["ready"] != true || summary["url"] != "https://example.com/card" {
|
||||
t.Fatalf("API 卡摘要错误: %+v", rows[0]["api_config"])
|
||||
}
|
||||
if strings.Contains(listResponse.Body.String(), "super-secret") || strings.Contains(listResponse.Body.String(), "Authorization") {
|
||||
t.Fatalf("API 卡响应泄漏敏感模板: %s", listResponse.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// itoa 封装itoa业务协调。
|
||||
func itoa(n int64) string { return strconv.FormatInt(n, 10) }
|
||||
@@ -207,7 +207,7 @@ func downloadImageURL(ctx context.Context, rawURL string) ([]byte, string, error
|
||||
|
||||
// publicHTTPClient 只允许连接公网地址,防止批量铺货图片 URL 访问本机或内网服务。
|
||||
func publicHTTPClient() *http.Client {
|
||||
return netguard.PublicHTTPClient(30 * time.Second)
|
||||
return netguard.ConfiguredHTTPClient(30 * time.Second)
|
||||
}
|
||||
|
||||
// validateBatchImageRef 封装validate批次图片Ref业务协调。
|
||||
|
||||
@@ -197,7 +197,15 @@ func validateSystemSettingValues(values map[string]string) error {
|
||||
if level, ok := values["log_level"]; ok {
|
||||
// err 是日志级别解析错误。
|
||||
_, err := logging.ParseLevel(level)
|
||||
return err
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
// raw、ok 保存公网限制设置的原始值及是否包含该字段。
|
||||
if raw, ok := values["outbound_http_public_only"]; ok {
|
||||
if !strings.EqualFold(strings.TrimSpace(raw), "true") && !strings.EqualFold(strings.TrimSpace(raw), "false") {
|
||||
return errors.New("outbound_http_public_only 必须是布尔值")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -273,12 +281,16 @@ func (s *Server) setSetting(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
if key == "log_level" {
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := logging.SetLevel(req.Value); err != nil {
|
||||
// err 表示单项日志级别校验错误。
|
||||
if _, err := logging.ParseLevel(req.Value); err != nil {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
}
|
||||
if key == "outbound_http_public_only" && !strings.EqualFold(strings.TrimSpace(req.Value), "true") && !strings.EqualFold(strings.TrimSpace(req.Value), "false") {
|
||||
writeErr(w, http.StatusBadRequest, "outbound_http_public_only 必须是布尔值")
|
||||
return
|
||||
}
|
||||
// sess 保存当前管理员会话,用于应用服务执行普通设置写入。
|
||||
sess := authSess(r)
|
||||
if sess == nil {
|
||||
@@ -290,6 +302,9 @@ func (s *Server) setSetting(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusInternalServerError, "保存失败")
|
||||
return
|
||||
}
|
||||
if key == "log_level" {
|
||||
_ = logging.SetLevel(req.Value)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, operationResponse{Success: true})
|
||||
}
|
||||
|
||||
|
||||
@@ -9,9 +9,18 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
cardsapp "xianyu-go/internal/application/cards"
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// apiRequestTesterStub 是卡券 API 测试请求的确定性替身,避免 OpenAPI 契约测试访问真实远端地址。
|
||||
type apiRequestTesterStub struct{}
|
||||
|
||||
// Test 返回固定的非敏感测试诊断结果。
|
||||
func (apiRequestTesterStub) Test(context.Context, cardsapp.APIRequestTestInput) (cardsapp.APIRequestTestResult, error) {
|
||||
return cardsapp.APIRequestTestResult{Status: "success", StatusCode: http.StatusOK, ResponseContentType: "application/json", ResponseFields: []string{"code", "data"}, ExtractedValue: "TEST-CODE", ResponsePreview: `{"data":{"code":"TEST-CODE"}}`}, nil
|
||||
}
|
||||
|
||||
// TestNamedSuccessResponseContracts 验证认证、订单和聊天主链路使用具名成功响应 DTO。
|
||||
func TestNamedSuccessResponseContracts(t *testing.T) {
|
||||
// srv 是用于验证成功响应 DTO 的 HTTP 测试服务。
|
||||
@@ -198,6 +207,8 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
|
||||
defer cleanup()
|
||||
// handler 是当前测试使用的完整路由树。
|
||||
handler := contractRecordingHandler(t, srv.Router())
|
||||
// apiRequestTester 使用确定性替身验证 HTTP DTO 和 OpenAPI 响应契约。
|
||||
srv.applications.apiRequestTester = apiRequestTesterStub{}
|
||||
// sessionCookie 是管理员登录后得到的认证会话。
|
||||
sessionCookie := loginHelper(t, handler)
|
||||
|
||||
@@ -277,6 +288,25 @@ func TestSettingsCardsNotificationsBatchContracts(t *testing.T) {
|
||||
t.Fatalf("card response=%+v", cardCreateResponse)
|
||||
}
|
||||
|
||||
// apiTestReq 是使用临时卡券配置执行 API 测试的版本化请求。
|
||||
apiTestReq := httptest.NewRequest(http.MethodPost, "/api/v1/cards/test-api", strings.NewReader(`{"api_config":{"url":"https://example.com/test","method":"GET","timeout_seconds":10}}`))
|
||||
apiTestReq.AddCookie(sessionCookie)
|
||||
// apiTestRecorder 捕获测试请求的具名诊断响应。
|
||||
apiTestRecorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(apiTestRecorder, apiTestReq)
|
||||
if apiTestRecorder.Code != http.StatusOK {
|
||||
t.Fatalf("api test status=%d body=%s", apiTestRecorder.Code, apiTestRecorder.Body.String())
|
||||
}
|
||||
// apiTestResponse 是 API 测试响应 DTO。
|
||||
var apiTestResponse cardAPITestResponse
|
||||
// apiTestDecodeErr 是 API 测试响应解码失败原因。
|
||||
if apiTestDecodeErr := json.Unmarshal(apiTestRecorder.Body.Bytes(), &apiTestResponse); apiTestDecodeErr != nil {
|
||||
t.Fatalf("decode api test response: %v", apiTestDecodeErr)
|
||||
}
|
||||
if apiTestResponse.Status != "success" || apiTestResponse.StatusCode != http.StatusOK || apiTestResponse.ExtractedValue != "TEST-CODE" {
|
||||
t.Fatalf("api test response=%+v", apiTestResponse)
|
||||
}
|
||||
|
||||
// cardGetReq 是读取卡券详情的请求。
|
||||
cardGetReq := httptest.NewRequest(http.MethodGet, "/api/v1/cards/"+strconv.FormatInt(cardCreateResponse.ID, 10), nil)
|
||||
cardGetReq.AddCookie(sessionCookie)
|
||||
|
||||
@@ -3,7 +3,6 @@ package server
|
||||
import (
|
||||
"encoding/json"
|
||||
|
||||
cardsapp "xianyu-go/internal/application/cards"
|
||||
defaultreplyapp "xianyu-go/internal/application/defaultreply"
|
||||
notificationsapp "xianyu-go/internal/application/notifications"
|
||||
)
|
||||
@@ -46,8 +45,8 @@ type cardResponse struct {
|
||||
Name string `json:"name"`
|
||||
// Type 是卡券类型。
|
||||
Type string `json:"type"`
|
||||
// APIConfig 是 API 卡券配置 JSON。
|
||||
APIConfig string `json:"api_config"`
|
||||
// APIConfig 是不含请求头、参数和密钥的 API 配置摘要;非 API 卡券省略该字段。
|
||||
APIConfig *apiCardConfigResponse `json:"api_config,omitempty"`
|
||||
// TextContent 是文本卡券内容。
|
||||
TextContent string `json:"text_content"`
|
||||
// DataContent 是批量数据卡券内容。
|
||||
@@ -70,27 +69,6 @@ type cardResponse struct {
|
||||
UserID int64 `json:"user_id,omitempty"`
|
||||
}
|
||||
|
||||
// newCardResponse 将应用层卡券模型转换为 HTTP DTO。
|
||||
func newCardResponse(card cardsapp.Card) cardResponse {
|
||||
return cardResponse{
|
||||
ID: card.ID, Name: card.Name, Type: card.Type, APIConfig: card.APIConfig,
|
||||
TextContent: card.TextContent, DataContent: card.DataContent, ImageURL: card.ImageURL,
|
||||
Description: card.Description, Enabled: card.Enabled, DelaySeconds: card.DelaySeconds,
|
||||
IsMultiSpec: card.IsMultiSpec, SpecName: card.SpecName, SpecValue: card.SpecValue, UserID: card.UserID,
|
||||
}
|
||||
}
|
||||
|
||||
// newCardResponses 批量转换应用层卡券列表,避免 HTTP 层暴露数据库模型。
|
||||
func newCardResponses(cards []cardsapp.Card) []cardResponse {
|
||||
// result 是转换后的卡券 DTO 列表。
|
||||
result := make([]cardResponse, 0, len(cards))
|
||||
// card 是当前待转换的卡券应用模型。
|
||||
for _, card := range cards {
|
||||
result = append(result, newCardResponse(card))
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// cardBatchResponse 是卡券批量创建接口的具名响应 DTO。
|
||||
type cardBatchResponse struct {
|
||||
// Success 表示批量解析和处理流程已完成。
|
||||
|
||||
@@ -37,6 +37,7 @@ func (s *Server) mountVersionedSettingsCardNotificationRoutes(r chi.Router) {
|
||||
|
||||
r.Get("/api/v1/cards", s.listCards)
|
||||
r.Post("/api/v1/cards", s.createCard)
|
||||
r.Post("/api/v1/cards/test-api", s.testCardAPI)
|
||||
r.Post("/api/v1/cards/batch", s.batchCreateCards)
|
||||
r.Post("/api/v1/cards/{card_id}/append-data", s.appendCardData)
|
||||
r.Get("/api/v1/cards/{card_id}/details", s.getCard)
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
import{b as ie,j as e,a as l,d as Me}from"./react-vendor-Bf9ELcll.js";import{r as q,c as L}from"./chat-metadata-74T0w35U.js";import{c as Ae,o as Pe}from"./contract-COFcZjyb.js";import{r as de,X as ce,h as Be,L as H,s as Te,t as Ge,u as Oe,v as qe,w as Le,U as Ie,x as te,y as ze,m as _e,Q as we,z as Ee,R as We,H as Ve,I as Je,T as Ne,K as Ke,J as He,N as Xe,g as Ye,O as Ze}from"./icons-vendor-BSp7PTZg.js";import"./vendor-BE-_xUHH.js";const Fe=(a,s)=>{const t=a.avatar_url||"";if(!t)return"";try{const r=new URL(t,window.location.origin);return r.hostname.endsWith("alicdn.com")&&r.searchParams.set("_v",s),r.toString()}catch{return t}},es=async a=>{const s=await q(n=>L.GET("/api/v1/accounts/details",{signal:n}),a),t=Ae(s,["data","accounts","details"]),r=Date.now().toString();return t.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,r),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(a,s)=>q(t=>L.GET("/api/v1/account-tasks/{cid}",{params:{path:{cid:a}},signal:t}),s),ke=async(a,s,t)=>q(r=>L.PUT("/api/v1/account-tasks/{cid}",{params:{path:{cid:a}},body:s,signal:r}),t),ss=async(a,s,t)=>q(r=>L.POST("/api/v1/account-tasks/{cid}/run",{params:{path:{cid:a}},body:{task_type:s},signal:r}),{timeoutMs:12e4,...t}),as=async a=>await q(t=>L.GET("/api/v1/accounts/runtime-status",{signal:t}),a),ts=async a=>q(s=>L.POST("/api/v1/qr-login/generate",{signal:s}),{...a,timeoutMs:(a==null?void 0:a.timeoutMs)??13e4}),rs=async(a,s)=>q(t=>L.GET("/api/v1/qr-login/check/{session_id}",{params:{path:{session_id:a}},signal:t}),{signal:s,timeoutMs:1e4}),ns=async(a,s)=>q(t=>L.POST("/api/v1/qr-login/complete-verification/{session_id}",{params:{path:{session_id:a}},body:{target_account_id:s||""},signal:t})),ls=async(a,s)=>q(t=>L.PUT("/api/v1/accounts/{cid}/status",{params:{path:{cid:a}},body:{enabled:s},signal:t})),os=async a=>q(s=>L.DELETE("/api/v1/accounts/{cid}",{params:{path:{cid:a}},signal:s})),is=async(a,s,t)=>q(r=>L.PUT("/api/v1/accounts/{cid}/pause-duration",{params:{path:{cid:a}},body:{pause_duration:s},signal:r}),t),cs=async(a,s,t)=>q(r=>L.PUT("/api/v1/accounts/{cid}/settings",{params:{path:{cid:a}},body:s,signal:r}),t),ds=async(a,s)=>q(t=>L.GET("/api/v1/accounts/{cid}/long-login",{params:{path:{cid:a}},signal:t}),s),us=async(a,s,t)=>q(r=>L.PUT("/api/v1/accounts/{cid}/long-login",{params:{path:{cid:a}},body:{enabled:s},signal:r}),t),xs=async(a,s)=>q(t=>L.POST("/api/v1/password-login",{body:a,signal:t}),s),ms=async(a,s)=>q(r=>L.GET("/api/v1/password-login/check/{session_id}",{params:{path:{session_id:a}},signal:r}),{signal:s,timeoutMs:1e4}),bs=async(a,s)=>q(t=>L.DELETE("/api/v1/password-login/cancel/{session_id}",{params:{path:{session_id:a}},signal:t}),s),hs=async a=>q(s=>L.POST("/api/v1/accounts/{cid}/refresh-profile",{params:{path:{cid:a}},signal:s})),gs=async a=>{const s=await q(t=>L.GET("/api/v1/settings/ai-reply",{signal:t}),a);return Pe(s,["settings","data","result"])||{}},ps=async(a,s)=>q(t=>L.GET("/api/v1/settings/ai-reply/{cookie_id}",{params:{path:{cookie_id:a}},signal:t}),s),fs=async(a,s,t)=>{const r={ai_enabled:s.ai_enabled??!1,auto_adjust_price_enabled:s.auto_adjust_price_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 q(n=>L.PUT("/api/v1/settings/ai-reply/{cookie_id}",{params:{path:{cookie_id:a}},body:r,signal:n}),t)},ys=a=>{if(Array.isArray(a))return a.filter(Boolean);if(typeof a!="string"||!a.trim())return[];try{const s=JSON.parse(a);if(Array.isArray(s))return s.filter(Boolean)}catch{}return a.split(/[,\s;]+/).map(s=>s.trim()).filter(Boolean)},js=async a=>{const s=await q(r=>L.GET("/api/v1/notifications/channels",{signal:r}),a);return{success:!0,data:Ae(s,["data","channels","items"]).map(r=>{const n={},c=r.type==="ding_talk"?"dingtalk":r.type==="lark"?"feishu":r.type;return{id:String(r.id),name:r.name,type:c,config:n,event_types:ys(r.event_types),enabled:r.enabled}})}},_s=async(a,s)=>{const t=await q(n=>L.GET("/api/v1/notifications/accounts/{cid}/bindings",{params:{path:{cid:a}},signal:n}),s),r=Pe(t,["data","result"])||{};return Array.isArray(r.channel_ids)?r.channel_ids:[]},ws=({account:a,settings:s,saving:t,onChange:r,onClose:n,onSave:c})=>{const i=y=>r({...s,...y}),d=()=>i(Line truncated
|
||||
import{b as ie,j as e,a as l,d as Me}from"./react-vendor-Bf9ELcll.js";import{r as q,c as L}from"./chat-metadata-CxFNzZmJ.js";import{c as Ae,o as Pe}from"./contract-COFcZjyb.js";import{r as de,X as ce,h as Be,L as H,s as Te,t as Ge,u as Oe,v as qe,w as Le,U as Ie,x as te,y as ze,m as _e,Q as we,z as Ee,R as We,H as Ve,I as Je,T as Ne,K as Ke,J as He,N as Xe,g as Ye,O as Ze}from"./icons-vendor-eB2mgMyz.js";import"./vendor-BE-_xUHH.js";const Fe=(a,s)=>{const t=a.avatar_url||"";if(!t)return"";try{const r=new URL(t,window.location.origin);return r.hostname.endsWith("alicdn.com")&&r.searchParams.set("_v",s),r.toString()}catch{return t}},es=async a=>{const s=await q(n=>L.GET("/api/v1/accounts/details",{signal:n}),a),t=Ae(s,["data","accounts","details"]),r=Date.now().toString();return t.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,r),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(a,s)=>q(t=>L.GET("/api/v1/account-tasks/{cid}",{params:{path:{cid:a}},signal:t}),s),ke=async(a,s,t)=>q(r=>L.PUT("/api/v1/account-tasks/{cid}",{params:{path:{cid:a}},body:s,signal:r}),t),ss=async(a,s,t)=>q(r=>L.POST("/api/v1/account-tasks/{cid}/run",{params:{path:{cid:a}},body:{task_type:s},signal:r}),{timeoutMs:12e4,...t}),as=async a=>await q(t=>L.GET("/api/v1/accounts/runtime-status",{signal:t}),a),ts=async a=>q(s=>L.POST("/api/v1/qr-login/generate",{signal:s}),{...a,timeoutMs:(a==null?void 0:a.timeoutMs)??13e4}),rs=async(a,s)=>q(t=>L.GET("/api/v1/qr-login/check/{session_id}",{params:{path:{session_id:a}},signal:t}),{signal:s,timeoutMs:1e4}),ns=async(a,s)=>q(t=>L.POST("/api/v1/qr-login/complete-verification/{session_id}",{params:{path:{session_id:a}},body:{target_account_id:s||""},signal:t})),ls=async(a,s)=>q(t=>L.PUT("/api/v1/accounts/{cid}/status",{params:{path:{cid:a}},body:{enabled:s},signal:t})),os=async a=>q(s=>L.DELETE("/api/v1/accounts/{cid}",{params:{path:{cid:a}},signal:s})),is=async(a,s,t)=>q(r=>L.PUT("/api/v1/accounts/{cid}/pause-duration",{params:{path:{cid:a}},body:{pause_duration:s},signal:r}),t),cs=async(a,s,t)=>q(r=>L.PUT("/api/v1/accounts/{cid}/settings",{params:{path:{cid:a}},body:s,signal:r}),t),ds=async(a,s)=>q(t=>L.GET("/api/v1/accounts/{cid}/long-login",{params:{path:{cid:a}},signal:t}),s),us=async(a,s,t)=>q(r=>L.PUT("/api/v1/accounts/{cid}/long-login",{params:{path:{cid:a}},body:{enabled:s},signal:r}),t),xs=async(a,s)=>q(t=>L.POST("/api/v1/password-login",{body:a,signal:t}),s),ms=async(a,s)=>q(r=>L.GET("/api/v1/password-login/check/{session_id}",{params:{path:{session_id:a}},signal:r}),{signal:s,timeoutMs:1e4}),bs=async(a,s)=>q(t=>L.DELETE("/api/v1/password-login/cancel/{session_id}",{params:{path:{session_id:a}},signal:t}),s),hs=async a=>q(s=>L.POST("/api/v1/accounts/{cid}/refresh-profile",{params:{path:{cid:a}},signal:s})),gs=async a=>{const s=await q(t=>L.GET("/api/v1/settings/ai-reply",{signal:t}),a);return Pe(s,["settings","data","result"])||{}},ps=async(a,s)=>q(t=>L.GET("/api/v1/settings/ai-reply/{cookie_id}",{params:{path:{cookie_id:a}},signal:t}),s),fs=async(a,s,t)=>{const r={ai_enabled:s.ai_enabled??!1,auto_adjust_price_enabled:s.auto_adjust_price_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 q(n=>L.PUT("/api/v1/settings/ai-reply/{cookie_id}",{params:{path:{cookie_id:a}},body:r,signal:n}),t)},ys=a=>{if(Array.isArray(a))return a.filter(Boolean);if(typeof a!="string"||!a.trim())return[];try{const s=JSON.parse(a);if(Array.isArray(s))return s.filter(Boolean)}catch{}return a.split(/[,\s;]+/).map(s=>s.trim()).filter(Boolean)},js=async a=>{const s=await q(r=>L.GET("/api/v1/notifications/channels",{signal:r}),a);return{success:!0,data:Ae(s,["data","channels","items"]).map(r=>{const n={},c=r.type==="ding_talk"?"dingtalk":r.type==="lark"?"feishu":r.type;return{id:String(r.id),name:r.name,type:c,config:n,event_types:ys(r.event_types),enabled:r.enabled}})}},_s=async(a,s)=>{const t=await q(n=>L.GET("/api/v1/notifications/accounts/{cid}/bindings",{params:{path:{cid:a}},signal:n}),s),r=Pe(t,["data","result"])||{};return Array.isArray(r.channel_ids)?r.channel_ids:[]},ws=({account:a,settings:s,saving:t,onChange:r,onClose:n,onSave:c})=>{const i=y=>r({...s,...y}),d=()=>i(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:t,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:t,children:[t?e.jsx(H,{className:"w-4 h-4 animate-spin"}):e.jsx(Te,{className:"w-4 h-4"}),t?"保存中...":"保存"]})]})})]})}),document.body)},Ce=a=>({account_id:a.id,auto_rate_enabled:a.auto_rate_enabled===!0,rate_content:a.rate_content||"不错的买家,交易愉快",auto_polish_enabled:a.auto_polish_enabled===!0,polish_time:a.polish_time||"03:00",last_rate_scan_at:a.last_rate_scan_at,last_polish_date:a.last_polish_date,last_polish_at:a.last_polish_at}),Z=(a,s,t)=>a===s&&!t.aborted,ye=(a,s)=>a instanceof Error?a.message:s,je=a=>a instanceof Error&&a.message==="请求已取消",Se=(a,s)=>!a&&s==="",Ns=({account:a,onSaved:s})=>{const[t,r]=l.useState(()=>Ce(a)),[n,c]=l.useState(!0),[i,d]=l.useState(!1),[m,x]=l.useState(""),[f,b]=l.useState(""),[h,y]=l.useState(null),[C,g]=l.useState(null),p=l.useRef(0),I=l.useRef(null);l.useEffect(()=>{var v;const R=++p.current;(v=I.current)==null||v.abort();const _=new AbortController;return I.current=_,r(Ce(a)),y(null),b(""),d(!1),x(""),g(null),c(!0),ve(a.id,{signal:_.signal}).then(A=>{Z(p.current,R,_.signal)&&r(A)}).catch(A=>{Z(p.current,R,_.signal)&&!je(A)&&b(ye(A,"加载任务设置失败"))}).finally(()=>{Z(p.current,R,_.signal)&&c(!1)}),(()=>_.abort())},[a.id]),l.useEffect(()=>(()=>{var R;return(R=I.current)==null?void 0:R.abort()}),[]);const B=l.useCallback(async()=>{var v;if(!Se(i,m))return;const R=++p.current;(v=I.current)==null||v.abort();const _=new AbortController;I.current=_,d(!0),b(""),g(null);try{const A=await ke(a.id,t,{signal:_.signal});if(!Z(p.current,R,_.signal))return;r(A),s(A)}catch(A){Z(p.current,R,_.signal)&&!je(A)&&(b(ye(A,"保存失败")),g(()=>B))}finally{Z(p.current,R,_.signal)&&d(!1)}},[a.id,t,s,m,i]),G=l.useCallback(async R=>{var A;if(!Se(i,m)||!a.enabled)return;const _=++p.current;(A=I.current)==null||A.abort();const v=new AbortController;I.current=v,x(R),b(""),y(null),g(null);try{await ke(a.id,t,{signal:v.signal});const N=await ss(a.id,R,{signal:v.signal}),P=await ve(a.id,{signal:v.signal});if(!Z(p.current,_,v.signal))return;y(N.summary),r(P),s(P)}catch(N){Z(p.current,_,v.signal)&&!je(N)&&(b(ye(N,"任务执行失败")),g(()=>(()=>G(R))))}finally{Z(p.current,_,v.signal)&&x("")}},[a.enabled,a.id,t,s,m,i]),D=l.useCallback(async()=>{C&&await C()},[C]);return{form:t,loading:n,saving:i,running:m,summary:h,error:f,retryAvailable:C!==null,setForm:r,save:B,run:G,retry:D}},Re=({checked:a,onChange:s,label:t})=>e.jsx("button",{type:"button","aria-label":t,"aria-pressed":a,onClick:s,className:`relative h-8 w-14 shrink-0 rounded-full transition-colors ${a?"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 ${a?"translate-x-6":""}`})}),vs=({account:a,onClose:s,onSaved:t})=>{const{form:r,loading:n,saving:c,running:i,error:d,summary:m,retryAvailable:x,setForm:f,save:b,run:h,retry:y}=Ns({account:a,onSaved:t});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:a.nickname||a.remark||a.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",{
Line truncated
|
||||
@@ -1,17 +0,0 @@
|
||||
import{a as c,b as U,j as e}from"./react-vendor-Bf9ELcll.js";import{r as M,c as O,b as ee}from"./chat-metadata-74T0w35U.js";import{c as te}from"./contract-COFcZjyb.js";import{X as V,$ as ae,W as z,a0 as se,L as q,P as J,e as X,a1 as le,a2 as K,a3 as Q,a4 as ne,V as re,a5 as oe,_ as ce,T as ie,o as de,s as xe}from"./icons-vendor-BSp7PTZg.js";import"./vendor-BE-_xUHH.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}},Y=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:Y(l),signal:n})),H=async(l,n)=>M(a=>O.PUT("/api/v1/cards/{card_id}",{params:{path:{card_id:String(l)}},body:Y(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(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: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(Q,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(K,{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:(()=>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(Q,{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=>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};
|
||||
@@ -0,0 +1,19 @@
|
||||
import{a as d,j as e,b as H}from"./react-vendor-Bf9ELcll.js";import{r as O,c as M,b as ie}from"./chat-metadata-CxFNzZmJ.js";import{c as ce}from"./contract-COFcZjyb.js";import{L as W,u as de,P as G,T as se,X as K,$ as pe,W as J,a0 as xe,e as ne,a1 as me,a2 as re,a3 as le,a4 as he,V as ue,a5 as be,_ as ye,o as ge,s as fe,a6 as je}from"./icons-vendor-eB2mgMyz.js";import"./vendor-BE-_xUHH.js";const _e=a=>{let s=a.api_config;if(typeof s=="string"&&s.trim())try{s=JSON.parse(s)}catch{s=void 0}return s&&typeof s=="object"&&s.timeout_seconds===void 0&&s.timeout!==void 0&&(s.timeout_seconds=Number(s.timeout)||10),s&&typeof s=="object"&&!s.content_type&&(s.content_type="application/json"),{...a,api_config:s||void 0}},U=a=>{if(a&&typeof a=="object"&&!Array.isArray(a))return a;if(typeof a!="string"||!a.trim())return;const s=JSON.parse(a);if(!s||typeof s!="object"||Array.isArray(s))throw new Error("请求头和请求参数必须是 JSON 对象");return s},X=a=>({name:a.name,type:a.type,api_config:typeof a.api_config=="string"?a.api_config:a.api_config?{...a.api_config,headers:U(a.api_config.headers),params:U(a.api_config.params),body:U(a.api_config.body),content_type:a.api_config.content_type||"application/json"}:void 0,text_content:a.text_content,data_content:a.data_content,image_url:a.image_url,description:a.description,enabled:a.enabled,delay_seconds:a.delay_seconds,is_multi_spec:a.is_multi_spec,spec_name:a.spec_name,spec_value:a.spec_value}),Ne=async a=>{const s=await O(u=>M.GET("/api/v1/cards",{signal:u}),a);return ce(s,["cards","data","items"]).map(_e)},ve=async a=>O(s=>M.POST("/api/v1/cards",{body:X(a),signal:s})),Q=async(a,s)=>O(n=>M.PUT("/api/v1/cards/{card_id}",{params:{path:{card_id:String(a)}},body:X(s),signal:n})),we=async a=>O(s=>M.DELETE("/api/v1/cards/{card_id}",{params:{path:{card_id:String(a)}},signal:s})),Ce=async(a,s)=>{const n=new FormData;return n.append("file",a),O(u=>M.POST("/api/v1/cards/batch",{body:ie(n),signal:u}),s)},ke=async(a,s,n)=>O(u=>M.POST("/api/v1/cards/{card_id}/append-data",{params:{path:{card_id:String(a)}},body:{content:s},signal:u}),n),Z=async a=>O(s=>M.POST("/api/v1/cards/test-api",{body:{api_config:X({name:"",type:"api",api_config:a}).api_config},signal:s})),Se=(a,s,n)=>{const u=n.trim().toLocaleLowerCase();return a.filter(b=>(!s||b.type===s)&&(!u||b.name.toLocaleLowerCase().includes(u)))},oe=a=>a.split(`
|
||||
`).map(s=>s.trim()).filter(Boolean),Te=(a,s,n)=>!!(a&&oe(s).length>0&&!n),L=(a,s,n,u)=>a===s&&n===u,ee=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:"",api_content_type:"application/json",api_body:"",api_response_path:"",api_retry_enabled:!1}),z=(a,s)=>a instanceof Error?a.message:s,Ae=({cards:a,loadCards:s})=>{const[n,u]=d.useState(!1),[b,_]=d.useState(!1),[j,N]=d.useState(null),[o,v]=d.useState({}),[p,x]=d.useState(ee),[h,f]=d.useState(""),[l,y]=d.useState(""),r=d.useMemo(()=>a.filter(c=>c.type==="data"),[a]),i=d.useMemo(()=>Se(a,h,l),[a,l,h]),I=d.useCallback(c=>{var t,m,w,S,k,g;N(c),v({id:c.id,name:c.name||"",type:c.type||"text",api_url:((t=c.api_config)==null?void 0:t.url)||"",api_method:((m=c.api_config)==null?void 0:m.method)||"GET",api_timeout:((w=c.api_config)==null?void 0:w.timeout_seconds)||10,api_headers:"",api_params:"",api_content_type:((S=c.api_config)==null?void 0:S.content_type)||"application/json",api_body:"",api_response_path:((k=c.api_config)==null?void 0:k.response_path)||"",api_retry_enabled:((g=c.api_config)==null?void 0:g.retry_enabled)||!1,api_headers_action:"retain",api_params_action:"retain",text_content:c.text_content||"",data_content:c.data_content||"",image_url:c.image_url||"",delay_seconds:c.delay_seconds||0,description:c.description||"",enabled:c.enabled}),u(!0)},[]),D=d.useCallback(async()=>{var c,t,m,w,S,k,g,A,P,T,B,Y;if(j){if(!((c=o.name)!=null&&c.trim())){alert("请输入卡密名称");return}if(!o.type){alert("请选择卡密类型");return}try{const R={name:o.name.trim(),type:o.type,description:(t=o.description)==null?void 0:t.trim(),delay_seconds:o.delay_seconds||0,enabled:o.enabled??!0};o.type==="api"?R.api_config={url:((m=o.api_url)==null?void 0:m.trim())||"",method:o.api_method||"GET",timeout_seconds:o.api_timeout||10,headers:o.api_headers_action==="clear"?void 0:o.api_headers_action==="replace"&&!((w=o.api_headers)!=null&&w.trim())?{}:((S=o.api_headers)==null?void 0:S.trim())||void 0,params:o.api_params_action==="clear"?void 0:o.api_params_action==="replace"&&!((k=o.api_params)!=null&&k.trim())?{}:((g=o.api_params)==null?void 0:g.trim())||void 0,content_type:o.api_content_type||"application/json",body:((A=o.api_body)==null?void 0:A.trim())||void 0,headers_action:o.api_headers_action||"retain",params_action:o.api_params_action||"retain",response_path:((P=o.api_response_path)==null?void 0:P.trim())||void 0,retry_enabled:o.api_retry_enabled||!1}:o.type==="text"?R.text_content=((T=o.text_content)==null?void 0:T.trim())||"":o.type==="data"?R.data_content=((B=o.data_content)==null?void 0:B.trim())||"":o.type==="image"&&(R.image_url=((Y=o.image_url)==null?void 0:Y.trim())||""),await Q(j.id,R),u(!1),await s()}catch(R){console.error("更新卡密失败:",R),alert(z(R,"更新失败,请重试"))}}},[o,s,j]),F=d.useCallback(async c=>{if(confirm("确认删除该卡密吗?"))try{await we(c),await s()}catch(t){console.error("删除卡密失败:",t),alert(z(t,"删除失败,请重试"))}},[s]),C=d.useCallback(async()=>{if(!p.name.trim()){alert("请输入卡密名称");return}if(!p.content.trim()){alert(p.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const c={name:p.name.trim(),type:p.type,description:p.description.trim(),enabled:p.enabled,delay_seconds:p.delay_seconds};p.type==="text"&&(c.text_content=p.content.trim()),p.type==="data"&&(c.data_content=p.content.trim()),p.type==="image"&&(c.image_url=p.content.trim()),p.type==="api"&&(c.api_config={url:p.content.trim(),method:p.api_method,timeout_seconds:p.api_timeout,headers:p.api_headers.trim()||void 0,params:p.api_params.trim()||void 0,content_type:p.api_content_type,body:p.api_body.trim()||void 0,response_path:p.api_response_path.trim()||void 0,retry_enabled:p.api_retry_enabled}),await ve(c),_(!1),x(ee()),await s()}catch(c){console.error("添加卡密失败:",c),alert(z(c,"添加失败,请重试"))}},[p,s]),E=d.useCallback(async c=>{try{await Q(c.id,{...c,enabled:!c.enabled}),await s()}catch(t){console.error("切换状态失败:",t)}},[s]),$=d.useCallback(async c=>{try{await navigator.clipboard.writeText(String(c)),alert(`已复制卡密组ID:${c}`)}catch{prompt("复制卡密组ID",String(c))}},[]),V=d.useCallback(()=>{const m=[["名称","类型","内容","描述","启用","延迟秒","多规格","规格名","规格值"],...[["VIP月卡","data",`VIP-MONTH-001
|
||||
VIP-MONTH-002
|
||||
VIP-MONTH-003`,"按行消费的卡密队列","是","0","否","",""],["感谢文案","text","感谢购买,如有问题联系客服~","固定文本","是","0","否","",""],["教程图","image","https://cdn.example.com/tutorial.jpg","图片URL","是","0","否","",""]]].map(g=>g.map(A=>`"${String(A).replace(/"/g,'""')}"`).join(",")).join(`
|
||||
`),w=new Blob(["\uFEFF"+m],{type:"text/csv;charset=utf-8"}),S=URL.createObjectURL(w),k=document.createElement("a");k.href=S,k.download="卡密组批量导入模板.csv",document.body.appendChild(k),k.click(),k.remove(),URL.revokeObjectURL(S)},[]);return{dataCards:r,filteredCards:i,typeFilter:h,setTypeFilter:f,nameSearch:l,setNameSearch:y,showEditModal:n,setShowEditModal:u,showAddModal:b,setShowAddModal:_,selectedCard:j,editForm:o,setEditForm:v,addForm:p,setAddForm:x,handleEdit:I,handleSaveEdit:D,handleDelete:F,handleAddCard:C,toggleCardStatus:E,copyCardID:$,downloadCardTemplate:V}},Ee=[{value:"application/json",label:"JSON(application/json)"},{value:"application/x-www-form-urlencoded",label:"表单键值(x-www-form-urlencoded)"},{value:"text/plain",label:"纯文本(text/plain)"},{value:"application/xml",label:"XML(application/xml)"}],Pe=a=>a.toLowerCase().includes("json"),te=a=>{if(!a.trim())return[{key:"",value:""}];try{const s=JSON.parse(a);if(!s||typeof s!="object"||Array.isArray(s))return[{key:"",value:""}];const n=Object.entries(s);return n.length===0?[{key:"",value:""}]:n.map(u=>{const[b,_]=u;return{key:b,value:typeof _=="string"?_:JSON.stringify(_)}})}catch{return[{key:"",value:a.trim()}]}},Be=a=>{const s=a.reduce((n,u)=>{const b=u.key.trim();return b&&(n[b]=u.value),n},{});return JSON.stringify(s)},q=({label:a,value:s,placeholder:n,onChange:u})=>{const[b,_]=d.useState(()=>te(s)),j=d.useRef(s);d.useEffect(()=>{s!==j.current&&(_(te(s)),j.current=s)},[s]);const N=x=>{const h=Be(x);_(x),j.current=h,u(h)},o=(x,h,f)=>{const l=b.map((y,r)=>r===x?{...y,[h]:f}:y);N(l)},v=()=>N([...b,{key:"",value:""}]),p=x=>N(b.filter((h,f)=>f!==x));return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("label",{className:"text-sm font-bold text-gray-800",children:a}),e.jsxs("button",{type:"button",onClick:v,className:"inline-flex items-center gap-1 rounded-lg px-2 py-1 text-xs font-bold text-blue-600 transition-colors hover:bg-blue-50",title:`添加${a}字段`,children:[e.jsx(G,{className:"h-3.5 w-3.5"}),"添加字段"]})]}),e.jsxs("div",{className:"overflow-hidden rounded-xl border border-gray-200 bg-white",children:[e.jsxs("div",{className:"grid grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)_40px] gap-2 border-b border-gray-100 bg-gray-50 px-3 py-2 text-[11px] font-bold uppercase tracking-wide text-gray-400",children:[e.jsx("span",{children:"KEY"}),e.jsx("span",{children:"VALUE"}),e.jsx("span",{"aria-hidden":"true"})]}),e.jsx("div",{className:"divide-y divide-gray-100",children:b.map((x,h)=>e.jsxs("div",{className:"grid grid-cols-[minmax(0,0.8fr)_minmax(0,1.2fr)_40px] items-center gap-2 px-3 py-2",children:[e.jsx("input",{"aria-label":`${a}第${h+1}行键名`,value:x.key,onChange:(f=>o(h,"key",f.target.value)),placeholder:h===0?n:"键名",className:"min-w-0 border-0 bg-transparent px-1 py-2 font-mono text-sm text-gray-800 outline-none ring-0 placeholder:text-gray-300"}),e.jsx("input",{"aria-label":`${a}第${h+1}行值`,value:x.value,onChange:(f=>o(h,"value",f.target.value)),placeholder:h===0?"输入值或动态变量,例如 {order_id}":"值",className:"min-w-0 border-0 bg-transparent px-1 py-2 font-mono text-sm text-gray-800 outline-none ring-0 placeholder:text-gray-300"}),e.jsx("button",{type:"button",onClick:(()=>p(h)),className:"inline-flex h-8 w-8 items-center justify-center rounded-lg text-gray-400 transition-colors hover:bg-red-50 hover:text-red-500",title:`删除${a}第${h+1}行`,"aria-label":`删除${a}第${h+1}行`,children:e.jsx(se,{className:"h-4 w-4"})})]},`${a}-${h}`))})]})]})},ae=({url:a,method:s,timeout:n,headers:u,params:b,contentType:_,body:j,responsePath:N,retryEnabled:o,headersAction:v,paramsAction:p,onChange:x,onTest:h})=>{const f=Pe(_),[l,y]=d.useState({loading:!1}),r=async()=>{if(h){y({loading:!0});try{y({loading:!1,result:await h()})}catch(i){y({loading:!1,error:i instanceof Error?i.message:"API 测试请求失败"})}}};return e.jsxs("div",{className:"space-y-5 rounded-2xl border border-blue-100 bg-blue-50/40 p-4 sm:p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-bold text-gray-900",children:"API 请求配置"}),e.jsx("p",{className:"mt-1 text-xs text-gray-500",children:"按 Postman 的请求结构填写,敏感模板只会加密保存在服务端。"})]}),e.jsx("span",{className:"rounded-full bg-white px-2.5 py-1 text-[11px] font-bold text-blue-600 shadow-sm",children:"API"})]}),h&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("button",{type:"button",onClick:r,disabled:l.loading,className:"inline-flex items-center gap-2 rounded-xl bg-gray-900 px-4 py-2.5 text-sm font-bold text-white transition-colors hover:bg-gray-700 disabled:cursor-wait disabled:opacity-60",children:[l.loading?e.jsx(W,{className:"h-4 w-4 animate-spin"}):e.jsx(de,{className:"h-4 w-4"}),"测试请求"]}),l.error&&e
Line truncated
|
||||
"order_id": "{order_id}"
|
||||
}`}):e.jsx(q,{label:"Body 字段",value:j,onChange:(i=>x("body",i)),placeholder:"field"}),e.jsx("p",{className:"text-xs text-gray-500",children:"GET 请求通常只使用 Params;POST 请求会按所选 Content-Type 发送 Body。"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 border-t border-blue-100 pt-5 sm:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]",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:N,onChange:(i=>x("responsePath",i.target.value)),className:"w-full ios-input rounded-xl px-4 py-3 font-mono text-sm",placeholder:"data.cards[0].code"})]}),e.jsxs("label",{className:"flex items-center gap-2 self-end pb-3 text-sm font-bold text-gray-700",children:[e.jsx("input",{type:"checkbox",checked:o,onChange:(i=>x("retryEnabled",i.target.checked))}),"启用幂等重试(需配置 ","{idempotency_key}",")"]})]})]})},Re=({dataCards:a,downloadCardTemplate:s,...n})=>{var y;const u=r=>{var i;n.setBatchFile(((i=r.target.files)==null?void 0:i[0])||null)},b=r=>{n.setAppendContent(r.target.value)},_=r=>{n.setAppendTargetId(r.target.value)},j=()=>n.closeBatchModal(),N=()=>n.setBatchTab("create"),o=()=>n.setBatchTab("append"),v=()=>void n.handleRetryBatchCreate(),p=()=>void n.handleRetryBatchAppend(),x=n.batchResult&&"rows"in n.batchResult?n.batchResult:null,h=r=>e.jsxs("option",{value:String(r.id),children:[r.name,"(ID: ",r.id,")"]},r.id),f=()=>void n.handleBatchCreate(),l=()=>void n.handleBatchAppend();return n.showBatchModal?H.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:j,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(K,{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:N,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${n.batchTab==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(pe,{className:"w-4 h-4"}),"批量创建卡密组"]}),e.jsxs("button",{onClick:o,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${n.batchTab==="append"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(J,{className:"w-4 h-4"}),"往单个组充卡密"]})]}),n.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:s,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(xe,{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(J,{className:"w-4 h-4"}),n.batchFile?n.batchFile.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:u})]})]}),((y=n.batchResult)==null?void 0:y.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:n.batchResult.error}),e.jsx("button",{type:"button",onClick:v,disabled:!n.batchFile||n.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),x&&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:["共 ",x.total," 行 · 成功 ",x.created," · 失败 ",x.failed]}),x.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:x.rows.filter(r=>!r.success).map(r=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",r.row_no," 行「",r.name,"」:",r.error]},r.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:a.length===0?e.jsx("div",{className:"rounded-xl bg-amber-50
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:["预览:",n.appendPreview.length," 个有效卡密,空行自动忽略。"]})]}),n.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:n.appendError}),e.jsx("button",{type:"button",onClick:p,disabled:n.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),n.appendResult&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",n.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:j,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),n.batchTab==="create"?e.jsxs("button",{onClick:f,disabled:!n.batchFile||n.batchBusy,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[n.batchBusy?e.jsx(W,{className:"w-4 h-4 animate-spin"}):e.jsx(J,{className:"w-4 h-4"}),n.batchBusy?"处理中...":"上传创建"]}):e.jsxs("button",{onClick:l,disabled:!n.appendTargetId||n.appendPreview.length===0||n.batchBusy||a.length===0,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[n.batchBusy?e.jsx(W,{className:"w-4 h-4 animate-spin"}):e.jsx(G,{className:"w-4 h-4"}),n.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},Ie=({type:a})=>{switch(a){case"text":return e.jsx(le,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(re,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(me,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(ne,{className:"w-5 h-5 text-gray-500"})}},Fe=()=>{const[a,s]=d.useState([]),[n,u]=d.useState(!0),b=d.useRef(0),_=d.useRef(null),j=d.useCallback(async()=>{var v;const N=++b.current;(v=_.current)==null||v.abort();const o=new AbortController;_.current=o,u(!0);try{const p=await Ne({signal:o.signal});if(N!==b.current)return;s(p)}catch(p){N===b.current&&!o.signal.aborted&&console.error("加载卡密库存失败:",p)}finally{N===b.current&&u(!1)}},[]);return d.useEffect(()=>(j(),()=>{var o;b.current+=1,(o=_.current)==null||o.abort()}),[j]),{cards:a,setCards:s,loading:n,loadCards:j}},$e=a=>{const s=a.dataCards,n=a.loadCards,[u,b]=d.useState(!1),[_,j]=d.useState("create"),[N,o]=d.useState(null),[v,p]=d.useState(null),[x,h]=d.useState(!1),[f,l]=d.useState(""),[y,r]=d.useState(""),[i,I]=d.useState(null),[D,F]=d.useState(""),C=d.useRef(0),E=d.useRef(null),$=d.useRef("");d.useEffect(()=>(()=>{var g;C.current+=1,(g=E.current)==null||g.abort()}),[]);const V=d.useMemo(()=>oe(y),[y]),c=d.useCallback(()=>{var g;j("create"),o(null),p(null),l((g=s[0])!=null&&g.id?String(s[0].id):""),r(""),I(null),F(""),b(!0)},[s]),t=d.useCallback(()=>{var g;C.current+=1,(g=E.current)==null||g.abort(),h(!1),b(!1)},[]),m=d.useCallback(async()=>{var P;if(!N||x)return;const g=++C.current;(P=E.current)==null||P.abort();const A=new AbortController;E.current=A,h(!0),p(null);try{const T=await Ce(N,{signal:A.signal});if(!L(g,C.current,"",""))return;p(T),T.created>0&&await n()}catch(T){if(!L(g,C.current,"",""))return;p({error:(T==null?void 0:T.message)||"上传失败"})}finally{L(g,C.current,"","")&&h(!1)}},[x,N,n]),w=d.useCallback(async()=>{var T;if(!Te(f,y,x))return;const g=f,A=++C.current;$.current=g,(T=E.current)==null||T.abort();const P=new AbortController;E.current=P,h(!0),I(null),F("");try{const B=await ke(g,y,{signal:P.signal});if(!L(A,C.current,g,f))return;I({added:B.added}),r(""),await n()}catch(B){if(!L(A,C.current,g,f))return;F((B==null?void 0:B.message)||"追加失败")}finally{L(A,C.current,g,f)&&h(!1)}},[y,f,x,n]),S=d.useCallback(async()=>{await m()},[m]),k=d.useCallback(async()=>{$.current&&f!==$.current||await w()},[f,w]);return{showBatchModal:u,setShowBatchModal:b,batchTab:_,setBatchTab:j,batchFile:N,setBatchFile:o,batchResult:v,batchBusy:x,appendTargetId:f,setAppendTargetId:l,appendContent:y,setAppendContent:r,appendResult:i,appendError:D,appendPreview:V,openBatchModal:c,closeBatchModal:t,handleBatchCreate:m,handleBatchAppend:w,handleRetryBatchCreate:S,handleRetryBatchAppend:k}},Je=()=>{const{cards:a,loadCards:s}=Fe(),n=Ae({cards:a,loadCards:s}),{dataCards:u,filteredCards:b,typeFilter:_,setTypeFilter:j,nameSearch:N,setNameSearch:o,showEditModal:v,setShowEditModal:p,showAddModal:x,setShowAddModal:h,selectedCard:f,editForm:l,setEditForm:y,addForm:r,setAddForm:i,handleEdit:I,handleSaveEdit:D,handleDelete:F,handleAddCard:C,toggleCardStatus:E,copyCardID:$,downloadCardTemplate:V}=n,c=$e({dataCards:u,loadCards:s});return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex f
Line truncated
|
||||
`).filter(S=>S.trim()).length} 条`:t.type==="text"&&t.text_content?m=t.text_content:t.type==="api"&&t.api_config?m=t.api_config.url:t.type==="image"&&t.image_url&&(m="图片链接"),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(Ie,{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:(()=>$(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(be,{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:m,children:m})}),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:(()=>E(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(ye,{className:"w-4 h-4"})}),e.jsx("button",{onClick:(()=>F(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(se,{className:"h-4 w-4"})})]})})]},t.id)})})]})}),b.length===0&&e.jsxs("div",{className:"py-20 text-center text-gray-400",children:[e.jsx(ge,{className:"w-12 h-12 mx-auto mb-4 opacity-30"}),e.jsx("p",{children:a.length===0?"暂无卡密配置,请点击右上角添加。":"没有符合当前筛选条件的卡密组。"})]})]}),v&&f&&H.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:(()=>p(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors",children:e.jsx(K,{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:l.name||"",onChange:(t=>y({...l,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:l.type||"text",onChange:(t=>y({...l,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:"data",children:"批量库存"}),e.jsx("option",{value:"text",children:"固定文字"}),e.jsx("option",{value:"image",children:"图片"}),e.jsx("option",{value:"api",children:"API 接口"})]})]})]}),l.type==="api"&&e.jsx(e.Fragment,{children:e.jsx(ae,{url:l.api_url||"",method:l.api_method||"GET",timeout:l.api_timeout||10,headers:l.api_headers||"",params:l.api_params||"",contentType:l.api_content_type||"application/json",body:l.api_body||"",responsePath:l.api_response_path||"",retryEnabled:l.api_retry_enabled||!1,headersAction:l.api_headers_action||"retain",paramsAction:l.api_params_action||"retain",onTest:(()=>Z({url:l.api_url||"",method:l.api_method||"GET",timeout_seconds:l.api_timeout||10,headers:l.api_headers||void 0,params:l.aLine 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:l.data_content?l.data_content.split(`
|
||||
`).filter(t=>t.trim()).length:0})," 条"]})]})]}),l.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:l.image_url||"",onChange:(t=>y({...l,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;发货时会临时下载并上传到闲鱼"})]}),l.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:l.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:l.delay_seconds||0,onChange:(t=>y({...l,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:l.description||"",onChange:(t=>y({...l,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:(()=>y({...l,enabled:!l.enabled})),className:`w-14 h-8 rounded-full transition-colors duration-300 relative ${l.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 ${l.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:(()=>p(!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:D,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(fe,{className:"w-4 h-4"}),"保存更改"]})]})})]})}),document.body),x&&H.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:(()=>h(!1)),className:"p-2 rounded-xl hover:bg-gray-100 transition-colors flex-shrink-0",title:"关闭",children:e.jsx(K,{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:r.name,onChange:(t=>i({...r,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-4 gap-2",children:[e.jsxs("button",{type:"button",onClick:(()=>i({...r,type:"data",content:""})),className:`p-3 rounded-xl font-bold transition-all ${r.type==="data"?"bg-brand text-white":"bg-gray-100 text-gray-600 hover:bg-gray-200"}`,children:[e.jsx(ne,{className:"w-5 h-5 mx-auto mb-1"}),"批量库存"]}),e.jsxs("button",{type:"button",onClick:(()=>i({...r,type:"text",content:""})),className:`p-3 rounded-xl font-bold transition-all ${r.type==="text"?"bg-brand text-white":"bg-gray-100 text-gray-600"}`,children:[e.jsx(le,{className:"w-5 h-5 mx-auto mb-1"}),"文本"]}),e.jsxs("button",{type:"button",onClick:(()=>i({...r,type:"image",content:""})),className:`p-3 rounded-xl font-bold transition-all ${r.type==="image"?"bg-brand text-white":"bLine truncated
|
||||
CODE-789012
|
||||
...`:"请输入每次发货时发送的固定文字"}),r.type==="data"&&e.jsxs("p",{className:"text-xs text-gray-500",children:["当前库存:",e.jsx("span",{className:"font-bold text-brand",children:r.content.split(`
|
||||
`).filter(t=>t.trim()).length})," 条"]})]}),r.type==="api"&&e.jsx(e.Fragment,{children:e.jsx(ae,{url:r.content,method:r.api_method,timeout:r.api_timeout,headers:r.api_headers,params:r.api_params,contentType:r.api_content_type,body:r.api_body,responsePath:r.api_response_path,retryEnabled:r.api_retry_enabled,onTest:(()=>Z({url:r.content,method:r.api_method,timeout_seconds:r.api_timeout,headers:r.api_headers||void 0,params:r.api_params||void 0,content_type:r.api_content_type,body:r.api_body||void 0,response_path:r.api_response_path||void 0,retry_enabled:r.api_retry_enabled})),onChange:((t,m)=>i(w=>({...w,...t==="url"?{content:String(m)}:{},...t==="method"?{api_method:m}:{},...t==="timeout"?{api_timeout:Number(m)}:{},...t==="headers"?{api_headers:String(m)}:{},...t==="params"?{api_params:String(m)}:{},...t==="contentType"?{api_content_type:String(m)}:{},...t==="body"?{api_body:String(m)}:{},...t==="responsePath"?{api_response_path:String(m)}:{},...t==="retryEnabled"?{api_retry_enabled:!!m}:{}})))})}),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:r.description,onChange:(t=>i({...r,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:r.delay_seconds,onChange:(t=>i({...r,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:(()=>h(!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:C,className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",children:[e.jsx(G,{className:"w-4 h-4"}),"添加卡密"]})]})})]})}),document.body),e.jsx(Re,{dataCards:u,downloadCardTemplate:V,...c})]})};export{Je as default};
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{d as E,j as e,a}from"./react-vendor-Bf9ELcll.js";import{L as pe}from"./vendor-BE-_xUHH.js";import{B as me}from"./audio-codec-mjVr_wwJ.js";import{L as G,an as de,ao as ge,u as xe,ap as ue,aq as he,M as Q0,V as _e,R as be,ag as D0,m as fe,ar as je,x as J0,as as we,at as Ne,au as ye,av as Ce,S as W0,X as Oe}from"./icons-vendor-BSp7PTZg.js";import{a as U0,i as R,d as i0,e as V0,f as z0,m as Z0,h as ve,j as ke,k as q0,l as Se,s as Re,n as Ee,o as Ie,p as Me,g as Le,q as G0,u as $0,t as P0,C as De}from"./chat-metadata-74T0w35U.js";import{p as Ue,s as qe}from"./index-Q3nlx6gR.js";const H0="ydisks:chat-audio-play",Pe=[6,10,15,8,17,12,7,16,11,6,14,9];function Te(u){const _=u.trim();if(typeof location>"u"||location.protocol!=="https:")return _;try{const n=new URL(_);return n.protocol==="http:"&&n.hostname.endsWith(".aliyuncs.com")&&(n.protocol="https:"),n.toString()}catch{return _}}function T0(u){const _=Number.isFinite(u)?Math.max(0,Math.floor(u)):0,n=Math.floor(_/60),l=_%60;return`${n}:${l.toString().padStart(2,"0")}`}function A0(u){window.dispatchEvent(new CustomEvent(H0,{detail:u}))}const Ae=({messageKey:u,src:_,outgoing:n,initialDuration:l=0})=>{const x=E.useRef(null),C=E.useRef(0),[o,I]=E.useState("idle"),[M,L]=E.useState(l),[V,T]=E.useState(0);E.useEffect(()=>(()=>{var d;C.current+=1,(d=x.current)==null||d.destroy(),x.current=null}),[_]),E.useEffect(()=>{L(Math.max(0,l))},[l]),E.useEffect(()=>{const d=f=>{const w=f.detail,N=x.current;w!==u&&(N!=null&&N.isPlaying())&&N.pause()};return window.addEventListener(H0,d),(()=>window.removeEventListener(H0,d))},[u]),E.useEffect(()=>{if(o!=="playing")return;const d=window.setInterval(()=>{const f=x.current;f&&T(f.getCurrentPosition())},100);return(()=>window.clearInterval(d))},[o]);const A=(d,f)=>{const w=()=>C.current===f&&x.current===d;d.onPlay(()=>{w()&&I("playing")}),d.onResume(()=>{w()&&I("playing")}),d.onPause(()=>{w()&&I("paused")}),d.onStop(()=>{w()&&(I("idle"),T(0))}),d.onEnded(()=>{w()&&(I("idle"),T(0))})},r0=async()=>{var w;const d=x.current;if(d!=null&&d.isPlaying()){d.pause();return}if(d!=null&&d.isPaused()){A0(u),d.resume();return}if(d!=null&&d.isInit()){A0(u),d.play();return}if(o==="loading")return;const f=C.current+1;C.current=f,I("loading"),T(0);try{const N=new me;if(x.current=N,A(N,f),await N.initWithUrl(Te(_)),C.current!==f||x.current!==N){N.destroy();return}L(N.getDuration()||Math.max(0,l)),A0(u),N.play()}catch{if(C.current!==f)return;(w=x.current)==null||w.destroy(),x.current=null,I("error"),T(0)}},H=o==="playing"||o==="paused"?V:M,$=M>0?o==="playing"||o==="paused"?`${T0(H)} / ${T0(M)}`:T0(M):"--:--",P=o==="loading"?"正在解码":o==="playing"?"正在播放":o==="paused"?"已暂停":o==="error"?"加载失败,点击重试":"语音消息",O=o==="playing"?"暂停语音消息":o==="paused"?"继续播放语音消息":o==="error"?"重新加载语音消息":o==="loading"?"正在加载语音消息":"播放语音消息";return e.jsxs("div",{className:`flex h-11 min-w-56 items-center gap-2 rounded-2xl border px-2 shadow-sm ${n?"rounded-br-md border-sky-400 bg-sky-500 text-white":"rounded-bl-md border-slate-200 bg-white text-slate-800"}`,children:[e.jsx("button",{type:"button","aria-label":O,title:O,disabled:o==="loading",onClick:(()=>void r0()),className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-full transition focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-wait ${n?"bg-white text-sky-600 hover:bg-sky-50 focus-visible:ring-white":"bg-sky-50 text-sky-600 hover:bg-sky-100 focus-visible:ring-sky-400"}`,children:o==="loading"?e.jsx(G,{className:"h-4 w-4 animate-spin"}):o==="playing"?e.jsx(de,{className:"h-4 w-4 fill-current"}):o==="error"?e.jsx(ge,{className:"h-4 w-4"}):e.jsx(xe,{className:"ml-px h-4 w-4 fill-current"})}),e.jsxs("div",{className:"min-w-0 flex flex-1 items-center gap-2",children:[e.jsx("div",{className:"flex h-5 flex-1 items-center gap-0.5","aria-hidden":"true",children:Pe.map((d,f)=>e.jsx("span",{className:`w-0.5 rounded-full ${o==="playing"?"animate-pulse":""} ${n?"bg-sky-100":o==="error"?"bg-red-300":"bg-sky-400"}`,style:{height:`${d}px`,animationDelay:`${f*45}ms`}},`${u}-${f}`))}),e.jsx("span",{className:`shrink-0 font-mono text-[11px] font-semibold tabular-nums ${n?"text-sky-100":o==="error"?"text-red-500":"text-slate-500"}`,children:$}),e.jsx("span",{className:"sr-only",children:P})]})]})},X0=[["尊嘟假嘟","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
Line truncated
|
||||
import{d as E,j as e,a}from"./react-vendor-Bf9ELcll.js";import{L as pe}from"./vendor-BE-_xUHH.js";import{B as me}from"./audio-codec-mjVr_wwJ.js";import{L as G,ao as de,ap as ge,u as xe,aq as ue,ar as he,M as Q0,V as _e,R as be,ah as D0,m as fe,as as je,x as J0,at as we,au as Ne,av as ye,aw as Ce,S as W0,X as Oe}from"./icons-vendor-eB2mgMyz.js";import{a as U0,i as R,d as i0,e as V0,f as z0,m as Z0,h as ve,j as ke,k as q0,l as Se,s as Re,n as Ee,o as Ie,p as Me,g as Le,q as G0,u as $0,t as P0,C as De}from"./chat-metadata-CxFNzZmJ.js";import{p as Ue,s as qe}from"./index-DO3sL4lx.js";const H0="ydisks:chat-audio-play",Pe=[6,10,15,8,17,12,7,16,11,6,14,9];function Te(u){const _=u.trim();if(typeof location>"u"||location.protocol!=="https:")return _;try{const n=new URL(_);return n.protocol==="http:"&&n.hostname.endsWith(".aliyuncs.com")&&(n.protocol="https:"),n.toString()}catch{return _}}function T0(u){const _=Number.isFinite(u)?Math.max(0,Math.floor(u)):0,n=Math.floor(_/60),l=_%60;return`${n}:${l.toString().padStart(2,"0")}`}function A0(u){window.dispatchEvent(new CustomEvent(H0,{detail:u}))}const Ae=({messageKey:u,src:_,outgoing:n,initialDuration:l=0})=>{const x=E.useRef(null),C=E.useRef(0),[o,I]=E.useState("idle"),[M,L]=E.useState(l),[V,T]=E.useState(0);E.useEffect(()=>(()=>{var d;C.current+=1,(d=x.current)==null||d.destroy(),x.current=null}),[_]),E.useEffect(()=>{L(Math.max(0,l))},[l]),E.useEffect(()=>{const d=f=>{const w=f.detail,N=x.current;w!==u&&(N!=null&&N.isPlaying())&&N.pause()};return window.addEventListener(H0,d),(()=>window.removeEventListener(H0,d))},[u]),E.useEffect(()=>{if(o!=="playing")return;const d=window.setInterval(()=>{const f=x.current;f&&T(f.getCurrentPosition())},100);return(()=>window.clearInterval(d))},[o]);const A=(d,f)=>{const w=()=>C.current===f&&x.current===d;d.onPlay(()=>{w()&&I("playing")}),d.onResume(()=>{w()&&I("playing")}),d.onPause(()=>{w()&&I("paused")}),d.onStop(()=>{w()&&(I("idle"),T(0))}),d.onEnded(()=>{w()&&(I("idle"),T(0))})},r0=async()=>{var w;const d=x.current;if(d!=null&&d.isPlaying()){d.pause();return}if(d!=null&&d.isPaused()){A0(u),d.resume();return}if(d!=null&&d.isInit()){A0(u),d.play();return}if(o==="loading")return;const f=C.current+1;C.current=f,I("loading"),T(0);try{const N=new me;if(x.current=N,A(N,f),await N.initWithUrl(Te(_)),C.current!==f||x.current!==N){N.destroy();return}L(N.getDuration()||Math.max(0,l)),A0(u),N.play()}catch{if(C.current!==f)return;(w=x.current)==null||w.destroy(),x.current=null,I("error"),T(0)}},H=o==="playing"||o==="paused"?V:M,$=M>0?o==="playing"||o==="paused"?`${T0(H)} / ${T0(M)}`:T0(M):"--:--",P=o==="loading"?"正在解码":o==="playing"?"正在播放":o==="paused"?"已暂停":o==="error"?"加载失败,点击重试":"语音消息",O=o==="playing"?"暂停语音消息":o==="paused"?"继续播放语音消息":o==="error"?"重新加载语音消息":o==="loading"?"正在加载语音消息":"播放语音消息";return e.jsxs("div",{className:`flex h-11 min-w-56 items-center gap-2 rounded-2xl border px-2 shadow-sm ${n?"rounded-br-md border-sky-400 bg-sky-500 text-white":"rounded-bl-md border-slate-200 bg-white text-slate-800"}`,children:[e.jsx("button",{type:"button","aria-label":O,title:O,disabled:o==="loading",onClick:(()=>void r0()),className:`flex h-7 w-7 shrink-0 items-center justify-center rounded-full transition focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-wait ${n?"bg-white text-sky-600 hover:bg-sky-50 focus-visible:ring-white":"bg-sky-50 text-sky-600 hover:bg-sky-100 focus-visible:ring-sky-400"}`,children:o==="loading"?e.jsx(G,{className:"h-4 w-4 animate-spin"}):o==="playing"?e.jsx(de,{className:"h-4 w-4 fill-current"}):o==="error"?e.jsx(ge,{className:"h-4 w-4"}):e.jsx(xe,{className:"ml-px h-4 w-4 fill-current"})}),e.jsxs("div",{className:"min-w-0 flex flex-1 items-center gap-2",children:[e.jsx("div",{className:"flex h-5 flex-1 items-center gap-0.5","aria-hidden":"true",children:Pe.map((d,f)=>e.jsx("span",{className:`w-0.5 rounded-full ${o==="playing"?"animate-pulse":""} ${n?"bg-sky-100":o==="error"?"bg-red-300":"bg-sky-400"}`,style:{height:`${d}px`,animationDelay:`${f*45}ms`}},`${u}-${f}`))}),e.jsx("span",{className:`shrink-0 font-mono text-[11px] font-semibold tabular-nums ${n?"text-sky-100":o==="error"?"text-red-500":"text-slate-500"}`,children:$}),e.jsx("span",{className:"sr-only",children:P})]})]})},X0=[["尊嘟假嘟","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
Line truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{j as e,a as c}from"./react-vendor-Bf9ELcll.js";import{f as ge}from"./dateTime-DDi7rqpW.js";import{l as xe,m as he,n as se,D as pe,d as be,o as fe,p as ae,E as ye,q as je}from"./icons-vendor-BSp7PTZg.js";import{R as P,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-DBu_rVrn.js";import{r as M,c as K}from"./chat-metadata-74T0w35U.js";import{c as ue,o as Se}from"./contract-COFcZjyb.js";import"./vendor-BE-_xUHH.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(P,{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(P,{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,tiLine truncated
|
||||
import{j as e,a as c}from"./react-vendor-Bf9ELcll.js";import{f as ge}from"./dateTime-DDi7rqpW.js";import{l as xe,m as he,n as se,D as pe,d as be,o as fe,p as ae,E as ye,q as je}from"./icons-vendor-eB2mgMyz.js";import{R as P,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-DBu_rVrn.js";import{r as M,c as K}from"./chat-metadata-CxFNzZmJ.js";import{c as ue,o as Se}from"./contract-COFcZjyb.js";import"./vendor-BE-_xUHH.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(P,{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(P,{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,tiLine truncated
|
||||
+1
-1
@@ -1,2 +1,2 @@
|
||||
import{j as e,a as n,b as we}from"./react-vendor-Bf9ELcll.js";import{r as B,c as q,b as Qe,A as gt}from"./chat-metadata-74T0w35U.js";import{c as et}from"./contract-COFcZjyb.js";import{a6 as yt,U as $e,R as Ie,P as De,a7 as Pe,a8 as _e,_ as ft,T as jt,B as vt,a9 as Oe,aa as Nt,ab as wt,A as _t,f as kt,X as ye,s as Ct,ac as Ue,V as ze}from"./icons-vendor-BSp7PTZg.js";import"./vendor-BE-_xUHH.js";const Ke="ydisks-amap-js-api",St="c9b68d4ce9a2a97f22a4a439404488ca";let fe=null;const It=()=>St,Pt=()=>window.AMap?Promise.resolve(window.AMap):fe||(fe=new Promise((s,a)=>{const r=document.getElementById(Ke),d=r||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 配置"))},r||document.head.appendChild(d)}).catch(s=>{throw fe=null,s}),fe),ke=s=>Number.isFinite(s)&&s!==0,Bt=s=>{var u,f;const a=Number((u=s.location)==null?void 0:u.lng),r=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:r,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(r)||a<-180||a>180||r<-90||r>90?null:d},qt=async(s,a,r={})=>{if(!ke(s)||!ke(a)||s<-180||s>180||a<-90||a>90)throw new Error("经纬度无效");const d=await Pt();return new Promise((u,f)=>{var $,R;let G=!1;const k=Math.max(1,r.timeoutMs??1e4),M=F=>{var p;G||(G=!0,globalThis.clearTimeout(W),(p=r.signal)==null||p.removeEventListener("abort",S),F())},S=()=>M(()=>f(new DOMException("aborted","AbortError"))),W=globalThis.setTimeout(()=>M(()=>f(new Error("高德地图附近地址查询超时,请稍后重试"))),k);if(($=r.signal)!=null&&$.aborted){S();return}(R=r.signal)==null||R.addEventListener("abort",S,{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"){M(()=>u([]));return}M(()=>f(new Error("高德地图附近地址查询失败,请稍后重试")));return}const E=(((x=p==null?void 0:p.poiList)==null?void 0:x.pois)||[]).map(Bt).filter(j=>j!==null);M(()=>u(E))})})},Et=async s=>B(a=>q.GET("/api/v1/accounts/details",{signal:a}),s),Je=async s=>B(a=>q.GET("/api/v1/automation-rules",{signal:a}),s),Lt=(s,a,r)=>qt(s,a,r),Be=(s,a)=>{if(s instanceof gt)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 r=typeof s=="object"&&s!==null&&"message"in s?s.message:void 0;return typeof r=="string"?r:a},qe=s=>s===!0||s===1||s==="1",Ze=async(s,a)=>{const r=await B(u=>q.GET("/api/v1/items",{params:{query:{cookie_id:s}},signal:u}),a);return et(r,["items","data","results"]).map(u=>({...u,id:u.id||`${u.cookie_id}-${u.item_id}`,is_multi_spec:qe(u.is_multi_spec),is_multi_qty_ship:qe(u.is_multi_qty_ship??u.multi_quantity_delivery),multi_quantity_delivery:qe(u.multi_quantity_delivery??u.is_multi_qty_ship)}))},At=async s=>B(a=>q.POST("/api/v1/items/get-all-from-account",{body:{cookie_id:s},signal:a})),Mt=async(s,a)=>B(r=>q.DELETE("/api/v1/items/{cookie_id}/{item_id}",{params:{path:{cookie_id:s,item_id:a}},signal:r})),Rt=async(s,a)=>B(r=>q.POST("/api/v1/items/{cookie_id}",{params:{path:{cookie_id:s}},body:a,signal:r})),Ft=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 r of s.images)a.append("images",r);return B(r=>q.POST("/api/v1/items/publish",{body:Qe(a),signal:r}))},Gt=async(s,a,r)=>B(d=>q.POST("/api/v1/items/publish-categories/recommend",{body:{cookie_id:s,keyword:a},signal:d}),r),Tt=async(s,a)=>{const r=new FormData;return r.set("file",s.file),s.imagesZLine truncated
|
||||
import{j as e,a as n,b as we}from"./react-vendor-Bf9ELcll.js";import{r as B,c as q,b as Qe,A as gt}from"./chat-metadata-CxFNzZmJ.js";import{c as et}from"./contract-COFcZjyb.js";import{a7 as yt,U as $e,R as Ie,P as De,a8 as Pe,a9 as _e,_ as ft,T as jt,B as vt,aa as Oe,ab as Nt,ac as wt,A as _t,f as kt,X as ye,s as Ct,ad as Ue,V as ze}from"./icons-vendor-eB2mgMyz.js";import"./vendor-BE-_xUHH.js";const Ke="ydisks-amap-js-api",St="c9b68d4ce9a2a97f22a4a439404488ca";let fe=null;const It=()=>St,Pt=()=>window.AMap?Promise.resolve(window.AMap):fe||(fe=new Promise((s,a)=>{const r=document.getElementById(Ke),d=r||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 配置"))},r||document.head.appendChild(d)}).catch(s=>{throw fe=null,s}),fe),ke=s=>Number.isFinite(s)&&s!==0,Bt=s=>{var u,f;const a=Number((u=s.location)==null?void 0:u.lng),r=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:r,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(r)||a<-180||a>180||r<-90||r>90?null:d},qt=async(s,a,r={})=>{if(!ke(s)||!ke(a)||s<-180||s>180||a<-90||a>90)throw new Error("经纬度无效");const d=await Pt();return new Promise((u,f)=>{var $,R;let G=!1;const k=Math.max(1,r.timeoutMs??1e4),M=F=>{var p;G||(G=!0,globalThis.clearTimeout(W),(p=r.signal)==null||p.removeEventListener("abort",S),F())},S=()=>M(()=>f(new DOMException("aborted","AbortError"))),W=globalThis.setTimeout(()=>M(()=>f(new Error("高德地图附近地址查询超时,请稍后重试"))),k);if(($=r.signal)!=null&&$.aborted){S();return}(R=r.signal)==null||R.addEventListener("abort",S,{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"){M(()=>u([]));return}M(()=>f(new Error("高德地图附近地址查询失败,请稍后重试")));return}const E=(((x=p==null?void 0:p.poiList)==null?void 0:x.pois)||[]).map(Bt).filter(j=>j!==null);M(()=>u(E))})})},Et=async s=>B(a=>q.GET("/api/v1/accounts/details",{signal:a}),s),Je=async s=>B(a=>q.GET("/api/v1/automation-rules",{signal:a}),s),Lt=(s,a,r)=>qt(s,a,r),Be=(s,a)=>{if(s instanceof gt)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 r=typeof s=="object"&&s!==null&&"message"in s?s.message:void 0;return typeof r=="string"?r:a},qe=s=>s===!0||s===1||s==="1",Ze=async(s,a)=>{const r=await B(u=>q.GET("/api/v1/items",{params:{query:{cookie_id:s}},signal:u}),a);return et(r,["items","data","results"]).map(u=>({...u,id:u.id||`${u.cookie_id}-${u.item_id}`,is_multi_spec:qe(u.is_multi_spec),is_multi_qty_ship:qe(u.is_multi_qty_ship??u.multi_quantity_delivery),multi_quantity_delivery:qe(u.multi_quantity_delivery??u.is_multi_qty_ship)}))},At=async s=>B(a=>q.POST("/api/v1/items/get-all-from-account",{body:{cookie_id:s},signal:a})),Mt=async(s,a)=>B(r=>q.DELETE("/api/v1/items/{cookie_id}/{item_id}",{params:{path:{cookie_id:s,item_id:a}},signal:r})),Rt=async(s,a)=>B(r=>q.POST("/api/v1/items/{cookie_id}",{params:{path:{cookie_id:s}},body:a,signal:r})),Ft=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 r of s.images)a.append("images",r);return B(r=>q.POST("/api/v1/items/publish",{body:Qe(a),signal:r}))},Gt=async(s,a,r)=>B(d=>q.POST("/api/v1/items/publish-categories/recommend",{body:{cookie_id:s,keyword:a},signal:d}),r),Tt=async(s,a)=>{const r=new FormData;return r.set("file",s.file),s.imagesZLine 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=n.useCallback(()=>{y(c=>({...c,cookie_id:s||c.cookie_id})),p(!0)},[s]),h=n.useCallback(()=>{v(c=>({...c,cookie_id:s||c.cookie_id})),x(!0)},[s]),L=n.useCallback(async c=>{if(!(c?s:g.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");O();const A=new AbortController;Q.current=A;const ee=++K.current;I(!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 Lt(T.coords.longitude,T.coords.latitude,{signal:A.signal});if(A.signal.aborted||ee!==K.current)return;if(!P.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");c?(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(Be(T,"获取发货地失败"))}finally{ee===K.current&&(Q.current=null,I(!1))}},[O,g.cookie_id,s,k,G]);return{selectedAccount:s,setSelectedAccount:a,loading:M,publishing:W,showEditModal:$,setShowEditModal:R,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}},Xt=s=>{const a=String(s||"").trim();return a?/^[¥¥]/.test(a)?a:`¥${a}`:"-"},ls=({onConfigureDelivery:s})=>{const[a,r]=n.useState([]),[d,u]=n.useState([]),[f,G]=n.useState([]),[k,M]=n.useState(""),[S,W]=n.useState(""),U=n.useRef(0),$=n.useRef(0),R=n.useCallback(async()=>{const t=++U.current,o=await Ze();t===U.current&&r(o)},[]),F=n.useCallback(async()=>{const t=++$.current,o=await Je();t===$.current&&u(o)},[]),p=Yt({selectedAccount:k,loadItems:R,loadShippingRules:F}),{showBatchModal:E,batchLoading:x,batchPhase:j,batchFile:I,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,c=Ht({selectedAccount:k,setSelectedAccount:M,setItems:r,loadItems:R,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:st,publishLocation:at,setPublishLocation:Ee,selectedItem:Le,editForm:se,setEditForm:Ne,addForm:J,setAddForm:pe,publishForm:w,setPublishForm:V,publishImagePreviews:Ae,handleSync:lt,handleEdit:rt,handleSaveEdit:nt,handleDelete:it,handleAddItem:ct,handlePublishItem:ot,downloadPublishTemplate:dt,openAddModal:xt,openPublishModal:mt,locateForPublish:Me}=c;n.useEffect(()=>{const t=new AbortController,o=++U.current,_=++$.current;let ge=!0;return Promise.all([Et({signal:t.signal}),Ze(void 0,{signal:t.signal}),Je({signal:t.signal}),tt(20,{signal:t.signal})]).then(([ce,ht,pt,Te])=>{if(!ge||t.signal.aborted||o!==U.current||_!==$.current)return;G(ce),r(ht),u(pt);const bt=Te.find(Se=>["running","canceling"].includes(Se.status))||Te.find(Se=>Se.status!=="preview");v(bt||null)}).catch(ce=>{t.signal.aborted||console.error("加载商品配置失败:",ce)}),(()=>{ge=!1,t.abort()})},[]);const ut=t=>d.filter(o=>o.cookie_id===t.cookie_id&&o.item_id===t.item_id).length>0?d.filter(o=>o.cookie_id===t.cookie_id&&o.item_id===t.item_id):d.filter(o=>o.cookie_id===t.cookie_id&&!o.item_id),Re=n.useMemo(()=>new Map(f.map(t=>[t.id,t])),[f]),Fe=n.useMemo(()=>S?a.filter(t=>t.cookie_id===S):a,[S,a]),be=t=>{const o=Re.get(t),_=(o==null?void 0:o.remark)||(o==null?void 0:o.nickname);return _?`${_} · ${t.slice(0,6)}`:`账号 ${t.slice(0,8)}`},Ge=t=>{const o=Re.get(t);return(o==null?void 0:o.remark)||(o==null?void 0:o.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{
Line truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{j as e,b as _e,a as d}from"./react-vendor-Bf9ELcll.js";import{al as te,S as ae,am as je,y as Q,g as I,L as J,H as Ne,T as ve,x as V,X as ne,J as re,N as le,s as ke,R as we,P as Se}from"./icons-vendor-BSp7PTZg.js";import{n as Ce}from"./settings-D-mx9vFJ.js";import{r as R,c as B}from"./chat-metadata-74T0w35U.js";import"./vendor-BE-_xUHH.js";const Y=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],H=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},oe=s=>{const t=Object.prototype.hasOwnProperty.call(s,"use_custom_smtp"),a=Y.some(r=>String(s[r]??"").trim()!=="");return{...s,use_custom_smtp:t?H(s.use_custom_smtp,!1):a}},ie=(s,t)=>{const a={...s,use_custom_smtp:!0};for(const r of Y)String(a[r]??"").trim()===""&&t[r]!==void 0&&(a[r]=t[r]);return a.smtp_port||(a.smtp_port=587),a.smtp_from_address||(a.smtp_from_address=a.smtp_user||""),a.smtp_use_tls=H(a.smtp_use_tls,!0),a.smtp_use_ssl=H(a.smtp_use_ssl,!1),a},ce=s=>{const t=oe(s),a={to_email:String(t.to_email??"").trim(),use_custom_smtp:t.use_custom_smtp===!0};if(a.use_custom_smtp)for(const r of Y)a[r]=t[r];return a},$={bark:{label:"Bark",icon:I,fields:[{key:"server_url",label:"Bark 服务器",placeholder:"https://api.day.app",required:!0},{key:"device_key",label:"Device Key",placeholder:"你的 Bark 设备 Key",required:!0},{key:"title",label:"标题(可选)",placeholder:"Ydisks闲鱼助手"},{key:"sound",label:"铃声(可选)",placeholder:"default"},{key:"group",label:"分组(可选)",placeholder:"xianyu"}],guide:{steps:["App Store 搜索并安装 Bark(免费)","打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app/<key>/这是测试推送内容","URL 路径里 <key> 那一段就是 Device Key,复制填入","服务器地址默认 https://api.day.app,自建服务端则填自建域名"],urlFormat:"https://api.day.app/<你的key>/测试内容",note:"不需要 secret,Device Key 本身就是唯一凭证。"}},dingtalk:{label:"钉钉机器人",icon:Q,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://oapi.dingtalk.com/robot/send?access_token=...",required:!0},{key:"secret",label:"加签密钥",placeholder:"SEC...",help:"安全设置勾选「加签」后生成,SEC 开头"}],guide:{steps:["钉钉进入一个群(可建单人群)→ 右上角 群设置","机器人 → 添加机器人 → 选择「自定义机器人」","安全设置勾选「加签」","完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制","Webhook URL 填上面,Secret 填加签密钥"],urlFormat:"https://oapi.dingtalk.com/robot/send?access_token=XXX",note:"加签密钥可选,但强烈建议启用,否则机器人可能被滥用。"}},feishu:{label:"飞书机器人",icon:Q,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://open.feishu.cn/open-apis/bot/v2/hook/...",required:!0},{key:"secret",label:"签名校验密钥",placeholder:"sec-...",help:"安全设置选「签名校验」后生成"}],guide:{steps:["飞书进入目标群 → 右上角 更多 → 设置","群机器人 → 添加机器人 → 自定义机器人","安全设置选择「签名校验」,复制生成的秘钥","完成会给 Webhook 地址,复制","Webhook URL 填上面,秘钥填签名校验密钥"],urlFormat:"https://open.feishu.cn/open-apis/bot/v2/hook/xxx",note:"签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。"}},wechat:{label:"企业微信机器人",icon:Q,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...",required:!0}],guide:{steps:["企业微信进入一个内部群 → 右上角 … → 群设置","找到「群机器人」(新版可能叫「消息推送」)","添加 → 选择自定义机器人","完成给 Webhook 地址(含 ?key=),复制填入"],urlFormat:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX",note:"不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。"}},webhook:{label:"自定义 Webhook",icon:je,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://your-server/notify",required:!0}],guide:{steps:["仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON","系统会 POST 这个 URL,Content-Type: application/json","请求体固定为右侧 JSON 格式,按需解析 message 字段"],urlFormat:'{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',note:"若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。"}},telegram:{label:"Telegram",icon:ae,fields:[{key:"bot_token",label:"Bot Token",placeholder:"123456:ABC-DEF...",required:!0},{key:"chat_id",laLine truncated
|
||||
import{j as e,b as _e,a as d}from"./react-vendor-Bf9ELcll.js";import{am as te,S as ae,an as je,y as Q,g as I,L as J,H as Ne,T as ve,x as V,X as ne,J as re,N as le,s as ke,R as we,P as Se}from"./icons-vendor-eB2mgMyz.js";import{n as Ce}from"./settings-D-mx9vFJ.js";import{r as R,c as B}from"./chat-metadata-CxFNzZmJ.js";import"./vendor-BE-_xUHH.js";const Y=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],H=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},oe=s=>{const t=Object.prototype.hasOwnProperty.call(s,"use_custom_smtp"),a=Y.some(r=>String(s[r]??"").trim()!=="");return{...s,use_custom_smtp:t?H(s.use_custom_smtp,!1):a}},ie=(s,t)=>{const a={...s,use_custom_smtp:!0};for(const r of Y)String(a[r]??"").trim()===""&&t[r]!==void 0&&(a[r]=t[r]);return a.smtp_port||(a.smtp_port=587),a.smtp_from_address||(a.smtp_from_address=a.smtp_user||""),a.smtp_use_tls=H(a.smtp_use_tls,!0),a.smtp_use_ssl=H(a.smtp_use_ssl,!1),a},ce=s=>{const t=oe(s),a={to_email:String(t.to_email??"").trim(),use_custom_smtp:t.use_custom_smtp===!0};if(a.use_custom_smtp)for(const r of Y)a[r]=t[r];return a},$={bark:{label:"Bark",icon:I,fields:[{key:"server_url",label:"Bark 服务器",placeholder:"https://api.day.app",required:!0},{key:"device_key",label:"Device Key",placeholder:"你的 Bark 设备 Key",required:!0},{key:"title",label:"标题(可选)",placeholder:"Ydisks闲鱼助手"},{key:"sound",label:"铃声(可选)",placeholder:"default"},{key:"group",label:"分组(可选)",placeholder:"xianyu"}],guide:{steps:["App Store 搜索并安装 Bark(免费)","打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app/<key>/这是测试推送内容","URL 路径里 <key> 那一段就是 Device Key,复制填入","服务器地址默认 https://api.day.app,自建服务端则填自建域名"],urlFormat:"https://api.day.app/<你的key>/测试内容",note:"不需要 secret,Device Key 本身就是唯一凭证。"}},dingtalk:{label:"钉钉机器人",icon:Q,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://oapi.dingtalk.com/robot/send?access_token=...",required:!0},{key:"secret",label:"加签密钥",placeholder:"SEC...",help:"安全设置勾选「加签」后生成,SEC 开头"}],guide:{steps:["钉钉进入一个群(可建单人群)→ 右上角 群设置","机器人 → 添加机器人 → 选择「自定义机器人」","安全设置勾选「加签」","完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制","Webhook URL 填上面,Secret 填加签密钥"],urlFormat:"https://oapi.dingtalk.com/robot/send?access_token=XXX",note:"加签密钥可选,但强烈建议启用,否则机器人可能被滥用。"}},feishu:{label:"飞书机器人",icon:Q,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://open.feishu.cn/open-apis/bot/v2/hook/...",required:!0},{key:"secret",label:"签名校验密钥",placeholder:"sec-...",help:"安全设置选「签名校验」后生成"}],guide:{steps:["飞书进入目标群 → 右上角 更多 → 设置","群机器人 → 添加机器人 → 自定义机器人","安全设置选择「签名校验」,复制生成的秘钥","完成会给 Webhook 地址,复制","Webhook URL 填上面,秘钥填签名校验密钥"],urlFormat:"https://open.feishu.cn/open-apis/bot/v2/hook/xxx",note:"签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。"}},wechat:{label:"企业微信机器人",icon:Q,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...",required:!0}],guide:{steps:["企业微信进入一个内部群 → 右上角 … → 群设置","找到「群机器人」(新版可能叫「消息推送」)","添加 → 选择自定义机器人","完成给 Webhook 地址(含 ?key=),复制填入"],urlFormat:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX",note:"不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。"}},webhook:{label:"自定义 Webhook",icon:je,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://your-server/notify",required:!0}],guide:{steps:["仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON","系统会 POST 这个 URL,Content-Type: application/json","请求体固定为右侧 JSON 格式,按需解析 message 字段"],urlFormat:'{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',note:"若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。"}},telegram:{label:"Telegram",icon:ae,fields:[{key:"bot_token",label:"Bot Token",placeholder:"123456:ABC-DEF...",required:!0},{key:"chat_id",laLine truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{j as e,b as Y,a as r}from"./react-vendor-Bf9ELcll.js";import{f as ee}from"./dateTime-DDi7rqpW.js";import{U as ne,V as ie,X as H,W as oe,R as K,P as ce,Y as se,p as te,E as de,N as xe,_ as ue,T as me,j as he,i as pe,s as ge}from"./icons-vendor-BSp7PTZg.js";import{r as O,c as M,b as be}from"./chat-metadata-74T0w35U.js";import{o as ye,c as fe}from"./contract-COFcZjyb.js";import"./vendor-BE-_xUHH.js";const je=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],ve=s=>{const t=typeof s=="object"&&s!==null?s:{},a=Array.isArray(t.results)?t.results:[];return{total:Number(t.total||0),success_count:Number(t.success_count||0),failed_count:Number(t.failed_count||0),results:a.map(Ne)}},Ne=s=>{const t=typeof s=="object"&&s!==null?s:{};return{order_id:String(t.order_id||"unknown"),success:t.success===!0,message:String(t.message||"")}},we=s=>(s==null?void 0:s.results.filter(_e))||[],_e=s=>!s.success,ke=(s,t)=>s!==null&&!t,Ce=s=>{if(!s)return"请选择订单文件";const t=s.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(t)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},z=(s,t)=>s===t,Se=(s,t)=>s instanceof Error&&s.message?s.message:t,Ee=({filter:s,onFilterChange:t,accountFilter:a,onAccountFilterChange:m,accounts:h,accountName:x,searchText:p,onSearchChange:f})=>{const b=i=>t(i.currentTarget.dataset.status||"all"),y=i=>m(i.target.value),j=i=>f(i.target.value);return e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:je.map(i=>e.jsx("button",{"data-status":i.key,onClick:b,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${s===i.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:i.label},i.key))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ne,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:a,onChange:y,className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),h.map(i=>e.jsx("option",{value:i.id,children:x(i.id)},i.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(ie,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:p,onChange:j,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Oe=s=>{const t=x=>{var p;s.setImportFile(((p=x.target.files)==null?void 0:p[0])||null)},a=()=>s.closeImportModal(),m=()=>void s.handleImportOrders(),h=()=>void s.handleRetryImport();return s.showImportModal?Y.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:a,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:t,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),s.importFile&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:s.importFile.name})]})}),s.importError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-100 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.importError}),e.jsx("button",{type:"button",onClick:h,disabled:s.importing||!s.importFile,className:"font-bold whitespace-nowrap",children:"重试"})]}),s.importResult&&s.importResult.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:Line truncated
|
||||
import{j as e,b as Y,a as r}from"./react-vendor-Bf9ELcll.js";import{f as ee}from"./dateTime-DDi7rqpW.js";import{U as ne,V as ie,X as H,W as oe,R as K,P as ce,Y as se,p as te,E as de,N as xe,_ as ue,T as me,j as he,i as pe,s as ge}from"./icons-vendor-eB2mgMyz.js";import{r as O,c as M,b as be}from"./chat-metadata-CxFNzZmJ.js";import{o as ye,c as fe}from"./contract-COFcZjyb.js";import"./vendor-BE-_xUHH.js";const je=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],ve=s=>{const t=typeof s=="object"&&s!==null?s:{},a=Array.isArray(t.results)?t.results:[];return{total:Number(t.total||0),success_count:Number(t.success_count||0),failed_count:Number(t.failed_count||0),results:a.map(Ne)}},Ne=s=>{const t=typeof s=="object"&&s!==null?s:{};return{order_id:String(t.order_id||"unknown"),success:t.success===!0,message:String(t.message||"")}},we=s=>(s==null?void 0:s.results.filter(_e))||[],_e=s=>!s.success,ke=(s,t)=>s!==null&&!t,Ce=s=>{if(!s)return"请选择订单文件";const t=s.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(t)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},z=(s,t)=>s===t,Se=(s,t)=>s instanceof Error&&s.message?s.message:t,Ee=({filter:s,onFilterChange:t,accountFilter:a,onAccountFilterChange:m,accounts:h,accountName:x,searchText:p,onSearchChange:f})=>{const b=i=>t(i.currentTarget.dataset.status||"all"),y=i=>m(i.target.value),j=i=>f(i.target.value);return e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:je.map(i=>e.jsx("button",{"data-status":i.key,onClick:b,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${s===i.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:i.label},i.key))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(ne,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:a,onChange:y,className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),h.map(i=>e.jsx("option",{value:i.id,children:x(i.id)},i.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(ie,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:p,onChange:j,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Oe=s=>{const t=x=>{var p;s.setImportFile(((p=x.target.files)==null?void 0:p[0])||null)},a=()=>s.closeImportModal(),m=()=>void s.handleImportOrders(),h=()=>void s.handleRetryImport();return s.showImportModal?Y.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:a,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(H,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:t,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),s.importFile&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oe,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:s.importFile.name})]})}),s.importError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-100 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.importError}),e.jsx("button",{type:"button",onClick:h,disabled:s.importing||!s.importFile,className:"font-bold whitespace-nowrap",children:"重试"})]}),s.importResult&&s.importResult.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{j as e,a as d,b as Oe}from"./react-vendor-Bf9ELcll.js";import{m as We,ai as ut,aj as St,p as Rt,ak as pt,R as Ge,P as rt,Z as lt,y as At,r as nt,V as Pt,a4 as Tt,X as Ae,_ as qe,T as Pe,j as Mt,i as $t,aa as Et,al as Lt,s as it,S as Dt}from"./icons-vendor-eB2mgMyz.js";import{r as N,c as w}from"./chat-metadata-CxFNzZmJ.js";import{o as $e,c as Ze}from"./contract-COFcZjyb.js";import"./vendor-BE-_xUHH.js";const Ve=(t,s)=>t.allowed_resolutions.includes(s),It=(t,s)=>({runs:t.runs.filter(l=>!s||l.cookie_id===s),pending_tasks:t.pending_tasks.filter(l=>!s||l.cookie_id===s)}),Ft=t=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[t]||"自动化异常",zt=({runs:t,pendingTasks:s,onResolveRun:l,onResolveDeferredTask:p})=>e.jsxs("section",{className:"rounded-2xl border border-red-200 bg-red-50 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(We,{className:"w-5 h-5 text-red-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-black text-red-900",children:"需要人工处理的自动化任务"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。"})]})]}),e.jsxs("div",{className:"space-y-3",children:[t.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 订单 ",r.order_id||"-"," · 已记录发送 ",r.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:Ft(r.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[Ve(r,"continue")&&e.jsx("button",{onClick:(()=>l(r.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),Ve(r,"retry")&&e.jsx("button",{onClick:(()=>l(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),Ve(r,"cancel")&&e.jsx("button",{onClick:(()=>l(r.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${r.id}`)),s.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 延迟任务重试已达 ",r.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:(()=>p(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:(()=>p(r.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${r.id}`))]})]}),Ot=async t=>N(s=>w.GET("/api/v1/accounts/details",{signal:s}),t),gt=async t=>N(s=>w.GET("/api/v1/cards",{signal:s}),t),bt=async(t,s)=>N(l=>w.GET("/api/v1/items",{params:{query:{cookie_id:t}},signal:l}),s),ht=t=>t.map(s=>{var l,p;return{id:String(s.id),name:s.name||"",trigger_type:s.trigger_type||"order_paid",item_keyword:s.item_title||s.item_id||"",cookie_id:s.cookie_id||"",item_id:s.item_id||"",item_title:s.item_title||"",card_group_id:Number(((l=(s.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:l.card_id)||0),card_group_name:((p=(s.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:p.card_name)||"",priority:s.priority||100,enabled:s.enabled||!1,config_json:s.config_json||"{}",actions:(s.actions||[]).map(r=>({id:r.id?String(r.id):void 0,action_type:r.action_type,card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),message_template:r.message_template||"",delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}",enabled:r.enabled!==!1,sort_order:Number(r.sort_order||0)})),variants:(s.actions||[]).filter(r=>r.action_type==="send_card").map(r=>{let h={};try{h=JSON.parse(r.config_json||"{}")}catch{}return{id:r.id?String(r.id):void 0,spec_name:h.spec_name||"",spec_value:h.spec_value||"",card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),enabled:r.enabled!==!1,delay_override:h.delay_override===!0,delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}"}})}}),Gt=async()=>{const t=await N(l=>w.GET("/api/v1/automation-rules",{signal:l})Line truncated
|
||||
@@ -1 +0,0 @@
|
||||
import{j as e,a as d,b as Oe}from"./react-vendor-Bf9ELcll.js";import{m as We,ah as ut,ai as St,p as Rt,aj as pt,R as Ge,P as rt,Z as lt,y as At,r as nt,V as Pt,a4 as Tt,X as Ae,_ as qe,T as Pe,j as Mt,i as $t,a9 as Et,ak as Lt,s as it,S as Dt}from"./icons-vendor-BSp7PTZg.js";import{r as N,c as w}from"./chat-metadata-74T0w35U.js";import{o as $e,c as Ze}from"./contract-COFcZjyb.js";import"./vendor-BE-_xUHH.js";const Ve=(t,s)=>t.allowed_resolutions.includes(s),It=(t,s)=>({runs:t.runs.filter(l=>!s||l.cookie_id===s),pending_tasks:t.pending_tasks.filter(l=>!s||l.cookie_id===s)}),Ft=t=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[t]||"自动化异常",zt=({runs:t,pendingTasks:s,onResolveRun:l,onResolveDeferredTask:u})=>e.jsxs("section",{className:"rounded-2xl border border-red-200 bg-red-50 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(We,{className:"w-5 h-5 text-red-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-black text-red-900",children:"需要人工处理的自动化任务"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。"})]})]}),e.jsxs("div",{className:"space-y-3",children:[t.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 订单 ",r.order_id||"-"," · 已记录发送 ",r.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:Ft(r.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[Ve(r,"continue")&&e.jsx("button",{onClick:(()=>l(r.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),Ve(r,"retry")&&e.jsx("button",{onClick:(()=>l(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),Ve(r,"cancel")&&e.jsx("button",{onClick:(()=>l(r.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${r.id}`)),s.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 延迟任务重试已达 ",r.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:(()=>u(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:(()=>u(r.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${r.id}`))]})]}),Ot=async t=>N(s=>w.GET("/api/v1/accounts/details",{signal:s}),t),gt=async t=>N(s=>w.GET("/api/v1/cards",{signal:s}),t),bt=async(t,s)=>N(l=>w.GET("/api/v1/items",{params:{query:{cookie_id:t}},signal:l}),s),ht=t=>t.map(s=>{var l,u;return{id:String(s.id),name:s.name||"",trigger_type:s.trigger_type||"order_paid",item_keyword:s.item_title||s.item_id||"",cookie_id:s.cookie_id||"",item_id:s.item_id||"",item_title:s.item_title||"",card_group_id:Number(((l=(s.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:l.card_id)||0),card_group_name:((u=(s.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:u.card_name)||"",priority:s.priority||100,enabled:s.enabled||!1,config_json:s.config_json||"{}",actions:(s.actions||[]).map(r=>({id:r.id?String(r.id):void 0,action_type:r.action_type,card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),message_template:r.message_template||"",delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}",enabled:r.enabled!==!1,sort_order:Number(r.sort_order||0)})),variants:(s.actions||[]).filter(r=>r.action_type==="send_card").map(r=>{let h={};try{h=JSON.parse(r.config_json||"{}")}catch{}return{id:r.id?String(r.id):void 0,spec_name:h.spec_name||"",spec_value:h.spec_value||"",card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),enabled:r.enabled!==!1,delay_override:h.delay_override===!0,delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}"}})}}),Gt=async()=>{const t=await N(l=>w.GET("/api/v1/automation-rules",{signal:l})Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
import{a as r,j as e}from"./react-vendor-Bf9ELcll.js";import{r as M,c as T}from"./chat-metadata-CxFNzZmJ.js";import{n as de,S as xe}from"./settings-D-mx9vFJ.js";import{h as ue,R as ae,ae as pe,v as me,J as D,N as O,af as he,x as ge,b as re,ag as le,ah as ye,s as be}from"./icons-vendor-eB2mgMyz.js";import"./vendor-BE-_xUHH.js";const ne="https://dashscope.aliyuncs.com/compatible-mode/v1",fe=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],we=new Set(["ai_api_key_configured","smtp_password_configured","qq_reply_secret_key_configured","captcha.remote_secret_key_configured","smtp_server","smtp_port","smtp_user","smtp_password","smtp_from","smtp_from_name","smtp_from_address","registration_enabled","show_default_login_info","login_captcha_enabled","item_sync_enabled","item_sync_interval","item_sync_max_pages","default_reply"]),je=s=>{const a={...s};for(const o of xe){const d=`${o}_configured`;d in a&&(a[d]=a[d]===!0||a[d]==="true")}if("renewal_log_retention_days"in a){const o=Number(a.renewal_log_retention_days);a.renewal_log_retention_days=Number.isFinite(o)?o:10}return"outbound_http_public_only"in a&&(a.outbound_http_public_only=a.outbound_http_public_only===!0||a.outbound_http_public_only==="true"),a},_e=async(s,a)=>M(o=>T.PUT("/api/v1/session/credentials",{body:s,signal:o}),a),ve=async s=>{const a=await M(o=>T.GET("/api/v1/settings/system",{signal:o}),s);return je(a)},Ne=async(s,a)=>M(o=>T.PUT("/api/v1/settings/system",{body:de(s),signal:o}),a),Se=async(s,a="",o)=>{const d=await M(N=>T.POST("/api/v1/settings/ai-models",{body:{base_url:s,api_key:a},signal:N}),o);return Array.isArray(d.models)?d.models:[]},ke=async s=>M(a=>T.GET("/api/v1/session",{signal:a}),s),Ce=s=>Object.fromEntries(Object.entries(s).filter(([a,o])=>!we.has(a)&&o!==void 0&&o!==null)),Ee=s=>s.new_username.trim().length<3?"用户名至少需要 3 个字符":s.current_password?s.new_password&&s.new_password.length<8?"新密码至少需要 8 个字符":s.new_password!==s.confirm_password?"两次输入的新密码不一致":"":"请输入当前密码确认身份",y=(s,a,o)=>s===a&&!o.aborted,K=s=>s instanceof Error&&s.message==="请求已取消",U=(s,a)=>s instanceof Error?s.message:a,Ae=(s="")=>({new_username:s,current_password:"",new_password:"",confirm_password:""}),$=(s,a)=>({type:s,text:a}),Pe=()=>{const[s,a]=r.useState(null),[o,d]=r.useState(!1),[N,p]=r.useState(""),[S,A]=r.useState(!1),[R,k]=r.useState(""),[C,f]=r.useState([]),[w,P]=r.useState(!1),[I,x]=r.useState(""),[G,j]=r.useState(!1),[z,L]=r.useState(!1),[F,u]=r.useState(!1),[b,J]=r.useState(!1),[V,Y]=r.useState(!1),[H,_]=r.useState(!1),[q,g]=r.useState(null),[t,ee]=r.useState(()=>Ae()),[oe,W]=r.useState("idle"),se=r.useRef(null),te=r.useRef(null),m=r.useRef(0),B=r.useRef(null);te.current=s;const E=r.useCallback(()=>{var c;(c=B.current)==null||c.abort();const n=new AbortController;return B.current=n,m.current+=1,{controller:n,sequence:m.current}},[]),Q=r.useCallback(async(n,c=!1,l)=>{const i=n||te.current,h=(i==null?void 0:i.ai_api_url)||(i==null?void 0:i.ai_base_url)||ne;P(!0),x("");try{const v=await Se(h,(i==null?void 0:i.ai_api_key)||"",{signal:l});if(l!=null&&l.aborted)return;f(v),j(c&&v.length>0),!(i!=null&&i.ai_model)&&v.length>0&&a(Z=>Z&&{...Z,ai_model:v[0]})}catch(v){if(l!=null&&l.aborted||K(v))return;f([]),j(!1),x(U(v,"读取模型失败"))}finally{l!=null&&l.aborted||P(!1)}},[]),X=r.useCallback(()=>{const{controller:n,sequence:c}=E();d(!0),W("loading"),p(""),Promise.all([ve({signal:n.signal}),ke({signal:n.signal})]).then(([l,i])=>{y(m.current,c,n.signal)&&(a(l),i.username&&ee(h=>({...h,new_username:i.username||""})),Q(l,!1,n.signal),W("success"))}).catch(l=>{!y(m.current,c,n.signal)||K(l)||(a(null),p(U(l,"加载配置失败")),W("error"))}).finally(()=>{y(m.current,c,n.signal)&&d(!1)})},[E,Q]);r.useEffect(()=>(X(),(()=>{var n;return(n=B.current)==null?void 0:n.abort()})),[X]),r.useEffect(()=>{const n=c=>{var l;(l=se.current)!=null&&l.contains(c.target)||j(!1)};return document.addEventListener("mousedown",n),(()=>document.removeEventListener("mousedown",n))},[]);const ce=r.useCallback(async()=>{if(!s||S)return;const{controller:n,sequence:c}=E();A(!0),k("");try{if(await Ne(Ce(s),{signal:n.signal}),!y(m.current,c,n.signal))return;window.alert("系统配置已保存")}catch(l){if(!y(m.current,c,n.signal)||K(l))return;k(U(l,"保存配置失败"))}finally{y(m.current,c,n.signal)&&A(!1)}},[E,S,s]),ie=r.useCallback(async n=>{n.preventDefault(),g(null);const c=Ee(t);if(c){g($("error",c));return}const{controller:l,sequence:i}=E();_(!0);try{const h=await _e({current_password:t.current_password,new_username:t.new_username.trim(),new_password:t.new_password||void 0},{signal:l.signal});if(!y(m.current,i,l.signal))return;if(!h.success){g($("error",h.message||"登录凭据更新失败"));return}g($("success",h.message||"登录凭据已更新")),window.setTimeout(()=>window.location.reload(),1400)}catch(h){if(!y(m.current,iLine truncated
|
||||
@@ -1 +0,0 @@
|
||||
import{a as r,j as e}from"./react-vendor-Bf9ELcll.js";import{r as M,c as R}from"./chat-metadata-74T0w35U.js";import{n as de,S as xe}from"./settings-D-mx9vFJ.js";import{h as ue,R as ae,ad as pe,v as me,J as D,N as O,ae as he,x as ge,b as re,af as le,ag as ye,s as fe}from"./icons-vendor-BSp7PTZg.js";import"./vendor-BE-_xUHH.js";const ne="https://dashscope.aliyuncs.com/compatible-mode/v1",be=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],we=new Set(["ai_api_key_configured","smtp_password_configured","qq_reply_secret_key_configured","captcha.remote_secret_key_configured","smtp_server","smtp_port","smtp_user","smtp_password","smtp_from","smtp_from_name","smtp_from_address","registration_enabled","show_default_login_info","login_captcha_enabled","item_sync_enabled","item_sync_interval","item_sync_max_pages","default_reply"]),je=s=>{const a={...s};for(const o of xe){const d=`${o}_configured`;d in a&&(a[d]=a[d]===!0||a[d]==="true")}if("renewal_log_retention_days"in a){const o=Number(a.renewal_log_retention_days);a.renewal_log_retention_days=Number.isFinite(o)?o:10}return a},ve=async(s,a)=>M(o=>R.PUT("/api/v1/session/credentials",{body:s,signal:o}),a),Ne=async s=>{const a=await M(o=>R.GET("/api/v1/settings/system",{signal:o}),s);return je(a)},_e=async(s,a)=>M(o=>R.PUT("/api/v1/settings/system",{body:de(s),signal:o}),a),Se=async(s,a="",o)=>{const d=await M(_=>R.POST("/api/v1/settings/ai-models",{body:{base_url:s,api_key:a},signal:_}),o);return Array.isArray(d.models)?d.models:[]},Ce=async s=>M(a=>R.GET("/api/v1/session",{signal:a}),s),ke=s=>Object.fromEntries(Object.entries(s).filter(([a,o])=>!we.has(a)&&o!==void 0&&o!==null)),Ee=s=>s.new_username.trim().length<3?"用户名至少需要 3 个字符":s.current_password?s.new_password&&s.new_password.length<8?"新密码至少需要 8 个字符":s.new_password!==s.confirm_password?"两次输入的新密码不一致":"":"请输入当前密码确认身份",y=(s,a,o)=>s===a&&!o.aborted,K=s=>s instanceof Error&&s.message==="请求已取消",U=(s,a)=>s instanceof Error?s.message:a,Ae=(s="")=>({new_username:s,current_password:"",new_password:"",confirm_password:""}),$=(s,a)=>({type:s,text:a}),Ie=()=>{const[s,a]=r.useState(null),[o,d]=r.useState(!1),[_,p]=r.useState(""),[S,A]=r.useState(!1),[L,C]=r.useState(""),[k,b]=r.useState([]),[w,I]=r.useState(!1),[P,x]=r.useState(""),[G,j]=r.useState(!1),[z,T]=r.useState(!1),[F,u]=r.useState(!1),[f,J]=r.useState(!1),[V,Y]=r.useState(!1),[W,v]=r.useState(!1),[q,g]=r.useState(null),[t,ee]=r.useState(()=>Ae()),[oe,B]=r.useState("idle"),se=r.useRef(null),te=r.useRef(null),m=r.useRef(0),H=r.useRef(null);te.current=s;const E=r.useCallback(()=>{var c;(c=H.current)==null||c.abort();const n=new AbortController;return H.current=n,m.current+=1,{controller:n,sequence:m.current}},[]),Q=r.useCallback(async(n,c=!1,l)=>{const i=n||te.current,h=(i==null?void 0:i.ai_api_url)||(i==null?void 0:i.ai_base_url)||ne;I(!0),x("");try{const N=await Se(h,(i==null?void 0:i.ai_api_key)||"",{signal:l});if(l!=null&&l.aborted)return;b(N),j(c&&N.length>0),!(i!=null&&i.ai_model)&&N.length>0&&a(Z=>Z&&{...Z,ai_model:N[0]})}catch(N){if(l!=null&&l.aborted||K(N))return;b([]),j(!1),x(U(N,"读取模型失败"))}finally{l!=null&&l.aborted||I(!1)}},[]),X=r.useCallback(()=>{const{controller:n,sequence:c}=E();d(!0),B("loading"),p(""),Promise.all([Ne({signal:n.signal}),Ce({signal:n.signal})]).then(([l,i])=>{y(m.current,c,n.signal)&&(a(l),i.username&&ee(h=>({...h,new_username:i.username||""})),Q(l,!1,n.signal),B("success"))}).catch(l=>{!y(m.current,c,n.signal)||K(l)||(a(null),p(U(l,"加载配置失败")),B("error"))}).finally(()=>{y(m.current,c,n.signal)&&d(!1)})},[E,Q]);r.useEffect(()=>(X(),(()=>{var n;return(n=H.current)==null?void 0:n.abort()})),[X]),r.useEffect(()=>{const n=c=>{var l;(l=se.current)!=null&&l.contains(c.target)||j(!1)};return document.addEventListener("mousedown",n),(()=>document.removeEventListener("mousedown",n))},[]);const ce=r.useCallback(async()=>{if(!s||S)return;const{controller:n,sequence:c}=E();A(!0),C("");try{if(await _e(ke(s),{signal:n.signal}),!y(m.current,c,n.signal))return;window.alert("系统配置已保存")}catch(l){if(!y(m.current,c,n.signal)||K(l))return;C(U(l,"保存配置失败"))}finally{y(m.current,c,n.signal)&&A(!1)}},[E,S,s]),ie=r.useCallback(async n=>{n.preventDefault(),g(null);const c=Ee(t);if(c){g($("error",c));return}const{controller:l,sequence:i}=E();v(!0);try{const h=await ve({current_password:t.current_password,new_username:t.new_username.trim(),new_password:t.new_password||void 0},{signal:l.signal});if(!y(m.current,i,l.signal))return;if(!h.success){g($("error",h.message||"登录凭据更新失败"));return}g($("success",h.message||"登录凭据已更新")),window.setTimeout(()=>window.location.reload(),1400)}catch(h){if(!y(m.current,i,l.signal)||K(h))return;g($("error",U(h,"登录凭据更新失败")))}finally{y(m.current,i,l.signal)&&v(!1)}},[E,t]);return{settingsLine truncated
|
||||
Loaded 100 of 106 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user