merge: 合并批量铺货发布强制间隔
# Conflicts: # internal/webui/static/assets/AccountList-CW56xo40.js # internal/webui/static/assets/AccountList-DcnUPoF-.js # internal/webui/static/assets/AccountList-i39PcoQv.js # internal/webui/static/assets/CardList-BWJaMF5O.js # internal/webui/static/assets/CardList-DXFjEouq.js # internal/webui/static/assets/CardList-z1WELq_d.js # internal/webui/static/assets/Dashboard-3YjsHK0L.js # internal/webui/static/assets/Dashboard-DtK1xauO.js # internal/webui/static/assets/Dashboard-xJlcwTaJ.js # internal/webui/static/assets/ItemList-DDiNaq3H.js # internal/webui/static/assets/Notifications-Cgc4sSHL.js # internal/webui/static/assets/Notifications-D_Iy_BIm.js # internal/webui/static/assets/Notifications-DcqcaoDO.js # internal/webui/static/assets/OrderList-BY2V4t6y.js # internal/webui/static/assets/OrderList-C59DQxfb.js # internal/webui/static/assets/OrderList-CljaoSLa.js # internal/webui/static/assets/Rules-BeCst9X9.js # internal/webui/static/assets/Rules-BiND-23Q.js # internal/webui/static/assets/Rules-Cl8LfxhU.js # internal/webui/static/assets/Settings-BIhrQYtY.js # internal/webui/static/assets/Settings-BhwR41fV.js # internal/webui/static/assets/Settings-CbEKYyJY.js # internal/webui/static/assets/index-CCqtUiU5.js # internal/webui/static/assets/index-Dw5V5tCq.js # internal/webui/static/assets/index-k6Tc6ww6.js # internal/webui/static/index.html
This commit is contained in:
commit
cad43780af
39 files changed
+362
-75
No files matched your search
@@ -1243,6 +1243,7 @@ const runVersionedItemBatchAPITest = async () => {
|
||||
defaultCookieId: 'acc1',
|
||||
fallbackCategory: { catId: 'cat-1', catName: '资料', channelCatId: 'channel-1', tbCatId: 'tb-1' },
|
||||
location: { area: '区域', city: '城市', division_id: '1', longitude: 120, latitude: 30, poi_id: 'poi-1', poi_name: '地点', province: '省' },
|
||||
publishIntervalSeconds: 12,
|
||||
});
|
||||
await startItemPublishBatch('preview-1');
|
||||
await getItemPublishBatches(10);
|
||||
@@ -1254,6 +1255,9 @@ const runVersionedItemBatchAPITest = async () => {
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(1, '/api/v1/items/get-all-from-account', expect.objectContaining({ method: 'POST' }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(2, '/api/v1/items/publish-categories/recommend', expect.objectContaining({ method: 'POST' }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(3, '/api/v1/items/publish-batches/preview', expect.objectContaining({ method: 'POST', body: expect.any(FormData) }));
|
||||
// previewBody 保存批量预检表单,确保用户设置的间隔进入后端持久化边界。
|
||||
const previewBody = fetchMock.mock.calls[2][1].body as FormData;
|
||||
expect(previewBody.get('publish_interval_seconds')).toBe('12');
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(4, '/api/v1/items/publish-batches', expect.objectContaining({ method: 'POST' }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(5, '/api/v1/items/publish-batches?limit=10', expect.objectContaining({ method: 'GET' }));
|
||||
expect(fetchMock).toHaveBeenNthCalledWith(6, '/api/v1/items/publish-batches/batch-1', expect.objectContaining({ method: 'GET' }));
|
||||
|
||||
@@ -109,6 +109,8 @@ export const previewItemPublishBatch = async (form: {
|
||||
/** tbCatId 表示淘宝分类标识。 */ tbCatId?: string;
|
||||
};
|
||||
/** location 表示地址。 */ location?: PublishLocation;
|
||||
/** publishIntervalSeconds 表示最终商品发布之间的最小间隔秒数。 */
|
||||
publishIntervalSeconds?: number;
|
||||
}, options?: RequestControlOptions): Promise<ItemPublishBatchPreviewResponse> => {
|
||||
// body 请求体,用于当前 API 处理流程。
|
||||
const body = new FormData();
|
||||
@@ -120,6 +122,7 @@ export const previewItemPublishBatch = async (form: {
|
||||
body.set('fallback_channel_category_id', form.fallbackCategory.channelCatId || '');
|
||||
body.set('fallback_tb_category_id', form.fallbackCategory.tbCatId || '');
|
||||
if (form.location) body.set('location', JSON.stringify(form.location));
|
||||
body.set('publish_interval_seconds', String(form.publishIntervalSeconds ?? 5));
|
||||
return postForm('/api/v1/items/publish-batches/preview', body, options);
|
||||
}
|
||||
|
||||
|
||||
@@ -45,6 +45,8 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
const [batchLocations, setBatchLocations] = useState<NonNullable<ItemPublishBatchState['batchLocations']>>([]);
|
||||
// batchLocation 保存批量任务当前选中的发货地。
|
||||
const [batchLocation, setBatchLocation] = useState<ItemPublishBatchState['batchLocation']>(null);
|
||||
// batchPublishIntervalSeconds 保存当前批量任务的最终发布最小间隔,默认五秒。
|
||||
const [batchPublishIntervalSeconds, setBatchPublishIntervalSeconds] = useState(5);
|
||||
// batchLoading 表示批量任务请求是否正在执行。
|
||||
const [batchLoading, setBatchLoading] = useState(false);
|
||||
// batchPollInFlight 防止同一批次的轮询请求重叠。
|
||||
@@ -97,6 +99,7 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
setBatchFallbackCategory({ catId: '', catName: '', channelCatId: '', tbCatId: '' });
|
||||
setBatchLocations([]);
|
||||
setBatchLocation(null);
|
||||
setBatchPublishIntervalSeconds(5);
|
||||
setShowBatchModal(true);
|
||||
setBatchLoading(true);
|
||||
try {
|
||||
@@ -111,6 +114,7 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
setRecentBatch(detail);
|
||||
setBatchDetail(detail);
|
||||
setBatchPublishIntervalSeconds(detail.publish_interval_seconds || 5);
|
||||
setBatchPhase(['running', 'canceling'].includes(detail.status) ? 'running' : 'done');
|
||||
}
|
||||
} catch (error /* 恢复任务错误 */) {
|
||||
@@ -177,6 +181,7 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
const detail = await getItemPublishBatch(recentBatch.id, { signal: request.controller.signal });
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
setBatchDetail(detail);
|
||||
setBatchPublishIntervalSeconds(detail.publish_interval_seconds || 5);
|
||||
setBatchPhase(['running', 'canceling'].includes(detail.status) ? 'running' : 'done');
|
||||
} catch (error /* 最近结果读取错误 */) {
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
@@ -211,6 +216,7 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
defaultCookieId: options.selectedAccount,
|
||||
fallbackCategory: batchFallbackCategory,
|
||||
location: batchLocation || undefined,
|
||||
publishIntervalSeconds: batchPublishIntervalSeconds,
|
||||
}, { signal: request.controller.signal });
|
||||
if (!isCurrentBatchOperation(request.requestGeneration, request.controller)) return;
|
||||
setBatchPreview(result);
|
||||
@@ -224,7 +230,7 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
if (isCurrentBatchOperation(request.requestGeneration, request.controller)) setBatchLoading(false);
|
||||
}
|
||||
},
|
||||
[batchFallbackCategory, batchFile, batchImagesZip, batchLocation, beginBatchRequest, isCurrentBatchOperation, options.selectedAccount],
|
||||
[batchFallbackCategory, batchFile, batchImagesZip, batchLocation, batchPublishIntervalSeconds, beginBatchRequest, isCurrentBatchOperation, options.selectedAccount],
|
||||
);
|
||||
|
||||
// handleStartBatch 启动预检通过的批量任务并读取首个详情。
|
||||
@@ -429,6 +435,8 @@ export const useItemPublishBatch = (options: ItemPublishBatchOptions): ItemPubli
|
||||
batchLocation,
|
||||
setBatchLocations,
|
||||
setBatchLocation,
|
||||
batchPublishIntervalSeconds,
|
||||
setBatchPublishIntervalSeconds,
|
||||
openBatchModal,
|
||||
handleRecommendBatchCategory,
|
||||
openRecentBatchResult,
|
||||
|
||||
@@ -79,6 +79,8 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
setRecentBatch,
|
||||
batchLocations,
|
||||
batchLocation,
|
||||
batchPublishIntervalSeconds,
|
||||
setBatchPublishIntervalSeconds,
|
||||
setBatchLocations,
|
||||
setBatchLocation,
|
||||
openBatchModal,
|
||||
@@ -657,9 +659,16 @@ const ItemList: React.FC<ItemListProps> = ({ onConfigureDelivery }) => {
|
||||
{batchLocations.length > 0 && <select className="w-full ios-input rounded-xl bg-white px-4 py-3" value={String(Math.max(0, batchLocations.indexOf(batchLocation!)))} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setBatchLocation(batchLocations[Number(e.target.value)] || null)}>
|
||||
{batchLocations.map(/* 当前回调处理集合中的单个元素。 */ (item, index) => <option key={`${item.division_id}-${item.poi_id}-${index}`} value={String(index)}>{[item.province, item.city, item.area, item.poi_name].filter(Boolean).join(' ')}</option>)}
|
||||
</select>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<div className="rounded-xl border border-violet-200 bg-violet-50 p-4 space-y-2">
|
||||
<label className="flex items-center justify-between gap-4" htmlFor="batch-publish-interval">
|
||||
<span className="min-w-0"><span className="block text-sm font-extrabold text-gray-900">商品发布强制间隔</span><span className="mt-1 block text-xs text-violet-800">图片会提前上传,只有最终发布请求之间至少等待该时间。</span></span>
|
||||
<span className="flex shrink-0 items-center gap-2"><input id="batch-publish-interval" type="number" min={1} max={3600} step={1} inputMode="numeric" className="ios-input w-24 rounded-xl bg-white px-3 py-2 text-right" value={batchPublishIntervalSeconds} onChange={/* 当前回调处理用户交互或异步状态变化。 */ e => setBatchPublishIntervalSeconds(Math.min(3600, Math.max(1, Number(e.target.value) || 1)))} /><span className="text-sm font-bold text-violet-900">秒</span></span>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
|
||||
<label className="flex min-h-[150px] cursor-pointer flex-col items-center justify-center rounded-2xl border-2 border-dashed border-gray-200 bg-gray-50 px-4 py-6 text-center hover:border-blue-300 hover:bg-blue-50 transition-colors">
|
||||
<UploadCloud className="w-9 h-9 text-blue-600 mb-3" />
|
||||
<span className="text-sm font-extrabold text-gray-900">上传商品表格</span>
|
||||
|
||||
@@ -95,6 +95,8 @@ export interface PublishBatchDetail {
|
||||
running: number;
|
||||
// retryable 是可重试失败行数。
|
||||
retryable: number;
|
||||
// publish_interval_seconds 是相邻最终商品发布请求的最小间隔秒数。
|
||||
publish_interval_seconds?: number;
|
||||
// rows 是逐行执行结果。
|
||||
rows: PublishBatchDetailRow[];
|
||||
}
|
||||
@@ -175,6 +177,10 @@ export interface ItemPublishBatchState {
|
||||
setBatchLocations: Dispatch<SetStateAction<PublishLocation[]>>;
|
||||
// setBatchLocation 更新批量当前发货地。
|
||||
setBatchLocation: Dispatch<SetStateAction<PublishLocation | null>>;
|
||||
// batchPublishIntervalSeconds 保存最终商品发布之间的最小间隔秒数。
|
||||
batchPublishIntervalSeconds: number;
|
||||
// setBatchPublishIntervalSeconds 更新用户设置的发布最小间隔。
|
||||
setBatchPublishIntervalSeconds: Dispatch<SetStateAction<number>>;
|
||||
// openBatchModal 打开批量铺货流程并恢复可继续任务。
|
||||
openBatchModal: () => Promise<void>;
|
||||
// handleRecommendBatchCategory 请求默认类目推荐。
|
||||
|
||||
@@ -1171,6 +1171,8 @@ export interface ItemPublishBatchResponse {
|
||||
rows: ItemPublishBatchRowResponse[];
|
||||
/** 批次统一发货地。 */
|
||||
location?: Record<string, unknown>;
|
||||
/** 最终商品发布之间的最小间隔秒数。 */
|
||||
publish_interval_seconds?: number;
|
||||
/** 创建时间。 */
|
||||
created_at: string;
|
||||
/** 更新时间。 */
|
||||
|
||||
@@ -45,7 +45,7 @@ func NewItemBatchPublishPort(store *db.Store, client func() mtop.Client, logger
|
||||
}
|
||||
|
||||
// PublishRemoteRow 执行单行商品远端发布并保存远端结果检查点,不写入本地商品或自动化规则。
|
||||
func (p *ItemBatchPublishPort) PublishRemoteRow(ctx context.Context, userID int64, row itemapp.BatchRow, workerToken string) (itemapp.BatchPublishOutcome, error) {
|
||||
func (p *ItemBatchPublishPort) PublishRemoteRow(ctx context.Context, userID int64, row itemapp.BatchRow, workerToken string, beforePublish func(context.Context) error) (itemapp.BatchPublishOutcome, error) {
|
||||
// validateErr 保存适配器依赖校验错误。
|
||||
if validateErr := p.validate(); validateErr != nil {
|
||||
return itemapp.BatchPublishOutcome{}, validateErr
|
||||
@@ -116,6 +116,7 @@ func (p *ItemBatchPublishPort) PublishRemoteRow(ctx context.Context, userID int6
|
||||
Title: row.Title, Description: firstBatchNonEmpty(row.Description, row.Title), PriceCents: priceCents,
|
||||
OriginalPriceCents: originalPriceCents, Quantity: row.Quantity, PostageMode: row.PostageMode,
|
||||
PostageCents: postageCents, Virtual: true, Location: location, PreferredCategory: preferredCategory, Images: images,
|
||||
BeforePublish: beforePublish,
|
||||
})
|
||||
cancel()
|
||||
// runtimeCookie、persistErr 保存会话写回后的运行时 Cookie 和错误。
|
||||
|
||||
@@ -77,7 +77,7 @@ func TestItemBatchPublishPortPersistsRemoteCheckpoint(t *testing.T) {
|
||||
},
|
||||
func(context.Context, string) ([]byte, string, error) { return nil, "", nil })
|
||||
// outcome、publishErr 保存远端端口结果及错误。
|
||||
outcome, publishErr := port.PublishRemoteRow(ctx, admin.ID, batchRowApplicationModel(storedRows[0]), "worker-remote")
|
||||
outcome, publishErr := port.PublishRemoteRow(ctx, admin.ID, batchRowApplicationModel(storedRows[0]), "worker-remote", nil)
|
||||
if publishErr != nil || outcome.Result == nil || outcome.Result.ItemID != "remote-item" {
|
||||
t.Fatalf("远端端口结果异常: outcome=%+v err=%v", outcome, publishErr)
|
||||
}
|
||||
@@ -95,7 +95,7 @@ func TestItemBatchPublishPortPersistsRemoteCheckpoint(t *testing.T) {
|
||||
checkpointPort := NewItemBatchPublishPort(store, func() mtop.Client { return client }, nil, nil, nil, nil, nil)
|
||||
// checkpointOutcome 保存从远端检查点恢复出的应用结果。
|
||||
// checkpointErr 保存检查点恢复阶段的错误。
|
||||
checkpointOutcome, checkpointErr := checkpointPort.PublishRemoteRow(ctx, admin.ID, batchRowApplicationModel(savedRows[0]), "worker-remote")
|
||||
checkpointOutcome, checkpointErr := checkpointPort.PublishRemoteRow(ctx, admin.ID, batchRowApplicationModel(savedRows[0]), "worker-remote", nil)
|
||||
if checkpointErr != nil || checkpointOutcome.Result == nil || checkpointOutcome.Result.ItemID != "remote-item" {
|
||||
t.Fatalf("远端检查点重试异常: outcome=%+v err=%v", checkpointOutcome, checkpointErr)
|
||||
}
|
||||
@@ -109,7 +109,7 @@ func TestItemBatchPublishPortRejectsMissingDependencies(t *testing.T) {
|
||||
// port 是未配置数据库的批量远端适配器。
|
||||
port := NewItemBatchPublishPort(nil, nil, nil, nil, nil, func(string, string) ([]byte, string, string, error) { return nil, "", "", nil }, func(context.Context, string) ([]byte, string, error) { return nil, "", nil })
|
||||
// _, publishErr 保存依赖校验错误。
|
||||
_, publishErr := port.PublishRemoteRow(context.Background(), 1, itemapp.BatchRow{BatchID: "batch"}, "worker")
|
||||
_, publishErr := port.PublishRemoteRow(context.Background(), 1, itemapp.BatchRow{BatchID: "batch"}, "worker", nil)
|
||||
if publishErr == nil {
|
||||
t.Fatal("缺少数据库时不应伪装批量远端发布成功")
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ func (r *ItemBatchRepository) CreateBatch(ctx context.Context, batch itemapp.Bat
|
||||
ErrorMessage: errorMessage, FailureKind: failureKind, RawJSON: string(rawJSON),
|
||||
})
|
||||
}
|
||||
return r.store.PublishBatches.Create(ctx, &db.ItemPublishBatch{ID: batch.ID, UserID: batch.UserID, DefaultCookieID: batch.DefaultCookieID, Filename: batch.Filename, UploadDir: batch.UploadDir, LocationJSON: string(locationJSON), Status: status}, databaseRows)
|
||||
return r.store.PublishBatches.Create(ctx, &db.ItemPublishBatch{ID: batch.ID, UserID: batch.UserID, DefaultCookieID: batch.DefaultCookieID, Filename: batch.Filename, UploadDir: batch.UploadDir, LocationJSON: string(locationJSON), PublishIntervalSeconds: batch.PublishIntervalSeconds, Status: status}, databaseRows)
|
||||
}
|
||||
|
||||
// PendingRows 查询批次待处理明细并转换为应用模型。
|
||||
@@ -107,6 +107,15 @@ func (r *ItemBatchRepository) RenewBatchLease(ctx context.Context, batchID, work
|
||||
return r.store.PublishBatches.RenewBatchLease(ctx, batchID, workerToken, leaseExpiresAt)
|
||||
}
|
||||
|
||||
// ReservePublishSlot 原子预留一次符合批次间隔的最终商品发布时刻。
|
||||
func (r *ItemBatchRepository) ReservePublishSlot(ctx context.Context, batchID, workerToken string, minimumLastStartedAtMillis, startedAtMillis int64) (bool, error) {
|
||||
// err 表示适配器依赖校验错误。
|
||||
if err := r.validate(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
return r.store.PublishBatches.ReservePublishSlot(ctx, batchID, workerToken, minimumLastStartedAtMillis, startedAtMillis)
|
||||
}
|
||||
|
||||
// GetBatch 查询批次并转换为应用状态模型。
|
||||
func (r *ItemBatchRepository) GetBatch(ctx context.Context, userID int64, batchID string) (itemapp.BatchInfo, error) {
|
||||
// err 表示适配器依赖校验错误。
|
||||
@@ -398,7 +407,8 @@ func batchInfoApplicationModel(batch db.ItemPublishBatch) itemapp.BatchInfo {
|
||||
return itemapp.BatchInfo{
|
||||
ID: batch.ID, UserID: batch.UserID, Status: batch.Status, WorkerToken: batch.WorkerToken,
|
||||
DefaultCookieID: batch.DefaultCookieID, Filename: batch.Filename, UploadDir: batch.UploadDir,
|
||||
LocationJSON: batch.LocationJSON, TotalCount: batch.TotalCount, SuccessCount: batch.SuccessCount,
|
||||
LocationJSON: batch.LocationJSON, PublishIntervalSeconds: batch.PublishIntervalSeconds, LastPublishStartedAtMillis: batch.LastPublishStartedAtMillis,
|
||||
TotalCount: batch.TotalCount, SuccessCount: batch.SuccessCount,
|
||||
FailedCount: batch.FailedCount, LeaseExpiresAt: batch.LeaseExpiresAt,
|
||||
CreatedAt: batch.CreatedAt, UpdatedAt: batch.UpdatedAt,
|
||||
}
|
||||
|
||||
@@ -19,6 +19,8 @@ type BatchPreviewPersistenceBatch struct {
|
||||
UploadDir string
|
||||
// Location 是批次统一使用的发货地。
|
||||
Location Location
|
||||
// PublishIntervalSeconds 是相邻两次最终商品发布请求的最小间隔秒数。
|
||||
PublishIntervalSeconds int
|
||||
// Status 是创建时的批次状态。
|
||||
Status string
|
||||
}
|
||||
|
||||
@@ -79,6 +79,10 @@ type BatchInfo struct {
|
||||
UploadDir string
|
||||
// LocationJSON 是批次统一发货地配置的 JSON。
|
||||
LocationJSON string
|
||||
// PublishIntervalSeconds 是相邻两次最终商品发布请求的最小间隔秒数。
|
||||
PublishIntervalSeconds int
|
||||
// LastPublishStartedAtMillis 是最近一次最终商品发布请求开始的 Unix 毫秒时间戳。
|
||||
LastPublishStartedAtMillis int64
|
||||
// TotalCount 是批次明细总数。
|
||||
TotalCount int
|
||||
// SuccessCount 是已成功发布的明细数。
|
||||
@@ -117,12 +121,14 @@ type BatchRepository interface {
|
||||
FinalizeInterrupted(context.Context, string, string, string) (string, bool, error)
|
||||
// DeleteUpload 清理已完成批次的上传文件及其数据库记录。
|
||||
DeleteUpload(context.Context, string, string) error
|
||||
// ReservePublishSlot 原子预留一次最终商品发布时刻。
|
||||
ReservePublishSlot(context.Context, string, string, int64, int64) (bool, error)
|
||||
}
|
||||
|
||||
// BatchPublisher 执行单条商品发布;平台、凭证和自动化细节由适配器负责。
|
||||
type BatchPublisher interface {
|
||||
// PublishRow 发布一条批量商品并完成本地结果落库。
|
||||
PublishRow(context.Context, int64, BatchRow, string) error
|
||||
// PublishRow 在图片上传和类目准备完成后调用 beforePublish,再发布一条商品并完成本地结果落库。
|
||||
PublishRow(context.Context, int64, BatchRow, string, func(context.Context) error) error
|
||||
}
|
||||
|
||||
// PostPublishError 表示平台发布成功后,响应 Cookie 或本地后置步骤未能完成。
|
||||
@@ -203,8 +209,8 @@ type BatchPublishOutcome struct {
|
||||
|
||||
// BatchPublishPort 定义单行批量远端发布能力;凭证和平台 DTO 由适配器内部处理。
|
||||
type BatchPublishPort interface {
|
||||
// PublishRemoteRow 执行远端发布并保存远端检查点,不负责商品自动化规则。
|
||||
PublishRemoteRow(context.Context, int64, BatchRow, string) (BatchPublishOutcome, error)
|
||||
// PublishRemoteRow 在图片准备完成后调用 beforePublish,再执行远端发布并保存检查点。
|
||||
PublishRemoteRow(context.Context, int64, BatchRow, string, func(context.Context) error) (BatchPublishOutcome, error)
|
||||
}
|
||||
|
||||
// FailureClassifier 将发布错误转换为用户可见消息和稳定失败分类。
|
||||
@@ -214,10 +220,10 @@ type FailureClassifier func(error, string) (string, string)
|
||||
type BatchRunOptions struct {
|
||||
// LeaseDuration 是每次续租所使用的租约时长。
|
||||
LeaseDuration time.Duration
|
||||
// JobDelay 根据已处理行下标返回下一行前的等待时长。
|
||||
JobDelay func(int) time.Duration
|
||||
// Wait 在等待行间隔期间响应 Context 取消。
|
||||
Wait func(context.Context, time.Duration) error
|
||||
// Now 提供当前时间,用于计算并持久化最终发布请求的强制间隔。
|
||||
Now func() time.Time
|
||||
// IsSessionExpired 判断错误是否要求立即中断剩余明细。
|
||||
IsSessionExpired func(error) bool
|
||||
// ClassifyFailure 生成失败明细的消息和分类。
|
||||
@@ -245,12 +251,12 @@ func NewBatchRunner(repository BatchRepository, publisher BatchPublisher, option
|
||||
if options.LeaseDuration <= 0 {
|
||||
options.LeaseDuration = 5 * time.Minute
|
||||
}
|
||||
if options.JobDelay == nil {
|
||||
options.JobDelay = func(index int) time.Duration { return time.Duration(10+index%21) * time.Second }
|
||||
}
|
||||
if options.Wait == nil {
|
||||
options.Wait = waitWithContext
|
||||
}
|
||||
if options.Now == nil {
|
||||
options.Now = time.Now
|
||||
}
|
||||
if options.IsSessionExpired == nil {
|
||||
options.IsSessionExpired = func(error) bool { return false }
|
||||
}
|
||||
@@ -270,8 +276,8 @@ func (runner *BatchRunner) Run(ctx context.Context, userID int64, batchID, worke
|
||||
}
|
||||
return err
|
||||
}
|
||||
// rowIndex 表示当前明细在 worker 队列中的下标;row 保存待发布商品明细。
|
||||
for rowIndex, row := range rows {
|
||||
// row 表示当前待发布商品明细。
|
||||
for _, row := range rows {
|
||||
if ctx.Err() != nil {
|
||||
runner.finishInterrupted(ctx, userID, batchID, workerToken)
|
||||
return ctx.Err()
|
||||
@@ -300,8 +306,12 @@ func (runner *BatchRunner) Run(ctx context.Context, userID int64, batchID, worke
|
||||
if !claimed {
|
||||
continue
|
||||
}
|
||||
// beforePublish 在图片上传和类目准备完成后,原子预留符合强制间隔的最终发布时刻。
|
||||
beforePublish := func(publishCtx context.Context) error {
|
||||
return runner.reservePublishSlot(publishCtx, userID, batchID, workerToken, batch.PublishIntervalSeconds)
|
||||
}
|
||||
// rowErr 保存当前商品发布及本地结果落库错误。
|
||||
if rowErr := runner.publisher.PublishRow(ctx, userID, row, workerToken); rowErr != nil {
|
||||
if rowErr := runner.publisher.PublishRow(ctx, userID, row, workerToken, beforePublish); rowErr != nil {
|
||||
// statusCtx、statusCancel 让外部动作已返回后的失败事实写入不受请求取消影响,并限制补偿等待时间。
|
||||
statusCtx, statusCancel := statusContext(ctx)
|
||||
// status 保存失败分类所需的批次状态。
|
||||
@@ -331,18 +341,52 @@ func (runner *BatchRunner) Run(ctx context.Context, userID int64, batchID, worke
|
||||
}
|
||||
return recountErr
|
||||
}
|
||||
if rowIndex < len(rows)-1 {
|
||||
// waitErr 保存行间隔等待期间的取消错误。
|
||||
if waitErr := runner.options.Wait(ctx, runner.options.JobDelay(rowIndex)); waitErr != nil {
|
||||
runner.finishInterrupted(ctx, userID, batchID, workerToken)
|
||||
return waitErr
|
||||
}
|
||||
}
|
||||
}
|
||||
runner.finish(ctx, userID, batchID, workerToken)
|
||||
return nil
|
||||
}
|
||||
|
||||
// reservePublishSlot 在最终商品发布请求前预留批次级时隙;图片上传和类目准备不受该等待影响。
|
||||
func (runner *BatchRunner) reservePublishSlot(ctx context.Context, userID int64, batchID, workerToken string, intervalSeconds int) error {
|
||||
// interval 保存归一化后的最小发布间隔;历史批次缺失配置时保持五秒默认值。
|
||||
interval := time.Duration(intervalSeconds) * time.Second
|
||||
if intervalSeconds <= 0 {
|
||||
interval = 5 * time.Second
|
||||
}
|
||||
for {
|
||||
// now 保存本次预留尝试使用的时间,统一换算为 Unix 毫秒避免秒级截断缩短间隔。
|
||||
now := runner.options.Now().UTC()
|
||||
// startedAtMillis 保存本次候选最终发布请求的开始毫秒值。
|
||||
startedAtMillis := now.UnixMilli()
|
||||
// minimumLastStartedAtMillis 保存允许替换旧时隙的最晚毫秒值。
|
||||
minimumLastStartedAtMillis := now.Add(-interval).UnixMilli()
|
||||
// reserved、reserveErr 保存原子时隙预留结果及持久化错误。
|
||||
reserved, reserveErr := runner.repository.ReservePublishSlot(ctx, batchID, workerToken, minimumLastStartedAtMillis, startedAtMillis)
|
||||
if reserveErr != nil {
|
||||
return reserveErr
|
||||
}
|
||||
if reserved {
|
||||
return nil
|
||||
}
|
||||
// batch、batchErr 保存用于判断租约和下次可发布时刻的最新批次快照。
|
||||
batch, batchErr := runner.repository.GetBatch(ctx, userID, batchID)
|
||||
if batchErr != nil || batch.Status != "running" || batch.WorkerToken != workerToken {
|
||||
return ErrBatchLeaseLost
|
||||
}
|
||||
// lastStartedAt 保存最近一次最终发布请求开始时间。
|
||||
lastStartedAt := time.UnixMilli(batch.LastPublishStartedAtMillis)
|
||||
// waitFor 保存距可用发布时隙还需等待的时间。
|
||||
waitFor := lastStartedAt.Add(interval).Sub(runner.options.Now().UTC())
|
||||
if waitFor <= 0 {
|
||||
waitFor = time.Millisecond
|
||||
}
|
||||
// waitErr 保存等待下一个可用最终发布时隙期间的取消错误。
|
||||
if waitErr := runner.options.Wait(ctx, waitFor); waitErr != nil {
|
||||
return waitErr
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// renewLease 续租批次并将失去租约转换为统一应用错误。
|
||||
func (runner *BatchRunner) renewLease(ctx context.Context, batchID, workerToken string) error {
|
||||
// renewed 表示数据库是否仍认可当前 worker 的租约。
|
||||
|
||||
@@ -104,6 +104,14 @@ func (r *batchRunnerRepository) FinalizeInterrupted(_ context.Context, _, _, _ s
|
||||
// DeleteUpload 记录上传目录清理调用。
|
||||
func (r *batchRunnerRepository) DeleteUpload(_ context.Context, _, _ string) error { return nil }
|
||||
|
||||
// ReservePublishSlot 测试仓储始终允许当前 worker 预留发布时隙。
|
||||
func (r *batchRunnerRepository) ReservePublishSlot(_ context.Context, _, _ string, _, startedAtMillis int64) (bool, error) {
|
||||
r.mu.Lock()
|
||||
defer r.mu.Unlock()
|
||||
r.batch.LastPublishStartedAtMillis = startedAtMillis
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// batchRunnerPublisher 是可控的单行发布替身。
|
||||
type batchRunnerPublisher struct {
|
||||
// err 保存发布失败错误。
|
||||
@@ -113,7 +121,7 @@ type batchRunnerPublisher struct {
|
||||
}
|
||||
|
||||
// PublishRow 返回预置错误并统计调用次数。
|
||||
func (p *batchRunnerPublisher) PublishRow(_ context.Context, _ int64, _ BatchRow, _ string) error {
|
||||
func (p *batchRunnerPublisher) PublishRow(_ context.Context, _ int64, _ BatchRow, _ string, _ func(context.Context) error) error {
|
||||
p.calls++
|
||||
return p.err
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ type batchCoordinatorBlockingPublisher struct {
|
||||
}
|
||||
|
||||
// PublishRow 等待 Context 取消并返回取消错误,模拟不可控外部发布调用。
|
||||
func (publisher *batchCoordinatorBlockingPublisher) PublishRow(ctx context.Context, _ int64, _ BatchRow, _ string) error {
|
||||
func (publisher *batchCoordinatorBlockingPublisher) PublishRow(ctx context.Context, _ int64, _ BatchRow, _ string, _ func(context.Context) error) error {
|
||||
select {
|
||||
case publisher.started <- struct{}{}:
|
||||
default:
|
||||
@@ -27,7 +27,7 @@ func (publisher *batchCoordinatorBlockingPublisher) PublishRow(ctx context.Conte
|
||||
type batchCoordinatorEmptyPublisher struct{}
|
||||
|
||||
// PublishRow 返回成功,避免测试等待真实平台调用。
|
||||
func (batchCoordinatorEmptyPublisher) PublishRow(context.Context, int64, BatchRow, string) error {
|
||||
func (batchCoordinatorEmptyPublisher) PublishRow(context.Context, int64, BatchRow, string, func(context.Context) error) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ func newBatchWorkerCoordinatorFixture(t *testing.T, publisher BatchPublisher) (*
|
||||
// repository 保存一个正在运行且包含一条待发布明细的批次。
|
||||
repository := &batchRunnerRepository{rows: []BatchRow{{ID: 1, BatchID: "batch-1"}}, batch: BatchInfo{ID: "batch-1", UserID: 7, Status: "running", WorkerToken: "token-1"}}
|
||||
// runner、err 保存应用层批次 worker。
|
||||
runner, err := NewBatchRunner(repository, publisher, BatchRunOptions{Wait: func(context.Context, time.Duration) error { return nil }, JobDelay: func(int) time.Duration { return 0 }})
|
||||
runner, err := NewBatchRunner(repository, publisher, BatchRunOptions{Wait: func(context.Context, time.Duration) error { return nil }})
|
||||
if err != nil {
|
||||
t.Fatalf("构造批次 runner: %v", err)
|
||||
}
|
||||
|
||||
@@ -27,14 +27,18 @@ type ItemPublishBatch struct {
|
||||
Filename string // 原始上传文件名
|
||||
UploadDir string // 图片资源目录(发布时读取商品图片的根目录)
|
||||
LocationJSON string // 批次统一使用的发货地 JSON
|
||||
Status string // 批次状态:pending/running/completed/partially_failed/failed
|
||||
TotalCount int // 明细行总数(Recount 维护)
|
||||
SuccessCount int // 成功数(Recount 维护)
|
||||
FailedCount int // 失败数(Recount 维护)
|
||||
WorkerToken string
|
||||
LeaseExpiresAt int64
|
||||
CreatedAt string
|
||||
UpdatedAt string
|
||||
// PublishIntervalSeconds 是相邻两次最终商品发布请求的最小间隔秒数。
|
||||
PublishIntervalSeconds int
|
||||
// LastPublishStartedAtMillis 是最近一次最终商品发布请求开始的 Unix 毫秒时间戳。
|
||||
LastPublishStartedAtMillis int64
|
||||
Status string // 批次状态:pending/running/completed/partially_failed/failed
|
||||
TotalCount int // 明细行总数(Recount 维护)
|
||||
SuccessCount int // 成功数(Recount 维护)
|
||||
FailedCount int // 失败数(Recount 维护)
|
||||
WorkerToken string
|
||||
LeaseExpiresAt int64
|
||||
CreatedAt string
|
||||
UpdatedAt string
|
||||
}
|
||||
|
||||
// ItemPublishBatchRow 是一条待发布的商品明细。
|
||||
@@ -72,6 +76,9 @@ func (b *ItemPublishBatches) Create(ctx context.Context, batch *ItemPublishBatch
|
||||
if strings.TrimSpace(batch.LocationJSON) == "" {
|
||||
batch.LocationJSON = "{}"
|
||||
}
|
||||
if batch.PublishIntervalSeconds <= 0 {
|
||||
batch.PublishIntervalSeconds = 5
|
||||
}
|
||||
// tx、err 用于本次流程后续判断的tx、err
|
||||
tx, err := b.DB.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
@@ -81,10 +88,10 @@ func (b *ItemPublishBatches) Create(ctx context.Context, batch *ItemPublishBatch
|
||||
if // err 用于本次流程后续判断的err
|
||||
_, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO item_publish_batches
|
||||
(id,user_id,default_cookie_id,filename,upload_dir,location_json,status,total_count,success_count,failed_count)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?)`,
|
||||
(id,user_id,default_cookie_id,filename,upload_dir,location_json,publish_interval_seconds,status,total_count,success_count,failed_count)
|
||||
VALUES (?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
batch.ID, batch.UserID, batch.DefaultCookieID, batch.Filename, batch.UploadDir,
|
||||
batch.LocationJSON, batch.Status, len(rows), 0, 0); err != nil {
|
||||
batch.LocationJSON, batch.PublishIntervalSeconds, batch.Status, len(rows), 0, 0); err != nil {
|
||||
return err
|
||||
}
|
||||
// row 表示当前遍历过程中的row
|
||||
@@ -131,11 +138,11 @@ func (b *ItemPublishBatches) Get(ctx context.Context, userID int64, id string) (
|
||||
var out ItemPublishBatch
|
||||
// err 用于本次流程后续判断的err
|
||||
err := b.DB.QueryRowContext(ctx,
|
||||
`SELECT id,user_id,default_cookie_id,filename,upload_dir,COALESCE(location_json,'{}'),status,total_count,success_count,failed_count,
|
||||
`SELECT id,user_id,default_cookie_id,filename,upload_dir,COALESCE(location_json,'{}'),COALESCE(publish_interval_seconds,5),COALESCE(last_publish_started_at_millis,0),status,total_count,success_count,failed_count,
|
||||
COALESCE(worker_token,''),COALESCE(lease_expires_at,0),
|
||||
created_at,updated_at
|
||||
FROM item_publish_batches WHERE id=? AND user_id=?`, id, userID).Scan(
|
||||
&out.ID, &out.UserID, &out.DefaultCookieID, &out.Filename, &out.UploadDir, &out.LocationJSON, &out.Status,
|
||||
&out.ID, &out.UserID, &out.DefaultCookieID, &out.Filename, &out.UploadDir, &out.LocationJSON, &out.PublishIntervalSeconds, &out.LastPublishStartedAtMillis, &out.Status,
|
||||
&out.TotalCount, &out.SuccessCount, &out.FailedCount, &out.WorkerToken, &out.LeaseExpiresAt,
|
||||
&out.CreatedAt, &out.UpdatedAt)
|
||||
if err != nil {
|
||||
@@ -153,7 +160,7 @@ func (b *ItemPublishBatches) ListForUser(ctx context.Context, userID int64, limi
|
||||
limit = 20
|
||||
}
|
||||
// rows、err 用于本次流程后续判断的rows、err
|
||||
rows, err := b.DB.QueryContext(ctx, `SELECT id,user_id,default_cookie_id,filename,upload_dir,COALESCE(location_json,'{}'),status,
|
||||
rows, err := b.DB.QueryContext(ctx, `SELECT id,user_id,default_cookie_id,filename,upload_dir,COALESCE(location_json,'{}'),COALESCE(publish_interval_seconds,5),COALESCE(last_publish_started_at_millis,0),status,
|
||||
total_count,success_count,failed_count,COALESCE(worker_token,''),COALESCE(lease_expires_at,0),created_at,updated_at
|
||||
FROM item_publish_batches WHERE user_id=? ORDER BY created_at DESC,id DESC LIMIT ?`, userID, limit)
|
||||
if err != nil {
|
||||
@@ -166,7 +173,7 @@ func (b *ItemPublishBatches) ListForUser(ctx context.Context, userID int64, limi
|
||||
// batch 用于本次流程后续判断的批次
|
||||
var batch ItemPublishBatch
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Scan(&batch.ID, &batch.UserID, &batch.DefaultCookieID, &batch.Filename, &batch.UploadDir, &batch.LocationJSON,
|
||||
err := rows.Scan(&batch.ID, &batch.UserID, &batch.DefaultCookieID, &batch.Filename, &batch.UploadDir, &batch.LocationJSON, &batch.PublishIntervalSeconds, &batch.LastPublishStartedAtMillis,
|
||||
&batch.Status, &batch.TotalCount, &batch.SuccessCount, &batch.FailedCount, &batch.WorkerToken,
|
||||
&batch.LeaseExpiresAt, &batch.CreatedAt, &batch.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
@@ -182,7 +189,7 @@ func (b *ItemPublishBatches) Recoverable(ctx context.Context, now int64, limit i
|
||||
limit = 20
|
||||
}
|
||||
// rows、err 用于本次流程后续判断的rows、err
|
||||
rows, err := b.DB.QueryContext(ctx, `SELECT id,user_id,default_cookie_id,filename,upload_dir,COALESCE(location_json,'{}'),status,
|
||||
rows, err := b.DB.QueryContext(ctx, `SELECT id,user_id,default_cookie_id,filename,upload_dir,COALESCE(location_json,'{}'),COALESCE(publish_interval_seconds,5),COALESCE(last_publish_started_at_millis,0),status,
|
||||
total_count,success_count,failed_count,COALESCE(worker_token,''),COALESCE(lease_expires_at,0),created_at,updated_at
|
||||
FROM item_publish_batches b
|
||||
WHERE (b.status IN ('running','canceling') AND (b.lease_expires_at=0 OR b.lease_expires_at<?))
|
||||
@@ -199,7 +206,7 @@ func (b *ItemPublishBatches) Recoverable(ctx context.Context, now int64, limit i
|
||||
// batch 用于本次流程后续判断的批次
|
||||
var batch ItemPublishBatch
|
||||
if // err 用于本次流程后续判断的err
|
||||
err := rows.Scan(&batch.ID, &batch.UserID, &batch.DefaultCookieID, &batch.Filename, &batch.UploadDir, &batch.LocationJSON,
|
||||
err := rows.Scan(&batch.ID, &batch.UserID, &batch.DefaultCookieID, &batch.Filename, &batch.UploadDir, &batch.LocationJSON, &batch.PublishIntervalSeconds, &batch.LastPublishStartedAtMillis,
|
||||
&batch.Status, &batch.TotalCount, &batch.SuccessCount, &batch.FailedCount, &batch.WorkerToken,
|
||||
&batch.LeaseExpiresAt, &batch.CreatedAt, &batch.UpdatedAt); err != nil {
|
||||
return nil, err
|
||||
@@ -652,6 +659,21 @@ func (b *ItemPublishBatches) RenewBatchLease(ctx context.Context, batchID, worke
|
||||
return err == nil && n == 1, err
|
||||
}
|
||||
|
||||
// ReservePublishSlot 仅在当前 worker 仍持有运行中批次且上一时隙已满足间隔时原子记录新的发布开始时刻。
|
||||
func (b *ItemPublishBatches) ReservePublishSlot(ctx context.Context, batchID, workerToken string, minimumLastStartedAtMillis, startedAtMillis int64) (bool, error) {
|
||||
// res、err 保存原子时隙更新结果。
|
||||
res, err := b.DB.ExecContext(ctx, `UPDATE item_publish_batches
|
||||
SET last_publish_started_at_millis=?,updated_at=CURRENT_TIMESTAMP
|
||||
WHERE id=? AND status='running' AND worker_token=? AND COALESCE(last_publish_started_at_millis,0)<=?`,
|
||||
startedAtMillis, batchID, workerToken, minimumLastStartedAtMillis)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
// n、rowsErr 保存本次时隙更新影响的行数及读取错误。
|
||||
n, rowsErr := res.RowsAffected()
|
||||
return rowsErr == nil && n == 1, rowsErr
|
||||
}
|
||||
|
||||
// FailClaimedBatch 释放初始化阶段失败的批次租约。worker token 防止旧 worker
|
||||
// 覆盖已经被新 worker 接管的状态。
|
||||
// FailClaimedBatch 封装FailClaimed批次业务协调。
|
||||
|
||||
@@ -107,7 +107,7 @@ func TestMigrate_AppliesCleanSchema(t *testing.T) {
|
||||
}
|
||||
|
||||
// TestMigrate_UpgradesDatabaseWithMainChatVersions 验证已发布 main 的 00029/00030
|
||||
// 聊天迁移可以原样升级到包含订单补偿幂等键的 00032 最终版本。
|
||||
// 聊天迁移可以原样升级到包含批量发布间隔字段的 00033 最终版本。
|
||||
func TestMigrate_UpgradesDatabaseWithMainChatVersions(t *testing.T) {
|
||||
// tmpDir 保存隔离的已发布 main 数据库目录,测试结束后由 testing 清理。
|
||||
tmpDir := t.TempDir()
|
||||
@@ -133,7 +133,7 @@ func TestMigrate_UpgradesDatabaseWithMainChatVersions(t *testing.T) {
|
||||
|
||||
// ctx 提供迁移 API 所需的调用上下文;升级本身不依赖请求生命周期。
|
||||
ctx := context.Background()
|
||||
// migrateErr 保存从 main 00030 接续 dev 00031/00032 时的迁移失败。
|
||||
// migrateErr 保存从 main 00030 接续 dev 00031/00032/00033 时的迁移失败。
|
||||
if migrateErr := Migrate(ctx, rawDB, DialectSQLite); migrateErr != nil {
|
||||
t.Fatalf("upgrade from main 00030: %v", migrateErr)
|
||||
}
|
||||
@@ -143,13 +143,13 @@ func TestMigrate_UpgradesDatabaseWithMainChatVersions(t *testing.T) {
|
||||
if !columnExists(t, rawDB, "chat_messages", "read_status") || !columnExists(t, rawDB, "chat_messages", "read_at") {
|
||||
t.Fatal("chat read tracking columns should remain after dev schema baseline upgrade")
|
||||
}
|
||||
// finalVersion 验证迁移账本已推进到包含补偿幂等键的最新 dev schema 版本。
|
||||
// finalVersion 验证迁移账本已推进到包含批量发布间隔的最新 dev schema 版本。
|
||||
finalVersion, versionErr := goose.GetDBVersion(rawDB)
|
||||
if versionErr != nil {
|
||||
t.Fatalf("read final migration version: %v", versionErr)
|
||||
}
|
||||
if finalVersion != 32 {
|
||||
t.Fatalf("final migration version=%d, want 32", finalVersion)
|
||||
if finalVersion != 33 {
|
||||
t.Fatalf("final migration version=%d, want 33", finalVersion)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
-- +goose Up
|
||||
-- +goose StatementBegin
|
||||
ALTER TABLE item_publish_batches ADD COLUMN publish_interval_seconds INTEGER NOT NULL DEFAULT 5;
|
||||
ALTER TABLE item_publish_batches ADD COLUMN last_publish_started_at_millis BIGINT NOT NULL DEFAULT 0;
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- +goose Down
|
||||
-- +goose StatementBegin
|
||||
ALTER TABLE item_publish_batches DROP COLUMN last_publish_started_at_millis;
|
||||
ALTER TABLE item_publish_batches DROP COLUMN publish_interval_seconds;
|
||||
-- +goose StatementEnd
|
||||
@@ -0,0 +1,11 @@
|
||||
-- +goose Up
|
||||
-- +goose StatementBegin
|
||||
ALTER TABLE item_publish_batches ADD COLUMN publish_interval_seconds INTEGER NOT NULL DEFAULT 5;
|
||||
ALTER TABLE item_publish_batches ADD COLUMN last_publish_started_at_millis BIGINT NOT NULL DEFAULT 0;
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- +goose Down
|
||||
-- +goose StatementBegin
|
||||
ALTER TABLE item_publish_batches DROP COLUMN last_publish_started_at_millis;
|
||||
ALTER TABLE item_publish_batches DROP COLUMN publish_interval_seconds;
|
||||
-- +goose StatementEnd
|
||||
@@ -0,0 +1,11 @@
|
||||
-- +goose Up
|
||||
-- +goose StatementBegin
|
||||
ALTER TABLE item_publish_batches ADD COLUMN publish_interval_seconds INTEGER NOT NULL DEFAULT 5;
|
||||
ALTER TABLE item_publish_batches ADD COLUMN last_publish_started_at_millis INTEGER NOT NULL DEFAULT 0;
|
||||
-- +goose StatementEnd
|
||||
|
||||
-- +goose Down
|
||||
-- +goose StatementBegin
|
||||
ALTER TABLE item_publish_batches DROP COLUMN last_publish_started_at_millis;
|
||||
ALTER TABLE item_publish_batches DROP COLUMN publish_interval_seconds;
|
||||
-- +goose StatementEnd
|
||||
@@ -50,6 +50,9 @@ func TestPublishBatches_CreateGetRows(t *testing.T) {
|
||||
if got.TotalCount != 3 || got.SuccessCount != 0 || got.FailedCount != 0 || got.Status != "pending" {
|
||||
t.Fatalf("batch 字段: %#v", got)
|
||||
}
|
||||
if got.PublishIntervalSeconds != 5 || got.LastPublishStartedAtMillis != 0 {
|
||||
t.Fatalf("批量发布间隔默认值异常: interval=%d last=%d", got.PublishIntervalSeconds, got.LastPublishStartedAtMillis)
|
||||
}
|
||||
// Get 隔离校验:不同 user_id 应 ErrNotFound。
|
||||
if _, err := s.PublishBatches.Get(ctx, uid+999, "b1"); !errors.Is(err, ErrNotFound) {
|
||||
t.Fatalf("跨用户 Get 应 ErrNotFound, got %v", err)
|
||||
@@ -82,6 +85,50 @@ func TestPublishBatches_CreateGetRows(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishBatches_ReservePublishSlot 验证批量最终发布时隙的原子预留和最小间隔条件。
|
||||
func TestPublishBatches_ReservePublishSlot(t *testing.T) {
|
||||
// s、cleanup 保存本次测试使用的 SQLite 存储及清理函数。
|
||||
s, cleanup := newTestDB(t)
|
||||
defer cleanup()
|
||||
// ctx 提供数据库操作的独立生命周期。
|
||||
ctx := context.Background()
|
||||
// uid 保存批次所属测试用户标识。
|
||||
uid, _ := seedAccount(t, s)
|
||||
// batch 保存配置了七秒最终发布间隔的测试批次。
|
||||
batch := makePublishBatch(uid, "slot-batch")
|
||||
batch.PublishIntervalSeconds = 7
|
||||
// createErr 保存批次及明细写入错误。
|
||||
if createErr := s.PublishBatches.Create(ctx, batch, []ItemPublishBatchRow{{RowNo: 1, Title: "A", Price: "1"}, {RowNo: 2, Title: "B", Price: "1"}}); createErr != nil {
|
||||
t.Fatal(createErr)
|
||||
}
|
||||
// startedAt 保存首次最终发布请求的模拟开始时刻。
|
||||
startedAt := int64(1_700_000_000_000)
|
||||
// claimed、claimErr 保存批次租约抢占结果及错误。
|
||||
if claimed, claimErr := s.PublishBatches.ClaimBatch(ctx, batch.ID, "slot-worker", time.Now().Add(time.Minute).Unix()); claimErr != nil || !claimed {
|
||||
t.Fatalf("claim batch: claimed=%v err=%v", claimed, claimErr)
|
||||
}
|
||||
// reserved、err 保存首次时隙预留结果。
|
||||
reserved, err := s.PublishBatches.ReservePublishSlot(ctx, batch.ID, "slot-worker", startedAt-7_000, startedAt)
|
||||
if err != nil || !reserved {
|
||||
t.Fatalf("首次预留失败: reserved=%v err=%v", reserved, err)
|
||||
}
|
||||
// blocked、err 保存未满足七秒间隔时的第二次预留结果。
|
||||
blocked, err := s.PublishBatches.ReservePublishSlot(ctx, batch.ID, "slot-worker", startedAt+6_999-7_000, startedAt+6_999)
|
||||
if err != nil || blocked {
|
||||
t.Fatalf("间隔不足时不应预留: blocked=%v err=%v", blocked, err)
|
||||
}
|
||||
// allowed、err 保存达到七秒间隔后的预留结果。
|
||||
allowed, err := s.PublishBatches.ReservePublishSlot(ctx, batch.ID, "slot-worker", startedAt, startedAt+7_000)
|
||||
if err != nil || !allowed {
|
||||
t.Fatalf("满足间隔后预留失败: allowed=%v err=%v", allowed, err)
|
||||
}
|
||||
// stored、err 保存数据库中最后一次预留时刻,用于确认重启恢复所需检查点已持久化。
|
||||
stored, err := s.PublishBatches.Get(ctx, uid, batch.ID)
|
||||
if err != nil || stored.LastPublishStartedAtMillis != startedAt+7_000 || stored.PublishIntervalSeconds != 7 {
|
||||
t.Fatalf("时隙检查点异常: batch=%+v err=%v", stored, err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPublishBatchesListAndRecoverInterrupted 封装Test发布批次列表ListAndRecoverInterrupted业务协调。
|
||||
func TestPublishBatchesListAndRecoverInterrupted(t *testing.T) {
|
||||
// s、cleanup 用于本次流程后续判断的s、cleanup
|
||||
|
||||
@@ -192,6 +192,12 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
// batchLocation 用于本次流程后续判断的批次地址
|
||||
var batchLocation publishBatchLocation
|
||||
// publishIntervalSeconds 保存用户为本批次设置的最终发布最小间隔,单位为秒。
|
||||
publishIntervalSeconds, intervalErr := parsePublishIntervalSeconds(r.FormValue("publish_interval_seconds"))
|
||||
if intervalErr != nil {
|
||||
writeErr(w, http.StatusBadRequest, intervalErr.Error())
|
||||
return
|
||||
}
|
||||
// locationJSON 用于本次流程后续判断的地址JSON
|
||||
locationJSON := strings.TrimSpace(r.FormValue("location"))
|
||||
if locationJSON != "" {
|
||||
@@ -307,7 +313,8 @@ func (s *Server) previewItemPublishBatch(w http.ResponseWriter, r *http.Request)
|
||||
// preview、err 保存预检结果持久化服务返回的应用模型及错误。
|
||||
preview, err := s.itemBatchPreviewPersistenceApplication().Persist(r.Context(), itemapp.BatchPreviewPersistenceBatch{
|
||||
ID: batchID, UserID: sess.UserID, DefaultCookieID: defaultCookieID, Filename: sourceName,
|
||||
UploadDir: uploadDir, Location: itemapp.Location{Area: batchLocation.Area, City: batchLocation.City, DivisionID: batchLocation.DivisionID, Longitude: batchLocation.Longitude, Latitude: batchLocation.Latitude, POIID: batchLocation.POIID, POIName: batchLocation.POIName, Province: batchLocation.Province},
|
||||
UploadDir: uploadDir, PublishIntervalSeconds: publishIntervalSeconds,
|
||||
Location: itemapp.Location{Area: batchLocation.Area, City: batchLocation.City, DivisionID: batchLocation.DivisionID, Longitude: batchLocation.Longitude, Latitude: batchLocation.Latitude, POIID: batchLocation.POIID, POIName: batchLocation.POIName, Province: batchLocation.Province},
|
||||
}, previewRows)
|
||||
if err != nil {
|
||||
if errors.Is(err, itemapp.ErrBatchPreviewNoRows) {
|
||||
@@ -618,7 +625,7 @@ func publishBatchApplicationToResponse(batch itemapp.BatchInfo, rows []itemapp.B
|
||||
ID: batch.ID, Status: batch.Status, Filename: batch.Filename,
|
||||
Total: batch.TotalCount, Success: batch.SuccessCount, Failed: batch.FailedCount,
|
||||
Pending: pending, Running: running, Retryable: retryable, Rows: outRows,
|
||||
Location: json.RawMessage(locationJSON), CreatedAt: batch.CreatedAt, UpdatedAt: batch.UpdatedAt,
|
||||
Location: json.RawMessage(locationJSON), PublishIntervalSeconds: batch.PublishIntervalSeconds, CreatedAt: batch.CreatedAt, UpdatedAt: batch.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -708,6 +715,24 @@ func atoiPublishDefault(raw string, def int) int {
|
||||
return def
|
||||
}
|
||||
|
||||
// parsePublishIntervalSeconds 解析批量铺货的最终发布最小间隔,空值使用五秒默认值。
|
||||
func parsePublishIntervalSeconds(raw string) (int, error) {
|
||||
// normalized 保存去除空白后的用户输入;空值保持兼容默认五秒。
|
||||
normalized := strings.TrimSpace(raw)
|
||||
if normalized == "" {
|
||||
return 5, nil
|
||||
}
|
||||
// interval、err 保存严格解析后的秒数与输入错误。
|
||||
interval, err := strconv.Atoi(normalized)
|
||||
if err != nil {
|
||||
return 0, errors.New("发布间隔必须是整数秒")
|
||||
}
|
||||
if interval < 1 || interval > 3600 {
|
||||
return 0, errors.New("发布间隔必须是 1 到 3600 秒")
|
||||
}
|
||||
return interval, nil
|
||||
}
|
||||
|
||||
// firstNonEmpty 返回参数中第一个非空白字符串。
|
||||
func firstNonEmpty(values ...string) string {
|
||||
// v 是当前遍历到的候选字符串。
|
||||
@@ -728,7 +753,7 @@ type serverBatchPublisher struct {
|
||||
}
|
||||
|
||||
// PublishRow 调用批量远端端口并收口本地结果,应用层不接触数据库或 MTOP 类型。
|
||||
func (p serverBatchPublisher) PublishRow(ctx context.Context, userID int64, row itemapp.BatchRow, workerToken string) error {
|
||||
func (p serverBatchPublisher) PublishRow(ctx context.Context, userID int64, row itemapp.BatchRow, workerToken string, beforePublish func(context.Context) error) error {
|
||||
if p.remotePort == nil {
|
||||
return errors.New("批量发布端口未装配")
|
||||
}
|
||||
@@ -736,7 +761,7 @@ func (p serverBatchPublisher) PublishRow(ctx context.Context, userID int64, row
|
||||
return errors.New("批量发布本地收口端口未装配")
|
||||
}
|
||||
// outcome、err 保存远端发布结果及适配器错误。
|
||||
outcome, err := p.remotePort.PublishRemoteRow(ctx, userID, row, workerToken)
|
||||
outcome, err := p.remotePort.PublishRemoteRow(ctx, userID, row, workerToken, beforePublish)
|
||||
if err != nil {
|
||||
// uncertainErr 表示远端调用已经发生但结果无法可靠确认。
|
||||
var uncertainErr *itemapp.UncertainRemotePublishError
|
||||
|
||||
@@ -531,7 +531,7 @@ func TestPublishBatchRetryResumesSavedRemoteResultWithoutPublishingAgain(t *test
|
||||
// applicationRow 保存恢复测试所需的非敏感批次明细模型。
|
||||
applicationRow := itemapp.BatchRow{ID: rows[0].ID, BatchID: rows[0].BatchID, RowNo: rows[0].RowNo, CookieID: rows[0].CookieID, Title: rows[0].Title, Description: rows[0].Description, Price: rows[0].Price, OriginalPrice: rows[0].OriginalPrice, Quantity: rows[0].Quantity, PostageMode: rows[0].PostageMode, Postage: rows[0].Postage, ImagesJSON: rows[0].ImagesJSON, CategoryJSON: rows[0].CategoryJSON, AutomationJSON: rows[0].AutomationJSON, RawJSON: rows[0].RawJSON, ItemID: rows[0].ItemID, ItemURL: rows[0].ItemURL, Status: rows[0].Status, ErrorMessage: rows[0].ErrorMessage, FailureKind: rows[0].FailureKind, WorkerToken: rows[0].WorkerToken, CreatedAt: rows[0].CreatedAt, UpdatedAt: rows[0].UpdatedAt}
|
||||
// err 保存应用层批量发布适配器的恢复结果。
|
||||
err = (serverBatchPublisher{remotePort: port, localService: localService}).PublishRow(ctx, admin.ID, applicationRow, "worker-2")
|
||||
err = (serverBatchPublisher{remotePort: port, localService: localService}).PublishRow(ctx, admin.ID, applicationRow, "worker-2", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("resume local persistence: %v", err)
|
||||
}
|
||||
|
||||
@@ -17,6 +17,38 @@ import (
|
||||
"xianyu-go/internal/db"
|
||||
)
|
||||
|
||||
// TestParsePublishIntervalSeconds 验证批量发布间隔的默认值与边界校验。
|
||||
func TestParsePublishIntervalSeconds(t *testing.T) {
|
||||
// cases 保存空值、有效值和越界值的确定性解析样例。
|
||||
cases := []struct {
|
||||
name string
|
||||
raw string
|
||||
want int
|
||||
bad bool
|
||||
}{
|
||||
{name: "default", raw: "", want: 5},
|
||||
{name: "custom", raw: "12", want: 12},
|
||||
{name: "not-number", raw: "abc", bad: true},
|
||||
{name: "zero", raw: "0", bad: true},
|
||||
{name: "too-large", raw: "3601", bad: true},
|
||||
}
|
||||
for _, testCase := range cases { // testCase 表示当前发布间隔解析样例。
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
// got、err 保存当前样例的解析结果。
|
||||
got, err := parsePublishIntervalSeconds(testCase.raw)
|
||||
if testCase.bad {
|
||||
if err == nil {
|
||||
t.Fatalf("非法间隔应返回错误,got=%d", got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil || got != testCase.want {
|
||||
t.Fatalf("解析结果=%d err=%v want=%d", got, err, testCase.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestParsePublishSheetBytes 表格解析各格式。
|
||||
func TestParsePublishSheetBytes(t *testing.T) {
|
||||
// CSV。
|
||||
@@ -69,7 +101,7 @@ func TestParsePublishSheetBytesWithLimitRejectsTooManyRows(t *testing.T) {
|
||||
// TestPreviewItemPublishBatchCSV 预检 CSV 批量发布(含图片 zip)。
|
||||
func TestPreviewItemPublishBatchCSV(t *testing.T) {
|
||||
// srv、cleanup 用于本次流程后续判断的srv、cleanup
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// h 用于本次流程后续判断的h
|
||||
h := srv.Router()
|
||||
@@ -95,6 +127,7 @@ func TestPreviewItemPublishBatchCSV(t *testing.T) {
|
||||
_ = mw.WriteField("fallback_category_id", "5001")
|
||||
_ = mw.WriteField("fallback_category_name", "虚拟商品")
|
||||
_ = mw.WriteField("fallback_channel_category_id", "6001")
|
||||
_ = mw.WriteField("publish_interval_seconds", "12")
|
||||
// csvField 用于本次流程后续判断的csv字段
|
||||
csvField, _ := mw.CreateFormFile("file", "products.csv")
|
||||
csvField.Write([]byte("账号ID,标题,价格,库存,图片\nacc1,商品A,12.50,5,img/a.png\n"))
|
||||
@@ -126,6 +159,11 @@ func TestPreviewItemPublishBatchCSV(t *testing.T) {
|
||||
if category["cat_id"] != "5001" || category["cat_name"] != "虚拟商品" {
|
||||
t.Fatalf("预检未保存兜底类目: %+v", category)
|
||||
}
|
||||
// storedBatch 验证页面设置的发布间隔已经进入批次持久化模型。
|
||||
storedBatch, storedErr := store.PublishBatches.Get(context.Background(), 1, res["preview_id"].(string))
|
||||
if storedErr != nil || storedBatch.PublishIntervalSeconds != 12 {
|
||||
t.Fatalf("批量发布间隔未持久化: batch=%+v err=%v", storedBatch, storedErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestPreviewItemPublishBatchAllowsEmptyDefaultCategory 封装TestPreview商品发布批次AllowsEmptyDefault分类业务协调。
|
||||
|
||||
@@ -1151,6 +1151,8 @@ type itemPublishBatchResponse struct {
|
||||
Rows []itemPublishBatchRowResponse `json:"rows"`
|
||||
// Location 是批次统一发货地对象。
|
||||
Location any `json:"location"`
|
||||
// PublishIntervalSeconds 是相邻两次最终商品发布请求的最小间隔秒数。
|
||||
PublishIntervalSeconds int `json:"publish_interval_seconds"`
|
||||
// CreatedAt 是任务创建时间。
|
||||
CreatedAt string `json:"created_at"`
|
||||
// UpdatedAt 是任务更新时间。
|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
import{r as n,j as e,b as ie,c as Oe}from"./react-vendor-C_od1ZSF.js";import{g as X,p as ae,a as ce,d as Pe}from"./index-k6Tc6ww6.js";import{c as Le,o as ke}from"./contract-COFcZjyb.js";import{X as de,n as ze,L as J,o as Ge,p as Ie,q as Te,r as $e,s as te,t as De,K as We,u as Ve,v as Je,e as Ke,w as ue,f as He,U as Ee,x as Xe,k as _e,Q as ve,R as Ye,y as Ze,z as Fe,F as Ne,H as es}from"./icons-vendor-CvzvbbIV.js";const ss=(s,t)=>{const r=s.avatar_url||"";if(!r)return"";try{const a=new URL(r,window.location.origin);return a.hostname.endsWith("alicdn.com")&&a.searchParams.set("_v",t),a.toString()}catch{return r}},ts=async s=>{const t=await X("/api/v1/accounts/details",void 0,s),r=Le(t,["data","accounts","details"]),a=Date.now().toString();return r.map(l=>({id:l.id,cookie_configured:l.has_cookie===!0,enabled:l.enabled,auto_confirm:l.auto_confirm,remark:l.remark,pause_duration:l.pause_duration,paused_until:Number(l.paused_until||0),paused:l.paused===!0,username:l.username||"",login_password_configured:void 0,show_browser:l.show_browser===!0||l.show_browser===1||l.show_browser==="1"||l.show_browser==="true",nickname:l.nickname||l.remark||`账号 ${l.id.substring(0,6)}`,avatar_url:ss(l,a),profile_error:l.profile_error||"",ai_enabled:!1,auto_rate_enabled:l.auto_rate_enabled,rate_content:l.rate_content||"不错的买家,交易愉快",auto_polish_enabled:l.auto_polish_enabled,polish_time:l.polish_time||"03:00",last_rate_scan_at:Number(l.last_rate_scan_at||0),last_polish_date:l.last_polish_date||"",last_polish_at:Number(l.last_polish_at||0)}))},as=async s=>{const t=await X("/api/v1/accounts/runtime-status",void 0,s);return ke(t,["statuses","data","result"])||{}},rs=async s=>ce("/api/v1/qr-login/generate",void 0,{...s,timeoutMs:(s==null?void 0:s.timeoutMs)??13e4}),ns=async(s,t)=>X(`/api/v1/qr-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),ls=async(s,t)=>ce(`/api/v1/qr-login/complete-verification/${s}`,{target_account_id:t||""}),os=async(s,t)=>ae(`/api/v1/accounts/${s}/status`,{enabled:t}),is=async s=>Pe(`/api/v1/accounts/${s}`),cs=async(s,t,r)=>ae(`/api/v1/accounts/${s}/pause-duration`,{pause_duration:t},r),ds=async(s,t,r)=>ae(`/api/v1/accounts/${s}/settings`,t,r),us=async(s,t)=>X(`/api/v1/accounts/${s}/long-login`,void 0,t),xs=async(s,t,r)=>ae(`/api/v1/accounts/${s}/long-login`,{enabled:t},r),ms=async(s,t)=>ce("/api/v1/password-login",s,t),bs=async(s,t)=>X(`/api/v1/password-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),hs=async(s,t)=>Pe(`/api/v1/password-login/cancel/${s}`,void 0,t),gs=async s=>ce(`/api/v1/accounts/${s}/refresh-profile`,{}),ps=async s=>{const t=await X("/api/v1/settings/ai-reply",void 0,s);return ke(t,["settings","data","result"])||{}},fs=async(s,t)=>X(`/api/v1/settings/ai-reply/${s}`,void 0,t),ys=async(s,t,r)=>{const a={ai_enabled:t.ai_enabled??!1,max_discount_percent:t.max_discount_percent??10,max_discount_amount:t.max_discount_amount??100,max_bargain_rounds:t.max_bargain_rounds??3,custom_prompts:t.custom_prompts??""};return ae(`/api/v1/settings/ai-reply/${s}`,a,r)},js=s=>{if(Array.isArray(s))return s.filter(Boolean);if(typeof s!="string"||!s.trim())return[];try{const t=JSON.parse(s);if(Array.isArray(t))return t.filter(Boolean)}catch{}return s.split(/[,\s;]+/).map(t=>t.trim()).filter(Boolean)},ws=async s=>{const t=await X("/api/v1/notifications/channels",void 0,s);return{success:!0,data:Le(t,["data","channels","items"]).map(a=>{let l;try{l=typeof a.config=="string"?JSON.parse(a.config):a.config}catch{l={}}const c=a.type==="ding_talk"?"dingtalk":a.type==="lark"?"feishu":a.type;return{id:String(a.id),name:a.name,type:c,config:l,event_types:js(a.event_types),enabled:a.enabled,created_at:a.created_at,updated_at:a.updated_at}})}},_s=async(s,t)=>{const r=await X(`/api/v1/notifications/accounts/${s}/bindings`,void 0,t),a=ke(r,["data","result"])||{};return Array.isArray(a.channel_ids)?a.channel_ids:[]},Ce=async(s,t)=>X(`/api/v1/account-tasks/${s}`,void 0,t),Se=async(s,t,r)=>ae(`/api/v1/account-tasks/${s}`,t,r),vs=async(s,t,r)=>ce(`/api/v1/account-tasks/${s}/run`,{task_type:t},{timeoutMs:12e4,...r}),Re=s=>({account_id:s.id,auto_rate_enabled:s.auto_rate_enabled===!0,rate_content:s.rate_content||"不错的买家,交易愉快",auto_polish_enabled:s.auto_polish_enabled===!0,polish_time:s.polish_time||"03:00",last_rate_scan_at:s.last_rate_scan_at,last_polish_date:s.last_polish_date,last_polish_at:s.last_polish_at}),Y=(s,t,r)=>s===t&&!r.aborted,je=(s,t)=>s instanceof Error?s.message:t,we=s=>s instanceof Error&&s.message==="请求已取消",Ae=(s,t)=>!s&&t==="",Ns=({account:s,onSaved:t})=>{const[r,a]=n.useState(()=>Re(s)),[l,c]=n.useState(!0),[i,d]=n.useState(!1),[b,m]=n.useState(""),[f,h]=n.useState(""),[u,A]=n.useState(null),[k,g]=n.useState(null),p=n.useRef(0),L=n.useRef(null);n.useEffect(()=>{var v;const S=++p.current;(v=L.current)==null||v.abort();const j=new AbortController;return L.current=j,a(Re(s)),A(null),h(""),d(!1),m(""),g(null),c(!0),Ce(s.id,{signal:j.signal}).then(R=>{Y(p.current,S,j.siLine truncated
|
||||
import{r as n,j as e,b as ie,c as Oe}from"./react-vendor-C_od1ZSF.js";import{g as X,p as ae,a as ce,d as Pe}from"./index-CCqtUiU5.js";import{c as Le,o as ke}from"./contract-COFcZjyb.js";import{X as de,n as ze,L as J,o as Ge,p as Ie,q as Te,r as $e,s as te,t as De,K as We,u as Ve,v as Je,e as Ke,w as ue,f as He,U as Ee,x as Xe,k as _e,Q as ve,R as Ye,y as Ze,z as Fe,F as Ne,H as es}from"./icons-vendor-CvzvbbIV.js";const ss=(s,t)=>{const r=s.avatar_url||"";if(!r)return"";try{const a=new URL(r,window.location.origin);return a.hostname.endsWith("alicdn.com")&&a.searchParams.set("_v",t),a.toString()}catch{return r}},ts=async s=>{const t=await X("/api/v1/accounts/details",void 0,s),r=Le(t,["data","accounts","details"]),a=Date.now().toString();return r.map(l=>({id:l.id,cookie_configured:l.has_cookie===!0,enabled:l.enabled,auto_confirm:l.auto_confirm,remark:l.remark,pause_duration:l.pause_duration,paused_until:Number(l.paused_until||0),paused:l.paused===!0,username:l.username||"",login_password_configured:void 0,show_browser:l.show_browser===!0||l.show_browser===1||l.show_browser==="1"||l.show_browser==="true",nickname:l.nickname||l.remark||`账号 ${l.id.substring(0,6)}`,avatar_url:ss(l,a),profile_error:l.profile_error||"",ai_enabled:!1,auto_rate_enabled:l.auto_rate_enabled,rate_content:l.rate_content||"不错的买家,交易愉快",auto_polish_enabled:l.auto_polish_enabled,polish_time:l.polish_time||"03:00",last_rate_scan_at:Number(l.last_rate_scan_at||0),last_polish_date:l.last_polish_date||"",last_polish_at:Number(l.last_polish_at||0)}))},as=async s=>{const t=await X("/api/v1/accounts/runtime-status",void 0,s);return ke(t,["statuses","data","result"])||{}},rs=async s=>ce("/api/v1/qr-login/generate",void 0,{...s,timeoutMs:(s==null?void 0:s.timeoutMs)??13e4}),ns=async(s,t)=>X(`/api/v1/qr-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),ls=async(s,t)=>ce(`/api/v1/qr-login/complete-verification/${s}`,{target_account_id:t||""}),os=async(s,t)=>ae(`/api/v1/accounts/${s}/status`,{enabled:t}),is=async s=>Pe(`/api/v1/accounts/${s}`),cs=async(s,t,r)=>ae(`/api/v1/accounts/${s}/pause-duration`,{pause_duration:t},r),ds=async(s,t,r)=>ae(`/api/v1/accounts/${s}/settings`,t,r),us=async(s,t)=>X(`/api/v1/accounts/${s}/long-login`,void 0,t),xs=async(s,t,r)=>ae(`/api/v1/accounts/${s}/long-login`,{enabled:t},r),ms=async(s,t)=>ce("/api/v1/password-login",s,t),bs=async(s,t)=>X(`/api/v1/password-login/check/${s}`,void 0,{signal:t,timeoutMs:1e4}),hs=async(s,t)=>Pe(`/api/v1/password-login/cancel/${s}`,void 0,t),gs=async s=>ce(`/api/v1/accounts/${s}/refresh-profile`,{}),ps=async s=>{const t=await X("/api/v1/settings/ai-reply",void 0,s);return ke(t,["settings","data","result"])||{}},fs=async(s,t)=>X(`/api/v1/settings/ai-reply/${s}`,void 0,t),ys=async(s,t,r)=>{const a={ai_enabled:t.ai_enabled??!1,max_discount_percent:t.max_discount_percent??10,max_discount_amount:t.max_discount_amount??100,max_bargain_rounds:t.max_bargain_rounds??3,custom_prompts:t.custom_prompts??""};return ae(`/api/v1/settings/ai-reply/${s}`,a,r)},js=s=>{if(Array.isArray(s))return s.filter(Boolean);if(typeof s!="string"||!s.trim())return[];try{const t=JSON.parse(s);if(Array.isArray(t))return t.filter(Boolean)}catch{}return s.split(/[,\s;]+/).map(t=>t.trim()).filter(Boolean)},ws=async s=>{const t=await X("/api/v1/notifications/channels",void 0,s);return{success:!0,data:Le(t,["data","channels","items"]).map(a=>{let l;try{l=typeof a.config=="string"?JSON.parse(a.config):a.config}catch{l={}}const c=a.type==="ding_talk"?"dingtalk":a.type==="lark"?"feishu":a.type;return{id:String(a.id),name:a.name,type:c,config:l,event_types:js(a.event_types),enabled:a.enabled,created_at:a.created_at,updated_at:a.updated_at}})}},_s=async(s,t)=>{const r=await X(`/api/v1/notifications/accounts/${s}/bindings`,void 0,t),a=ke(r,["data","result"])||{};return Array.isArray(a.channel_ids)?a.channel_ids:[]},Ce=async(s,t)=>X(`/api/v1/account-tasks/${s}`,void 0,t),Se=async(s,t,r)=>ae(`/api/v1/account-tasks/${s}`,t,r),vs=async(s,t,r)=>ce(`/api/v1/account-tasks/${s}/run`,{task_type:t},{timeoutMs:12e4,...r}),Re=s=>({account_id:s.id,auto_rate_enabled:s.auto_rate_enabled===!0,rate_content:s.rate_content||"不错的买家,交易愉快",auto_polish_enabled:s.auto_polish_enabled===!0,polish_time:s.polish_time||"03:00",last_rate_scan_at:s.last_rate_scan_at,last_polish_date:s.last_polish_date,last_polish_at:s.last_polish_at}),Y=(s,t,r)=>s===t&&!r.aborted,je=(s,t)=>s instanceof Error?s.message:t,we=s=>s instanceof Error&&s.message==="请求已取消",Ae=(s,t)=>!s&&t==="",Ns=({account:s,onSaved:t})=>{const[r,a]=n.useState(()=>Re(s)),[l,c]=n.useState(!0),[i,d]=n.useState(!1),[b,m]=n.useState(""),[f,h]=n.useState(""),[u,A]=n.useState(null),[k,g]=n.useState(null),p=n.useRef(0),L=n.useRef(null);n.useEffect(()=>{var v;const S=++p.current;(v=L.current)==null||v.abort();const j=new AbortController;return L.current=j,a(Re(s)),A(null),h(""),d(!1),m(""),g(null),c(!0),Ce(s.id,{signal:j.signal}).then(R=>{Y(p.current,S,j.siLine 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(He,{className:"w-4 h-4"}),"AI如何工作"]}),e.jsxs("ul",{className:"text-xs text-blue-800 space-y-1",children:[e.jsx("li",{children:"• 自动识别买家的砍价请求"}),e.jsx("li",{children:"• 根据设定的策略智能回复"}),e.jsx("li",{children:"• 在合理范围内同意降价或礼貌拒绝"}),e.jsx("li",{children:"• 保持专业友好的沟通风格"})]})]})]}),e.jsx("div",{className:"modal-footer",children:e.jsxs("div",{className:"flex gap-3 w-full",children:[e.jsx("button",{onClick:l,className:"flex-1 px-6 py-3 rounded-xl font-bold bg-gray-100 text-gray-700 hover:bg-gray-200 transition-colors",disabled:r,children:"取消"}),e.jsxs("button",{onClick:(()=>void c()),className:"flex-1 ios-btn-primary px-6 py-3 rounded-xl font-bold flex items-center justify-center gap-2",disabled:r,children:[r?e.jsx(J,{className:"w-4 h-4 animate-spin"}):e.jsx($e,{className:"w-4 h-4"}),r?"保存中...":"保存"]})]})})]})}),document.body)},Rs=(s,t)=>{if(!s||!t)return!1;const r=Date.parse(s),a=Date.parse(t);return Number.isFinite(r)&&Number.isFinite(a)&&a<r},As=(s,t)=>s.map(r=>{const a=t[r.id];return!a||Rs(r.runtime_updated_at,a.updated_at)?r:{...r,runtime_state:a.state,runtime_message:a.message||"",runtime_connected:a.connected,runtime_updated_at:a.updated_at}}),qs=s=>{if(!s.enabled||s.runtime_state==="disabled")return{label:"已停用",badge:"bg-gray-100 text-gray-500",dot:"bg-gray-300"};switch(s.runtime_state){case"online":return{label:"在线",badge:"bg-green-100 text-green-700",dot:"bg-green-500"};case"starting":case"connecting":return{label:"连接中",badge:"bg-blue-100 text-blue-700",dot:"bg-blue-500"};case"reconnecting":return{label:"重连中",badge:"bg-amber-100 text-amber-700",dot:"bg-amber-500"};case"auth_expired":return{label:"登录已失效",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};case"verification_required":return{label:"需要验证",badge:"bg-orange-100 text-orange-700",dot:"bg-orange-500"};case"error":case"stopped":return{label:"运行异常",badge:"bg-red-100 text-red-700",dot:"bg-red-500"};default:return{label:"状态检测中",badge:"bg-gray-100 text-gray-600",dot:"bg-gray-400"}}},Ps=Oe.memo(function({account:t,refreshing:r,deleting:a,onRefreshProfile:l,onReauthorize:c,onEdit:i,onAI:d,onTasks:b,onToggle:m,onDelete:f}){const h=qs(t),u=t.runtime_state==="auth_expired"||t.runtime_state==="verification_required";return e.jsx("div",{className:"ios-card rounded-xl p-6 group transition-all duration-300 hover:border-brand",children:e.jsxs("div",{className:"flex min-w-0 items-start gap-5 sm:gap-8",children:[e.jsxs("div",{className:"relative",children:[t.avatar_url?e.jsx("img",{src:t.avatar_url,alt:t.nickname||"账号头像",className:"w-20 h-20 rounded-full object-cover shadow-md ring-4 ring-white bg-gray-100"}):e.jsx("div",{className:"w-20 h-20 rounded-full bg-gray-100 text-gray-400 shadow-md ring-4 ring-white flex items-center justify-center",children:e.jsx(Ee,{className:"w-9 h-9"})}),e.jsx("div",{className:`absolute -bottom-1 -right-1 w-6 h-6 rounded-full border-4 border-white flex items-center justify-center ${h.dot}`,children:t.runtime_state==="online"&&e.jsx(te,{className:"w-3 h-3 text-white"})})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2.5 mb-1",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900 break-words",children:t.nickname||t.remark||`账号 ${t.id.substring(0,6)}...`}),e.jsx("span",{className:`px-2.5 py-0.5 rounded-lg text-xs font-bold ${h.badge}`,children:h.label}),t.ai_enabled&&e.jsxs("span",{className:"px-2.5 py-0.5 rounded-lg bg-purple-100 text-purple-700 text-xs font-bold flex items-center gap-1",children:[e.jsx(ue,{className:"w-3 h-3"})," AI"]}),t.auto_rate_enabled&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-emerald-100 px-2.5 py-0.5 text-xs font-bold text-emerald-700",children:[e.jsx(Xe,{className:"h-3 w-3"})," 自动评价"]}),t.auto_polish_enabled&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-amber-100 px-2.5 py-0.5 text-xs font-bold text-amber-700",children:[e.jsx(Ie,{className:"h-3 w-3"})," 每日擦亮"]}),t.auto_confirm&&e.jsxs("span",{className:"flex items-center gap-1 rounded-lg bg-blue-50 px-2.5 py-0.5 text-xs font-bold text-blue-700",children:[e.jsx(te,{className:"h-3 w-3"})," 自动确认发货"]}),t.profile_error&&e.jsxs("span",{className:"px-2.5 py-0.5 rounded-lg bg-amber-100 text-amber-700 text-xs font-bold flex items-center gap-1",title:t.profile_error,children:[e.jsx(_e,{className:"w-3 h-3"})," 资料未同步"]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap items-center justify-between
Line truncated
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import{b as z,j as e,r as i}from"./react-vendor-C_od1ZSF.js";import{X as G,W as Z,J as D,Y as ee,L as U,N as V,C as H,_ as te,$ as W,a0 as X,a1 as ae,I as se,a2 as le,V as ne,F as re,P as oe,r as ie}from"./icons-vendor-CvzvbbIV.js";import{g as ce,p as de,d as xe,a as Y,b as pe}from"./index-k6Tc6ww6.js";import{c as me}from"./contract-COFcZjyb.js";const he=({dataCards:l,downloadCardTemplate:n,...a})=>{var x;const u=s=>{var h;a.setBatchFile(((h=s.target.files)==null?void 0:h[0])||null)},m=s=>{a.setAppendContent(s.target.value)},_=s=>{a.setAppendTargetId(s.target.value)},f=()=>a.closeBatchModal(),j=()=>a.setBatchTab("create"),d=()=>a.setBatchTab("append"),A=()=>void a.handleRetryBatchCreate(),c=()=>void a.handleRetryBatchAppend(),y=a.batchResult&&"rows"in a.batchResult?a.batchResult:null,N=s=>e.jsxs("option",{value:String(s.id),children:[s.name,"(ID: ",s.id,")"]},s.id),b=()=>void a.handleBatchCreate(),r=()=>void a.handleBatchAppend();return a.showBatchModal?z.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:f,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(G,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:j,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Z,{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(D,{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(ee,{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(D,{className:"w-4 h-4"}),a.batchFile?a.batchFile.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:u})]})]}),((x=a.batchResult)==null?void 0:x.error)&&e.jsxs("div",{className:"rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.batchResult.error}),e.jsx("button",{type:"button",onClick:A,disabled:!a.batchFile||a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),y&&e.jsxs("div",{className:"rounded-xl border border-gray-200 p-4 space-y-2",children:[e.jsxs("div",{className:"text-sm font-bold text-gray-900",children:["共 ",y.total," 行 · 成功 ",y.created," · 失败 ",y.failed]}),y.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:y.rows.filter(s=>!s.success).map(s=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",s.row_no," 行「",s.name,"」:",s.error]},s.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:l.length===0?e.jsx("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 text-sm text-amber-800",children:"暂无 data(批量卡密)类型的卡密组,请先创建一个再充卡密。"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"选择卡密组"}),e.jsx("select",{value:a.appendTargetId,onChange:_,className:"w-full ios-input px-4 py-3 rounded-xl text-sm",children:l.map(N)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"卡密号(每行一个)"}),e.jsx("textarea",{vaLine truncated
|
||||
import{b as z,j as e,r as i}from"./react-vendor-C_od1ZSF.js";import{X as G,W as Z,J as D,Y as ee,L as U,N as V,C as H,_ as te,$ as W,a0 as X,a1 as ae,I as se,a2 as le,V as ne,F as re,P as oe,r as ie}from"./icons-vendor-CvzvbbIV.js";import{g as ce,p as de,d as xe,a as Y,b as pe}from"./index-CCqtUiU5.js";import{c as me}from"./contract-COFcZjyb.js";const he=({dataCards:l,downloadCardTemplate:n,...a})=>{var x;const u=s=>{var h;a.setBatchFile(((h=s.target.files)==null?void 0:h[0])||null)},m=s=>{a.setAppendContent(s.target.value)},_=s=>{a.setAppendTargetId(s.target.value)},f=()=>a.closeBatchModal(),j=()=>a.setBatchTab("create"),d=()=>a.setBatchTab("append"),A=()=>void a.handleRetryBatchCreate(),c=()=>void a.handleRetryBatchAppend(),y=a.batchResult&&"rows"in a.batchResult?a.batchResult:null,N=s=>e.jsxs("option",{value:String(s.id),children:[s.name,"(ID: ",s.id,")"]},s.id),b=()=>void a.handleBatchCreate(),r=()=>void a.handleBatchAppend();return a.showBatchModal?z.createPortal(e.jsx("div",{className:"modal-overlay",children:e.jsxs("div",{className:"modal-container",style:{maxWidth:"40rem"},children:[e.jsxs("div",{className:"px-6 py-5 border-b border-gray-100 flex items-center justify-between",children:[e.jsx("h3",{className:"text-xl font-extrabold text-gray-900",children:"批量导入卡密"}),e.jsx("button",{onClick:f,className:"w-10 h-10 rounded-2xl bg-gray-100 hover:bg-gray-200 flex items-center justify-center",children:e.jsx(G,{className:"w-5 h-5 text-gray-600"})})]}),e.jsxs("div",{className:"px-6 py-5 space-y-5",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 p-2 bg-gray-100/50 rounded-2xl",children:[e.jsxs("button",{onClick:j,className:`flex-1 inline-flex items-center justify-center gap-2 px-4 py-2.5 rounded-xl text-sm font-bold transition-all ${a.batchTab==="create"?"bg-brand text-white shadow-md":"bg-white text-gray-600 hover:bg-gray-50"}`,children:[e.jsx(Z,{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(D,{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(ee,{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(D,{className:"w-4 h-4"}),a.batchFile?a.batchFile.name:"选择 .xlsx / .csv / .tsv",e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv",className:"hidden",onChange:u})]})]}),((x=a.batchResult)==null?void 0:x.error)&&e.jsxs("div",{className:"rounded-xl border border-red-200 bg-red-50 p-4 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.batchResult.error}),e.jsx("button",{type:"button",onClick:A,disabled:!a.batchFile||a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),y&&e.jsxs("div",{className:"rounded-xl border border-gray-200 p-4 space-y-2",children:[e.jsxs("div",{className:"text-sm font-bold text-gray-900",children:["共 ",y.total," 行 · 成功 ",y.created," · 失败 ",y.failed]}),y.failed>0&&e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-1",children:y.rows.filter(s=>!s.success).map(s=>e.jsxs("div",{className:"text-xs text-red-600",children:["第 ",s.row_no," 行「",s.name,"」:",s.error]},s.row_no))})]})]}):e.jsx("div",{className:"space-y-4",children:l.length===0?e.jsx("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-4 text-sm text-amber-800",children:"暂无 data(批量卡密)类型的卡密组,请先创建一个再充卡密。"}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"选择卡密组"}),e.jsx("select",{value:a.appendTargetId,onChange:_,className:"w-full ios-input px-4 py-3 rounded-xl text-sm",children:l.map(N)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"block text-sm font-bold text-gray-800",children:"卡密号(每行一个)"}),e.jsx("textarea",{vaLine truncated
|
||||
VIP-002
|
||||
VIP-003`,className:"w-full ios-input px-4 py-3 rounded-xl text-sm font-mono h-40 resize-y"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["预览:",a.appendPreview.length," 个有效卡密,空行自动忽略。"]})]}),a.appendError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-200 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:a.appendError}),e.jsx("button",{type:"button",onClick:c,disabled:a.batchBusy,className:"font-bold whitespace-nowrap",children:"重试"})]}),a.appendResult&&e.jsxs("div",{className:"rounded-xl bg-green-50 border border-green-200 p-3 text-sm text-green-700 font-bold",children:["已追加 ",a.appendResult.added," 个卡密"]})]})})]}),e.jsxs("div",{className:"px-6 py-4 border-t border-gray-100 flex items-center justify-end gap-3",children:[e.jsx("button",{onClick:f,className:"px-5 py-2.5 rounded-xl bg-gray-100 hover:bg-gray-200 font-bold text-gray-700 transition-colors",children:"关闭"}),a.batchTab==="create"?e.jsxs("button",{onClick:b,disabled:!a.batchFile||a.batchBusy,className:"ios-btn-primary px-6 py-2.5 rounded-xl font-bold flex items-center gap-2 disabled:opacity-50",children:[a.batchBusy?e.jsx(U,{className:"w-4 h-4 animate-spin"}):e.jsx(D,{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(U,{className:"w-4 h-4 animate-spin"}):e.jsx(V,{className:"w-4 h-4"}),a.batchBusy?"处理中...":"追加卡密"]})]})]})}),document.body):null},ue=({type:l})=>{switch(l){case"text":return e.jsx(X,{className:"w-5 h-5 text-blue-500"});case"image":return e.jsx(W,{className:"w-5 h-5 text-purple-500"});case"api":return e.jsx(te,{className:"w-5 h-5 text-blue-500"});default:return e.jsx(H,{className:"w-5 h-5 text-gray-500"})}},be=l=>{let n=l.api_config;if(typeof n=="string"&&n.trim())try{n=JSON.parse(n)}catch{n=void 0}return{...l,api_config:n||void 0}},K=l=>({...l,api_config:l.api_config?JSON.stringify(l.api_config):""}),ge=async l=>{const n=await ce("/api/v1/cards",void 0,l);return me(n,["cards","data","items"]).map(be)},ye=async l=>Y("/api/v1/cards",K(l)),J=async(l,n)=>de(`/api/v1/cards/${l}`,K(n)),fe=async l=>xe(`/api/v1/cards/${l}`),je=async(l,n)=>{const a=new FormData;return a.append("file",l),pe("/api/v1/cards/batch",a,n)},Ne=async(l,n,a)=>Y(`/api/v1/cards/${l}/append-data`,{content:n},a),ve=(l,n,a)=>{const u=a.trim().toLocaleLowerCase();return l.filter(m=>(!n||m.type===n)&&(!u||m.name.toLocaleLowerCase().includes(u)))},Q=l=>l.split(`
|
||||
`).map(n=>n.trim()).filter(Boolean),we=(l,n,a)=>!!(l&&Q(n).length>0&&!a),F=(l,n,a,u)=>l===n&&a===u,Ce=()=>{const[l,n]=i.useState([]),[a,u]=i.useState(!0),m=i.useRef(0),_=i.useRef(null),f=i.useCallback(async()=>{var A;const j=++m.current;(A=_.current)==null||A.abort();const d=new AbortController;_.current=d,u(!0);try{const c=await ge({signal:d.signal});if(j!==m.current)return;n(c)}catch(c){j===m.current&&!d.signal.aborted&&console.error("加载卡密库存失败:",c)}finally{j===m.current&&u(!1)}},[]);return i.useEffect(()=>(f(),()=>{var d;m.current+=1,(d=_.current)==null||d.abort()}),[f]),{cards:l,setCards:n,loading:a,loadCards:f}},_e=l=>{const n=l.dataCards,a=l.loadCards,[u,m]=i.useState(!1),[_,f]=i.useState("create"),[j,d]=i.useState(null),[A,c]=i.useState(null),[y,N]=i.useState(!1),[b,r]=i.useState(""),[x,s]=i.useState(""),[h,E]=i.useState(null),[M,R]=i.useState(""),v=i.useRef(0),T=i.useRef(null),P=i.useRef("");i.useEffect(()=>(()=>{var p;v.current+=1,(p=T.current)==null||p.abort()}),[]);const $=i.useMemo(()=>Q(x),[x]),o=i.useCallback(()=>{var p;f("create"),d(null),c(null),r((p=n[0])!=null&&p.id?String(n[0].id):""),s(""),E(null),R(""),m(!0)},[n]),t=i.useCallback(()=>{var p;v.current+=1,(p=T.current)==null||p.abort(),N(!1),m(!1)},[]),g=i.useCallback(async()=>{var w;if(!j||y)return;const p=++v.current;(w=T.current)==null||w.abort();const B=new AbortController;T.current=B,N(!0),c(null);try{const I=await je(j,{signal:B.signal});if(!F(p,v.current,"",""))return;c(I),I.created>0&&await a()}catch(I){if(!F(p,v.current,"",""))return;c({error:(I==null?void 0:I.message)||"上传失败"})}finally{F(p,v.current,"","")&&N(!1)}},[y,j,a]),k=i.useCallback(async()=>{var I;if(!we(b,x,y))return;const p=b,B=++v.current;P.current=p,(I=T.current)==null||I.abort();const w=new AbortController;T.current=w,N(!0),E(null),R("");try{const O=await Ne(p,x,{signal:w.signal});if(!F(B,v.current,p,b))return;E({added:O.added}),s(""),await a()}catch(O){if(!F(B,v.current,p,b))return;R((O==null?void 0:O.message)||"追加失败")}finally{F(B,v.current,p,b)&&N(!1)}},[x,b,y,a]),S=i.useCallback(async()=>{await g()},[g]),C=i.useCallback(async()=>{P.current&&b!==P.current||await k()},[b,k]);return{showBatchModal:u,setShowBatchModal:m,batchTab:_,setBatchTab:f,batchFile:j,setBatchFile:d,batchResult:A,batchBusy:y,appendTargetId:b,setAppendTargetId:r,appendContent:x,setAppendContent:s,appendResult:h,appendError:M,appendPreview:$,openBatchModal:o,closeBatchModal:t,handleBatchCreate:g,handleBatchAppend:k,handleRetryBatchCreate:S,handleRetryBatchAppend:C}},q=()=>({name:"",type:"data",content:"",description:"",enabled:!0,delay_seconds:0,api_method:"GET",api_timeout:10,api_headers:"",api_params:""}),L=(l,n)=>l instanceof Error?l.message:n,ke=({cards:l,loadCards:n})=>{const[a,u]=i.useState(!1),[m,_]=i.useState(!1),[f,j]=i.useState(null),[d,A]=i.useState({}),[c,y]=i.useState(q),[N,b]=i.useState(""),[r,x]=i.useState(""),s=i.useMemo(()=>l.filter(o=>o.type==="data"),[l]),h=i.useMemo(()=>ve(l,N,r),[l,r,N]),E=i.useCallback(o=>{var t,g,k,S,C;j(o),A({id:o.id,name:o.name||"",type:o.type||"text",api_url:((t=o.api_config)==null?void 0:t.url)||"",api_method:((g=o.api_config)==null?void 0:g.method)||"GET",api_timeout:((k=o.api_config)==null?void 0:k.timeout)||10,api_headers:((S=o.api_config)==null?void 0:S.headers)||"",api_params:((C=o.api_config)==null?void 0:C.params)||"",text_content:o.text_content||"",data_content:o.data_content||"",image_url:o.image_url||"",delay_seconds:o.delay_seconds||0,description:o.description||"",enabled:o.enabled}),u(!0)},[]),M=i.useCallback(async()=>{var o,t,g,k,S,C,p,B;if(f){if(!((o=d.name)!=null&&o.trim())){alert("请输入卡密名称");return}if(!d.type){alert("请选择卡密类型");return}try{const w={name:d.name.trim(),type:d.type,description:(t=d.description)==null?void 0:t.trim(),delay_seconds:d.delay_seconds||0,enabled:d.enabled??!0};d.type==="api"?w.api_config={url:((g=d.api_url)==null?void 0:g.trim())||"",method:d.api_method||"GET",timeout:d.api_timeout||10,headers:((k=d.api_headers)==null?void 0:k.trim())||void 0,params:((S=d.api_params)==null?void 0:S.trim())||void 0}:d.type==="text"?w.text_content=((C=d.text_content)==null?void 0:C.trim())||"":d.type==="data"?w.data_content=((p=d.data_content)==null?void 0:p.trim())||"":d.type==="image"&&(w.image_url=((B=d.image_url)==null?void 0:B.trim())||""),await J(f.id,w),u(!1),await n()}catch(w){console.error("更新卡密失败:",w),alert(L(w,"更新失败,请重试"))}}},[d,n,f]),R=i.useCallback(async o=>{if(confirm("确认删除该卡密吗?"))try{await fe(o),await n()}catch(t){console.error("删除卡密失败:",t),alert(L(t,"删除失败,请重试"))}},[n]),v=i.useCallback(async()=>{if(!c.name.trim()){alert("请输入卡密名称");return}if(!c.content.trim()){alert(c.type==="api"?"请输入 API 地址":"请输入卡密内容");return}try{const o={name:c.name.trim(),type:c.type,description:c.description.trim(),enabled:c.enabled,delay_seconds:c.delay_seconds};c.type==="text"&&(
Line truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{j as e,c as h0,r as i}from"./react-vendor-C_od1ZSF.js";import{L as me}from"./vendor-Es4K8PXl.js";import{g as k0,a as G0,b as pe}from"./index-k6Tc6ww6.js";import{o as X0}from"./contract-COFcZjyb.js";import{L as K,ak as ge,al as de,M as P0,I as xe,R as ue,ad as U0,k as he,am as _e,s as z0,an as be,ao as fe,ah as B0,X as je}from"./icons-vendor-CvzvbbIV.js";const K0=[["尊嘟假嘟","https://img.alicdn.com/imgextra/i2/O1CN01hWzOgD1KcmFEIaGwE_!!6000000001185-2-tps-64-64.png_110x10000.jpg_.webp"],["鸡哔你","https://img.alicdn.com/imgextra/i1/O1CN01P9TVJl1JCqCZcQIdW_!!6000000000993-2-tps-64-64.png_110x10000.jpg_.webp"],["谁懂啊","https://img.alicdn.com/imgextra/i1/O1CN01r9qUnx1g3tcrtSmcs_!!6000000004087-2-tps-64-64.png_110x10000.jpg_.webp"],["吗喽","https://img.alicdn.com/imgextra/i4/O1CN01dTynZh1LnbIYTHI1D_!!6000000001344-2-tps-64-64.png_110x10000.jpg_.webp"],["功德+1","https://img.alicdn.com/imgextra/i1/O1CN01l1G5pS1IVn37pfQJi_!!6000000000899-2-tps-64-64.png_110x10000.jpg_.webp"],["city不city啊","https://img.alicdn.com/imgextra/i2/O1CN01zRjPTR29lWHqabmDA_!!6000000008108-2-tps-64-64.png_110x10000.jpg_.webp"],["激推","https://img.alicdn.com/imgextra/i3/O1CN01ADTJ6u1khypfxbfnQ_!!6000000004716-2-tps-64-64.png_110x10000.jpg_.webp"],["微笑","https://img.alicdn.com/imgextra/i1/O1CN017b61R51wRk2lVV7vx_!!6000000006305-2-tps-980-980.png_110x10000.jpg_.webp"],["龇牙","https://img.alicdn.com/imgextra/i2/O1CN01nmOh4S22Yxz8IdEVf_!!6000000007133-2-tps-980-980.png_110x10000.jpg_.webp"],["流泪","https://img.alicdn.com/imgextra/i2/O1CN01Ec1EaL1zqQETcM2dX_!!6000000006765-2-tps-980-980.png_110x10000.jpg_.webp"],["尴尬","https://img.alicdn.com/imgextra/i2/O1CN01UrWH7a1ZVBrgRYXlc_!!6000000003199-2-tps-980-980.png_110x10000.jpg_.webp"],["撇嘴","https://img.alicdn.com/imgextra/i2/O1CN01Sr7o2b1lUWg5KfOD8_!!6000000004822-2-tps-980-980.png_110x10000.jpg_.webp"],["破涕为笑","https://img.alicdn.com/imgextra/i4/O1CN01pPetah1gkwndfn7Fs_!!6000000004181-2-tps-980-980.png_110x10000.jpg_.webp"],["捂脸哭","https://img.alicdn.com/imgextra/i2/O1CN0170KgpE1dE1TuQgd66_!!6000000003703-2-tps-980-980.png_110x10000.jpg_.webp"],["害羞","https://img.alicdn.com/imgextra/i3/O1CN01ZoB0Lb1ps7XpqP8PQ_!!6000000005415-2-tps-980-980.png_110x10000.jpg_.webp"],["感动","https://img.alicdn.com/imgextra/i2/O1CN01wqD4ly29yndR3Qp3A_!!6000000008137-2-tps-980-980.png_110x10000.jpg_.webp"],["滴泪","https://img.alicdn.com/imgextra/i1/O1CN01MpkJ3L1oUTTqfryOn_!!6000000005228-2-tps-980-980.png_110x10000.jpg_.webp"],["暗中观察","https://img.alicdn.com/imgextra/i1/O1CN010LO9yj272W07GlLls_!!6000000007739-2-tps-980-980.png_110x10000.jpg_.webp"],["偷笑","https://img.alicdn.com/imgextra/i4/O1CN01vJtO031g818IuYO7x_!!6000000004096-2-tps-980-980.png_110x10000.jpg_.webp"],["ok","https://img.alicdn.com/imgextra/i3/O1CN01QRkqDF25tz0WcANje_!!6000000007585-2-tps-980-980.png_110x10000.jpg_.webp"],["送花","https://img.alicdn.com/imgextra/i2/O1CN01PpzBNX1JNpeJBWnvr_!!6000000001017-2-tps-980-980.png_110x10000.jpg_.webp"],["大哭","https://img.alicdn.com/imgextra/i4/O1CN014TiaNb1ViEgNvRrTB_!!6000000002686-2-tps-980-980.png_110x10000.jpg_.webp"],["色","https://img.alicdn.com/imgextra/i2/O1CN01840t1B1JaCLGvHnBK_!!6000000001044-2-tps-980-980.png_110x10000.jpg_.webp"],["惊慌","https://img.alicdn.com/imgextra/i1/O1CN01mnqO7G1LAfUnfAN2U_!!6000000001259-2-tps-980-980.png_110x10000.jpg_.webp"],["惊讶","https://img.alicdn.com/imgextra/i3/O1CN0127IeyS1Kw0p0P4jzI_!!6000000001227-2-tps-980-980.png_110x10000.jpg_.webp"],["得意","https://img.alicdn.com/imgextra/i4/O1CN018QUnFv1WpOUES9POZ_!!6000000002837-2-tps-980-980.png_110x10000.jpg_.webp"],["睡","https://img.alicdn.com/imgextra/i2/O1CN01RprGZl1lqVgnEJLCx_!!6000000004870-2-tps-980-980.png_110x10000.jpg_.webp"],["不好意思","https://img.alicdn.com/imgextra/i3/O1CN01rMJJgn1SUXzuVpUhO_!!6000000002250-2-tps-980-980.png_110x10000.jpg_.webp"],["托腮","https://img.alicdn.com/imgextra/i1/O1CN01w3reBU1d3wlgOBtyZ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["发怒","https://img.alicdn.com/imgextra/i2/O1CN013Wzy8d2A8PxGJZPpT_!!6000000008158-2-tps-980-980.png_110x10000.jpg_.webp"],["难过","https://img.alicdn.com/imgextra/i2/O1CN01zcwaSh1G9gZCFuFal_!!6000000000580-2-tps-980-980.png_110x10000.jpg_.webp"],["调皮","https://img.alicdn.com/imgextra/i3/O1CN01Zd1YHi1TI0lwpBe8c_!!6000000002358-2-tps-980-980.png_110x10000.jpg_.webp"],["愉快","https://img.alicdn.com/imgextra/i2/O1CN0145wDk21SWpyjTvsvA_!!6000000002255-2-tps-980-980.png_110x10000.jpg_.webp"],["白眼","https://img.alicdn.com/imgextra/i4/O1CN01nexGth1hwEAT1SHO2_!!6000000004341-2-tps-980-980.png_110x10000.jpg_.webp"],["拒绝","https://img.alicdn.com/imgextra/i2/O1CN01nqusqS1uHXzoUcpXr_!!6000000006012-2-tps-980-980.png_110x10000.jpg_.webp"],["期待","https://img.alicdn.com/imgextra/i3/O1CN01M44QY11Oh8Q5PdMIx_!!6000000001736-2-tps-980-980.png_110x10000.jpg_.webp"],["困","https://img.alicdn.com/imgextra/i4/O1CN01J4hFFz1Y9pmNdBq76_!!60
Line truncated
|
||||
import{j as e,c as h0,r as i}from"./react-vendor-C_od1ZSF.js";import{L as me}from"./vendor-Es4K8PXl.js";import{g as k0,a as G0,b as pe}from"./index-CCqtUiU5.js";import{o as X0}from"./contract-COFcZjyb.js";import{L as K,ak as ge,al as de,M as P0,I as xe,R as ue,ad as U0,k as he,am as _e,s as z0,an as be,ao as fe,ah as B0,X as je}from"./icons-vendor-CvzvbbIV.js";const K0=[["尊嘟假嘟","https://img.alicdn.com/imgextra/i2/O1CN01hWzOgD1KcmFEIaGwE_!!6000000001185-2-tps-64-64.png_110x10000.jpg_.webp"],["鸡哔你","https://img.alicdn.com/imgextra/i1/O1CN01P9TVJl1JCqCZcQIdW_!!6000000000993-2-tps-64-64.png_110x10000.jpg_.webp"],["谁懂啊","https://img.alicdn.com/imgextra/i1/O1CN01r9qUnx1g3tcrtSmcs_!!6000000004087-2-tps-64-64.png_110x10000.jpg_.webp"],["吗喽","https://img.alicdn.com/imgextra/i4/O1CN01dTynZh1LnbIYTHI1D_!!6000000001344-2-tps-64-64.png_110x10000.jpg_.webp"],["功德+1","https://img.alicdn.com/imgextra/i1/O1CN01l1G5pS1IVn37pfQJi_!!6000000000899-2-tps-64-64.png_110x10000.jpg_.webp"],["city不city啊","https://img.alicdn.com/imgextra/i2/O1CN01zRjPTR29lWHqabmDA_!!6000000008108-2-tps-64-64.png_110x10000.jpg_.webp"],["激推","https://img.alicdn.com/imgextra/i3/O1CN01ADTJ6u1khypfxbfnQ_!!6000000004716-2-tps-64-64.png_110x10000.jpg_.webp"],["微笑","https://img.alicdn.com/imgextra/i1/O1CN017b61R51wRk2lVV7vx_!!6000000006305-2-tps-980-980.png_110x10000.jpg_.webp"],["龇牙","https://img.alicdn.com/imgextra/i2/O1CN01nmOh4S22Yxz8IdEVf_!!6000000007133-2-tps-980-980.png_110x10000.jpg_.webp"],["流泪","https://img.alicdn.com/imgextra/i2/O1CN01Ec1EaL1zqQETcM2dX_!!6000000006765-2-tps-980-980.png_110x10000.jpg_.webp"],["尴尬","https://img.alicdn.com/imgextra/i2/O1CN01UrWH7a1ZVBrgRYXlc_!!6000000003199-2-tps-980-980.png_110x10000.jpg_.webp"],["撇嘴","https://img.alicdn.com/imgextra/i2/O1CN01Sr7o2b1lUWg5KfOD8_!!6000000004822-2-tps-980-980.png_110x10000.jpg_.webp"],["破涕为笑","https://img.alicdn.com/imgextra/i4/O1CN01pPetah1gkwndfn7Fs_!!6000000004181-2-tps-980-980.png_110x10000.jpg_.webp"],["捂脸哭","https://img.alicdn.com/imgextra/i2/O1CN0170KgpE1dE1TuQgd66_!!6000000003703-2-tps-980-980.png_110x10000.jpg_.webp"],["害羞","https://img.alicdn.com/imgextra/i3/O1CN01ZoB0Lb1ps7XpqP8PQ_!!6000000005415-2-tps-980-980.png_110x10000.jpg_.webp"],["感动","https://img.alicdn.com/imgextra/i2/O1CN01wqD4ly29yndR3Qp3A_!!6000000008137-2-tps-980-980.png_110x10000.jpg_.webp"],["滴泪","https://img.alicdn.com/imgextra/i1/O1CN01MpkJ3L1oUTTqfryOn_!!6000000005228-2-tps-980-980.png_110x10000.jpg_.webp"],["暗中观察","https://img.alicdn.com/imgextra/i1/O1CN010LO9yj272W07GlLls_!!6000000007739-2-tps-980-980.png_110x10000.jpg_.webp"],["偷笑","https://img.alicdn.com/imgextra/i4/O1CN01vJtO031g818IuYO7x_!!6000000004096-2-tps-980-980.png_110x10000.jpg_.webp"],["ok","https://img.alicdn.com/imgextra/i3/O1CN01QRkqDF25tz0WcANje_!!6000000007585-2-tps-980-980.png_110x10000.jpg_.webp"],["送花","https://img.alicdn.com/imgextra/i2/O1CN01PpzBNX1JNpeJBWnvr_!!6000000001017-2-tps-980-980.png_110x10000.jpg_.webp"],["大哭","https://img.alicdn.com/imgextra/i4/O1CN014TiaNb1ViEgNvRrTB_!!6000000002686-2-tps-980-980.png_110x10000.jpg_.webp"],["色","https://img.alicdn.com/imgextra/i2/O1CN01840t1B1JaCLGvHnBK_!!6000000001044-2-tps-980-980.png_110x10000.jpg_.webp"],["惊慌","https://img.alicdn.com/imgextra/i1/O1CN01mnqO7G1LAfUnfAN2U_!!6000000001259-2-tps-980-980.png_110x10000.jpg_.webp"],["惊讶","https://img.alicdn.com/imgextra/i3/O1CN0127IeyS1Kw0p0P4jzI_!!6000000001227-2-tps-980-980.png_110x10000.jpg_.webp"],["得意","https://img.alicdn.com/imgextra/i4/O1CN018QUnFv1WpOUES9POZ_!!6000000002837-2-tps-980-980.png_110x10000.jpg_.webp"],["睡","https://img.alicdn.com/imgextra/i2/O1CN01RprGZl1lqVgnEJLCx_!!6000000004870-2-tps-980-980.png_110x10000.jpg_.webp"],["不好意思","https://img.alicdn.com/imgextra/i3/O1CN01rMJJgn1SUXzuVpUhO_!!6000000002250-2-tps-980-980.png_110x10000.jpg_.webp"],["托腮","https://img.alicdn.com/imgextra/i1/O1CN01w3reBU1d3wlgOBtyZ_!!6000000003681-2-tps-980-980.png_110x10000.jpg_.webp"],["发怒","https://img.alicdn.com/imgextra/i2/O1CN013Wzy8d2A8PxGJZPpT_!!6000000008158-2-tps-980-980.png_110x10000.jpg_.webp"],["难过","https://img.alicdn.com/imgextra/i2/O1CN01zcwaSh1G9gZCFuFal_!!6000000000580-2-tps-980-980.png_110x10000.jpg_.webp"],["调皮","https://img.alicdn.com/imgextra/i3/O1CN01Zd1YHi1TI0lwpBe8c_!!6000000002358-2-tps-980-980.png_110x10000.jpg_.webp"],["愉快","https://img.alicdn.com/imgextra/i2/O1CN0145wDk21SWpyjTvsvA_!!6000000002255-2-tps-980-980.png_110x10000.jpg_.webp"],["白眼","https://img.alicdn.com/imgextra/i4/O1CN01nexGth1hwEAT1SHO2_!!6000000004341-2-tps-980-980.png_110x10000.jpg_.webp"],["拒绝","https://img.alicdn.com/imgextra/i2/O1CN01nqusqS1uHXzoUcpXr_!!6000000006012-2-tps-980-980.png_110x10000.jpg_.webp"],["期待","https://img.alicdn.com/imgextra/i3/O1CN01M44QY11Oh8Q5PdMIx_!!6000000001736-2-tps-980-980.png_110x10000.jpg_.webp"],["困","https://img.alicdn.com/imgextra/i4/O1CN01J4hFFz1Y9pmNdBq76_!!60
Line truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{r as c,j as e}from"./react-vendor-C_od1ZSF.js";import{f as me}from"./dateTime-DDi7rqpW.js";import{g as q}from"./index-k6Tc6ww6.js";import{c as de,o as ge}from"./contract-COFcZjyb.js";import{j as xe,k as he,l as te,D as pe,c as be,P as fe,m as se,E as ye,T as je}from"./icons-vendor-CvzvbbIV.js";import{R as E,B as ve,X as ae,Y as re,T as F,a as Ne,C as U,A as we,b as _e,c as ke,P as ne,d as le,L as De}from"./charts-vendor-deWqkrdG.js";import"./vendor-Es4K8PXl.js";const M=t=>{const a=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),l=String(t.getDate()).padStart(2,"0");return`${a}-${s}-${l}`},H=(t,a)=>{const s=new Date(t);return s.setHours(12,0,0,0),s.setDate(s.getDate()+a),s},X=(t,a)=>({startDate:M(H(t,-(a-1))),endDate:M(t)}),ue=(t,a=new Date,s="",l="")=>{if(t==="custom"&&s&&l){if(s>l)throw new Error("开始日期不能晚于结束日期");return{startDate:s,endDate:l}}return t==="yesterday"?X(H(a,-1),1):X(a,t==="3days"?3:t==="30days"?30:t==="today"?1:7)},Se=t=>{const a=new Date(`${t.startDate}T12:00:00`),s=new Date(`${t.endDate}T12:00:00`),l=Math.round((s.getTime()-a.getTime())/864e5)+1,n=H(a,-1);return X(n,l)},Ce=t=>{const a={};return t.forEach(s=>{a[s.item_id]=s.item_title||s.item_id}),a},$e=t=>{var a;return((a=t.daily_stats)==null?void 0:a.map(s=>({name:s.date.slice(5),amount:s.amount,orders:s.order_count,avgAmount:s.order_count>0?(s.amount/s.order_count).toFixed(2):0})))||[]},Re=(t,a)=>(t.item_stats||[]).map(s=>{const l=a[s.item_id]||s.item_id;return{name:l.length>12?`${l.substring(0,12)}...`:l,sales:s.order_count}}).sort((s,l)=>l.sales-s.sales).slice(0,10),Le=(t,a,s)=>{const l=t.revenue_stats.total_orders||0;return(t.item_stats||[]).map(n=>{const o=a[n.item_id]||n.item_id;return{name:o.length>10?`${o.substring(0,10)}...`:o,value:n.order_count,percent:l>0?n.order_count/l*100:0}}).sort((n,o)=>o.value-n.value).slice(0,6).map((n,o)=>({...n,color:s[o%s.length]}))},Ae=(t,a,s)=>{const l=t.revenue_stats.total_amount||0;return(t.item_stats||[]).map(n=>{const o=a[n.item_id]||n.item_id;return{name:o.length>12?`${o.substring(0,12)}...`:o,value:n.total_amount,orderCount:n.order_count,percentage:l>0?n.total_amount/l*100:0}}).sort((n,o)=>o.value-n.value).slice(0,5).map((n,o)=>({...n,color:s[o%s.length],percentage:n.percentage.toFixed(1)}))},Oe=(t,a)=>{if(!t||!a)return null;const s=t.revenue_stats.total_amount,l=a.revenue_stats.total_amount;if(l===0)return s>0?"+100%":"0%";const n=(s-l)/l*100;return`${n>=0?"+":""}${n.toFixed(1)}%`},Te=t=>({today:"今天",yesterday:"昨天","3days":"三天内","7days":"7天内","30days":"一个月内",custom:"自定义"})[t.range]||"所选范围",ze=t=>Math.max(...t.map(a=>a.sales),1),P=(t,a,s)=>t===a&&!s.aborted,oe=t=>{const a=String(t||"");return a==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(a)?a:"unknown"},Pe=async t=>q("/api/v1/analytics/dashboard",void 0,t),We=async(t,a)=>{const s=await q("/api/v1/items",void 0,a);return de(s,["items","data","results"]).map(n=>({...n,id:n.id||`${n.cookie_id}-${n.item_id}`,is_multi_spec:n.is_multi_spec===!0||n.is_multi_spec===1,multi_quantity_delivery:n.multi_quantity_delivery===!0||n.multi_quantity_delivery===1}))},ie=async(t=7,a)=>{let s;if(typeof t=="number"){const l=new Date,n=new Date;n.setDate(n.getDate()-t),s={start_date:M(n),end_date:M(l)}}else s=t;return q("/api/v1/analytics/orders",{...s,timezone_offset_minutes:-new Date().getTimezoneOffset()},a)},Ee=async(t,a)=>{const s=await q("/api/v1/analytics/orders/valid",{...t,timezone_offset_minutes:-new Date().getTimezoneOffset()},a),l=ge(s,["data","result"])||{},o=de(s,["orders","data","items"]).map(b=>({...b,id:b.order_id,status:oe(b.status||b.order_status),order_status:oe(b.order_status),quantity:Number(b.quantity||1)}));return{orders:o,total:Number(l.total??o.length),truncated:l.truncated===!0}},ce=t=>t instanceof Error&&t.message==="请求已取消",G=(t,a)=>t instanceof Error?t.message:a,Fe=t=>{const{range:a,customStartDate:s,customEndDate:l,customRangeVersion:n}=t,[o,b]=c.useState(null),[_,I]=c.useState(null),[K,v]=c.useState({overview:"idle",range:"idle",error:""}),[d,T]=c.useState(0),R=c.useRef(0),S=c.useRef(0),L=c.useMemo(()=>({range:a,customStartDate:s,customEndDate:l}),[l,s,a]),D=c.useCallback(()=>T(u=>u+1),[]);c.useEffect(()=>{const u=++S.current,h=new AbortController;return v(m=>({...m,overview:"loading",error:""})),Promise.all([Pe({signal:h.signal}),We(void 0,{signal:h.signal})]).then(([m,g])=>{P(S.current,u,h.signal)&&(b({stats:m,items:g,itemNames:Ce(g)}),v(p=>({...p,overview:"success"})))}).catch(m=>{!P(S.current,u,h.signal)||ce(m)||v(g=>({...g,overview:"error",error:G(m,"概览加载失败")}))}),(()=>h.abort())},[d]),c.useEffect(()=>{let u;try{u=ue(a,new Date,s,l)}catch(p){v(w=>({...w,range:"error",error:G(p,"日期范围无效")}));return}const h=Se(u),m=++R.current,g=new AbortController;return v(p=>({...p,range:"loading",error:""})),Promise.all([ie({start_date:u.startDate,end_date:u.endDate},{signLine truncated
|
||||
import{r as c,j as e}from"./react-vendor-C_od1ZSF.js";import{f as me}from"./dateTime-DDi7rqpW.js";import{g as q}from"./index-CCqtUiU5.js";import{c as de,o as ge}from"./contract-COFcZjyb.js";import{j as xe,k as he,l as te,D as pe,c as be,P as fe,m as se,E as ye,T as je}from"./icons-vendor-CvzvbbIV.js";import{R as E,B as ve,X as ae,Y as re,T as F,a as Ne,C as U,A as we,b as _e,c as ke,P as ne,d as le,L as De}from"./charts-vendor-deWqkrdG.js";import"./vendor-Es4K8PXl.js";const M=t=>{const a=t.getFullYear(),s=String(t.getMonth()+1).padStart(2,"0"),l=String(t.getDate()).padStart(2,"0");return`${a}-${s}-${l}`},H=(t,a)=>{const s=new Date(t);return s.setHours(12,0,0,0),s.setDate(s.getDate()+a),s},X=(t,a)=>({startDate:M(H(t,-(a-1))),endDate:M(t)}),ue=(t,a=new Date,s="",l="")=>{if(t==="custom"&&s&&l){if(s>l)throw new Error("开始日期不能晚于结束日期");return{startDate:s,endDate:l}}return t==="yesterday"?X(H(a,-1),1):X(a,t==="3days"?3:t==="30days"?30:t==="today"?1:7)},Se=t=>{const a=new Date(`${t.startDate}T12:00:00`),s=new Date(`${t.endDate}T12:00:00`),l=Math.round((s.getTime()-a.getTime())/864e5)+1,n=H(a,-1);return X(n,l)},Ce=t=>{const a={};return t.forEach(s=>{a[s.item_id]=s.item_title||s.item_id}),a},$e=t=>{var a;return((a=t.daily_stats)==null?void 0:a.map(s=>({name:s.date.slice(5),amount:s.amount,orders:s.order_count,avgAmount:s.order_count>0?(s.amount/s.order_count).toFixed(2):0})))||[]},Re=(t,a)=>(t.item_stats||[]).map(s=>{const l=a[s.item_id]||s.item_id;return{name:l.length>12?`${l.substring(0,12)}...`:l,sales:s.order_count}}).sort((s,l)=>l.sales-s.sales).slice(0,10),Le=(t,a,s)=>{const l=t.revenue_stats.total_orders||0;return(t.item_stats||[]).map(n=>{const o=a[n.item_id]||n.item_id;return{name:o.length>10?`${o.substring(0,10)}...`:o,value:n.order_count,percent:l>0?n.order_count/l*100:0}}).sort((n,o)=>o.value-n.value).slice(0,6).map((n,o)=>({...n,color:s[o%s.length]}))},Ae=(t,a,s)=>{const l=t.revenue_stats.total_amount||0;return(t.item_stats||[]).map(n=>{const o=a[n.item_id]||n.item_id;return{name:o.length>12?`${o.substring(0,12)}...`:o,value:n.total_amount,orderCount:n.order_count,percentage:l>0?n.total_amount/l*100:0}}).sort((n,o)=>o.value-n.value).slice(0,5).map((n,o)=>({...n,color:s[o%s.length],percentage:n.percentage.toFixed(1)}))},Oe=(t,a)=>{if(!t||!a)return null;const s=t.revenue_stats.total_amount,l=a.revenue_stats.total_amount;if(l===0)return s>0?"+100%":"0%";const n=(s-l)/l*100;return`${n>=0?"+":""}${n.toFixed(1)}%`},Te=t=>({today:"今天",yesterday:"昨天","3days":"三天内","7days":"7天内","30days":"一个月内",custom:"自定义"})[t.range]||"所选范围",ze=t=>Math.max(...t.map(a=>a.sales),1),P=(t,a,s)=>t===a&&!s.aborted,oe=t=>{const a=String(t||"");return a==="paid"?"pending_ship":["processing","pending_ship","shipped","completed","cancelled","refunding"].includes(a)?a:"unknown"},Pe=async t=>q("/api/v1/analytics/dashboard",void 0,t),We=async(t,a)=>{const s=await q("/api/v1/items",void 0,a);return de(s,["items","data","results"]).map(n=>({...n,id:n.id||`${n.cookie_id}-${n.item_id}`,is_multi_spec:n.is_multi_spec===!0||n.is_multi_spec===1,multi_quantity_delivery:n.multi_quantity_delivery===!0||n.multi_quantity_delivery===1}))},ie=async(t=7,a)=>{let s;if(typeof t=="number"){const l=new Date,n=new Date;n.setDate(n.getDate()-t),s={start_date:M(n),end_date:M(l)}}else s=t;return q("/api/v1/analytics/orders",{...s,timezone_offset_minutes:-new Date().getTimezoneOffset()},a)},Ee=async(t,a)=>{const s=await q("/api/v1/analytics/orders/valid",{...t,timezone_offset_minutes:-new Date().getTimezoneOffset()},a),l=ge(s,["data","result"])||{},o=de(s,["orders","data","items"]).map(b=>({...b,id:b.order_id,status:oe(b.status||b.order_status),order_status:oe(b.order_status),quantity:Number(b.quantity||1)}));return{orders:o,total:Number(l.total??o.length),truncated:l.truncated===!0}},ce=t=>t instanceof Error&&t.message==="请求已取消",G=(t,a)=>t instanceof Error?t.message:a,Fe=t=>{const{range:a,customStartDate:s,customEndDate:l,customRangeVersion:n}=t,[o,b]=c.useState(null),[_,I]=c.useState(null),[K,v]=c.useState({overview:"idle",range:"idle",error:""}),[d,T]=c.useState(0),R=c.useRef(0),S=c.useRef(0),L=c.useMemo(()=>({range:a,customStartDate:s,customEndDate:l}),[l,s,a]),D=c.useCallback(()=>T(u=>u+1),[]);c.useEffect(()=>{const u=++S.current,h=new AbortController;return v(m=>({...m,overview:"loading",error:""})),Promise.all([Pe({signal:h.signal}),We(void 0,{signal:h.signal})]).then(([m,g])=>{P(S.current,u,h.signal)&&(b({stats:m,items:g,itemNames:Ce(g)}),v(p=>({...p,overview:"success"})))}).catch(m=>{!P(S.current,u,h.signal)||ce(m)||v(g=>({...g,overview:"error",error:G(m,"概览加载失败")}))}),(()=>h.abort())},[d]),c.useEffect(()=>{let u;try{u=ue(a,new Date,s,l)}catch(p){v(w=>({...w,range:"error",error:G(p,"日期范围无效")}));return}const h=Se(u),m=++R.current,g=new AbortController;return v(p=>({...p,range:"loading",error:""})),Promise.all([ie({start_date:u.startDate,end_date:u.endDate},{signLine truncated
|
||||
@@ -0,0 +1,2 @@
|
||||
import{r as n,j as e,b as be}from"./react-vendor-C_od1ZSF.js";import{g as me,a as Q,b as We,d as Ye,p as yt}from"./index-CCqtUiU5.js";import{c as He}from"./contract-COFcZjyb.js";import{a3 as ft,U as Me,R as we,N as Ee,a4 as _e,a5 as ye,V as jt,F as vt,B as Nt,a6 as Ge,a7 as wt,a8 as _t,A as kt,d as Ct,X as de,r as It,a9 as $e,I as De}from"./icons-vendor-CvzvbbIV.js";const Ue="ydisks-amap-js-api",St="c9b68d4ce9a2a97f22a4a439404488ca";let xe=null;const Pt=()=>St,Bt=()=>window.AMap?Promise.resolve(window.AMap):xe||(xe=new Promise((s,r)=>{const c=document.getElementById(Ue),m=c||document.createElement("script"),u=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(S)},j=()=>{window.AMap?(u(),s(window.AMap)):(u(),r(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},S=window.setTimeout(()=>{u(),r(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=j,m.id=Ue,m.async=!0,m.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(Pt())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,m.onerror=()=>{u(),r(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},c||document.head.appendChild(m)}).catch(s=>{throw xe=null,s}),xe),fe=s=>Number.isFinite(s)&&s!==0,qt=s=>{var u,j;const r=Number((u=s.location)==null?void 0:u.lng),c=Number((j=s.location)==null?void 0:j.lat),m={area:String(s.adname||"").trim(),city:String(s.cityname||"").trim(),division_id:String(s.adcode||"").trim(),longitude:r,latitude:c,poi_id:String(s.id||"").trim(),poi_name:String(s.name||"").trim(),province:String(s.pname||"").trim()};return!m.division_id||!m.province||!m.city||!m.poi_id||!m.poi_name||!fe(r)||!fe(c)||r<-180||r>180||c<-90||c>90?null:m},Ft=async(s,r)=>{if(!fe(s)||!fe(r)||s<-180||s>180||r<-90||r>90)throw new Error("经纬度无效");const c=await Bt();return new Promise((m,u)=>{new c.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[s,r],1e3,(S,w)=>{var I;if(S!=="complete"){if(S==="no_data"){m([]);return}u(new Error("高德地图附近地址查询失败,请稍后重试"));return}const R=(((I=w==null?void 0:w.poiList)==null?void 0:I.pois)||[]).map(qt).filter(U=>U!==null);m(R)})})},Rt=async s=>me("/api/v1/accounts/details",void 0,s),ze=async s=>me("/api/v1/automation-rules",void 0,s),ke=s=>s===!0||s===1||s==="1",Oe=async(s,r)=>{const c=await me("/api/v1/items",void 0,r);return He(c,["items","data","results"]).map(u=>({...u,id:u.id||`${u.cookie_id}-${u.item_id}`,is_multi_spec:ke(u.is_multi_spec),is_multi_qty_ship:ke(u.is_multi_qty_ship??u.multi_quantity_delivery),multi_quantity_delivery:ke(u.multi_quantity_delivery??u.is_multi_qty_ship)}))},Lt=async s=>Q("/api/v1/items/get-all-from-account",{cookie_id:s}),At=async(s,r)=>Ye(`/api/v1/items/${s}/${r}`),Mt=async(s,r)=>Q(`/api/v1/items/${s}`,r),Et=async s=>{const r=new FormData;r.set("cookie_id",s.cookie_id),r.set("title",s.title),r.set("description",s.description),r.set("price",s.price),r.set("original_price",s.original_price||""),r.set("quantity",String(s.quantity)),r.set("postage_mode",s.postage_mode),r.set("postage",s.postage||""),s.location&&r.set("location",JSON.stringify(s.location));for(const c of s.images)r.append("images",c);return We("/api/v1/items/publish",r)},Gt=async(s,r,c)=>Q("/api/v1/items/publish-categories/recommend",{cookie_id:s,keyword:r},c),$t=async(s,r)=>{const c=new FormData;return c.set("file",s.file),s.imagesZip&&c.set("images_zip",s.imagesZip),s.defaultCookieId&&c.set("default_cookie_id",s.defaultCookieId),c.set("fallback_category_id",s.fallbackCategory.catId),c.set("fallback_category_name",s.fallbackCategory.catName),c.set("fallback_channel_category_id",s.fallbackCategory.channelCatId||""),c.set("fallback_tb_category_id",s.fallbackCategory.tbCatId||""),s.location&&c.set("location",JSON.stringify(s.location)),c.set("publish_interval_seconds",String(s.publishIntervalSeconds??5)),We("/api/v1/items/publish-batches/preview",c,r)},Dt=async(s,r)=>Q("/api/v1/items/publish-batches",{preview_id:s},r),X=async(s,r)=>me(`/api/v1/items/publish-batches/${s}`,void 0,r),Xe=async(s=20,r)=>{const c=await me("/api/v1/items/publish-batches",{limit:s},r);return He(c,["batches","data","items"])},Te=async(s,r)=>Ye(`/api/v1/items/publish-batches/${s}`,void 0,r),Ut=async(s,r)=>Q(`/api/v1/items/publish-batches/${s}/cancel`,{},r),zt=async(s,r)=>Q(`/api/v1/items/publish-batches/${s}/retry-failed`,{},r),Ot=async(s,r,c)=>yt(`/api/v1/items/${s}/${r}`,c),Tt=s=>s.find(r=>r.status==="running"||r.status==="canceling"),Ie=s=>s==="running"||s==="canceling",Kt=s=>!!(s!=null&&s.preview_id&&Number(s.valid||0)>0),Jt=s=>!!(s!=null&&s.id&&Number(s.retryable||0)>0&&!Ie(s.status)),Zt=(s,r)=>s===r,Ke=s=>{switch(s){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":returLine truncated
|
||||
`),g=new Blob(["\uFEFF"+o],{type:"text/csv;charset=utf-8"}),ne=URL.createObjectURL(g),K=document.createElement("a");K.href=ne,K.download="批量铺货模板.csv",document.body.appendChild(K),K.click(),K.remove(),URL.revokeObjectURL(ne)},[]),le=n.useCallback(()=>{y(a=>({...a,cookie_id:s||a.cookie_id})),b(!0)},[s]),re=n.useCallback(()=>{F(a=>({...a,cookie_id:s||a.cookie_id})),d(!0)},[s]),ue=n.useCallback(async a=>{if(!(a?s:p.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");C(!0),navigator.geolocation.getCurrentPosition(async o=>{try{const g=await Ft(o.coords.longitude,o.coords.latitude);if(!g.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");a?(S(g),w(g[0])):(O(g),L(g[0]))}catch(g){alert(Ce(g,"获取发货地失败"))}finally{C(!1)}},o=>{C(!1),alert(o.code===o.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},[p.cookie_id,s,w,S]);return{selectedAccount:s,setSelectedAccount:r,loading:R,publishing:U,showEditModal:E,setShowEditModal:P,showAddModal:G,setShowAddModal:b,showPublishModal:B,setShowPublishModal:d,locationLoading:v,publishLocations:z,setPublishLocations:O,publishLocation:T,setPublishLocation:L,selectedItem:q,editForm:k,setEditForm:V,addForm:h,setAddForm:y,publishForm:p,setPublishForm:F,publishImagePreviews:f,handleSync:ee,handleEdit:te,handleSaveEdit:W,handleDelete:Z,handleAddItem:se,handlePublishItem:Y,downloadPublishTemplate:ae,openAddModal:le,openPublishModal:re,locateForPublish:ue}},Yt=({phase:s})=>{const r=[["upload","1 上传"],["preview","2 预检"],["running","3 发布"],["done","4 结果"]];return e.jsx("div",{className:"grid grid-cols-4 gap-2",children:r.map(([c,m])=>e.jsx("div",{className:`rounded-xl px-3 py-2 text-center text-xs font-extrabold border ${s===c?"bg-blue-600 text-white border-blue-600":"bg-gray-50 text-gray-500 border-gray-100"}`,children:m},c))})},Ht=s=>{const r=String(s||"").trim();return r?/^[¥¥]/.test(r)?r:`¥${r}`:"-"},ss=({onConfigureDelivery:s})=>{const[r,c]=n.useState([]),[m,u]=n.useState([]),[j,S]=n.useState([]),[w,R]=n.useState(""),[I,U]=n.useState(""),M=n.useRef(0),E=n.useRef(0),P=n.useCallback(async()=>{const t=++M.current,i=await Oe();t===M.current&&c(i)},[]),G=n.useCallback(async()=>{const t=++E.current,i=await ze();t===E.current&&u(i)},[]),b=Vt({selectedAccount:w,loadItems:P,loadShippingRules:G}),{showBatchModal:B,batchLoading:d,batchPhase:v,batchFile:C,setBatchFile:z,batchImagesZip:O,setBatchImagesZip:T,batchCategoryKeyword:L,setBatchCategoryKeyword:q,batchCategoryLoading:$,batchFallbackCategory:k,setBatchFallbackCategory:V,batchPreview:h,batchDetail:y,recentBatch:p,setRecentBatch:F,batchLocations:f,batchLocation:x,batchPublishIntervalSeconds:ee,setBatchPublishIntervalSeconds:te,setBatchLocations:W,setBatchLocation:Z,openBatchModal:se,handleRecommendBatchCategory:Y,openRecentBatchResult:ae,handlePreviewBatch:le,handleStartBatch:re,handleCancelBatch:ue,abandonBatchPreview:a,closeBatchModal:l,handleRetryBatchFailed:o}=b,g=Wt({selectedAccount:w,setSelectedAccount:R,setItems:c,loadItems:P,loadShippingRules:G,onConfigureDelivery:s,setBatchLocations:W,setBatchLocation:Z}),{loading:ne,publishing:K,showEditModal:je,setShowEditModal:ve,showAddModal:Qe,setShowAddModal:et,showPublishModal:tt,setShowPublishModal:st,locationLoading:he,publishLocations:pe,setPublishLocations:at,publishLocation:lt,setPublishLocation:Se,selectedItem:Pe,editForm:J,setEditForm:ge,addForm:A,setAddForm:ie,publishForm:N,setPublishForm:D,publishImagePreviews:Be,handleSync:rt,handleEdit:nt,handleSaveEdit:it,handleDelete:ct,handleAddItem:ot,handlePublishItem:dt,downloadPublishTemplate:xt,openAddModal:mt,openPublishModal:ut,locateForPublish:qe}=g;n.useEffect(()=>{const t=new AbortController,i=++M.current,_=++E.current;let oe=!0;return Promise.all([Rt({signal:t.signal}),Oe(void 0,{signal:t.signal}),ze({signal:t.signal}),Xe(20,{signal:t.signal})]).then(([H,pt,gt,Ae])=>{if(!oe||t.signal.aborted||i!==M.current||_!==E.current)return;S(H),c(pt),u(gt);const bt=Ae.find(Ne=>["running","canceling"].includes(Ne.status))||Ae.find(Ne=>Ne.status!=="preview");F(bt||null)}).catch(H=>{t.signal.aborted||console.error("加载商品配置失败:",H)}),(()=>{oe=!1,t.abort()})},[]);const ht=t=>m.filter(i=>i.cookie_id===t.cookie_id&&i.item_id===t.item_id).length>0?m.filter(i=>i.cookie_id===t.cookie_id&&i.item_id===t.item_id):m.filter(i=>i.cookie_id===t.cookie_id&&!i.item_id),Fe=n.useMemo(()=>new Map(j.map(t=>[t.id,t])),[j]),Re=n.useMemo(()=>I?r.filter(t=>t.cookie_id===I):r,[I,r]),ce=t=>{const i=Fe.get(t),_=(i==null?void 0:i.remark)||(i==null?void 0:i.nickname);return _?`${_} · ${t.slice(0,6)}`:`账号 ${t.slice(0,8)}`},Le=t=>{const i=Fe.get(t);return(i==null?void 0:i.remark)||(i==null?void 0:i.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fa
Line truncated
|
||||
@@ -1,2 +0,0 @@
|
||||
import{r as i,j as e,b as be}from"./react-vendor-C_od1ZSF.js";import{g as xe,a as te,b as We,d as Ye,p as gt}from"./index-k6Tc6ww6.js";import{c as He}from"./contract-COFcZjyb.js";import{a3 as bt,U as Me,R as we,N as Ee,a4 as _e,a5 as ye,V as yt,F as ft,B as jt,a6 as Ge,a7 as vt,a8 as Nt,A as wt,d as _t,X as oe,r as kt,a9 as $e,I as De}from"./icons-vendor-CvzvbbIV.js";const Ue="ydisks-amap-js-api",Ct="c9b68d4ce9a2a97f22a4a439404488ca";let de=null;const It=()=>Ct,St=()=>window.AMap?Promise.resolve(window.AMap):de||(de=new Promise((s,r)=>{const o=document.getElementById(Ue),u=o||document.createElement("script"),h=()=>{window.__ydisksAmapLoaded=void 0,window.clearTimeout(S)},j=()=>{window.AMap?(h(),s(window.AMap)):(h(),r(new Error("高德地图 API 加载完成但未找到 AMap 对象")))},S=window.setTimeout(()=>{h(),r(new Error("高德地图 API 加载超时,请检查网络或 VITE_AMAP_JS_KEY 配置"))},15e3);window.__ydisksAmapLoaded=j,u.id=Ue,u.async=!0,u.src=`https://webapi.amap.com/maps?v=2.0&key=${encodeURIComponent(It())}&plugin=AMap.PlaceSearch&callback=__ydisksAmapLoaded`,u.onerror=()=>{h(),r(new Error("高德地图 API 加载失败,请检查网络或 VITE_AMAP_JS_KEY 配置"))},o||document.head.appendChild(u)}).catch(s=>{throw de=null,s}),de),fe=s=>Number.isFinite(s)&&s!==0,Pt=s=>{var h,j;const r=Number((h=s.location)==null?void 0:h.lng),o=Number((j=s.location)==null?void 0:j.lat),u={area:String(s.adname||"").trim(),city:String(s.cityname||"").trim(),division_id:String(s.adcode||"").trim(),longitude:r,latitude:o,poi_id:String(s.id||"").trim(),poi_name:String(s.name||"").trim(),province:String(s.pname||"").trim()};return!u.division_id||!u.province||!u.city||!u.poi_id||!u.poi_name||!fe(r)||!fe(o)||r<-180||r>180||o<-90||o>90?null:u},Bt=async(s,r)=>{if(!fe(s)||!fe(r)||s<-180||s>180||r<-90||r>90)throw new Error("经纬度无效");const o=await St();return new Promise((u,h)=>{new o.PlaceSearch({extensions:"all",pageSize:10}).searchNearBy("",[s,r],1e3,(S,w)=>{var C;if(S!=="complete"){if(S==="no_data"){u([]);return}h(new Error("高德地图附近地址查询失败,请稍后重试"));return}const R=(((C=w==null?void 0:w.poiList)==null?void 0:C.pois)||[]).map(Pt).filter(D=>D!==null);u(R)})})},qt=async s=>xe("/api/v1/accounts/details",void 0,s),ze=async s=>xe("/api/v1/automation-rules",void 0,s),ke=s=>s===!0||s===1||s==="1",Oe=async(s,r)=>{const o=await xe("/api/v1/items",void 0,r);return He(o,["items","data","results"]).map(h=>({...h,id:h.id||`${h.cookie_id}-${h.item_id}`,is_multi_spec:ke(h.is_multi_spec),is_multi_qty_ship:ke(h.is_multi_qty_ship??h.multi_quantity_delivery),multi_quantity_delivery:ke(h.multi_quantity_delivery??h.is_multi_qty_ship)}))},Ft=async s=>te("/api/v1/items/get-all-from-account",{cookie_id:s}),Rt=async(s,r)=>Ye(`/api/v1/items/${s}/${r}`),Lt=async(s,r)=>te(`/api/v1/items/${s}`,r),At=async s=>{const r=new FormData;r.set("cookie_id",s.cookie_id),r.set("title",s.title),r.set("description",s.description),r.set("price",s.price),r.set("original_price",s.original_price||""),r.set("quantity",String(s.quantity)),r.set("postage_mode",s.postage_mode),r.set("postage",s.postage||""),s.location&&r.set("location",JSON.stringify(s.location));for(const o of s.images)r.append("images",o);return We("/api/v1/items/publish",r)},Mt=async(s,r,o)=>te("/api/v1/items/publish-categories/recommend",{cookie_id:s,keyword:r},o),Et=async(s,r)=>{const o=new FormData;return o.set("file",s.file),s.imagesZip&&o.set("images_zip",s.imagesZip),s.defaultCookieId&&o.set("default_cookie_id",s.defaultCookieId),o.set("fallback_category_id",s.fallbackCategory.catId),o.set("fallback_category_name",s.fallbackCategory.catName),o.set("fallback_channel_category_id",s.fallbackCategory.channelCatId||""),o.set("fallback_tb_category_id",s.fallbackCategory.tbCatId||""),s.location&&o.set("location",JSON.stringify(s.location)),We("/api/v1/items/publish-batches/preview",o,r)},Gt=async(s,r)=>te("/api/v1/items/publish-batches",{preview_id:s},r),ee=async(s,r)=>xe(`/api/v1/items/publish-batches/${s}`,void 0,r),Xe=async(s=20,r)=>{const o=await xe("/api/v1/items/publish-batches",{limit:s},r);return He(o,["batches","data","items"])},Te=async(s,r)=>Ye(`/api/v1/items/publish-batches/${s}`,void 0,r),$t=async(s,r)=>te(`/api/v1/items/publish-batches/${s}/cancel`,{},r),Dt=async(s,r)=>te(`/api/v1/items/publish-batches/${s}/retry-failed`,{},r),Ut=async(s,r,o)=>gt(`/api/v1/items/${s}/${r}`,o),zt=s=>s.find(r=>r.status==="running"||r.status==="canceling"),Ie=s=>s==="running"||s==="canceling",Ot=s=>!!(s!=null&&s.preview_id&&Number(s.valid||0)>0),Tt=s=>!!(s!=null&&s.id&&Number(s.retryable||0)>0&&!Ie(s.status)),Kt=(s,r)=>s===r,Ke=s=>{switch(s){case"preview":return"待确认";case"pending":return"等待中";case"running":return"发布中";case"canceling":return"正在安全取消";case"success":return"成功";case"failed":return"失败";case"completed":return"已完成";case"partially_failed":return"部分失败";case"canceled":return"已取消";default:returLine truncated
|
||||
`),P=new Blob(["\uFEFF"+I],{type:"text/csv;charset=utf-8"}),ue=URL.createObjectURL(P),W=document.createElement("a");W.href=ue,W.download="批量铺货模板.csv",document.body.appendChild(W),W.click(),W.remove(),URL.revokeObjectURL(ue)},[]),me=i.useCallback(()=>{f(l=>({...l,cookie_id:s||l.cookie_id})),b(!0)},[s]),a=i.useCallback(()=>{m(l=>({...l,cookie_id:s||l.cookie_id})),d(!0)},[s]),n=i.useCallback(async l=>{if(!(l?s:x.cookie_id))return alert("请先选择发布账号");if(!navigator.geolocation)return alert("当前浏览器不支持定位");k(!0),navigator.geolocation.getCurrentPosition(async I=>{try{const P=await Bt(I.coords.longitude,I.coords.latitude);if(!P.length)throw new Error("当前位置附近没有可用的高德发货地,请稍后重试");l?(S(P),w(P[0])):(z(P),L(P[0]))}catch(P){alert(Ce(P,"获取发货地失败"))}finally{k(!1)}},I=>{k(!1),alert(I.code===I.PERMISSION_DENIED?"定位权限被拒绝,请在浏览器设置中允许定位":"无法获取当前位置,请稍后重试")},{enableHighAccuracy:!0,timeout:15e3,maximumAge:6e4})},[x.cookie_id,s,w,S]);return{selectedAccount:s,setSelectedAccount:r,loading:R,publishing:D,showEditModal:E,setShowEditModal:B,showAddModal:G,setShowAddModal:b,showPublishModal:q,setShowPublishModal:d,locationLoading:v,publishLocations:U,setPublishLocations:z,publishLocation:O,setPublishLocation:L,selectedItem:F,editForm:y,setEditForm:T,addForm:g,setAddForm:f,publishForm:x,setPublishForm:m,publishImagePreviews:K,handleSync:H,handleEdit:V,handleSaveEdit:se,handleDelete:X,handleAddItem:ae,handlePublishItem:le,downloadPublishTemplate:re,openAddModal:me,openPublishModal:a,locateForPublish:n}},Vt=({phase:s})=>{const r=[["upload","1 上传"],["preview","2 预检"],["running","3 发布"],["done","4 结果"]];return e.jsx("div",{className:"grid grid-cols-4 gap-2",children:r.map(([o,u])=>e.jsx("div",{className:`rounded-xl px-3 py-2 text-center text-xs font-extrabold border ${s===o?"bg-blue-600 text-white border-blue-600":"bg-gray-50 text-gray-500 border-gray-100"}`,children:u},o))})},Wt=s=>{const r=String(s||"").trim();return r?/^[¥¥]/.test(r)?r:`¥${r}`:"-"},es=({onConfigureDelivery:s})=>{const[r,o]=i.useState([]),[u,h]=i.useState([]),[j,S]=i.useState([]),[w,R]=i.useState(""),[C,D]=i.useState(""),M=i.useRef(0),E=i.useRef(0),B=i.useCallback(async()=>{const t=++M.current,c=await Oe();t===M.current&&o(c)},[]),G=i.useCallback(async()=>{const t=++E.current,c=await ze();t===E.current&&h(c)},[]),b=Jt({selectedAccount:w,loadItems:B,loadShippingRules:G}),{showBatchModal:q,batchLoading:d,batchPhase:v,batchFile:k,setBatchFile:U,batchImagesZip:z,setBatchImagesZip:O,batchCategoryKeyword:L,setBatchCategoryKeyword:F,batchCategoryLoading:Z,batchFallbackCategory:y,setBatchFallbackCategory:T,batchPreview:g,batchDetail:f,recentBatch:x,setRecentBatch:m,batchLocations:K,batchLocation:Y,setBatchLocations:H,setBatchLocation:V,openBatchModal:se,handleRecommendBatchCategory:X,openRecentBatchResult:ae,handlePreviewBatch:le,handleStartBatch:re,handleCancelBatch:me,abandonBatchPreview:a,closeBatchModal:n,handleRetryBatchFailed:l}=b,p=Zt({selectedAccount:w,setSelectedAccount:R,setItems:o,loadItems:B,loadShippingRules:G,onConfigureDelivery:s,setBatchLocations:H,setBatchLocation:V}),{loading:I,publishing:P,showEditModal:ue,setShowEditModal:W,showAddModal:je,setShowAddModal:ve,showPublishModal:Qe,setShowPublishModal:et,locationLoading:he,publishLocations:pe,setPublishLocations:tt,publishLocation:st,setPublishLocation:Se,selectedItem:Pe,editForm:J,setEditForm:ge,addForm:A,setAddForm:ne,publishForm:N,setPublishForm:$,publishImagePreviews:Be,handleSync:at,handleEdit:lt,handleSaveEdit:rt,handleDelete:nt,handleAddItem:it,handlePublishItem:ct,downloadPublishTemplate:ot,openAddModal:dt,openPublishModal:xt,locateForPublish:qe}=p;i.useEffect(()=>{const t=new AbortController,c=++M.current,_=++E.current;let ce=!0;return Promise.all([qt({signal:t.signal}),Oe(void 0,{signal:t.signal}),ze({signal:t.signal}),Xe(20,{signal:t.signal})]).then(([Q,ut,ht,Ae])=>{if(!ce||t.signal.aborted||c!==M.current||_!==E.current)return;S(Q),o(ut),h(ht);const pt=Ae.find(Ne=>["running","canceling"].includes(Ne.status))||Ae.find(Ne=>Ne.status!=="preview");m(pt||null)}).catch(Q=>{t.signal.aborted||console.error("加载商品配置失败:",Q)}),(()=>{ce=!1,t.abort()})},[]);const mt=t=>u.filter(c=>c.cookie_id===t.cookie_id&&c.item_id===t.item_id).length>0?u.filter(c=>c.cookie_id===t.cookie_id&&c.item_id===t.item_id):u.filter(c=>c.cookie_id===t.cookie_id&&!c.item_id),Fe=i.useMemo(()=>new Map(j.map(t=>[t.id,t])),[j]),Re=i.useMemo(()=>C?r.filter(t=>t.cookie_id===C):r,[C,r]),ie=t=>{const c=Fe.get(t),_=(c==null?void 0:c.remark)||(c==null?void 0:c.nickname);return _?`${_} · ${t.slice(0,6)}`:`账号 ${t.slice(0,8)}`},Le=t=>{const c=Fe.get(t);return(c==null?void 0:c.remark)||(c==null?void 0:c.nickname)||"未命名账号"};return e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsxs("div",{className:"flex flex-col xl:flex-row xl:
Line truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{j as e,b as _e,r as d}from"./react-vendor-C_od1ZSF.js";import{ai as ee,ah as se,aj as Ne,x as K,e as W,L as I,y as ve,F as ke,s as Q,X as te,u as ae,v as ne,r as we,R as Se,N as Ce}from"./icons-vendor-CvzvbbIV.js";import{g as re,p as le,a as oe,d as Te}from"./index-k6Tc6ww6.js";const H=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],G=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},ie=s=>{const t=Object.prototype.hasOwnProperty.call(s,"use_custom_smtp"),a=H.some(n=>String(s[n]??"").trim()!=="");return{...s,use_custom_smtp:t?G(s.use_custom_smtp,!1):a}},ce=(s,t)=>{const a={...s,use_custom_smtp:!0};for(const n of H)String(a[n]??"").trim()===""&&t[n]!==void 0&&(a[n]=t[n]);return a.smtp_port||(a.smtp_port=587),a.smtp_from_address||(a.smtp_from_address=a.smtp_user||""),a.smtp_use_tls=G(a.smtp_use_tls,!0),a.smtp_use_ssl=G(a.smtp_use_ssl,!1),a},de=s=>{const t=ie(s),a={to_email:String(t.to_email??"").trim(),use_custom_smtp:t.use_custom_smtp===!0};if(a.use_custom_smtp)for(const n of H)a[n]=t[n];return a},B={bark:{label:"Bark",icon:W,fields:[{key:"server_url",label:"Bark 服务器",placeholder:"https://api.day.app",required:!0},{key:"device_key",label:"Device Key",placeholder:"你的 Bark 设备 Key",required:!0},{key:"title",label:"标题(可选)",placeholder:"Ydisks闲鱼助手"},{key:"sound",label:"铃声(可选)",placeholder:"default"},{key:"group",label:"分组(可选)",placeholder:"xianyu"}],guide:{steps:["App Store 搜索并安装 Bark(免费)","打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app/<key>/这是测试推送内容","URL 路径里 <key> 那一段就是 Device Key,复制填入","服务器地址默认 https://api.day.app,自建服务端则填自建域名"],urlFormat:"https://api.day.app/<你的key>/测试内容",note:"不需要 secret,Device Key 本身就是唯一凭证。"}},dingtalk:{label:"钉钉机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://oapi.dingtalk.com/robot/send?access_token=...",required:!0},{key:"secret",label:"加签密钥",placeholder:"SEC...",help:"安全设置勾选「加签」后生成,SEC 开头"}],guide:{steps:["钉钉进入一个群(可建单人群)→ 右上角 群设置","机器人 → 添加机器人 → 选择「自定义机器人」","安全设置勾选「加签」","完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制","Webhook URL 填上面,Secret 填加签密钥"],urlFormat:"https://oapi.dingtalk.com/robot/send?access_token=XXX",note:"加签密钥可选,但强烈建议启用,否则机器人可能被滥用。"}},feishu:{label:"飞书机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://open.feishu.cn/open-apis/bot/v2/hook/...",required:!0},{key:"secret",label:"签名校验密钥",placeholder:"sec-...",help:"安全设置选「签名校验」后生成"}],guide:{steps:["飞书进入目标群 → 右上角 更多 → 设置","群机器人 → 添加机器人 → 自定义机器人","安全设置选择「签名校验」,复制生成的秘钥","完成会给 Webhook 地址,复制","Webhook URL 填上面,秘钥填签名校验密钥"],urlFormat:"https://open.feishu.cn/open-apis/bot/v2/hook/xxx",note:"签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。"}},wechat:{label:"企业微信机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...",required:!0}],guide:{steps:["企业微信进入一个内部群 → 右上角 … → 群设置","找到「群机器人」(新版可能叫「消息推送」)","添加 → 选择自定义机器人","完成给 Webhook 地址(含 ?key=),复制填入"],urlFormat:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX",note:"不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。"}},webhook:{label:"自定义 Webhook",icon:Ne,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://your-server/notify",required:!0}],guide:{steps:["仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON","系统会 POST 这个 URL,Content-Type: application/json","请求体固定为右侧 JSON 格式,按需解析 message 字段"],urlFormat:'{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',note:"若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。"}},telegram:{label:"Telegram",icon:se,fields:[{key:"bot_token",label:"Bot Token",placeholder:"123456:ABC-DEF...",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"-1001234567890 或你的用户 ID",Line truncated
|
||||
import{j as e,b as _e,r as d}from"./react-vendor-C_od1ZSF.js";import{ai as ee,ah as se,aj as Ne,x as K,e as W,L as I,y as ve,F as ke,s as Q,X as te,u as ae,v as ne,r as we,R as Se,N as Ce}from"./icons-vendor-CvzvbbIV.js";import{g as re,p as le,a as oe,d as Te}from"./index-CCqtUiU5.js";const H=["smtp_server","smtp_port","smtp_user","smtp_password","smtp_from_name","smtp_from_address","smtp_use_tls","smtp_use_ssl"],G=(s,t)=>{if(typeof s=="boolean")return s;if(typeof s=="string"){if(["true","1","yes","on"].includes(s.toLowerCase()))return!0;if(["false","0","no","off"].includes(s.toLowerCase()))return!1}return t},ie=s=>{const t=Object.prototype.hasOwnProperty.call(s,"use_custom_smtp"),a=H.some(n=>String(s[n]??"").trim()!=="");return{...s,use_custom_smtp:t?G(s.use_custom_smtp,!1):a}},ce=(s,t)=>{const a={...s,use_custom_smtp:!0};for(const n of H)String(a[n]??"").trim()===""&&t[n]!==void 0&&(a[n]=t[n]);return a.smtp_port||(a.smtp_port=587),a.smtp_from_address||(a.smtp_from_address=a.smtp_user||""),a.smtp_use_tls=G(a.smtp_use_tls,!0),a.smtp_use_ssl=G(a.smtp_use_ssl,!1),a},de=s=>{const t=ie(s),a={to_email:String(t.to_email??"").trim(),use_custom_smtp:t.use_custom_smtp===!0};if(a.use_custom_smtp)for(const n of H)a[n]=t[n];return a},B={bark:{label:"Bark",icon:W,fields:[{key:"server_url",label:"Bark 服务器",placeholder:"https://api.day.app",required:!0},{key:"device_key",label:"Device Key",placeholder:"你的 Bark 设备 Key",required:!0},{key:"title",label:"标题(可选)",placeholder:"Ydisks闲鱼助手"},{key:"sound",label:"铃声(可选)",placeholder:"default"},{key:"group",label:"分组(可选)",placeholder:"xianyu"}],guide:{steps:["App Store 搜索并安装 Bark(免费)","打开 Bark App,首页会显示一条测试 URL,形如 https://api.day.app/<key>/这是测试推送内容","URL 路径里 <key> 那一段就是 Device Key,复制填入","服务器地址默认 https://api.day.app,自建服务端则填自建域名"],urlFormat:"https://api.day.app/<你的key>/测试内容",note:"不需要 secret,Device Key 本身就是唯一凭证。"}},dingtalk:{label:"钉钉机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://oapi.dingtalk.com/robot/send?access_token=...",required:!0},{key:"secret",label:"加签密钥",placeholder:"SEC...",help:"安全设置勾选「加签」后生成,SEC 开头"}],guide:{steps:["钉钉进入一个群(可建单人群)→ 右上角 群设置","机器人 → 添加机器人 → 选择「自定义机器人」","安全设置勾选「加签」","完成页同时展示 Webhook 地址和 SEC 开头的 Secret,两个都复制","Webhook URL 填上面,Secret 填加签密钥"],urlFormat:"https://oapi.dingtalk.com/robot/send?access_token=XXX",note:"加签密钥可选,但强烈建议启用,否则机器人可能被滥用。"}},feishu:{label:"飞书机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://open.feishu.cn/open-apis/bot/v2/hook/...",required:!0},{key:"secret",label:"签名校验密钥",placeholder:"sec-...",help:"安全设置选「签名校验」后生成"}],guide:{steps:["飞书进入目标群 → 右上角 更多 → 设置","群机器人 → 添加机器人 → 自定义机器人","安全设置选择「签名校验」,复制生成的秘钥","完成会给 Webhook 地址,复制","Webhook URL 填上面,秘钥填签名校验密钥"],urlFormat:"https://open.feishu.cn/open-apis/bot/v2/hook/xxx",note:"签名密钥可选,建议启用。频率限制:单机器人 100 次/分钟。"}},wechat:{label:"企业微信机器人",icon:K,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=...",required:!0}],guide:{steps:["企业微信进入一个内部群 → 右上角 … → 群设置","找到「群机器人」(新版可能叫「消息推送」)","添加 → 选择自定义机器人","完成给 Webhook 地址(含 ?key=),复制填入"],urlFormat:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=XXX",note:"不需要 secret,URL 里的 key 就是唯一凭证,注意不要泄露。频率限制 20 条/分钟。"}},webhook:{label:"自定义 Webhook",icon:Ne,fields:[{key:"webhook_url",label:"Webhook URL",placeholder:"https://your-server/notify",required:!0}],guide:{steps:["仅适用于自己有服务器的用户:在你自己的机器上起一个 HTTP 接口收 JSON","系统会 POST 这个 URL,Content-Type: application/json","请求体固定为右侧 JSON 格式,按需解析 message 字段"],urlFormat:'{"message":"告警正文","timestamp":"2026-07-05 12:00:00","source":"xianyu-auto-reply"}',note:"若用 Server酱 / PushPlus 等第三方推送服务,格式不兼容,需写中间脚本转发,或改用对应专用渠道。"}},telegram:{label:"Telegram",icon:se,fields:[{key:"bot_token",label:"Bot Token",placeholder:"123456:ABC-DEF...",required:!0},{key:"chat_id",label:"Chat ID",placeholder:"-1001234567890 或你的用户 ID",Line truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{j as e,b as J,r as a}from"./react-vendor-C_od1ZSF.js";import{U as te,I as re,X as W,J as ne,R as H,N as ie,O as Y,m as Z,E as ce,v as oe,V as de,F as xe,h as me,g as ue,r as he}from"./icons-vendor-CvzvbbIV.js";import{g as X,b as ae,a as K,p as ge,d as pe}from"./index-k6Tc6ww6.js";import{o as be,c as ye}from"./contract-COFcZjyb.js";import{f as ee}from"./dateTime-DDi7rqpW.js";const fe=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],je=s=>{const t=typeof s=="object"&&s!==null?s:{},c=Array.isArray(t.results)?t.results:[];return{total:Number(t.total||0),success_count:Number(t.success_count||0),failed_count:Number(t.failed_count||0),results:c.map(ve)}},ve=s=>{const t=typeof s=="object"&&s!==null?s:{};return{order_id:String(t.order_id||"unknown"),success:t.success===!0,message:String(t.message||"")}},Ne=s=>(s==null?void 0:s.results.filter(we))||[],we=s=>!s.success,_e=(s,t)=>s!==null&&!t,ke=s=>{if(!s)return"请选择订单文件";const t=s.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(t)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},T=(s,t)=>s===t,Ce=(s,t)=>s instanceof Error&&s.message?s.message:t,Se=({filter:s,onFilterChange:t,accountFilter:c,onAccountFilterChange:h,accounts:g,accountName:m,searchText:u,onSearchChange:p})=>{const b=r=>t(r.currentTarget.dataset.status||"all"),_=r=>h(r.target.value),y=r=>p(r.target.value);return e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:fe.map(r=>e.jsx("button",{"data-status":r.key,onClick:b,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${s===r.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:r.label},r.key))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(te,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:c,onChange:_,className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),g.map(r=>e.jsx("option",{value:r.id,children:m(r.id)},r.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(re,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:u,onChange:y,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Ee=s=>{const t=m=>{var u;s.setImportFile(((u=m.target.files)==null?void 0:u[0])||null)},c=()=>s.closeImportModal(),h=()=>void s.handleImportOrders(),g=()=>void s.handleRetryImport();return s.showImportModal?J.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:c,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(W,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:t,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),s.importFile&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ne,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:s.importFile.name})]})}),s.importError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-100 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.importError}),e.jsx("button",{type:"button",onClick:g,disabled:s.importing||!s.importFile,className:"font-bold whitespace-nowrap",children:"重试"})]}),s.importResult&&s.importResult.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:成功 ",s.importResultLine truncated
|
||||
import{j as e,b as J,r as a}from"./react-vendor-C_od1ZSF.js";import{U as te,I as re,X as W,J as ne,R as H,N as ie,O as Y,m as Z,E as ce,v as oe,V as de,F as xe,h as me,g as ue,r as he}from"./icons-vendor-CvzvbbIV.js";import{g as X,b as ae,a as K,p as ge,d as pe}from"./index-CCqtUiU5.js";import{o as be,c as ye}from"./contract-COFcZjyb.js";import{f as ee}from"./dateTime-DDi7rqpW.js";const fe=[{key:"all",label:"全部"},{key:"processing",label:"处理中"},{key:"shipped",label:"已发货"},{key:"pending_ship",label:"待发货"},{key:"completed",label:"已完成"},{key:"cancelled",label:"已取消"},{key:"refunding",label:"退款中"}],je=s=>{const t=typeof s=="object"&&s!==null?s:{},c=Array.isArray(t.results)?t.results:[];return{total:Number(t.total||0),success_count:Number(t.success_count||0),failed_count:Number(t.failed_count||0),results:c.map(ve)}},ve=s=>{const t=typeof s=="object"&&s!==null?s:{};return{order_id:String(t.order_id||"unknown"),success:t.success===!0,message:String(t.message||"")}},Ne=s=>(s==null?void 0:s.results.filter(we))||[],we=s=>!s.success,_e=(s,t)=>s!==null&&!t,ke=s=>{if(!s)return"请选择订单文件";const t=s.name.toLowerCase().split(".").pop()||"";return["xlsx","csv","tsv","json"].includes(t)?"":"仅支持 .xlsx、.csv、.tsv、.json 格式"},T=(s,t)=>s===t,Ce=(s,t)=>s instanceof Error&&s.message?s.message:t,Se=({filter:s,onFilterChange:t,accountFilter:c,onAccountFilterChange:h,accounts:g,accountName:m,searchText:u,onSearchChange:p})=>{const b=r=>t(r.currentTarget.dataset.status||"all"),_=r=>h(r.target.value),y=r=>p(r.target.value);return e.jsxs("div",{className:"p-4 border-b border-gray-50 flex flex-col md:flex-row gap-4 justify-between items-center bg-surface-muted",children:[e.jsx("div",{className:"flex gap-1 p-1 bg-gray-200/50 rounded-xl overflow-x-auto max-w-full",children:fe.map(r=>e.jsx("button",{"data-status":r.key,onClick:b,className:`px-5 py-2 rounded-lg text-sm font-bold transition-all whitespace-nowrap ${s===r.key?"bg-white text-black shadow-sm":"text-gray-500 hover:text-gray-700"}`,children:r.label},r.key))}),e.jsxs("div",{className:"flex w-full md:w-auto flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(te,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 pointer-events-none"}),e.jsxs("select",{"aria-label":"按账号筛选订单",value:c,onChange:_,className:"ios-input pl-10 pr-9 py-2.5 rounded-xl w-full sm:w-56 bg-white border-none shadow-sm",children:[e.jsx("option",{value:"",children:"全部账号"}),g.map(r=>e.jsx("option",{value:r.id,children:m(r.id)},r.id))]})]}),e.jsxs("div",{className:"relative group",children:[e.jsx(re,{className:"w-4 h-4 absolute left-4 top-1/2 -translate-y-1/2 text-gray-400 group-focus-within:text-brand transition-colors"}),e.jsx("input",{type:"text",placeholder:"搜索订单号/商品/买家...",value:u,onChange:y,className:"ios-input pl-10 pr-4 py-2.5 rounded-xl w-64 bg-white border-none shadow-sm focus:ring-0"})]})]})]})},Ee=s=>{const t=m=>{var u;s.setImportFile(((u=m.target.files)==null?void 0:u[0])||null)},c=()=>s.closeImportModal(),h=()=>void s.handleImportOrders(),g=()=>void s.handleRetryImport();return s.showImportModal?J.createPortal(e.jsx("div",{className:"modal-overlay-centered",children:e.jsxs("div",{className:"modal-container",children:[e.jsx("div",{className:"modal-header",children:e.jsxs("div",{className:"flex items-center justify-between w-full",children:[e.jsx("h3",{className:"text-2xl font-extrabold text-gray-900",children:"插入订单"}),e.jsx("button",{onClick:c,className:"p-2 bg-gray-100 rounded-full hover:bg-gray-200 transition-colors",children:e.jsx(W,{className:"w-5 h-5 text-gray-600"})})]})}),e.jsxs("div",{className:"modal-body space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-bold text-gray-700 mb-2",children:"选择Excel文件"}),e.jsx("input",{type:"file",accept:".xlsx,.csv,.tsv,.json",onChange:t,className:"w-full ios-input px-4 py-3 rounded-xl text-sm"}),e.jsx("p",{className:"text-xs text-gray-500 mt-2",children:"支持 .xlsx、.csv、.tsv、.json 格式"})]}),s.importFile&&e.jsx("div",{className:"p-3 bg-blue-50 rounded-xl",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ne,{className:"w-4 h-4 text-blue-600"}),e.jsx("span",{className:"text-sm font-medium text-blue-900",children:s.importFile.name})]})}),s.importError&&e.jsxs("div",{className:"rounded-xl bg-red-50 border border-red-100 p-3 text-sm text-red-700 flex items-center justify-between gap-3",children:[e.jsx("span",{children:s.importError}),e.jsx("button",{type:"button",onClick:g,disabled:s.importing||!s.importFile,className:"font-bold whitespace-nowrap",children:"重试"})]}),s.importResult&&s.importResult.failed_count>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-100 p-3 text-sm font-bold text-amber-800",children:["导入完成:成功 ",s.importResultLine truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{j as e,r as o,b as De}from"./react-vendor-C_od1ZSF.js";import{k as Je,ae as it,af as vt,m as Nt,R as Te,N as Ye,Z as He,x as wt,w as et,I as kt,a1 as Ct,X as ke,V as ze,F as Ce,h as St,g as Rt,a6 as At,ag as $t,r as tt,ah as Mt}from"./icons-vendor-CvzvbbIV.js";import{g as Z,p as Ge,a as fe,d as Ke}from"./index-k6Tc6ww6.js";import{o as Ae,c as Ue}from"./contract-COFcZjyb.js";const Ee=(t,a)=>t.allowed_resolutions.includes(a),Pt=(t,a)=>({runs:t.runs.filter(i=>!a||i.cookie_id===a),pending_tasks:t.pending_tasks.filter(i=>!a||i.cookie_id===a)}),Lt=t=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[t]||"自动化异常",It=({runs:t,pendingTasks:a,onResolveRun:i,onResolveDeferredTask:u})=>e.jsxs("section",{className:"rounded-2xl border border-red-200 bg-red-50 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-black text-red-900",children:"需要人工处理的自动化任务"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。"})]})]}),e.jsxs("div",{className:"space-y-3",children:[t.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 订单 ",r.order_id||"-"," · 已记录发送 ",r.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:Lt(r.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[Ee(r,"continue")&&e.jsx("button",{onClick:(()=>i(r.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),Ee(r,"retry")&&e.jsx("button",{onClick:(()=>i(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),Ee(r,"cancel")&&e.jsx("button",{onClick:(()=>i(r.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${r.id}`)),a.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 延迟任务重试已达 ",r.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:(()=>u(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:(()=>u(r.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${r.id}`))]})]}),Ft=async t=>Z("/api/v1/accounts/details",void 0,t),ot=async t=>Z("/api/v1/cards",void 0,t),dt=async(t,a)=>Z("/api/v1/items",void 0,a),ct=t=>t.map(a=>{var i,u;return{id:String(a.id),name:a.name||"",trigger_type:a.trigger_type||"order_paid",item_keyword:a.item_title||a.item_id||"",cookie_id:a.cookie_id||"",item_id:a.item_id||"",item_title:a.item_title||"",card_group_id:Number(((i=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:i.card_id)||0),card_group_name:((u=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:u.card_name)||"",priority:a.priority||100,enabled:a.enabled||!1,config_json:a.config_json||"{}",actions:(a.actions||[]).map(r=>({id:r.id?String(r.id):void 0,action_type:r.action_type,card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),message_template:r.message_template||"",delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}",enabled:r.enabled!==!1,sort_order:Number(r.sort_order||0)})),variants:(a.actions||[]).filter(r=>r.action_type==="send_card").map(r=>{let y={};try{y=JSON.parse(r.config_json||"{}")}catch{}return{id:r.id?String(r.id):void 0,spec_name:y.spec_name||"",spec_value:y.spec_value||"",card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),enabled:r.enabled!==!1,delay_override:y.delay_override===!0,delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}"}})}}),Dt=async()=>{const t=await Z("/api/v1/automation-rules"),a=Ue(t,["data","rules","items"]);return ct(a)},Tt=async({cookieId:t,triggerType:a,enabled:i,search:u,page:r=1,pageSizeLine truncated
|
||||
import{j as e,r as o,b as De}from"./react-vendor-C_od1ZSF.js";import{k as Je,ae as it,af as vt,m as Nt,R as Te,N as Ye,Z as He,x as wt,w as et,I as kt,a1 as Ct,X as ke,V as ze,F as Ce,h as St,g as Rt,a6 as At,ag as $t,r as tt,ah as Mt}from"./icons-vendor-CvzvbbIV.js";import{g as Z,p as Ge,a as fe,d as Ke}from"./index-CCqtUiU5.js";import{o as Ae,c as Ue}from"./contract-COFcZjyb.js";const Ee=(t,a)=>t.allowed_resolutions.includes(a),Pt=(t,a)=>({runs:t.runs.filter(i=>!a||i.cookie_id===a),pending_tasks:t.pending_tasks.filter(i=>!a||i.cookie_id===a)}),Lt=t=>({external_result_unknown:"外部动作结果未知",invalid_snapshot:"历史数据无法恢复",rule_unavailable:"规则不可用",partial_failure:"部分动作失败",execution_failed:"动作执行失败"})[t]||"自动化异常",It=({runs:t,pendingTasks:a,onResolveRun:i,onResolveDeferredTask:u})=>e.jsxs("section",{className:"rounded-2xl border border-red-200 bg-red-50 p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Je,{className:"w-5 h-5 text-red-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-black text-red-900",children:"需要人工处理的自动化任务"}),e.jsx("p",{className:"text-sm text-red-700 mt-1",children:"请先在闲鱼聊天、订单或商品列表中核对真实结果,再选择继续或重试。"})]})]}),e.jsxs("div",{className:"space-y-3",children:[t.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 订单 ",r.order_id||"-"," · 已记录发送 ",r.sent_count," 条"]}),e.jsx("div",{className:"text-xs font-bold text-red-800 mt-1",children:Lt(r.issue_kind)}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 shrink-0",children:[Ee(r,"continue")&&e.jsx("button",{onClick:(()=>i(r.id,"continue")),className:"px-3 py-2 rounded-lg bg-emerald-100 text-emerald-800 text-xs font-bold",children:"已执行,继续下一步"}),Ee(r,"retry")&&e.jsx("button",{onClick:(()=>i(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"未执行,安全重试"}),Ee(r,"cancel")&&e.jsx("button",{onClick:(()=>i(r.id,"cancel")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"终止"})]})]},`run-${r.id}`)),a.map(r=>e.jsxs("div",{className:"rounded-xl border border-red-100 bg-white p-4 flex flex-col lg:flex-row lg:items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"font-bold text-gray-900",children:["账号 ",r.cookie_id," · 延迟任务重试已达 ",r.attempt_count," 次"]}),e.jsx("div",{className:"text-xs text-red-700 mt-1 break-words",children:r.error_message})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[e.jsx("button",{onClick:(()=>u(r.id,"retry")),className:"px-3 py-2 rounded-lg bg-amber-100 text-amber-800 text-xs font-bold",children:"重新入队"}),e.jsx("button",{onClick:(()=>u(r.id,"dismiss")),className:"px-3 py-2 rounded-lg bg-gray-100 text-gray-700 text-xs font-bold",children:"忽略"})]})]},`task-${r.id}`))]})]}),Ft=async t=>Z("/api/v1/accounts/details",void 0,t),ot=async t=>Z("/api/v1/cards",void 0,t),dt=async(t,a)=>Z("/api/v1/items",void 0,a),ct=t=>t.map(a=>{var i,u;return{id:String(a.id),name:a.name||"",trigger_type:a.trigger_type||"order_paid",item_keyword:a.item_title||a.item_id||"",cookie_id:a.cookie_id||"",item_id:a.item_id||"",item_title:a.item_title||"",card_group_id:Number(((i=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:i.card_id)||0),card_group_name:((u=(a.actions||[]).find(r=>r.action_type==="send_card"))==null?void 0:u.card_name)||"",priority:a.priority||100,enabled:a.enabled||!1,config_json:a.config_json||"{}",actions:(a.actions||[]).map(r=>({id:r.id?String(r.id):void 0,action_type:r.action_type,card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),message_template:r.message_template||"",delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}",enabled:r.enabled!==!1,sort_order:Number(r.sort_order||0)})),variants:(a.actions||[]).filter(r=>r.action_type==="send_card").map(r=>{let y={};try{y=JSON.parse(r.config_json||"{}")}catch{}return{id:r.id?String(r.id):void 0,spec_name:y.spec_name||"",spec_value:y.spec_value||"",card_id:Number(r.card_id||0),card_name:r.card_name||"",delivery_count:Number(r.delivery_count||1),enabled:r.enabled!==!1,delay_override:y.delay_override===!0,delay_seconds:Number(r.delay_seconds||0),config_json:r.config_json||"{}"}})}}),Dt=async()=>{const t=await Z("/api/v1/automation-rules"),a=Ue(t,["data","rules","items"]);return ct(a)},Tt=async({cookieId:t,triggerType:a,enabled:i,search:u,page:r=1,pageSizeLine truncated
|
||||
+1
-1
@@ -1 +1 @@
|
||||
import{r,j as e}from"./react-vendor-C_od1ZSF.js";import{a as xe,g as re,p as le}from"./index-k6Tc6ww6.js";import{f as ue,R as se,aa as pe,p as me,u as R,v as O,ab as he,s as ge,S as te,ac as ae,ad as ye,r as fe}from"./icons-vendor-CvzvbbIV.js";const ne="https://dashscope.aliyuncs.com/compatible-mode/v1",be=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],we=new Set(["ai_api_key_configured","smtp_password_configured","qq_reply_secret_key_configured","captcha.remote_secret_key_configured","smtp_server","smtp_port","smtp_user","smtp_password","smtp_from","smtp_from_name","smtp_from_address","registration_enabled","show_default_login_info","login_captcha_enabled","item_sync_enabled","item_sync_interval","item_sync_max_pages","default_reply"]),oe=new Set(["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"]),je=s=>{if("values"in s||"secrets"in s)return s;const a={},o={};for(const[d,h]of Object.entries(s))if(h!=null){if(oe.has(d)){o[d]=h===""?{action:"clear"}:{action:"replace",value:String(h)};continue}a[d]=h}return Object.keys(o).length>0?{values:a,secrets:o}:a},ve=s=>{const a={...s};for(const o of oe){const d=`${o}_configured`;d in a&&(a[d]=a[d]===!0||a[d]==="true")}if("renewal_log_retention_days"in a){const o=Number(a.renewal_log_retention_days);a.renewal_log_retention_days=Number.isFinite(o)?o:10}return a},_e=async(s,a)=>le("/api/v1/session/credentials",s,a),Ne=async s=>{const a=await re("/api/v1/settings/system",void 0,s),o=a.data||a.settings||a;return ve(o)},Se=async(s,a)=>le("/api/v1/settings/system",je(s),a),ke=async(s,a="",o)=>{const d=await xe("/api/v1/settings/ai-models",{base_url:s,api_key:a},o);return Array.isArray(d.models)?d.models:[]},Ce=async s=>re("/api/v1/session",void 0,s),Ee=s=>Object.fromEntries(Object.entries(s).filter(([a,o])=>!we.has(a)&&o!==void 0&&o!==null)),Ae=s=>s.new_username.trim().length<3?"用户名至少需要 3 个字符":s.current_password?s.new_password&&s.new_password.length<8?"新密码至少需要 8 个字符":s.new_password!==s.confirm_password?"两次输入的新密码不一致":"":"请输入当前密码确认身份",f=(s,a,o)=>s===a&&!o.aborted,D=s=>s instanceof Error&&s.message==="请求已取消",K=(s,a)=>s instanceof Error?s.message:a,Ie=(s="")=>({new_username:s,current_password:"",new_password:"",confirm_password:""}),T=(s,a)=>({type:s,text:a}),Me=()=>{const[s,a]=r.useState(null),[o,d]=r.useState(!1),[h,p]=r.useState(""),[S,A]=r.useState(!1),[P,k]=r.useState(""),[C,w]=r.useState([]),[j,I]=r.useState(!1),[M,x]=r.useState(""),[$,v]=r.useState(!1),[U,q]=r.useState(!1),[z,u]=r.useState(!1),[b,F]=r.useState(!1),[G,V]=r.useState(!1),[Y,_]=r.useState(!1),[L,y]=r.useState(null),[t,X]=r.useState(()=>Ie()),[ce,J]=r.useState("idle"),Z=r.useRef(null),ee=r.useRef(null),m=r.useRef(0),W=r.useRef(null);ee.current=s;const E=r.useCallback(()=>{var c;(c=W.current)==null||c.abort();const n=new AbortController;return W.current=n,m.current+=1,{controller:n,sequence:m.current}},[]),B=r.useCallback(async(n,c=!1,l)=>{const i=n||ee.current,g=(i==null?void 0:i.ai_api_url)||(i==null?void 0:i.ai_base_url)||ne;I(!0),x("");try{const N=await ke(g,(i==null?void 0:i.ai_api_key)||"",{signal:l});if(l!=null&&l.aborted)return;w(N),v(c&&N.length>0),!(i!=null&&i.ai_model)&&N.length>0&&a(Q=>Q&&{...Q,ai_model:N[0]})}catch(N){if(l!=null&&l.aborted||D(N))return;w([]),v(!1),x(K(N,"读取模型失败"))}finally{l!=null&&l.aborted||I(!1)}},[]),H=r.useCallback(()=>{const{controller:n,sequence:c}=E();d(!0),J("loading"),p(""),Promise.all([Ne({signal:n.signal}),Ce({signal:n.signal})]).then(([l,i])=>{f(m.current,c,n.signal)&&(a(l),i.username&&X(g=>({...g,new_username:i.username||""})),B(l,!1,n.signal),J("success"))}).catch(l=>{!f(m.current,c,n.signal)||D(l)||(a(null),p(K(l,"加载配置失败")),J("error"))}).finally(()=>{f(m.current,c,n.signal)&&d(!1)})},[E,B]);r.useEffect(()=>(H(),(()=>{var n;return(n=W.current)==null?void 0:n.abort()})),[H]),r.useEffect(()=>{const n=c=>{var l;(l=Z.current)!=null&&l.contains(c.target)||v(!1)};return document.addEventListener("mousedown",n),(()=>document.removeEventListener("mousedown",n))},[]);const ie=r.useCallback(async()=>{if(!s||S)return;const{controller:n,sequence:c}=E();A(!0),k("");try{if(await Se(Ee(s),{signal:n.signal}),!f(m.current,c,n.signal))return;window.alert("系统配置已保存")}catch(l){if(!f(m.current,c,n.signal)||D(l))return;k(K(l,"保存配置失败"))}finally{f(m.current,c,n.signal)&&A(!1)}},[E,S,s]),de=r.useCallback(async n=>{n.preventDefault(),y(null);const c=Ae(t);if(c){y(T("error",c));return}const{controller:l,sequence:i}=E();_(!0);try{const g=await _e({current_password:t.current_password,new_username:t.new_username.trim(),new_password:t.new_password||void 0},{signal:l.signal});if(!f(m.current,i,l.signal))return;if(!g.success){y(T("error",g.message||"登录凭据更新失败"));return}y(T("success",g.message||"登录凭据已更新")),window.setTimeout(()=>windLine truncated
|
||||
import{r,j as e}from"./react-vendor-C_od1ZSF.js";import{a as xe,g as re,p as le}from"./index-CCqtUiU5.js";import{f as ue,R as se,aa as pe,p as me,u as R,v as O,ab as he,s as ge,S as te,ac as ae,ad as ye,r as fe}from"./icons-vendor-CvzvbbIV.js";const ne="https://dashscope.aliyuncs.com/compatible-mode/v1",be=[{value:"debug",label:"Debug"},{value:"info",label:"Info"},{value:"warn",label:"Warn"},{value:"error",label:"Error"}],we=new Set(["ai_api_key_configured","smtp_password_configured","qq_reply_secret_key_configured","captcha.remote_secret_key_configured","smtp_server","smtp_port","smtp_user","smtp_password","smtp_from","smtp_from_name","smtp_from_address","registration_enabled","show_default_login_info","login_captcha_enabled","item_sync_enabled","item_sync_interval","item_sync_max_pages","default_reply"]),oe=new Set(["ai_api_key","smtp_password","qq_reply_secret_key","captcha.remote_secret_key"]),je=s=>{if("values"in s||"secrets"in s)return s;const a={},o={};for(const[d,h]of Object.entries(s))if(h!=null){if(oe.has(d)){o[d]=h===""?{action:"clear"}:{action:"replace",value:String(h)};continue}a[d]=h}return Object.keys(o).length>0?{values:a,secrets:o}:a},ve=s=>{const a={...s};for(const o of oe){const d=`${o}_configured`;d in a&&(a[d]=a[d]===!0||a[d]==="true")}if("renewal_log_retention_days"in a){const o=Number(a.renewal_log_retention_days);a.renewal_log_retention_days=Number.isFinite(o)?o:10}return a},_e=async(s,a)=>le("/api/v1/session/credentials",s,a),Ne=async s=>{const a=await re("/api/v1/settings/system",void 0,s),o=a.data||a.settings||a;return ve(o)},Se=async(s,a)=>le("/api/v1/settings/system",je(s),a),ke=async(s,a="",o)=>{const d=await xe("/api/v1/settings/ai-models",{base_url:s,api_key:a},o);return Array.isArray(d.models)?d.models:[]},Ce=async s=>re("/api/v1/session",void 0,s),Ee=s=>Object.fromEntries(Object.entries(s).filter(([a,o])=>!we.has(a)&&o!==void 0&&o!==null)),Ae=s=>s.new_username.trim().length<3?"用户名至少需要 3 个字符":s.current_password?s.new_password&&s.new_password.length<8?"新密码至少需要 8 个字符":s.new_password!==s.confirm_password?"两次输入的新密码不一致":"":"请输入当前密码确认身份",f=(s,a,o)=>s===a&&!o.aborted,D=s=>s instanceof Error&&s.message==="请求已取消",K=(s,a)=>s instanceof Error?s.message:a,Ie=(s="")=>({new_username:s,current_password:"",new_password:"",confirm_password:""}),T=(s,a)=>({type:s,text:a}),Me=()=>{const[s,a]=r.useState(null),[o,d]=r.useState(!1),[h,p]=r.useState(""),[S,A]=r.useState(!1),[P,k]=r.useState(""),[C,w]=r.useState([]),[j,I]=r.useState(!1),[M,x]=r.useState(""),[$,v]=r.useState(!1),[U,q]=r.useState(!1),[z,u]=r.useState(!1),[b,F]=r.useState(!1),[G,V]=r.useState(!1),[Y,_]=r.useState(!1),[L,y]=r.useState(null),[t,X]=r.useState(()=>Ie()),[ce,J]=r.useState("idle"),Z=r.useRef(null),ee=r.useRef(null),m=r.useRef(0),W=r.useRef(null);ee.current=s;const E=r.useCallback(()=>{var c;(c=W.current)==null||c.abort();const n=new AbortController;return W.current=n,m.current+=1,{controller:n,sequence:m.current}},[]),B=r.useCallback(async(n,c=!1,l)=>{const i=n||ee.current,g=(i==null?void 0:i.ai_api_url)||(i==null?void 0:i.ai_base_url)||ne;I(!0),x("");try{const N=await ke(g,(i==null?void 0:i.ai_api_key)||"",{signal:l});if(l!=null&&l.aborted)return;w(N),v(c&&N.length>0),!(i!=null&&i.ai_model)&&N.length>0&&a(Q=>Q&&{...Q,ai_model:N[0]})}catch(N){if(l!=null&&l.aborted||D(N))return;w([]),v(!1),x(K(N,"读取模型失败"))}finally{l!=null&&l.aborted||I(!1)}},[]),H=r.useCallback(()=>{const{controller:n,sequence:c}=E();d(!0),J("loading"),p(""),Promise.all([Ne({signal:n.signal}),Ce({signal:n.signal})]).then(([l,i])=>{f(m.current,c,n.signal)&&(a(l),i.username&&X(g=>({...g,new_username:i.username||""})),B(l,!1,n.signal),J("success"))}).catch(l=>{!f(m.current,c,n.signal)||D(l)||(a(null),p(K(l,"加载配置失败")),J("error"))}).finally(()=>{f(m.current,c,n.signal)&&d(!1)})},[E,B]);r.useEffect(()=>(H(),(()=>{var n;return(n=W.current)==null?void 0:n.abort()})),[H]),r.useEffect(()=>{const n=c=>{var l;(l=Z.current)!=null&&l.contains(c.target)||v(!1)};return document.addEventListener("mousedown",n),(()=>document.removeEventListener("mousedown",n))},[]);const ie=r.useCallback(async()=>{if(!s||S)return;const{controller:n,sequence:c}=E();A(!0),k("");try{if(await Se(Ee(s),{signal:n.signal}),!f(m.current,c,n.signal))return;window.alert("系统配置已保存")}catch(l){if(!f(m.current,c,n.signal)||D(l))return;k(K(l,"保存配置失败"))}finally{f(m.current,c,n.signal)&&A(!1)}},[E,S,s]),de=r.useCallback(async n=>{n.preventDefault(),y(null);const c=Ae(t);if(c){y(T("error",c));return}const{controller:l,sequence:i}=E();_(!0);try{const g=await _e({current_password:t.current_password,new_username:t.new_username.trim(),new_password:t.new_password||void 0},{signal:l.signal});if(!f(m.current,i,l.signal))return;if(!g.success){y(T("error",g.message||"登录凭据更新失败"));return}y(T("success",g.message||"登录凭据已更新")),window.setTimeout(()=>windLine truncated
|
||||
@@ -1 +0,0 @@
|
||||
*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(147 197 253 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(147 197 253 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:rgb(var(--color-neutral-200) / 1)}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:rgb(var(--color-neutral-400) / 1)}input::placeholder,textarea::placeholder{opacity:1;color:rgb(var(--color-neutral-400) / 1)}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.\!container{width:100%!important}.container{width:100%}@media(min-width:640px){.\!container{max-width:640px!important}.container{max-width:6Line truncated
|
||||
+2
-2
@@ -1,2 +1,2 @@
|
||||
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-3YjsHK0L.js","assets/react-vendor-C_od1ZSF.js","assets/dateTime-DDi7rqpW.js","assets/contract-COFcZjyb.js","assets/icons-vendor-CvzvbbIV.js","assets/charts-vendor-deWqkrdG.js","assets/vendor-Es4K8PXl.js","assets/vendor-DUblxfbA.css","assets/AccountList-i39PcoQv.js","assets/OrderList-CljaoSLa.js","assets/CardList-z1WELq_d.js","assets/ItemList-DDiNaq3H.js","assets/Settings-BIhrQYtY.js","assets/Rules-BiND-23Q.js","assets/Notifications-DcqcaoDO.js","assets/Chat-BfnRPAOt.js"])))=>i.map(i=>d[i]);
|
||||
import{c as S,j as e,r as c,d as H}from"./react-vendor-C_od1ZSF.js";import{L as T,a as P,S as J,U as Y,A as K,b as Q,c as W,M as X,C as ee,B as te,d as se,Z as ne,e as re,f as ae,G as k,g as oe,h as ie,i as le}from"./icons-vendor-CvzvbbIV.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))d(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&d(a)}).observe(document,{childList:!0,subtree:!0});function s(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function d(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();class ce extends S.Component{constructor(){super(...arguments),this.state={hasError:!1},this.handleReload=()=>{window.location.reload()}}static getDerivedStateFromError(){return{hasError:!0}}render(){const{hasError:n}=this.state,{children:s}=this.props;return n?e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-6 text-ink",children:e.jsxs("section",{className:"max-w-md text-center",children:[e.jsx("h1",{className:"text-xl font-semibold",children:"页面暂时无法显示"}),e.jsx("button",{className:"ios-btn-primary mt-6 px-4 py-2",type:"button",onClick:this.handleReload,children:"重新加载"})]})}):s}}const de=3e4,ue=10*6e4;let N=!1;const I=()=>{N||typeof window>"u"||(N=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{N=!1}))},he=t=>{if(!t)return"";const n=new URLSearchParams;for(const[d,r]of Object.entries(t))r!=null&&n.set(d,String(r));const s=n.toString();return s?`?${s}`:""},L=async(t,n,s={})=>{var o;const d=he(s.params),r=`${n}${d}`,i=$(s.signal,s.timeoutMs??de);let a;try{a=await fetch(r,{method:t,credentials:"include",signal:i.signal,headers:{...s.body===void 0?{}:{"Content-Type":"application/json"}},body:s.body===void 0?void 0:JSON.stringify(s.body)})}catch(m){throw i.signal.aborted?new Error((o=s.signal)!=null&&o.aborted?"请求已取消":"请求超时,请稍后重试"):m}finally{i.cleanup()}const h=(a.headers.get("content-type")||"").includes("application/json");if(!a.ok){a.status===401&&!s.skipAuthLogout&&I();const m=h?await a.json().catch(()=>{}):await a.text().catch(()=>{}),f=z(m,a.status);throw new Error(f)}return h?await a.json():await a.text()},D=async(t,n,s)=>L("GET",t,{params:n,...s}),_=async(t,n,s)=>L("POST",t,{body:n,...s}),Ve=async(t,n,s)=>L("PUT",t,{body:n,...s}),Ue=async(t,n,s)=>L("DELETE",t,{params:n,...s}),Ge=async(t,n,s={})=>{var h;const d=$(s.signal,s.timeoutMs??ue);let r;try{r=await fetch(t,{method:"POST",credentials:"include",signal:d.signal,body:n})}catch(o){throw d.signal.aborted?new Error((h=s.signal)!=null&&h.aborted?"请求已取消":"上传超时,请稍后重试"):o}finally{d.cleanup()}const l=(r.headers.get("content-type")||"").includes("application/json")?await r.json().catch(()=>{}):await r.text().catch(()=>{});if(!r.ok){r.status===401&&I();const o=z(l,r.status),m=new Error(o);throw m.payload=l,m}return l},$=(t,n)=>{const s=new AbortController,d=()=>s.abort(t==null?void 0:t.reason);t!=null&&t.aborted?d():t==null||t.addEventListener("abort",d,{once:!0});const r=globalThis.setTimeout(()=>s.abort(new DOMException("timeout","TimeoutError")),Math.max(1,n));return{signal:s.signal,cleanup:()=>{globalThis.clearTimeout(r),t==null||t.removeEventListener("abort",d)}}},me=t=>{if(typeof t!="object"||t===null)return!1;const n=t;return typeof n.code=="string"&&typeof n.message=="string"},z=(t,n)=>typeof t=="string"?t:me(t)?t.message:`请求失败: ${n}`,fe=async t=>_("/api/v1/session/login",t,{skipAuthLogout:!0}),xe=async t=>_("/api/v1/session/initialize",{password:t},{skipAuthLogout:!0}),pe=async t=>D("/api/v1/session",void 0,t),ge=async()=>_("/api/v1/session/logout",{}),M=c.createContext(void 0),be=({children:t})=>{const[n,s]=c.useState(!1),[d,r]=c.useState(!1),[i,a]=c.useState(!0),[l,h]=c.useState(!1),o=()=>{s(!1),r(!1)};c.useEffect(()=>{const b=new AbortController;let g=!0;pe({signal:b.signal}).then(p=>{if(g){if((p==null?void 0:p.initialized)===!1){h(!0),o();return}h(!1),p!=null&&p.authenticated?(s(!0),r(p.is_admin===!0)):o()}}).catch(p=>{!g||p instanceof DOMException&&p.name==="AbortError"||(h(!1),o())}).finally(()=>{g&&a(!1)});const u=()=>o();return window.addEventListener("auth:logout",u),(()=>{g=!1,b.abort(),window.removeEventListener("auth:logout",u)})},[]);const m=async b=>{const g=await fe(b);return g.success&&(h(!1),s(!0),r(g.is_admin===!0)),g},f=async b=>{const g=await xe(b);return g.success&&(h(!1),s(!0),r(g.is_admin===!0)),g},x=async()=>{try{await ge()}finally{o()}};return e.jsx(M.Provider,{value:{checkingAuth:i,isLoggedIn:n,isAdmin:d,needsInit:l,signIn:m,initialize:f,signOut:Line truncated
|
||||
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/Dashboard-xJlcwTaJ.js","assets/react-vendor-C_od1ZSF.js","assets/dateTime-DDi7rqpW.js","assets/contract-COFcZjyb.js","assets/icons-vendor-CvzvbbIV.js","assets/charts-vendor-deWqkrdG.js","assets/vendor-Es4K8PXl.js","assets/vendor-DUblxfbA.css","assets/AccountList-CW56xo40.js","assets/OrderList-BY2V4t6y.js","assets/CardList-DXFjEouq.js","assets/ItemList-CnEIHIcF.js","assets/Settings-CbEKYyJY.js","assets/Rules-BeCst9X9.js","assets/Notifications-Cgc4sSHL.js","assets/Chat-o8zU9itw.js"])))=>i.map(i=>d[i]);
|
||||
import{c as S,j as e,r as c,d as H}from"./react-vendor-C_od1ZSF.js";import{L as T,a as P,S as J,U as Y,A as K,b as Q,c as W,M as X,C as ee,B as te,d as se,Z as ne,e as re,f as ae,G as k,g as oe,h as ie,i as le}from"./icons-vendor-CvzvbbIV.js";(function(){const n=document.createElement("link").relList;if(n&&n.supports&&n.supports("modulepreload"))return;for(const r of document.querySelectorAll('link[rel="modulepreload"]'))d(r);new MutationObserver(r=>{for(const i of r)if(i.type==="childList")for(const a of i.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&d(a)}).observe(document,{childList:!0,subtree:!0});function s(r){const i={};return r.integrity&&(i.integrity=r.integrity),r.referrerPolicy&&(i.referrerPolicy=r.referrerPolicy),r.crossOrigin==="use-credentials"?i.credentials="include":r.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function d(r){if(r.ep)return;r.ep=!0;const i=s(r);fetch(r.href,i)}})();class ce extends S.Component{constructor(){super(...arguments),this.state={hasError:!1},this.handleReload=()=>{window.location.reload()}}static getDerivedStateFromError(){return{hasError:!0}}render(){const{hasError:n}=this.state,{children:s}=this.props;return n?e.jsx("main",{className:"flex min-h-screen items-center justify-center bg-canvas p-6 text-ink",children:e.jsxs("section",{className:"max-w-md text-center",children:[e.jsx("h1",{className:"text-xl font-semibold",children:"页面暂时无法显示"}),e.jsx("button",{className:"ios-btn-primary mt-6 px-4 py-2",type:"button",onClick:this.handleReload,children:"重新加载"})]})}):s}}const de=3e4,ue=10*6e4;let N=!1;const I=()=>{N||typeof window>"u"||(N=!0,window.dispatchEvent(new Event("auth:logout")),queueMicrotask(()=>{N=!1}))},he=t=>{if(!t)return"";const n=new URLSearchParams;for(const[d,r]of Object.entries(t))r!=null&&n.set(d,String(r));const s=n.toString();return s?`?${s}`:""},L=async(t,n,s={})=>{var o;const d=he(s.params),r=`${n}${d}`,i=$(s.signal,s.timeoutMs??de);let a;try{a=await fetch(r,{method:t,credentials:"include",signal:i.signal,headers:{...s.body===void 0?{}:{"Content-Type":"application/json"}},body:s.body===void 0?void 0:JSON.stringify(s.body)})}catch(m){throw i.signal.aborted?new Error((o=s.signal)!=null&&o.aborted?"请求已取消":"请求超时,请稍后重试"):m}finally{i.cleanup()}const h=(a.headers.get("content-type")||"").includes("application/json");if(!a.ok){a.status===401&&!s.skipAuthLogout&&I();const m=h?await a.json().catch(()=>{}):await a.text().catch(()=>{}),f=z(m,a.status);throw new Error(f)}return h?await a.json():await a.text()},D=async(t,n,s)=>L("GET",t,{params:n,...s}),_=async(t,n,s)=>L("POST",t,{body:n,...s}),Ve=async(t,n,s)=>L("PUT",t,{body:n,...s}),Ue=async(t,n,s)=>L("DELETE",t,{params:n,...s}),Ge=async(t,n,s={})=>{var h;const d=$(s.signal,s.timeoutMs??ue);let r;try{r=await fetch(t,{method:"POST",credentials:"include",signal:d.signal,body:n})}catch(o){throw d.signal.aborted?new Error((h=s.signal)!=null&&h.aborted?"请求已取消":"上传超时,请稍后重试"):o}finally{d.cleanup()}const l=(r.headers.get("content-type")||"").includes("application/json")?await r.json().catch(()=>{}):await r.text().catch(()=>{});if(!r.ok){r.status===401&&I();const o=z(l,r.status),m=new Error(o);throw m.payload=l,m}return l},$=(t,n)=>{const s=new AbortController,d=()=>s.abort(t==null?void 0:t.reason);t!=null&&t.aborted?d():t==null||t.addEventListener("abort",d,{once:!0});const r=globalThis.setTimeout(()=>s.abort(new DOMException("timeout","TimeoutError")),Math.max(1,n));return{signal:s.signal,cleanup:()=>{globalThis.clearTimeout(r),t==null||t.removeEventListener("abort",d)}}},me=t=>{if(typeof t!="object"||t===null)return!1;const n=t;return typeof n.code=="string"&&typeof n.message=="string"},z=(t,n)=>typeof t=="string"?t:me(t)?t.message:`请求失败: ${n}`,fe=async t=>_("/api/v1/session/login",t,{skipAuthLogout:!0}),xe=async t=>_("/api/v1/session/initialize",{password:t},{skipAuthLogout:!0}),pe=async t=>D("/api/v1/session",void 0,t),ge=async()=>_("/api/v1/session/logout",{}),M=c.createContext(void 0),be=({children:t})=>{const[n,s]=c.useState(!1),[d,r]=c.useState(!1),[i,a]=c.useState(!0),[l,h]=c.useState(!1),o=()=>{s(!1),r(!1)};c.useEffect(()=>{const b=new AbortController;let g=!0;pe({signal:b.signal}).then(p=>{if(g){if((p==null?void 0:p.initialized)===!1){h(!0),o();return}h(!1),p!=null&&p.authenticated?(s(!0),r(p.is_admin===!0)):o()}}).catch(p=>{!g||p instanceof DOMException&&p.name==="AbortError"||(h(!1),o())}).finally(()=>{g&&a(!1)});const u=()=>o();return window.addEventListener("auth:logout",u),(()=>{g=!1,b.abort(),window.removeEventListener("auth:logout",u)})},[]);const m=async b=>{const g=await fe(b);return g.success&&(h(!1),s(!0),r(g.is_admin===!0)),g},f=async b=>{const g=await xe(b);return g.success&&(h(!1),s(!0),r(g.is_admin===!0)),g},x=async()=>{try{await ge()}finally{o()}};return e.jsx(M.Provider,{value:{checkingAuth:i,isLoggedIn:n,isAdmin:d,needsInit:l,signIn:m,initialize:f,signOut:Line truncated
|
||||
@@ -0,0 +1 @@
|
||||
*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(147 197 253 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(147 197 253 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:rgb(var(--color-neutral-200) / 1)}:before,:after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:-apple-system,BlinkMacSystemFont,PingFang SC,Hiragino Sans GB,Microsoft YaHei,Helvetica Neue,Helvetica,Arial,sans-serif;font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:rgb(var(--color-neutral-400) / 1)}input::placeholder,textarea::placeholder{opacity:1;color:rgb(var(--color-neutral-400) / 1)}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}.\!container{width:100%!important}.container{width:100%}@media(min-width:640px){.\!container{max-width:640px!important}.container{max-width:6Line truncated
|
||||
@@ -6,10 +6,10 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Ydisks闲鱼助手 - 自动发货与管家系统</title>
|
||||
<meta name="description" content="Ydisks闲鱼助手 - 自动回复、自动发货、订单管理、AI智能议价一体化解决方案" />
|
||||
<script type="module" crossorigin src="/static/assets/index-k6Tc6ww6.js"></script>
|
||||
<script type="module" crossorigin src="/static/assets/index-CCqtUiU5.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/react-vendor-C_od1ZSF.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/assets/icons-vendor-CvzvbbIV.js">
|
||||
<link rel="stylesheet" crossorigin href="/static/assets/index-BgG-QVY7.css">
|
||||
<link rel="stylesheet" crossorigin href="/static/assets/index-fhlAsi4b.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -117,6 +117,8 @@ type PublishItemRequest struct {
|
||||
PreferredCategory *PublishCategory
|
||||
Location *PublishLocation
|
||||
Images []PublishImage
|
||||
// BeforePublish 在图片上传和类目准备完成后、最终商品发布请求发出前执行,可响应批次节流取消。
|
||||
BeforePublish func(context.Context) error
|
||||
}
|
||||
|
||||
// PublishItemResult 用于本次流程后续判断的发布商品结果
|
||||
@@ -204,6 +206,12 @@ func (c *ClientImpl) PublishItem(ctx context.Context, cookiesStr string, req Pub
|
||||
}
|
||||
}
|
||||
}
|
||||
if req.BeforePublish != nil {
|
||||
// err 保存发布前闸门等待或取消错误。
|
||||
if err := req.BeforePublish(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return c.publishItemOnce(ctx, currentCookies, req, uploaded, category)
|
||||
}
|
||||
|
||||
|
||||
@@ -89,11 +89,16 @@ func TestPublishItemDescriptionDefaultsToTitle(t *testing.T) {
|
||||
png1 := tinyPNG(t)
|
||||
// gotDesc 用于本次流程后续判断的gotDesc
|
||||
var gotDesc string
|
||||
// uploadFinished 记录图片上传是否已经完成,确保发布前闸门不会提前执行。
|
||||
uploadFinished := false
|
||||
// beforePublishCalled 记录最终发布前回调是否被调用。
|
||||
beforePublishCalled := false
|
||||
// publishedData 用于本次流程后续判断的published数据
|
||||
var publishedData map[string]any
|
||||
// dt 用于本次流程后续判断的dt
|
||||
dt := &dispatchTransport{handlers: map[string]http.HandlerFunc{
|
||||
"_upload": func(w http.ResponseWriter, r *http.Request) {
|
||||
uploadFinished = true
|
||||
fmt.Fprint(w, `{"object":{"url":"https://cdn/a.jpg","pix":"800x600"}}`)
|
||||
},
|
||||
"mtop.taobao.idle.kgraph.property.recommend": func(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -128,6 +133,13 @@ func TestPublishItemDescriptionDefaultsToTitle(t *testing.T) {
|
||||
PostageCents: 500,
|
||||
Location: &PublishLocation{Area: "X", City: "Y", DivisionID: "1", Longitude: 118.7, Latitude: 31.9, POIID: "p1", POIName: "P", Province: "Z"},
|
||||
Images: []PublishImage{{Filename: "a.png", ContentType: "image/png", Data: png1}},
|
||||
BeforePublish: func(context.Context) error {
|
||||
if !uploadFinished {
|
||||
t.Fatal("最终发布前图片尚未上传完成")
|
||||
}
|
||||
beforePublishCalled = true
|
||||
return nil
|
||||
},
|
||||
}
|
||||
// res、err 用于本次流程后续判断的res、err
|
||||
res, err := client.PublishItem(context.Background(), consignCookies, req)
|
||||
@@ -146,6 +158,9 @@ func TestPublishItemDescriptionDefaultsToTitle(t *testing.T) {
|
||||
if res.ImageURL != "https://cdn/a.jpg" {
|
||||
t.Fatalf("ImageURL=%q", res.ImageURL)
|
||||
}
|
||||
if !beforePublishCalled {
|
||||
t.Fatal("最终发布前闸门未执行")
|
||||
}
|
||||
// addr、ok 用于本次流程后续判断的addr、ok
|
||||
addr, ok := publishedData["itemAddrDTO"].(map[string]any)
|
||||
if !ok || addr["gps"] != "31.9,118.7" {
|
||||
|
||||
Reference in new issue
Block a user